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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
061478842688533a52c569a891f65709f1ec7aae
| 1,019
|
hpp
|
C++
|
src/rendering.hpp
|
IsaacWoods/Islands
|
d4b14b34884ca3f7ba1a97670dfef653b207befa
|
[
"MIT"
] | null | null | null |
src/rendering.hpp
|
IsaacWoods/Islands
|
d4b14b34884ca3f7ba1a97670dfef653b207befa
|
[
"MIT"
] | null | null | null |
src/rendering.hpp
|
IsaacWoods/Islands
|
d4b14b34884ca3f7ba1a97670dfef653b207befa
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2017, Isaac Woods.
* See LICENCE.md
*/
#pragma once
#include <gl3w.hpp>
#include <maths.hpp>
#include <asset.hpp>
#include <entity.hpp>
// --- Mesh ---
struct Mesh
{
Mesh(const MeshData& meshData);
~Mesh();
unsigned int numElements;
GLuint vao;
GLuint vbo;
GLuint ebo;
};
void DrawMesh(Mesh& mesh);
// --- Shaders ---
struct Shader
{
Shader(const char* basePath);
~Shader();
GLuint handle;
unsigned int textureCount;
};
void UseShader(Shader& shader);
template<typename T> void SetUniform(Shader& shader, const char* name, const T& value);
// --- Textures ---
struct Texture
{
Texture(const char* path);
~Texture();
GLuint handle;
unsigned int width;
unsigned int height;
};
// --- Rendering ---
struct Renderer
{
Renderer(unsigned int width, unsigned int height);
void StartFrame();
void RenderEntity(Entity* entity);
void EndFrame();
unsigned int width;
unsigned int height;
Shader shader;
Mat<4u> projection;
};
| 15.676923
| 87
| 0.651619
|
IsaacWoods
|
0615fe2d21d35e02f9957a6dcc70cad407e9469e
| 1,867
|
cpp
|
C++
|
modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.cpp
|
Oskg/pp_2021_autumn
|
c05d35f4d4b324cc13e58188b4a0c0174f891976
|
[
"BSD-3-Clause"
] | 1
|
2021-12-09T17:20:25.000Z
|
2021-12-09T17:20:25.000Z
|
modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.cpp
|
Oskg/pp_2021_autumn
|
c05d35f4d4b324cc13e58188b4a0c0174f891976
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.cpp
|
Oskg/pp_2021_autumn
|
c05d35f4d4b324cc13e58188b4a0c0174f891976
|
[
"BSD-3-Clause"
] | 3
|
2022-02-23T14:20:50.000Z
|
2022-03-30T09:00:02.000Z
|
// Copyright 2021 Vitulin Ivan 381908-1
#include <mpi.h>
#include <vector>
#include <random>
#include <algorithm>
#include "../../../modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.h"
std::vector<int> getRandomVectorElements(int vector_size, int k) {
std::random_device dev;
std::mt19937 gen(dev());
std::vector<int> vect(vector_size);
for (int i = 0; i < vector_size; i++) { vect[i] = gen() % k; }
return vect;
}
int getSumOfVectorElementsSequentially(std::vector<int> vect) {
const int vector_size = vect.size();
int sum_vect_elements = 0;
for (int i = 0; i < vector_size; i++) {
sum_vect_elements += vect[i];
}
return sum_vect_elements;
}
int getSumOfVectorElementsParallelly(std::vector<int> global_vector, int count_size_vec) {
int ProcessNum, ProcessRank;
MPI_Comm_size(MPI_COMM_WORLD, &ProcessNum);
MPI_Comm_rank(MPI_COMM_WORLD, &ProcessRank);
int addition = ProcessNum - count_size_vec % ProcessNum;
for (int i = 0; i < addition; i++) {
global_vector.push_back(0);
count_size_vec++;
}
int local_part = count_size_vec / ProcessNum;
std::vector<int> local_vector(local_part);
if (ProcessRank == 0) {
for (int i = 1; i < ProcessNum; i++) {
MPI_Send(&global_vector[0] + i * local_part, local_part, MPI_INT, i, 1, MPI_COMM_WORLD);
}
local_vector = std::vector<int>(global_vector.begin(), global_vector.begin() + local_part);
} else {
MPI_Status status;
MPI_Recv(&local_vector[0], local_part, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
}
int global_sum_elements = 0;
int local_sum_elements = getSumOfVectorElementsSequentially(local_vector);
MPI_Reduce(&local_sum_elements, &global_sum_elements, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
return global_sum_elements;
}
| 35.226415
| 100
| 0.677022
|
Oskg
|
061635a4452d766021fcb322ad836e7e98c9d49d
| 1,942
|
cpp
|
C++
|
src/main.cpp
|
dleliuhin/cservice_template
|
63d47faee1065e3615c47ebfd222b49cbd8b7bd8
|
[
"DOC"
] | null | null | null |
src/main.cpp
|
dleliuhin/cservice_template
|
63d47faee1065e3615c47ebfd222b49cbd8b7bd8
|
[
"DOC"
] | null | null | null |
src/main.cpp
|
dleliuhin/cservice_template
|
63d47faee1065e3615c47ebfd222b49cbd8b7bd8
|
[
"DOC"
] | 1
|
2021-08-06T22:15:04.000Z
|
2021-08-06T22:15:04.000Z
|
/*! \file main.cpp
* \brief Entry app file.
*
* \authors Dmitrii Leliuhin
* \date July 2020
*
* Details.
*
*/
//=======================================================================================
#include "subscribe.h"
#include "config.h"
#include "core.h"
#include "publish.h"
#ifdef GUI
#include "view.h"
#endif
#include "args_parser/arguments.h"
#include "vapplication.h"
#include "vthread.h"
#include <iostream>
//=======================================================================================
/*! \fn int main( int argc, char **argv )
* \brief Entry point.
*
* Execution of the program starts here.
*
* \param[in] argc Number of arguments.
* \param[in] argv List of arguments.
*
* \return App exit status.
*/
int main( int argc, char **argv )
{
// Parse config && create PID
service::arguments sargs( argc, argv,
"cservice_template",
Config::by_default() );
Config config;
{
config.capture( sargs.settings() );
config.logs.setup();
}
//-----------------------------------------------------------------------------------
// Link signals -> slots
Subscribe subscriber( config );
Publish publisher( config );
Core core( config );
subscriber.received.link( &core, &Core::run );
core.processed.link( &publisher, &Publish::send );
//-----------------------------------------------------------------------------------
// GUI in separate thread
#ifdef GUI
vthread thread;
thread.invoke( [&]
{
View viewer( sargs.app_name() );
core.plot_data.link( &viewer, &View::plot );
viewer.run();
} );
#endif
//-----------------------------------------------------------------------------------
vapplication::poll();
return EXIT_SUCCESS;
}
//=======================================================================================
| 22.847059
| 89
| 0.427909
|
dleliuhin
|
1646f6cfdc0e1c95857e9ef9a0754cfe0d94d27a
| 3,206
|
cpp
|
C++
|
src/cpp/utils/StringMatching.cpp
|
DimaRU/Fast-DDS
|
4874d11575f396f7787c0f93254a989e7f523e68
|
[
"Apache-2.0"
] | 548
|
2020-06-02T11:59:31.000Z
|
2022-03-30T00:59:33.000Z
|
src/cpp/utils/StringMatching.cpp
|
DimaRU/Fast-DDS
|
4874d11575f396f7787c0f93254a989e7f523e68
|
[
"Apache-2.0"
] | 1,068
|
2020-06-01T12:36:33.000Z
|
2022-03-31T09:57:34.000Z
|
src/cpp/utils/StringMatching.cpp
|
DimaRU/Fast-DDS
|
4874d11575f396f7787c0f93254a989e7f523e68
|
[
"Apache-2.0"
] | 230
|
2020-06-04T02:46:23.000Z
|
2022-03-30T01:35:58.000Z
|
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file StringMatching.cpp
*
*/
#include <fastrtps/utils/StringMatching.h>
#include <limits.h>
#include <errno.h>
#if defined(__cplusplus_winrt)
#include <algorithm>
#include <regex>
#elif defined(_WIN32)
#include "Shlwapi.h"
#else
#include <fnmatch.h>
#endif // if defined(__cplusplus_winrt)
namespace eprosima {
namespace fastrtps {
namespace rtps {
StringMatching::StringMatching()
{
// TODO Auto-generated constructor stub
}
StringMatching::~StringMatching()
{
// TODO Auto-generated destructor stub
}
#if defined(__cplusplus_winrt)
void replace_all(
std::string& subject,
const std::string& search,
const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
bool StringMatching::matchPattern(
const char* pattern,
const char* str)
{
std::string path(pattern);
std::string spec(str);
replace_all(pattern, "*", ".*");
replace_all(pattern, "?", ".");
std::regex path_regex(path);
std::smatch spec_match;
if (std::regex_match(spec, spec_match, path_regex))
{
return true;
}
return false;
}
bool StringMatching::matchString(
const char* str1,
const char* str2)
{
if (StringMatching::matchPattern(str1, str2))
{
return true;
}
if (StringMatching::matchPattern(str2, str1))
{
return true;
}
return false;
}
#elif defined(_WIN32)
bool StringMatching::matchPattern(
const char* pattern,
const char* str)
{
if (PathMatchSpec(str, pattern))
{
return true;
}
return false;
}
bool StringMatching::matchString(
const char* str1,
const char* str2)
{
if (PathMatchSpec(str1, str2))
{
return true;
}
if (PathMatchSpec(str2, str1))
{
return true;
}
return false;
}
#else
bool StringMatching::matchPattern(
const char* pattern,
const char* str)
{
if (fnmatch(pattern, str, FNM_NOESCAPE) == 0)
{
return true;
}
return false;
}
bool StringMatching::matchString(
const char* str1,
const char* str2)
{
if (fnmatch(str1, str2, FNM_NOESCAPE) == 0)
{
return true;
}
if (fnmatch(str2, str1, FNM_NOESCAPE) == 0)
{
return true;
}
return false;
}
#endif // if defined(__cplusplus_winrt)
} // namespace rtps
} /* namespace rtps */
} /* namespace eprosima */
| 20.291139
| 75
| 0.635059
|
DimaRU
|
16485af28f3bbcfb93e31d8ef700c6925714eaa4
| 4,169
|
cpp
|
C++
|
TEST_TOOL/project/Hermes/Novatel_Log_Handler/controllwidget.cpp
|
EIDOSDATA/ARGOS_QT_Series
|
f451312249607b03ed4d6848ec8bc068f245718f
|
[
"Unlicense"
] | null | null | null |
TEST_TOOL/project/Hermes/Novatel_Log_Handler/controllwidget.cpp
|
EIDOSDATA/ARGOS_QT_Series
|
f451312249607b03ed4d6848ec8bc068f245718f
|
[
"Unlicense"
] | null | null | null |
TEST_TOOL/project/Hermes/Novatel_Log_Handler/controllwidget.cpp
|
EIDOSDATA/ARGOS_QT_Series
|
f451312249607b03ed4d6848ec8bc068f245718f
|
[
"Unlicense"
] | null | null | null |
#include "controllwidget.h"
#include "ui_controllwidget.h"
#include <QFileDialog>
#include <QDropEvent>
#include <QMimeData>
#include <sstream>
std::vector<std::string> tokenize(const std::string& data, const char delimiter = ' ')
{
std::vector<std::string> result;
std::string token;
std::stringstream ss(data);
while (getline(ss, token, delimiter)) {
result.push_back(token);
}
return result;
}
ControllWidget::ControllWidget(QWidget *parent) :
QDockWidget(parent),
ui(new Ui::ControllWidget)
{
ui->setupUi(this);
}
ControllWidget::~ControllWidget()
{
delete ui;
}
void ControllWidget::setCountTable(MESSAGE_ID id, int count)
{
recvSetCountTable(id, count);
}
QString ControllWidget::getColumnColor(MESSAGE_ID id)
{
switch (id)
{
case MESSAGE_ID::BESTPOS:
return ui->cb_bestpos->currentText();
break;
case MESSAGE_ID::MARKPOS:
return ui->cb_markpos->currentText();
break;
case MESSAGE_ID::MARK2POS:
return ui->cb_mark2pos->currentText();
break;
case MESSAGE_ID::MARK3POS:
return ui->cb_mark3pos->currentText();
break;
case MESSAGE_ID::MARK4POS:
return ui->cb_mark4pos->currentText();
break;
case MESSAGE_ID::MARK1PVA:
return ui->cb_mark1pva->currentText();
break;
case MESSAGE_ID::MARK2PVA:
return ui->cb_mark2pva->currentText();
break;
case MESSAGE_ID::MARK3PVA:
return ui->cb_mark3pva->currentText();
break;
case MESSAGE_ID::MARK4PVA:
return ui->cb_mark4pva->currentText();
break;
default:
return "";
}
}
std::vector<bool> ControllWidget::getShowingList()
{
std::vector<bool> temp;
temp.push_back(ui->checkBox->isChecked());
temp.push_back(ui->checkBox_2->isChecked());
temp.push_back(ui->checkBox_3->isChecked());
temp.push_back(ui->checkBox_4->isChecked());
temp.push_back(ui->checkBox_5->isChecked());
temp.push_back(ui->checkBox_6->isChecked());
temp.push_back(ui->checkBox_7->isChecked());
temp.push_back(ui->checkBox_8->isChecked());
temp.push_back(ui->checkBox_9->isChecked());
return temp;
}
void ControllWidget::on_pb_open_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Select pwrpak7 log File"),"/home/",tr("log file (*.*)"));
if(fileName != NULL)
{
ui->lb_filepath->setText(fileName);
std::vector<std::string> tempString = tokenize(fileName.toStdString(), '/');
ui->le_label->setText(QString::fromStdString(tempString.back()));
emit sendFilePath(ui->lb_filepath->text());
}
}
void ControllWidget::recvSetCountTable(MESSAGE_ID id, int count)
{
QLineEdit *lineEdit = NULL;
switch (id)
{
case MESSAGE_ID::BESTPOS:
lineEdit = ui->le_count_bestpos;
break;
case MESSAGE_ID::MARKPOS:
lineEdit = ui->le_count_markpos;
break;
case MESSAGE_ID::MARK2POS:
lineEdit = ui->le_count_mark2pos;
break;
case MESSAGE_ID::MARK3POS:
lineEdit = ui->le_count_mark3pos;
break;
case MESSAGE_ID::MARK4POS:
lineEdit = ui->le_count_mark4pos;
break;
case MESSAGE_ID::MARK1PVA:
lineEdit = ui->le_count_mark1pva;
break;
case MESSAGE_ID::MARK2PVA:
lineEdit = ui->le_count_mark2pva;
break;
case MESSAGE_ID::MARK3PVA:
lineEdit = ui->le_count_mark3pva;
break;
case MESSAGE_ID::MARK4PVA:
lineEdit = ui->le_count_mark4pva;
break;
default:
return;
}
if(lineEdit != NULL)
lineEdit->setText(QString::number(count));
}
void ControllWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
#include <iostream>
void ControllWidget::dropEvent(QDropEvent *event)
{
for(int i = 0; i < event->mimeData()->urls().size(); i++)
{
std::cout << event->mimeData()->urls().at(i).toLocalFile().toStdString() << std::endl;
}
ui->lb_filepath->setText(event->mimeData()->urls().at(0).toLocalFile());
std::vector<std::string> tempString = tokenize(event->mimeData()->urls().at(0).toLocalFile().toStdString(), '/');
ui->le_label->setText(QString::fromStdString(tempString.back()));
emit sendFilePath(ui->lb_filepath->text());
}
void ControllWidget::on_pb_export_clicked()
{
emit sendExport();
}
void ControllWidget::on_pb_upload_clicked()
{
emit sendUpload(ui->le_date->text(), ui->le_maker->text(), ui->le_label->text(), ui->cb_db->currentText());
}
| 23.6875
| 115
| 0.716479
|
EIDOSDATA
|
16501f43eed203126863529622aa43d9f9a295cf
| 26,971
|
cpp
|
C++
|
src/compiler/EncodeDecode.cpp
|
yudanli/fast_ber
|
d3e790f86ff91df8b6d6a0f308803606f59452af
|
[
"BSL-1.0"
] | 74
|
2019-02-07T03:24:10.000Z
|
2022-03-22T04:40:44.000Z
|
src/compiler/EncodeDecode.cpp
|
yudanli/fast_ber
|
d3e790f86ff91df8b6d6a0f308803606f59452af
|
[
"BSL-1.0"
] | 32
|
2019-06-02T10:13:13.000Z
|
2021-12-09T08:56:08.000Z
|
src/compiler/EncodeDecode.cpp
|
yudanli/fast_ber
|
d3e790f86ff91df8b6d6a0f308803606f59452af
|
[
"BSL-1.0"
] | 11
|
2019-05-26T18:06:00.000Z
|
2021-11-21T16:08:07.000Z
|
#include "fast_ber/compiler/EncodeDecode.hpp"
#include "fast_ber/compiler/CppGeneration.hpp"
#include "fast_ber/compiler/Identifier.hpp"
#include "fast_ber/compiler/ResolveType.hpp"
#include "fast_ber/compiler/Visit.hpp"
#include "absl/strings/string_view.h"
#include <iostream>
#include <string>
#include <vector>
std::string make_component_function(const std::string& function, const NamedType& component, const Module& module,
const Asn1Tree& tree)
{
if (is_generated(resolve_type(tree, module.module_reference, component).type))
{
auto id = identifier(component.type, module, tree);
if (!id.is_default_tagged)
return function + "_with_id<" + id.name() + ">";
}
return function;
}
template <typename CollectionType>
CodeBlock create_collection_encode_functions(const std::string& name, const CollectionType& collection,
const Module& module, const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("inline EncodeResult " + name + "::encode_with_id(absl::Span<uint8_t> output) const noexcept");
{
auto scope = CodeScope(block);
block.add_line("constexpr std::size_t header_length_guess = fast_ber::encoded_length(0, Identifier_{});");
block.add_line("if (output.length() < header_length_guess)");
{
auto scope2 = CodeScope(block);
block.add_line("return EncodeResult{false, 0};");
}
if (collection.components.size() != 0)
{
block.add_line("EncodeResult res;");
block.add_line("auto content = output;");
block.add_line("content.remove_prefix(header_length_guess);");
}
block.add_line("std::size_t content_length = 0;");
for (const ComponentType& component : collection.components)
{
block.add_line("res = " + component.named_type.name + "." +
make_component_function("encode", component.named_type, module, tree) + "(content);");
block.add_line("if (!res.success)");
{
auto scope2 = CodeScope(block);
block.add_line("return res;");
}
block.add_line("content.remove_prefix(res.length);");
block.add_line("content_length += res.length;");
}
block.add_line("return wrap_with_ber_header(output, content_length, Identifier_{}, header_length_guess);");
}
block.add_line();
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("std::size_t " + name + "::encoded_length_with_id() const noexcept");
{
auto scope = CodeScope(block);
block.add_line("std::size_t content_length = 0;");
block.add_line();
for (const ComponentType& component : collection.components)
{
block.add_line("content_length += this->" + component.named_type.name + "." +
make_component_function("encoded_length", component.named_type, module, tree) + "();");
}
block.add_line();
block.add_line("return fast_ber::encoded_length(content_length, Identifier_{});");
}
block.add_line();
return block;
}
CodeBlock create_choice_encode_functions(const std::string& name, const ChoiceType& choice, const Module& module,
const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("inline EncodeResult " + name + "::encode_with_id(absl::Span<uint8_t> output) const noexcept");
{
auto scope1 = CodeScope(block);
block.add_line("EncodeResult res;");
block.add_line("auto content = output;");
// If an alternative (non ChoiceId) identifier is provided choice type should be wrapped,
// else use identifier of selected choice
block.add_line("std::size_t header_length_guess = 0;");
block.add_line("if (!IsChoiceId<Identifier_>::value)");
{
auto scope2 = CodeScope(block);
block.add_line(" header_length_guess = fast_ber::encoded_length(0,Identifier_{});");
block.add_line("if (output.length() < header_length_guess)");
{
auto scope3 = CodeScope(block);
block.add_line("return EncodeResult{false, 0};");
}
block.add_line("content.remove_prefix(header_length_guess);");
}
block.add_line("switch (this->index())");
{
auto scope2 = CodeScope(block);
for (std::size_t i = 0; i < choice.choices.size(); i++)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line(" res = fast_ber::get<" + std::to_string(i) + ">(*this)." +
make_component_function("encode", choice.choices[i], module, tree) + "(content);");
block.add_line(" break;");
}
block.add_line("default: assert(0);");
}
block.add_line("if (!IsChoiceId<Identifier_>::value)");
{
auto scope2 = CodeScope(block);
block.add_line("if (!res.success)");
{
auto scope3 = CodeScope(block);
block.add_line("return res;");
}
block.add_line("const std::size_t content_length = res.length;");
block.add_line("res = wrap_with_ber_header(output, content_length, Identifier_{}, header_length_guess);");
block.add_line("return res;");
}
block.add_line("else");
{
auto scope2 = CodeScope(block);
block.add_line("return res;");
}
}
block.add_line();
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("inline std::size_t " + name + "::encoded_length_with_id() const noexcept");
{
auto scope1 = CodeScope(block);
block.add_line("std::size_t content_length = 0;");
block.add_line("switch (this->index())");
{
auto scope2 = CodeScope(block);
for (std::size_t i = 0; i < choice.choices.size(); i++)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line(" content_length = fast_ber::get<" + std::to_string(i) + ">(*this)." +
make_component_function("encoded_length", choice.choices[i], module, tree) + "();");
block.add_line(" break;");
}
block.add_line("default: assert(0);");
}
block.add_line("if (!IsChoiceId<Identifier_>::value)");
{
auto scope2 = CodeScope(block);
block.add_line("return fast_ber::encoded_length(content_length, Identifier_{});");
}
block.add_line("else");
{
auto scope2 = CodeScope(block);
block.add_line("return content_length;");
}
}
block.add_line();
return block;
}
template <typename CollectionType>
CodeBlock create_collection_decode_functions(const std::string& name, const CollectionType& collection,
const Module& module, const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("DecodeResult " + name + "::decode_with_id(BerView input) noexcept");
{
auto scope = CodeScope(block);
block.add_line("if (!input.is_valid())");
{
auto scope2 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Invalid packet when decoding collection [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line("if (!has_correct_header(input, Identifier_{}, Construction::constructed))");
{
auto scope2 = CodeScope(block);
block.add_line(
R"(FAST_BER_ERROR("Invalid identifier [", input.identifier(), "] when decoding collection [)" + name +
R"(]");)");
block.add_line("return DecodeResult{false};");
}
if (collection.components.size() > 0)
{
block.add_line("DecodeResult res;");
block.add_line("auto iterator = (Identifier_::depth() == 1) ? input.begin()");
block.add_line(" : input.begin()->begin();");
if (std::is_same<CollectionType, SetType>::value)
{
block.add_line("auto const end = (Identifier_::depth() == 1) ? input.end()");
block.add_line(" : input.begin()->end();");
block.add_line();
block.add_line("std::array<std::size_t, " + std::to_string(collection.components.size()) +
"> decode_counts = {};");
block.add_line("while (iterator != end)");
{
auto scope2 = CodeScope(block);
if (module.tagging_default == TaggingMode::automatic)
{
block.add_line("if (iterator->class_() == " + to_string(Class::context_specific) + ")");
auto scope3 = CodeScope(block);
{
block.add_line("switch (iterator->tag())");
auto scope4 = CodeScope(block);
std::size_t i = 0;
for (const ComponentType& component : collection.components)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type, module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope5 = CodeScope(block);
{
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" +
component.named_type.name + R"(] of collection [)" + name +
R"(]");)");
block.add_line("return res;");
}
}
block.add_line("++decode_counts[" + std::to_string(i) + "];");
block.add_line("++iterator;");
block.add_line("continue;");
i++;
}
}
}
else
{
for (Class class_ : {
Class::universal,
Class::application,
Class::context_specific,
Class::private_,
})
{
if (std::any_of(collection.components.begin(), collection.components.end(),
[&](const ComponentType& component) {
const std::vector<Identifier>& outer_ids =
outer_identifiers(component.named_type.type, module, tree);
return std::any_of(
outer_ids.begin(), outer_ids.end(),
[class_](const Identifier& id) { return id.class_ == class_; });
}))
{
block.add_line("if (iterator->class_() == " + to_string(class_) + ")");
auto scope3 = CodeScope(block);
{
block.add_line("switch (iterator->tag())");
auto scope4 = CodeScope(block);
std::size_t i = 0;
for (const ComponentType& component : collection.components)
{
const std::vector<Identifier>& ids =
outer_identifiers(component.named_type.type, module, tree);
for (const Identifier& id : ids)
{
if (id.class_ == class_)
{
block.add_line("case " + std::to_string(id.tag_number) + ":");
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type,
module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope5 = CodeScope(block);
{
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" +
component.named_type.name +
R"(] of collection [)" + name + R"(]");)");
block.add_line("return res;");
}
}
block.add_line("++decode_counts[" + std::to_string(i) + "];");
block.add_line("++iterator;");
block.add_line("continue;");
}
}
i++;
}
}
}
}
}
if (!collection.allow_extensions)
{
block.add_line(R"(FAST_BER_ERROR("Invalid ID when decoding set [)" + name +
R"(] [", iterator->identifier(), "]");)");
block.add_line("return fast_ber::DecodeResult{false};");
}
else
{
block.add_line("++iterator;");
}
}
std::size_t i = 0;
for (const ComponentType& component : collection.components)
{
block.add_line("if (decode_counts[" + std::to_string(i) + "] == 0)");
{
auto scope3 = CodeScope(block);
if (component.is_optional)
{
block.add_line("this->" + component.named_type.name + " = fast_ber::empty;");
}
else if (component.default_value)
{
block.add_line("this->" + component.named_type.name + ".set_to_default();");
}
else
{
block.add_line(R"(FAST_BER_ERROR("Missing non-optional member [)" +
component.named_type.name + R"(] of set [)" + name + R"(]");)");
block.add_line("return fast_ber::DecodeResult{false};");
}
}
block.add_line("if (decode_counts[" + std::to_string(i) + "] > 1)");
{
auto scope3 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Member [)" + component.named_type.name +
R"(] present multiple times in set [)" + name + R"(]");)");
block.add_line("return fast_ber::DecodeResult{false};");
}
i++;
}
}
else
{
for (const ComponentType& component : collection.components)
{
if (component.is_optional || component.default_value)
{
std::string id_check = "if (iterator->is_valid() && (false ";
for (const Identifier& id : outer_identifiers(component.named_type.type, module, tree))
{
id_check += " || " + id.name() + "::check_id_match(iterator->class_(), iterator->tag())";
}
id_check += "))";
block.add_line(id_check);
{
auto scope2 = CodeScope(block);
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type, module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope3 = CodeScope(block);
{
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" +
component.named_type.name + R"(] of collection [)" + name +
R"(]");)");
block.add_line("return res;");
}
}
block.add_line("++iterator;");
}
block.add_line("else");
{
auto scope3 = CodeScope(block);
if (component.is_optional)
{
block.add_line("this->" + component.named_type.name + " = fast_ber::empty;");
}
else
{
block.add_line("this->" + component.named_type.name + ".set_to_default();");
}
}
}
else
{
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type, module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope2 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" + component.named_type.name +
R"(] of collection [)" + name + R"(]");)");
block.add_line("return res;");
}
block.add_line("++iterator;");
}
}
}
}
block.add_line("return DecodeResult{true};");
}
return block;
}
CodeBlock create_choice_decode_functions(const std::string& name, const ChoiceType& choice, const Module& module,
const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier"}));
block.add_line("inline DecodeResult " + name + "::decode_with_id(BerView input) noexcept");
{
auto scope1 = CodeScope(block);
block.add_line("BerView content(input);");
block.add_line("if (!IsChoiceId<Identifier>::value)");
{
auto scope2 = CodeScope(block);
block.add_line("if (!input.is_valid())");
{
auto scope3 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Invalid packet when decoding choice [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line("if (!has_correct_header(input, Identifier{}, Construction::constructed))");
{
auto scope3 = CodeScope(block);
block.add_line(
R"(FAST_BER_ERROR("Invalid header when decoding choice type [", input.identifier(), "] in choice [)" +
name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line(
"BerViewIterator child = (Identifier::depth() == 1) ? input.begin() : input.begin()->begin();");
block.add_line("if (!child->is_valid())");
{
auto scope3 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Invalid child packet when decoding choice [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line("content = *child;");
}
if (module.tagging_default == TaggingMode::automatic)
{
block.add_line("switch (content.tag())");
{
auto scope2 = CodeScope(block);
for (std::size_t i = 0; i < choice.choices.size(); i++)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line(" return this->template emplace<" + std::to_string(i) + ">()." +
make_component_function("decode", choice.choices[i], module, tree) + "(content);");
}
}
}
else
{
for (Class class_ : {
Class::universal,
Class::application,
Class::context_specific,
Class::private_,
})
{
const std::vector<Identifier>& outer_ids = outer_identifiers(choice, module, tree);
if (std::any_of(outer_ids.begin(), outer_ids.end(),
[class_](const Identifier& id) { return id.class_ == class_; }))
{
block.add_line("switch (content.tag())");
auto scope2 = CodeScope(block);
std::size_t i = 0;
for (const NamedType& named_type : choice.choices)
{
const std::vector<Identifier>& ids = outer_identifiers(named_type.type, module, tree);
for (const Identifier& id : ids)
{
if (id.class_ == class_)
{
block.add_line("case " + std::to_string(id.tag_number) + ":");
block.add_line(" return this->template emplace<" + std::to_string(i) + ">()." +
make_component_function("decode", choice.choices[i], module, tree) +
"(content);");
}
}
i++;
}
}
}
}
block.add_line(R"(FAST_BER_ERROR("Unknown tag [", content.identifier(), "] in choice [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line();
return block;
}
CodeBlock create_encode_functions_impl(const Asn1Tree& tree, const Module& module, const Type& type,
const std::string& name)
{
if (is_sequence(type))
{
const SequenceType& sequence = absl::get<SequenceType>(absl::get<BuiltinType>(type));
return create_collection_encode_functions(name, sequence, module, tree);
}
else if (is_set(type))
{
const SetType& set = absl::get<SetType>(absl::get<BuiltinType>(type));
return create_collection_encode_functions(name, set, module, tree);
}
else if (is_choice(type))
{
const ChoiceType& choice = absl::get<ChoiceType>(absl::get<BuiltinType>(type));
return create_choice_encode_functions(name, choice, module, tree);
}
return {};
}
CodeBlock create_decode_functions_impl(const Asn1Tree& tree, const Module& module, const Type& type,
const std::string& name)
{
if (is_sequence(type))
{
const SequenceType& sequence = absl::get<SequenceType>(absl::get<BuiltinType>(type));
return create_collection_decode_functions(name, sequence, module, tree);
}
else if (is_set(type))
{
const SetType& set = absl::get<SetType>(absl::get<BuiltinType>(type));
return create_collection_decode_functions(name, set, module, tree);
}
else if (is_choice(type))
{
const ChoiceType& choice = absl::get<ChoiceType>(absl::get<BuiltinType>(type));
return create_choice_decode_functions(name, choice, module, tree);
}
return {};
}
std::string create_encode_functions(const Assignment& assignment, const Module& module, const Asn1Tree& tree)
{
if (absl::holds_alternative<TypeAssignment>(assignment.specific))
{
return visit_all_types(tree, module, assignment, create_encode_functions_impl).to_string();
}
return "";
}
std::string create_decode_functions(const Assignment& assignment, const Module& module, const Asn1Tree& tree)
{
if (absl::holds_alternative<TypeAssignment>(assignment.specific))
{
return visit_all_types(tree, module, assignment, create_decode_functions_impl).to_string();
}
return "";
}
| 46.262436
| 122
| 0.45497
|
yudanli
|
16517c730c5ab6812c064ae5c6a1bfbda0aafbaf
| 2,906
|
cpp
|
C++
|
Lab 8/src/utils/source/outUtils.cpp
|
chemizt/parallel-programming-labs
|
b8ba6e41bc03cf8c9e9bff1e353f8c7af9a45c20
|
[
"WTFPL"
] | 1
|
2019-11-25T10:19:46.000Z
|
2019-11-25T10:19:46.000Z
|
Lab 8/src/utils/source/outUtils.cpp
|
chemizt/parallel-programming-labs
|
b8ba6e41bc03cf8c9e9bff1e353f8c7af9a45c20
|
[
"WTFPL"
] | 3
|
2019-12-01T22:27:43.000Z
|
2019-12-01T22:38:54.000Z
|
Lab 8/src/utils/source/outUtils.cpp
|
chemizt/parallel-programming-labs
|
b8ba6e41bc03cf8c9e9bff1e353f8c7af9a45c20
|
[
"WTFPL"
] | null | null | null |
#include "outUtils.hpp"
struct Comma final : std::numpunct<char> // inspired by (copy-typed from) https://stackoverflow.com/a/42331536
{
char do_decimal_point() const override { return ','; }
};
void outputIntMatrix(intMatrix matrix)
{
uInt maxNumLength = getMaxNumberLengthInIntMatrix(matrix);
for (uInt i = 0; i < matrix.size(); i++)
{
for (uInt j = 0; j < matrix.at(i).size(); j++)
{
cout << matrix.at(i).at(j) << getSpaces(maxNumLength * 2 - getIntNumberLength(matrix.at(i).at(j)));
}
cout << "\n";
}
cout << "\n";
}
void outputIntVector(vector<int> vector)
{
for (uInt i = 0; i < vector.size(); i++)
{
cout << vector.at(i) << " ";
}
cout << "\n\n";
}
void outputDoubleMatrix(doubleMatrix matrix)
{
uInt maxNumLength = getMaxNumberLengthInDoubleMatrix(matrix);
cout << fixed << setprecision(2);
for (uInt i = 0; i < matrix.size(); i++)
{
for (uInt j = 0; j < matrix.at(i).size(); j++)
{
cout << matrix.at(i).at(j) << getSpaces(maxNumLength * 2 - getDoubleNumberLength(matrix.at(i).at(j)));
}
cout << "\n";
}
cout << "\n";
}
void outputDoubleVector(vector<double> vector)
{
cout << fixed << setprecision(2);
for (uInt i = 0; i < vector.size(); i++)
{
cout << vector.at(i) << " ";
}
cout << "\n\n";
}
void logOutput(string message)
{
ofstream resultsFile;
string timeStamp = getCurrentTimeStampAsString();
resultsFile.open(LOG_FILE_NAME, std::ios_base::app);
cout << timeStamp << ": " << message << endl;
resultsFile << timeStamp << ": " << message << endl;
resultsFile.close();
}
template <typename type>
void outputMatrixToFile(vector<vector<type>> matrix, string fileName)
{
ofstream resultsFile;
resultsFile.open(fileName, std::ios_base::app);
resultsFile.imbue(locale(locale::classic(), new Comma));
for (uInt i = 0; i < matrix.size(); i++)
{
for (uInt j = 0; j < matrix.at(i).size(); j++)
{
if (j < matrix.at(i).size() - 1)
{
resultsFile << matrix.at(i).at(j) << ";";
}
else
{
resultsFile << matrix.at(i).at(j) << "\n";
}
}
}
resultsFile << "\n\n";
resultsFile.close();
}
template <typename type>
void outputVectorToFile(vector<type> vector, string fileName)
{
ofstream resultsFile;
resultsFile.open(fileName, std::ios_base::app);
resultsFile.imbue(locale(locale::classic(), new Comma));
for (uInt i = 0; i < vector.size(); i++)
{
if (i < vector.size() - 1)
{
resultsFile << vector.at(i) << ";";
}
else
{
resultsFile << vector.at(i) << "\n";
}
}
resultsFile << "\n\n";
resultsFile.close();
}
| 24.216667
| 114
| 0.538885
|
chemizt
|
165191a2f7f5f5f718fe2c045b55e1df7b870e19
| 20,173
|
cpp
|
C++
|
sp/src/game/server/mod/npc_base_custom.cpp
|
jarnar85/source-sdk-2013
|
8c279299883421fd78e7691545522ea863e0b646
|
[
"Unlicense"
] | null | null | null |
sp/src/game/server/mod/npc_base_custom.cpp
|
jarnar85/source-sdk-2013
|
8c279299883421fd78e7691545522ea863e0b646
|
[
"Unlicense"
] | 8
|
2019-09-07T10:19:52.000Z
|
2020-03-31T19:44:45.000Z
|
sp/src/game/server/mod/npc_base_custom.cpp
|
jarnar85/source-sdk-2013
|
8c279299883421fd78e7691545522ea863e0b646
|
[
"Unlicense"
] | null | null | null |
//=//=============================================================================//
//
// Purpose: A base class from which to extend new custom NPCs.
// This class may seem redundant with CAI_BaseNPC and a lot of Valve's NPC classes.
// However, the redundancy is necessary for compatibility with a variety of mods;
// I want all new NPC content to be isolated from existing classes.
//
// Author: 1upD
//
//=============================================================================//
#include "cbase.h"
#include "npc_base_custom.h"
#include "ai_hull.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "engine/IEngineSound.h"
#include "basehlcombatweapon_shared.h"
#include "ai_squadslot.h"
#include "ai_squad.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//---------------------------------------------------------
// Constants
//---------------------------------------------------------
// TODO: Replace these with fields so that other NPCs can override them
const float MIN_TIME_NEXT_SOUND = 0.5f;
const float MAX_TIME_NEXT_SOUND = 1.0f;
const float MIN_TIME_NEXT_FOUNDENEMY_SOUND = 2.0f;
const float MAX_TIME_NEXT_FOUNDENEMY_SOUND = 5.0f;
LINK_ENTITY_TO_CLASS(npc_base_custom, CNPC_BaseCustomNPC);
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC(CNPC_BaseCustomNPC)
DEFINE_KEYFIELD(m_iszWeaponModelName, FIELD_STRING, "WeaponModel"),
DEFINE_KEYFIELD(m_iHealth, FIELD_INTEGER, "Health"),
DEFINE_KEYFIELD(m_iszFearSound, FIELD_SOUNDNAME, "FearSound"),
DEFINE_KEYFIELD(m_iszDeathSound, FIELD_SOUNDNAME, "DeathSound"),
DEFINE_KEYFIELD(m_iszIdleSound, FIELD_SOUNDNAME, "IdleSound"),
DEFINE_KEYFIELD(m_iszPainSound, FIELD_SOUNDNAME, "PainSound"),
DEFINE_KEYFIELD(m_iszAlertSound, FIELD_SOUNDNAME, "AlertSound"),
DEFINE_KEYFIELD(m_iszLostEnemySound, FIELD_SOUNDNAME, "LostEnemySound"),
DEFINE_KEYFIELD(m_iszFoundEnemySound, FIELD_SOUNDNAME, "FoundEnemySound"),
DEFINE_KEYFIELD(m_bUseBothSquadSlots, FIELD_BOOLEAN, "UseBothSquadSlots"),
DEFINE_KEYFIELD(m_bCannotOpenDoors, FIELD_BOOLEAN, "CannotOpenDoors"),
DEFINE_KEYFIELD(m_bCanPickupWeapons, FIELD_BOOLEAN, "CanPickupWeapons"),
DEFINE_FIELD(m_iNumSquadmates, FIELD_INTEGER),
DEFINE_FIELD(m_bWanderToggle, FIELD_BOOLEAN),
DEFINE_FIELD(m_flNextSoundTime, FIELD_TIME),
DEFINE_FIELD(m_flNextFoundEnemySoundTime, FIELD_TIME),
DEFINE_FIELD(m_flSpeedModifier, FIELD_TIME),
DEFINE_INPUTFUNC(FIELD_FLOAT, "SetSpeedModifier", InputSetSpeedModifier),
DEFINE_INPUTFUNC(FIELD_VOID, "EnableOpenDoors", InputEnableOpenDoors),
DEFINE_INPUTFUNC(FIELD_VOID, "DisableOpenDoors", InputDisableOpenDoors),
DEFINE_INPUTFUNC(FIELD_VOID, "EnablePickupWeapons", InputEnablePickupWeapons),
DEFINE_INPUTFUNC(FIELD_VOID, "DisablePickupWeapons", InputDisablePickupWeapons)
END_DATADESC()
AI_BEGIN_CUSTOM_NPC(npc_base_custom, CNPC_BaseCustomNPC)
//=========================================================
// > Melee_Attack_NoInterrupt
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MELEE_ATTACK_NOINTERRUPT,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_ANNOUNCE_ATTACK 1" // 1 = primary attack
" TASK_MELEE_ATTACK1 0"
""
" Interrupts"
" COND_ENEMY_DEAD"
" COND_ENEMY_OCCLUDED"
);
//=========================================================
// SCHED_HIDE
//=========================================================
DEFINE_SCHEDULE
(
SCHED_HIDE,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBAT_FACE"
" TASK_STOP_MOVING 0"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_HEAR_DANGER"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
);
AI_END_CUSTOM_NPC()
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::Precache( void )
{
// If no model name is supplied, use the default citizen model
if (!GetModelName())
{
SetModelName(MAKE_STRING("models/monster/subject.mdl")); // TODO replace this with citizen
}
if (&m_iszWeaponModelName && m_iszWeaponModelName != MAKE_STRING("")) {
PrecacheModel(STRING(m_iszWeaponModelName));
}
else {
PrecacheModel("models/props_canal/mattpipe.mdl"); // Default weapon model
}
PrecacheModel(STRING(GetModelName()));
PrecacheNPCSoundScript(&m_iszFearSound, MAKE_STRING("NPC_BaseCustomr.Fear"));
PrecacheNPCSoundScript(&m_iszIdleSound, MAKE_STRING("NPC_BaseCustom.Idle"));
PrecacheNPCSoundScript(&m_iszAlertSound, MAKE_STRING("NPC_BaseCustom.Alert"));
PrecacheNPCSoundScript(&m_iszPainSound, MAKE_STRING("NPC_BaseCustom.Pain"));
PrecacheNPCSoundScript(&m_iszLostEnemySound, MAKE_STRING("NPC_BaseCustom.LostEnemy"));
PrecacheNPCSoundScript(&m_iszFoundEnemySound, MAKE_STRING("NPC_BaseCustom.FoundEnemy"));
PrecacheNPCSoundScript(&m_iszDeathSound, MAKE_STRING("NPC_BaseCustom.Death"));
m_bWanderToggle = false;
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::Spawn( void )
{
Precache();
SetModel(STRING(GetModelName()));
SetHullType(HULL_HUMAN);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
SetMoveType( MOVETYPE_STEP );
SetBloodColor( BLOOD_COLOR_RED );
// If the health has not been set through Hammer, use a default health value of 75
if (m_iHealth < 1)
{
m_iHealth = 75;
}
m_flFieldOfView = 0.5;
m_flNextSoundTime = gpGlobals->curtime;
m_flNextFoundEnemySoundTime = gpGlobals->curtime;
m_NPCState = NPC_STATE_NONE;
m_flSpeedModifier = 1.0f;
CapabilitiesClear();
if (!HasSpawnFlags(SF_NPC_START_EFFICIENT))
{
CapabilitiesAdd(bits_CAP_ANIMATEDFACE | bits_CAP_TURN_HEAD); // The default model has no face animations, but a custom model might
CapabilitiesAdd(bits_CAP_SQUAD);
CapabilitiesAdd(bits_CAP_USE_WEAPONS | bits_CAP_AIM_GUN | bits_CAP_MOVE_SHOOT);
CapabilitiesAdd(bits_CAP_WEAPON_MELEE_ATTACK1 || bits_CAP_WEAPON_MELEE_ATTACK2);
CapabilitiesAdd(bits_CAP_DUCK);
CapabilitiesAdd(bits_CAP_USE_SHOT_REGULATOR);
if (!m_bCannotOpenDoors) {
CapabilitiesAdd(bits_CAP_DOORS_GROUP);
}
}
CapabilitiesAdd(bits_CAP_MOVE_GROUND);
SetMoveType(MOVETYPE_STEP);
NPCInit();
}
void CNPC_BaseCustomNPC::Activate()
{
BaseClass::Activate();
FixupWeapon();
}
//-----------------------------------------------------------------------------
// Purpose: If this NPC has some kind of custom weapon behavior,
// set up the weapon after spawn.
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::FixupWeapon()
{
// Do nothing
}
//-----------------------------------------------------------------------------
// Purpose: Choose a schedule after schedule failed
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode)
{
switch (failedSchedule)
{
case SCHED_NEW_WEAPON:
// If failed trying to pick up a weapon, try again in one second. This is because other AI code
// has put this off for 10 seconds under the assumption that the citizen would be able to
// pick up the weapon that they found.
m_flNextWeaponSearchTime = gpGlobals->curtime + 1.0f;
break;
}
return BaseClass::SelectFailSchedule(failedSchedule, failedTask, taskFailCode);
}
//-----------------------------------------------------------------------------
// Purpose: Select a schedule to retrieve better weapons if they are available.
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectScheduleRetrieveItem()
{
if (m_bCanPickupWeapons && HasCondition(COND_BETTER_WEAPON_AVAILABLE))
{
CBaseHLCombatWeapon *pWeapon = dynamic_cast<CBaseHLCombatWeapon *>(Weapon_FindUsable(WEAPON_SEARCH_DELTA));
if (pWeapon)
{
m_flNextWeaponSearchTime = gpGlobals->curtime + 10.0;
// Now lock the weapon for several seconds while we go to pick it up.
pWeapon->Lock(10.0, this);
SetTarget(pWeapon);
return SCHED_NEW_WEAPON;
}
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
// Purpose: Select ideal state.
// Conditions for custom states are defined here.
//-----------------------------------------------------------------------------
NPC_STATE CNPC_BaseCustomNPC::SelectIdealState(void)
{
switch ((int)this->m_NPCState) {
case NPC_STATE_AMBUSH:
return SelectAmbushIdealState();
case NPC_STATE_SURRENDER:
return SelectSurrenderIdealState();
default:
return BaseClass::SelectIdealState();
}
}
NPC_STATE CNPC_BaseCustomNPC::SelectAmbushIdealState()
{
// AMBUSH goes to ALERT upon death of enemy
if (GetEnemy() == NULL)
{
return NPC_STATE_ALERT;
}
// If I am not in a squad, there is no reason to ambush
if (!m_pSquad) {
return NPC_STATE_COMBAT;
}
// If I am the last in a squad, attack!
if (m_pSquad->NumMembers() == 1) {
return NPC_STATE_COMBAT;
}
if (OccupyStrategySlotRange(SQUAD_SLOT_CHASE_1, SQUAD_SLOT_CHASE_2)) {
return NPC_STATE_COMBAT;
}
// The best ideal state is the current ideal state.
return (NPC_STATE)NPC_STATE_AMBUSH;
}
NPC_STATE CNPC_BaseCustomNPC::SelectSurrenderIdealState()
{
return NPC_STATE_ALERT;
}
//-----------------------------------------------------------------------------
// Purpose: Select a schedule to retrieve better weapons if they are available.
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectScheduleWander()
{
m_bWanderToggle = !m_bWanderToggle;
if (m_bWanderToggle) {
return SCHED_IDLE_WANDER;
}
else {
return SCHED_NONE;
}
}
//-----------------------------------------------------------------------------
// Purpose: Select a schedule to execute based on conditions.
// This is the most critical AI method.
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectSchedule()
{
switch ((int)m_NPCState)
{
case NPC_STATE_IDLE:
AssertMsgOnce(GetEnemy() == NULL, "NPC has enemy but is not in combat state?");
return SelectIdleSchedule();
case NPC_STATE_ALERT:
AssertMsgOnce(GetEnemy() == NULL, "NPC has enemy but is not in combat state?");
return SelectAlertSchedule();
case NPC_STATE_COMBAT:
return SelectCombatSchedule();
case NPC_STATE_AMBUSH:
return SelectAmbushSchedule();
case NPC_STATE_SURRENDER:
return SelectSurrenderSchedule();
default:
return BaseClass::SelectSchedule();
}
}
//-----------------------------------------------------------------------------
// Idle schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectIdleSchedule()
{
int nSched = SelectFlinchSchedule();
if (nSched != SCHED_NONE)
return nSched;
if (HasCondition(COND_HEAR_DANGER) ||
HasCondition(COND_HEAR_COMBAT) ||
HasCondition(COND_HEAR_WORLD) ||
HasCondition(COND_HEAR_BULLET_IMPACT) ||
HasCondition(COND_HEAR_PLAYER))
{
// Investigate sound source
return SCHED_ALERT_FACE_BESTSOUND;
}
nSched = SelectScheduleRetrieveItem();
if (nSched != SCHED_NONE)
return nSched;
// no valid route! Wander instead
if (GetNavigator()->GetGoalType() == GOALTYPE_NONE) {
return SCHED_IDLE_STAND;
}
// valid route. Get moving
return SCHED_IDLE_WALK;
}
//-----------------------------------------------------------------------------
// Alert schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectAlertSchedule()
{
// Per default base NPC, check flinch schedule first
int nSched = SelectFlinchSchedule();
if (nSched != SCHED_NONE)
return nSched;
// Scan around for new enemies
if (HasCondition(COND_ENEMY_DEAD) && SelectWeightedSequence(ACT_VICTORY_DANCE) != ACTIVITY_NOT_AVAILABLE)
return SCHED_ALERT_SCAN;
if (HasCondition(COND_HEAR_DANGER) ||
HasCondition(COND_HEAR_PLAYER) ||
HasCondition(COND_HEAR_WORLD) ||
HasCondition(COND_HEAR_BULLET_IMPACT) ||
HasCondition(COND_HEAR_COMBAT))
{
// Investigate sound source
AlertSound();
return SCHED_ALERT_FACE_BESTSOUND;
}
nSched = SelectScheduleRetrieveItem();
if (nSched != SCHED_NONE)
return nSched;
// no valid route! Wander instead
if (GetNavigator()->GetGoalType() == GOALTYPE_NONE) {
return SCHED_ALERT_STAND;
}
// valid route. Get moving
return SCHED_ALERT_WALK;
}
//-----------------------------------------------------------------------------
// Combat schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectCombatSchedule()
{
return BaseClass::SelectSchedule(); // Let Base NPC handle it
}
//-----------------------------------------------------------------------------
// Combat schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectAmbushSchedule()
{
// Check enemy death
if (HasCondition(COND_ENEMY_DEAD))
{
// clear the current (dead) enemy and try to find another.
SetEnemy(NULL);
if (ChooseEnemy())
{
SetState(NPC_STATE_COMBAT);
FoundEnemySound();
ClearCondition(COND_ENEMY_DEAD);
return SelectSchedule();
}
SetState(NPC_STATE_ALERT);
return SelectSchedule();
}
CBaseEntity* pEnemy = GetEnemy();
if (pEnemy && EnemyDistance(pEnemy) < 128)
{
SetState(NPC_STATE_COMBAT);
return SelectSchedule();
}
if (pEnemy == NULL || HasCondition(COND_LOST_ENEMY)) {
SetState(NPC_STATE_ALERT);
return SelectSchedule();
}
// If I am the last in a squad, attack!
if (m_iNumSquadmates > m_pSquad->NumMembers())
SetState(SelectAmbushIdealState());
if (HasCondition(COND_LIGHT_DAMAGE)) {
SetState(NPC_STATE_COMBAT);
}
if (HasCondition(COND_SEE_ENEMY) && HasCondition(COND_ENEMY_FACING_ME) && HasCondition(COND_HAVE_ENEMY_LOS)) {
if(GetState() != NPC_STATE_COMBAT)
SetState(SelectAmbushIdealState());
return SCHED_HIDE;
}
m_iNumSquadmates = m_pSquad->NumMembers();
return SCHED_COMBAT_FACE;
}
int CNPC_BaseCustomNPC::SelectSurrenderSchedule()
{
return BaseClass::SelectSchedule();
}
bool CNPC_BaseCustomNPC::HasRangedWeapon()
{
CBaseCombatWeapon *pWeapon = GetActiveWeapon();
if (pWeapon)
return !(FClassnameIs(pWeapon, "weapon_crowbar") || FClassnameIs(pWeapon, "weapon_stunstick") || FClassnameIs(pWeapon, "weapon_custommelee"));
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Override base class activiites
//-----------------------------------------------------------------------------
Activity CNPC_BaseCustomNPC::NPC_TranslateActivity(Activity activity)
{
switch (activity) {
case ACT_RUN_AIM_SHOTGUN:
return ACT_RUN_AIM_RIFLE;
case ACT_WALK_AIM_SHOTGUN:
return ACT_WALK_AIM_RIFLE;
case ACT_IDLE_ANGRY_SHOTGUN:
return ACT_IDLE_ANGRY_SMG1;
case ACT_RANGE_ATTACK_SHOTGUN_LOW:
return ACT_RANGE_ATTACK_SMG1_LOW;
case ACT_IDLE_MELEE:
case ACT_IDLE_ANGRY_MELEE: // If the NPC has a melee weapon but is in an idle state, don't raise the weapon
if (m_NPCState == NPC_STATE_IDLE)
return ACT_IDLE_SUITCASE;
default:
return BaseClass::NPC_TranslateActivity(activity);
}
}
//-----------------------------------------------------------------------------
// Purpose: Override base class schedules
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::TranslateSchedule(int scheduleType)
{
return BaseClass::TranslateSchedule(scheduleType);
}
//-----------------------------------------------------------------------------
// Purpose: Play sound when an enemy is spotted. This sound has a separate
// timer from other sounds to prevent looping if the NPC gets caught
// in a 'found enemy' condition.
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::FoundEnemySound(void)
{
if (gpGlobals->curtime > m_flNextFoundEnemySoundTime)
{
m_flNextFoundEnemySoundTime = gpGlobals->curtime + random->RandomFloat(MIN_TIME_NEXT_FOUNDENEMY_SOUND, MAX_TIME_NEXT_FOUNDENEMY_SOUND);
PlaySound(m_iszFoundEnemySound, true);
}
}
//-----------------------------------------------------------------------------
// Purpose: Play NPC soundscript
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::PlaySound(string_t soundname, bool required /*= false */)
{
// TODO: Check if silent
if (required || gpGlobals->curtime > m_flNextSoundTime)
{
m_flNextSoundTime = gpGlobals->curtime + random->RandomFloat(MIN_TIME_NEXT_SOUND, MAX_TIME_NEXT_SOUND);
//CPASAttenuationFilter filter2(this, STRING(soundname));
EmitSound(STRING(soundname));
}
}
//-----------------------------------------------------------------------------
// Purpose: Assign a default soundscript if none is provided, then precache
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::PrecacheNPCSoundScript(string_t * SoundName, string_t defaultSoundName)
{
if (!SoundName) {
*SoundName = defaultSoundName;
}
PrecacheScriptSound(STRING(*SoundName));
}
//-----------------------------------------------------------------------------
// Purpose: Get movement speed, multipled by modifier
//-----------------------------------------------------------------------------
float CNPC_BaseCustomNPC::GetSequenceGroundSpeed(CStudioHdr *pStudioHdr, int iSequence)
{
float t = SequenceDuration(pStudioHdr, iSequence);
if (t > 0)
{
return (GetSequenceMoveDist(pStudioHdr, iSequence) * m_flSpeedModifier / t);
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to change the speed of the NPC
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputSetSpeedModifier(inputdata_t &inputdata)
{
this->m_flSpeedModifier = inputdata.value.Float();
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable opening doors
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputEnableOpenDoors(inputdata_t &inputdata)
{
m_bCannotOpenDoors = false;
if (!HasSpawnFlags(SF_NPC_START_EFFICIENT))
{
CapabilitiesAdd(bits_CAP_DOORS_GROUP);
}
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable opening doors
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputDisableOpenDoors(inputdata_t &inputdata)
{
m_bCannotOpenDoors = true;
if (!HasSpawnFlags(SF_NPC_START_EFFICIENT))
{
CapabilitiesRemove(bits_CAP_DOORS_GROUP);
}
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable weapon pickup behavior
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputEnablePickupWeapons(inputdata_t &inputdata)
{
m_bCanPickupWeapons = true;
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable weapon pickup behavior
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputDisablePickupWeapons(inputdata_t &inputdata)
{
m_bCanPickupWeapons = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
// Output :
//-----------------------------------------------------------------------------
Class_T CNPC_BaseCustomNPC::Classify( void )
{
return CLASS_NONE;
}
| 31.768504
| 144
| 0.598374
|
jarnar85
|
16526570f5c665f6ef3d7f50e27cc69083c71453
| 489
|
cpp
|
C++
|
53_soma_casas_forca_bruta.cpp
|
dannluciano/codcad
|
a226fa11dab0e1cc6524c42859b01435d58ce4f0
|
[
"MIT"
] | null | null | null |
53_soma_casas_forca_bruta.cpp
|
dannluciano/codcad
|
a226fa11dab0e1cc6524c42859b01435d58ce4f0
|
[
"MIT"
] | null | null | null |
53_soma_casas_forca_bruta.cpp
|
dannluciano/codcad
|
a226fa11dab0e1cc6524c42859b01435d58ce4f0
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
int main() {
int numero_de_casas;
scanf("%d", &numero_de_casas);
int casas[numero_de_casas];
for (int i = 0; i < numero_de_casas; i++) {
scanf("%d", &casas[i]);
}
int soma_das_casas;
scanf("%d", &soma_das_casas);
for (int i = 0; i < numero_de_casas - 1; i++) {
for (int j = i + 1; j < numero_de_casas; j++) {
if (casas[i] + casas[j] == soma_das_casas) {
printf("%d %d", casas[i], casas[j]);
}
}
}
return 0;
}
| 21.26087
| 51
| 0.543967
|
dannluciano
|
165e1d9c106c370b141dcf62bc6db45a84154fc2
| 14,930
|
cpp
|
C++
|
src/libtsduck/plugin/tsInputSwitcherArgs.cpp
|
cedinu/tsduck
|
dc693912b1fda85bcac3fcb830d7753bd8112552
|
[
"BSD-2-Clause"
] | null | null | null |
src/libtsduck/plugin/tsInputSwitcherArgs.cpp
|
cedinu/tsduck
|
dc693912b1fda85bcac3fcb830d7753bd8112552
|
[
"BSD-2-Clause"
] | null | null | null |
src/libtsduck/plugin/tsInputSwitcherArgs.cpp
|
cedinu/tsduck
|
dc693912b1fda85bcac3fcb830d7753bd8112552
|
[
"BSD-2-Clause"
] | null | null | null |
//----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// 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 OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
#include "tsInputSwitcherArgs.h"
#include "tsArgsWithPlugins.h"
TSDUCK_SOURCE;
#if defined(TS_NEED_STATIC_CONST_DEFINITIONS)
constexpr size_t ts::InputSwitcherArgs::DEFAULT_MAX_INPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::MIN_INPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::DEFAULT_MAX_OUTPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::MIN_OUTPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::DEFAULT_BUFFERED_PACKETS;
constexpr size_t ts::InputSwitcherArgs::MIN_BUFFERED_PACKETS;
constexpr ts::MilliSecond ts::InputSwitcherArgs::DEFAULT_RECEIVE_TIMEOUT;
#endif
//----------------------------------------------------------------------------
// Constructors.
//----------------------------------------------------------------------------
ts::InputSwitcherArgs::InputSwitcherArgs() :
appName(),
fastSwitch(false),
delayedSwitch(false),
terminate(false),
reusePort(false),
firstInput(0),
primaryInput(NPOS),
cycleCount(1),
bufferedPackets(0),
maxInputPackets(0),
maxOutputPackets(0),
eventCommand(),
eventUDP(),
eventLocalAddress(),
eventTTL(0),
sockBuffer(0),
remoteServer(),
allowedRemote(),
receiveTimeout(0),
inputs(),
output()
{
}
//----------------------------------------------------------------------------
// Enforce default or minimum values.
//----------------------------------------------------------------------------
void ts::InputSwitcherArgs::enforceDefaults()
{
if (inputs.empty()) {
// If no input plugin is used, used only standard input.
inputs.push_back(PluginOptions(u"file"));
}
if (output.name.empty()) {
output.set(u"file");
}
if (receiveTimeout <= 0 && primaryInput != NPOS) {
receiveTimeout = DEFAULT_RECEIVE_TIMEOUT;
}
firstInput = std::min(firstInput, inputs.size() - 1);
bufferedPackets = std::max(bufferedPackets, MIN_BUFFERED_PACKETS);
maxInputPackets = std::max(maxInputPackets, MIN_INPUT_PACKETS);
maxOutputPackets = std::max(maxOutputPackets, MIN_OUTPUT_PACKETS);
}
//----------------------------------------------------------------------------
// Define command line options in an Args.
//----------------------------------------------------------------------------
void ts::InputSwitcherArgs::defineArgs(Args& args) const
{
args.option(u"allow", 'a', Args::STRING);
args.help(u"allow",
u"Specify an IP address or host name which is allowed to send remote commands. "
u"Several --allow options are allowed. By default, all remote commands are accepted.");
args.option(u"buffer-packets", 'b', Args::POSITIVE);
args.help(u"buffer-packets",
u"Specify the size in TS packets of each input plugin buffer. "
u"The default is " + UString::Decimal(DEFAULT_BUFFERED_PACKETS) + u" packets.");
args.option(u"cycle", 'c', Args::POSITIVE);
args.help(u"cycle",
u"Specify how many times to repeat the cycle through all input plugins in sequence. "
u"By default, all input plugins are executed in sequence only once (--cycle 1). "
u"The options --cycle, --infinite and --terminate are mutually exclusive.");
args.option(u"delayed-switch", 'd');
args.help(u"delayed-switch",
u"Perform delayed input switching. When switching from one input plugin to another one, "
u"the second plugin is started first. Packets from the first plugin continue to be "
u"output while the second plugin is starting. Then, after the second plugin starts to "
u"receive packets, the switch occurs: packets are now fetched from the second plugin. "
u"Finally, after the switch, the first plugin is stopped.");
args.option(u"event-command", 0, Args::STRING);
args.help(u"event-command", u"'command'",
u"When a switch event occurs, run this external shell command. "
u"This can be used to notify some external system of the event. "
u"The command receives additional parameters:\n\n"
u"1. Event name, currently only \"newinput\" is defined.\n"
u"2. The input index before the event.\n"
u"3. The input index after the event.");
args.option(u"event-udp", 0, Args::STRING);
args.help(u"event-udp", u"address:port",
u"When a switch event occurs, send a short JSON description over UDP/IP to the specified destination. "
u"This can be used to notify some external system of the event. "
u"The 'address' specifies an IP address which can be either unicast or multicast. "
u"It can be also a host name that translates to an IP address. "
u"The 'port' specifies the destination UDP port.");
args.option(u"event-local-address", 0, Args::STRING);
args.help(u"event-local-address", u"address",
u"With --event-udp, when the destination is a multicast address, specify "
u"the IP address of the outgoing local interface. It can be also a host "
u"name that translates to a local address.");
args.option(u"event-ttl", 0, Args::POSITIVE);
args.help(u"event-ttl",
u"With --event-udp, specifies the TTL (Time-To-Live) socket option. "
u"The actual option is either \"Unicast TTL\" or \"Multicast TTL\", "
u"depending on the destination address. Remember that the default "
u"Multicast TTL is 1 on most systems.");
args.option(u"fast-switch", 'f');
args.help(u"fast-switch",
u"Perform fast input switching. All input plugins are started at once and they "
u"continuously receive packets in parallel. Packets are dropped, except for the "
u"current input plugin. This option is typically used when all inputs are live "
u"streams on distinct devices (not the same DVB tuner for instance).\n\n"
u"By default, only one input plugin is started at a time. When switching, "
u"the current input is first stopped and then the next one is started.");
args.option(u"first-input", 0, Args::UNSIGNED);
args.help(u"first-input",
u"Specify the index of the first input plugin to start. "
u"By default, the first plugin (index 0) is used.");
args.option(u"infinite", 'i');
args.help(u"infinite", u"Infinitely repeat the cycle through all input plugins in sequence.");
args.option(u"max-input-packets", 0, Args::POSITIVE);
args.help(u"max-input-packets",
u"Specify the maximum number of TS packets to read at a time. "
u"This value may impact the switch response time. "
u"The default is " + UString::Decimal(DEFAULT_MAX_INPUT_PACKETS) + u" packets. "
u"The actual value is never more than half the --buffer-packets value.");
args.option(u"max-output-packets", 0, Args::POSITIVE);
args.help(u"max-output-packets",
u"Specify the maximum number of TS packets to write at a time. "
u"The default is " + UString::Decimal(DEFAULT_MAX_OUTPUT_PACKETS) + u" packets.");
args.option(u"primary-input", 'p', Args::UNSIGNED);
args.help(u"primary-input",
u"Specify the index of the input plugin which is considered as primary "
u"or preferred. This input plugin is always started, never stopped, even "
u"without --fast-switch. When no packet is received on this plugin, the "
u"normal switching rules apply. However, as soon as packets are back on "
u"the primary input, the reception is immediately switched back to it. "
u"By default, there is no primary input, all input plugins are equal.");
args.option(u"no-reuse-port");
args.help(u"no-reuse-port",
u"Disable the reuse port socket option for the remote control. "
u"Do not use unless completely necessary.");
args.option(u"receive-timeout", 0, Args::UNSIGNED);
args.help(u"receive-timeout",
u"Specify a receive timeout in milliseconds. "
u"When the current input plugin has received no packet within "
u"this timeout, automatically switch to the next plugin. "
u"By default, without --primary-input, there is no automatic switch "
u"when the current input plugin is waiting for packets. With "
u"--primary-input, the default is " + UString::Decimal(DEFAULT_RECEIVE_TIMEOUT) + u" ms.");
args.option(u"remote", 'r', Args::STRING);
args.help(u"remote", u"[address:]port",
u"Specify the local UDP port which is used to receive remote commands. "
u"If an optional address is specified, it must be a local IP address of the system. "
u"By default, there is no remote control.");
args.option(u"terminate", 't');
args.help(u"terminate", u"Terminate execution when the current input plugin terminates.");
args.option(u"udp-buffer-size", 0, Args::UNSIGNED);
args.help(u"udp-buffer-size",
u"Specifies the UDP socket receive buffer size (socket option).");
}
//----------------------------------------------------------------------------
// Load arguments from command line.
//----------------------------------------------------------------------------
bool ts::InputSwitcherArgs::loadArgs(DuckContext& duck, Args& args)
{
appName = args.appName();
fastSwitch = args.present(u"fast-switch");
delayedSwitch = args.present(u"delayed-switch");
terminate = args.present(u"terminate");
args.getIntValue(cycleCount, u"cycle", args.present(u"infinite") ? 0 : 1);
args.getIntValue(bufferedPackets, u"buffer-packets", DEFAULT_BUFFERED_PACKETS);
maxInputPackets = std::min(args.intValue<size_t>(u"max-input-packets", DEFAULT_MAX_INPUT_PACKETS), bufferedPackets / 2);
args.getIntValue(maxOutputPackets, u"max-output-packets", DEFAULT_MAX_OUTPUT_PACKETS);
const UString remoteName(args.value(u"remote"));
reusePort = !args.present(u"no-reuse-port");
args.getIntValue(sockBuffer, u"udp-buffer-size");
args.getIntValue(firstInput, u"first-input", 0);
args.getIntValue(primaryInput, u"primary-input", NPOS);
args.getIntValue(receiveTimeout, u"receive-timeout", primaryInput >= inputs.size() ? 0 : DEFAULT_RECEIVE_TIMEOUT);
// Event reporting.
args.getValue(eventCommand, u"event-command");
setEventUDP(args.value(u"event-udp"), args.value(u"event-local-address"), args);
args.getIntValue(eventTTL, u"event-ttl", 0);
// Check conflicting modes.
if (args.present(u"cycle") + args.present(u"infinite") + args.present(u"terminate") > 1) {
args.error(u"options --cycle, --infinite and --terminate are mutually exclusive");
}
if (fastSwitch && delayedSwitch) {
args.error(u"options --delayed-switch and --fast-switch are mutually exclusive");
}
// Resolve network names. The resolve() method reports error and set the args error state.
if (!remoteName.empty() && remoteServer.resolve(remoteName, args) && !remoteServer.hasPort()) {
args.error(u"missing UDP port number in --remote");
}
// Resolve all allowed remote.
UStringVector remotes;
args.getValues(remotes, u"allow");
allowedRemote.clear();
for (auto it = remotes.begin(); it != remotes.end(); ++it) {
const IPv4Address addr(*it, args);
if (addr.hasAddress()) {
allowedRemote.insert(addr);
}
}
// Load all plugin descriptions. Default output is the standard output file.
ArgsWithPlugins* pargs = dynamic_cast<ArgsWithPlugins*>(&args);
if (pargs != nullptr) {
pargs->getPlugins(inputs, PluginType::INPUT);
pargs->getPlugin(output, PluginType::OUTPUT, u"file");
}
else {
inputs.clear();
output.set(u"file");
}
if (inputs.empty()) {
// If no input plugin is used, used only standard input.
inputs.push_back(PluginOptions(u"file"));
}
// Check validity of input indexes.
if (firstInput >= inputs.size()) {
args.error(u"invalid input index for --first-input %d", {firstInput});
}
if (primaryInput != NPOS && primaryInput >= inputs.size()) {
args.error(u"invalid input index for --primary-input %d", {primaryInput});
}
return args.valid();
}
//----------------------------------------------------------------------------
// Set the UDP destination for event reporting using strings.
//----------------------------------------------------------------------------
bool ts::InputSwitcherArgs::setEventUDP(const UString& destination, const UString& local, Report& report)
{
if (destination.empty()) {
eventUDP.clear();
}
else if (!eventUDP.resolve(destination, report)) {
return false;
}
else if (!eventUDP.hasAddress() || !eventUDP.hasPort()) {
report.error(u"event reporting through UDP requires an IP address and a UDP port");
return false;
}
if (local.empty()) {
eventLocalAddress.clear();
}
else if (!eventLocalAddress.resolve(local, report)) {
return false;
}
return true;
}
| 45.242424
| 124
| 0.624313
|
cedinu
|
166846b6ee5a616929638ff6570411fe764d5a03
| 7,166
|
hpp
|
C++
|
ivarp/include/ivarp/math_fn/n_ary_ops.hpp
|
phillip-keldenich/squares-in-disk
|
501ebeb00b909b9264a9611fd63e082026cdd262
|
[
"MIT"
] | null | null | null |
ivarp/include/ivarp/math_fn/n_ary_ops.hpp
|
phillip-keldenich/squares-in-disk
|
501ebeb00b909b9264a9611fd63e082026cdd262
|
[
"MIT"
] | null | null | null |
ivarp/include/ivarp/math_fn/n_ary_ops.hpp
|
phillip-keldenich/squares-in-disk
|
501ebeb00b909b9264a9611fd63e082026cdd262
|
[
"MIT"
] | null | null | null |
// The code is open source under the MIT license.
// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group
// https://ibr.cs.tu-bs.de/alg
//
// 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.
//
// Created by Phillip Keldenich on 06.11.19.
//
#pragma once
namespace ivarp {
struct MathNAryMinTag {
struct EvalBounds {
template<typename B1, typename... Bs> struct Eval {
static constexpr std::int64_t lb = fixed_point_bounds::minimum(B1::lb, Bs::lb...);
static constexpr std::int64_t ub = fixed_point_bounds::minimum(B1::ub, Bs::ub...);
};
};
static const char* name() noexcept {
return "min";
}
template<typename Context> IVARP_HD static EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1) noexcept {
return a1;
}
template<typename Context, typename A1> IVARP_H static DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1) {
return ivarp::forward<A1>(a1);
}
template<typename Context> static IVARP_HD
EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1, typename Context::NumberType a2) noexcept
{
return minimum(a1, a2);
}
template<typename Context, typename A1, typename A2> static IVARP_H DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1, A2&& a2)
{
return minimum(ivarp::forward<A1>(a1), ivarp::forward<A2>(a2));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_HD EnableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args) noexcept
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_H DisableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args)
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
};
struct MathNAryMaxTag {
struct EvalBounds {
template<typename B1, typename... Bs> struct Eval {
static constexpr std::int64_t lb = fixed_point_bounds::maximum(B1::lb, Bs::lb...);
static constexpr std::int64_t ub = fixed_point_bounds::maximum(B1::ub, Bs::ub...);
};
};
static const char* name() noexcept {
return "max";
}
template<typename Context> IVARP_HD static EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1) noexcept {
return a1;
}
template<typename Context, typename A1> IVARP_H static DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1) {
return ivarp::forward<A1>(a1);
}
template<typename Context> static IVARP_HD
EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1, typename Context::NumberType a2) noexcept
{
return maximum(a1, a2);
}
template<typename Context, typename A1, typename A2> static IVARP_H DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1, A2&& a2)
{
return maximum(ivarp::forward<A1>(a1), ivarp::forward<A2>(a2));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_HD EnableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args) noexcept
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_H DisableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args)
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
};
/// The MathExpression type of an n-ary operator, if at least one argument is a math expression and all
/// arguments are math expressions, numbers or integers.
template<typename Tag, bool Ok, typename... Args> struct NAryOpResult;
template<typename Tag, typename... Args> struct NAryOpResult<Tag, true, Args...> {
using Type = MathNAry<Tag, EnsureExpr<Args>...>;
};
/// Shorthand for NAryOpResult; also applies decay and checks arguments.
template<typename Tag, typename... Args> using NAryOpResultType =
typename NAryOpResult<Tag,
OneOf<IsMathExpr<Args>::value...>::value &&
AllOf<IsExprOrConstant<Args>::value...>::value,
BareType<Args>...>::Type;
/// MathExpression for minimum of k >= 1 arguments.
template<typename A1, typename... Args> static inline NAryOpResultType<MathNAryMinTag, A1, Args...>
minimum(A1&& a1, Args&&... args)
{
return {ivarp::forward<A1>(a1), ivarp::forward<Args>(args)...};
}
/// MathExpression for maximum of k >= 1 arguments.
template<typename A1, typename... Args> static inline NAryOpResultType<MathNAryMaxTag, A1, Args...>
maximum(A1&& a1, Args&&... args)
{
return {ivarp::forward<A1>(a1), ivarp::forward<Args>(args)...};
}
}
| 50.111888
| 175
| 0.653224
|
phillip-keldenich
|
16703495a18512431801766b039c37972da543e0
| 2,774
|
cc
|
C++
|
server/db_slice.cc
|
romange/midi-redis
|
35e7bce4ce6246716464fb78445babc0317b5000
|
[
"Apache-2.0"
] | 12
|
2021-12-09T18:50:47.000Z
|
2022-03-11T17:47:04.000Z
|
server/db_slice.cc
|
romange/midi-redis
|
35e7bce4ce6246716464fb78445babc0317b5000
|
[
"Apache-2.0"
] | null | null | null |
server/db_slice.cc
|
romange/midi-redis
|
35e7bce4ce6246716464fb78445babc0317b5000
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021, Roman Gershman. All rights reserved.
// See LICENSE for licensing terms.
//
#include "server/db_slice.h"
#include <boost/fiber/fiber.hpp>
#include <boost/fiber/operations.hpp>
#include "base/logging.h"
#include "server/engine_shard_set.h"
#include "util/fiber_sched_algo.h"
#include "util/proactor_base.h"
namespace dfly {
using namespace boost;
using namespace std;
using namespace util;
DbSlice::DbSlice(uint32_t index, EngineShard* owner) : shard_id_(index), owner_(owner) {
db_arr_.emplace_back();
CreateDbRedis(0);
}
DbSlice::~DbSlice() {
for (auto& db : db_arr_) {
if (!db.main_table)
continue;
db.main_table.reset();
}
}
void DbSlice::Reserve(DbIndex db_ind, size_t key_size) {
ActivateDb(db_ind);
auto& db = db_arr_[db_ind];
DCHECK(db.main_table);
db.main_table->reserve(key_size);
}
auto DbSlice::Find(DbIndex db_index, std::string_view key) const -> OpResult<MainIterator> {
DCHECK_LT(db_index, db_arr_.size());
DCHECK(db_arr_[db_index].main_table);
auto& db = db_arr_[db_index];
MainIterator it = db.main_table->find(key);
if (it == db.main_table->end()) {
return OpStatus::KEY_NOTFOUND;
}
return it;
}
auto DbSlice::AddOrFind(DbIndex db_index, std::string_view key) -> pair<MainIterator, bool> {
DCHECK_LT(db_index, db_arr_.size());
DCHECK(db_arr_[db_index].main_table);
auto& db = db_arr_[db_index];
pair<MainIterator, bool> res = db.main_table->emplace(key, MainValue{});
if (res.second) { // new entry
db.stats.obj_memory_usage += res.first->first.capacity();
return make_pair(res.first, true);
}
return res;
}
void DbSlice::ActivateDb(DbIndex db_ind) {
if (db_arr_.size() <= db_ind)
db_arr_.resize(db_ind + 1);
CreateDbRedis(db_ind);
}
void DbSlice::CreateDbRedis(unsigned index) {
auto& db = db_arr_[index];
if (!db.main_table) {
db.main_table.reset(new MainTable);
}
}
void DbSlice::AddNew(DbIndex db_ind, std::string_view key, MainValue obj, uint64_t expire_at_ms) {
CHECK(AddIfNotExist(db_ind, key, std::move(obj), expire_at_ms));
}
bool DbSlice::AddIfNotExist(DbIndex db_ind, std::string_view key, MainValue obj,
uint64_t expire_at_ms) {
auto& db = db_arr_[db_ind];
auto [new_entry, success] = db.main_table->emplace(key, obj);
if (!success)
return false; // in this case obj won't be moved and will be destroyed during unwinding.
db.stats.obj_memory_usage += (new_entry->first.capacity() + new_entry->second.capacity());
if (expire_at_ms) {
// TODO
}
return true;
}
size_t DbSlice::DbSize(DbIndex db_ind) const {
DCHECK_LT(db_ind, db_array_size());
if (IsDbValid(db_ind)) {
return db_arr_[db_ind].main_table->size();
}
return 0;
}
} // namespace dfly
| 23.709402
| 98
| 0.695746
|
romange
|
167617b29e0a47bd7fa225320f67a6ac0effe74f
| 9,027
|
cpp
|
C++
|
vnext/Microsoft.ReactNative.IntegrationTests/TurboModuleTests.cpp
|
harinikmsft/react-native-windows
|
c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21
|
[
"MIT"
] | 2
|
2020-12-19T17:37:56.000Z
|
2021-10-18T03:28:11.000Z
|
vnext/Microsoft.ReactNative.IntegrationTests/TurboModuleTests.cpp
|
sjalim/react-native-windows
|
04e766ef7304d0852a06e772cbfc1982897a3808
|
[
"MIT"
] | 2
|
2020-11-04T17:36:33.000Z
|
2020-11-16T10:12:46.000Z
|
vnext/Microsoft.ReactNative.IntegrationTests/TurboModuleTests.cpp
|
sjalim/react-native-windows
|
04e766ef7304d0852a06e772cbfc1982897a3808
|
[
"MIT"
] | 1
|
2019-10-17T20:48:17.000Z
|
2019-10-17T20:48:17.000Z
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include <NativeModules.h>
#include <sstream>
#include <string>
using namespace React;
using namespace winrt::Microsoft::ReactNative;
namespace ReactNativeIntegrationTests {
REACT_MODULE(SampleTurboModule)
struct SampleTurboModule {
REACT_INIT(Initialize)
void Initialize(ReactContext const & /*reactContext*/) noexcept {}
REACT_CONSTANT(m_constantString, L"constantString")
const std::string m_constantString{"constantString"};
REACT_CONSTANT(m_constantInt, L"constantInt")
const int m_constantInt{3};
REACT_CONSTANT_PROVIDER(GetConstants)
void GetConstants(React::ReactConstantProvider &provider) noexcept {
provider.Add(L"constantString2", L"Hello");
provider.Add(L"constantInt2", 10);
}
REACT_METHOD(Succeeded, L"succeeded")
void Succeeded() noexcept {
succeededSignal.set_value(true);
}
REACT_METHOD(OnError, L"onError")
void OnError(std::string errorMessage) noexcept {
// intended to keep the parameter name for debug purpose
succeededSignal.set_value(false);
}
REACT_METHOD(PromiseFunction, L"promiseFunction")
void PromiseFunction(std::string a, int b, bool c, ReactPromise<React::JSValue> result) noexcept {
auto resultString = (std::stringstream() << a << ", " << b << ", " << (c ? "true" : "false")).str();
result.Resolve({resultString});
// TODO:
// calling ".then" in the bundle fails, figure out why
// it could be an issue about environment setup
// since the issue doesn't happen in Playground.sln
PromiseFunctionResult(resultString);
}
REACT_METHOD(PromiseFunctionResult, L"promiseFunctionResult")
void PromiseFunctionResult(std::string a) noexcept {
promiseFunctionSignal.set_value(a);
}
REACT_SYNC_METHOD(SyncFunction, L"syncFunction")
std::string SyncFunction(std::string a, int b, bool c) noexcept {
auto resultString = (std::stringstream() << a << ", " << b << ", " << (c ? "true" : "false")).str();
return resultString;
}
REACT_METHOD(SyncFunctionResult, L"syncFunctionResult")
void SyncFunctionResult(std::string a) noexcept {
syncFunctionSignal.set_value(a);
}
REACT_METHOD(Constants, L"constants")
void Constants(std::string a, int b, std::string c, int d) noexcept {
auto resultString = (std::stringstream() << a << ", " << b << ", " << c << ", " << d).str();
constantsSignal.set_value(resultString);
}
REACT_METHOD(OneCallback, L"oneCallback")
void OneCallback(int a, int b, const std::function<void(int)> &resolve) noexcept {
resolve(a + b);
}
REACT_METHOD(OneCallbackResult, L"oneCallbackResult")
void OneCallbackResult(int r) noexcept {
oneCallbackSignal.set_value(r);
}
REACT_METHOD(TwoCallbacks, L"twoCallbacks")
void TwoCallbacks(
bool succeeded,
int a,
std::string b,
const std::function<void(int)> &resolve,
const std::function<void(std::string)> &reject) noexcept {
if (succeeded) {
resolve(a);
} else {
reject(b);
}
}
REACT_METHOD(TwoCallbacksResolved, L"twoCallbacksResolved")
void TwoCallbacksResolved(int r) noexcept {
twoCallbacksResolvedSignal.set_value(r);
}
REACT_METHOD(TwoCallbacksRejected, L"twoCallbacksRejected")
void TwoCallbacksRejected(std::string r) noexcept {
twoCallbacksRejectedSignal.set_value(r);
}
static std::promise<bool> succeededSignal;
static std::promise<std::string> promiseFunctionSignal;
static std::promise<std::string> syncFunctionSignal;
static std::promise<std::string> constantsSignal;
static std::promise<int> oneCallbackSignal;
static std::promise<int> twoCallbacksResolvedSignal;
static std::promise<std::string> twoCallbacksRejectedSignal;
};
std::promise<bool> SampleTurboModule::succeededSignal;
std::promise<std::string> SampleTurboModule::promiseFunctionSignal;
std::promise<std::string> SampleTurboModule::syncFunctionSignal;
std::promise<std::string> SampleTurboModule::constantsSignal;
std::promise<int> SampleTurboModule::oneCallbackSignal;
std::promise<int> SampleTurboModule::twoCallbacksResolvedSignal;
std::promise<std::string> SampleTurboModule::twoCallbacksRejectedSignal;
struct SampleTurboModuleSpec : TurboModuleSpec {
static constexpr auto methods = std::tuple{
Method<void() noexcept>{0, L"succeeded"},
Method<void(std::string) noexcept>{0, L"onError"},
Method<void(std::string, int, bool, ReactPromise<React::JSValue>) noexcept>{2, L"promiseFunction"},
Method<void(std::string) noexcept>{3, L"promiseFunctionResult"},
SyncMethod<std::string(std::string, int, bool) noexcept>{4, L"syncFunction"},
Method<void(std::string) noexcept>{5, L"syncFunctionResult"},
Method<void(std::string, int, std::string, int) noexcept>{6, L"constants"},
Method<void(int, int, const std::function<void(int)> &) noexcept>{7, L"oneCallback"},
Method<void(int) noexcept>{8, L"oneCallbackResult"},
Method<void(
bool,
int,
std::string,
const std::function<void(int)> &,
const std::function<void(std::string)> &) noexcept>{9, L"twoCallbacks"},
Method<void(int) noexcept>{10, L"twoCallbacksResolved"},
Method<void(std::string) noexcept>{11, L"twoCallbacksRejected"},
};
template <class TModule>
static constexpr void ValidateModule() noexcept {
constexpr auto methodCheckResults = CheckMethods<TModule, SampleTurboModuleSpec>();
REACT_SHOW_METHOD_SPEC_ERRORS(0, "succeeded", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(1, "onError", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(2, "promiseFunction", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(3, "promiseFunctionResult", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(4, "syncFunction", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(5, "syncFunctionResult", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(6, "constants", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(7, "oneCallback", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(8, "oneCallbackResult", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(9, "twoCallbacks", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(10, "twoCallbacksResolved", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(11, "twoCallbacksRejected", "I don't care error message");
}
};
struct SampleTurboModulePackageProvider : winrt::implements<SampleTurboModulePackageProvider, IReactPackageProvider> {
void CreatePackage(IReactPackageBuilder const &packageBuilder) noexcept {
auto experimental = packageBuilder.as<IReactPackageBuilderExperimental>();
experimental.AddTurboModule(
L"SampleTurboModule", MakeTurboModuleProvider<SampleTurboModule, SampleTurboModuleSpec>());
}
};
TEST_CLASS (TurboModuleTests) {
TEST_METHOD(ExecuteSampleTurboModule) {
ReactNativeHost host{};
auto queueController = winrt::Windows::System::DispatcherQueueController::CreateOnDedicatedThread();
queueController.DispatcherQueue().TryEnqueue([&]() noexcept {
host.PackageProviders().Append(winrt::make<SampleTurboModulePackageProvider>());
// bundle is assumed to be co-located with the test binary
wchar_t testBinaryPath[MAX_PATH];
TestCheck(GetModuleFileNameW(NULL, testBinaryPath, MAX_PATH) < MAX_PATH);
testBinaryPath[std::wstring_view{testBinaryPath}.rfind(L"\\")] = 0;
host.InstanceSettings().BundleRootPath(testBinaryPath);
host.InstanceSettings().JavaScriptBundleFile(L"TurboModuleTests");
host.InstanceSettings().UseDeveloperSupport(false);
host.InstanceSettings().UseWebDebugger(false);
host.InstanceSettings().UseFastRefresh(false);
host.InstanceSettings().UseLiveReload(false);
host.InstanceSettings().EnableDeveloperMenu(false);
host.LoadInstance();
});
TestCheckEqual(true, SampleTurboModule::succeededSignal.get_future().get());
TestCheckEqual("something, 1, true", SampleTurboModule::promiseFunctionSignal.get_future().get());
TestCheckEqual("something, 2, false", SampleTurboModule::syncFunctionSignal.get_future().get());
TestCheckEqual("constantString, 3, Hello, 10", SampleTurboModule::constantsSignal.get_future().get());
TestCheckEqual(3, SampleTurboModule::oneCallbackSignal.get_future().get());
TestCheckEqual(123, SampleTurboModule::twoCallbacksResolvedSignal.get_future().get());
TestCheckEqual("Failed", SampleTurboModule::twoCallbacksRejectedSignal.get_future().get());
host.UnloadInstance().get();
queueController.ShutdownQueueAsync().get();
}
};
} // namespace ReactNativeIntegrationTests
| 42.580189
| 119
| 0.713305
|
harinikmsft
|
16767a771591a5d8a76020a00e589ef65359e441
| 33,346
|
cpp
|
C++
|
s32v234_sdk/libs/apexcv_pro/orb/src/apexcv_pro_orb.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | null | null | null |
s32v234_sdk/libs/apexcv_pro/orb/src/apexcv_pro_orb.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | null | null | null |
s32v234_sdk/libs/apexcv_pro/orb/src/apexcv_pro_orb.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | 2
|
2021-01-21T02:06:16.000Z
|
2021-01-28T10:47:37.000Z
|
/*******************************************************************************
*
* NXP Confidential Proprietary
*
* Copyright (c) 2016-2017 NXP Semiconductor;
* All Rights Reserved
*
*******************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP OR ITS 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 <oal.h>
#include <algorithm>
#include <vector>
#include "apexcv_pro_orb.h"
#include "apexcv_pro_fast.h"
#include <APU_ORB_RBRIEF.hpp>
#include <APU_ORB_ORIENTATION.hpp>
/* This is the standardized sampling pattern for Orb, this will work with descriptor
* sizes of a maximum 256 bits
* If bigger descriptors are needed plese generate a new sampling pattern and plug-it into
* APEX.
* https://github.com/opencv/opencv/blob/master/modules/features2d/src/orb.cpp :: line 375
*/
static int8_t samplingPattern[1024] =
{
8, -3, 9, 5, 4, 2, 7, -12, -11, 9, -8, 2, 7, -12, 12, -13,
2, -13, 2, 12, 1, -7, 1, 6, -2, -10, -2, -4, -13, -13, -11, -8,
-13, -3, -12, -9, 10, 4, 11, 9, -13, -8, -8, -9, -11, 7, -9, 12,
7, 7, 12, 6, -4, -5, -3, 0, -13, 2, -12, -3, -9, 0, -7, 5,
12, -6, 12, -1, -3, 6, -2, 12, -6, -13, -4, -8, 11, -13, 12, -8,
4, 7, 5, 1, 5, -3, 10, -3, 3, -7, 6, 12, -8, -7, -6, -2,
-2, 11, -1, -10, -13, 12, -8, 10, -7, 3, -5, -3, -4, 2, -3, 7,
-10, -12, -6, 11, 5, -12, 6, -7, 5, -6, 7, -1, 1, 0, 4, -5,
9, 11, 11, -13, 4, 7, 4, 12, 2, -1, 4, 4, -4, -12, -2, 7,
-8, -5, -7, -10, 4, 11, 9, 12, 0, -8, 1, -13, -13, -2, -8, 2,
-3, -2, -2, 3, -6, 9, -4, -9, 8, 12, 10, 7, 0, 9, 1, 3,
7, -5, 11, -10, -13, -6, -11, 0, 10, 7, 12, 1, -6, -3, -6, 12,
10, -9, 12, -4, -13, 8, -8, -12, -13, 0, -8, -4, 3, 3, 7, 8,
5, 7, 10, -7, -1, 7, 1, -12, 3, -10, 5, 6, 2, -4, 3, -10,
-13, 0, -13, 5, -13, -7, -12, 12, -13, 3, -11, 8, -7, 12, -4, 7,
6, -10, 12, 8, -9, -1, -7, -6, -2, -5, 0, 12, -12, 5, -7, 5,
3, -10, 8, -13, -7, -7, -4, 5, -3, -2, -1, -7, 2, 9, 5, -11,
-11, -13, -5, -13, -1, 6, 0, -1, 5, -3, 5, 2, -4, -13, -4, 12,
-9, -6, -9, 6, -12, -10, -8, -4, 10, 2, 12, -3, 7, 12, 12, 12,
-7, -13, -6, 5, -4, 9, -3, 4, 7, -1, 12, 2, -7, 6, -5, 1,
-13, 11, -12, 5, -3, 7, -2, -6, 7, -8, 12, -7, -13, -7, -11, -12,
1, -3, 12, 12, 2, -6, 3, 0, -4, 3, -2, -13, -1, -13, 1, 9,
7, 1, 8, -6, 1, -1, 3, 12, 9, 1, 12, 6, -1, -9, -1, 3,
-13, -13, -10, 5, 7, 7, 10, 12, 12, -5, 12, 9, 6, 3, 7, 11,
5, -13, 6, 10, 2, -12, 2, 3, 3, 8, 4, -6, 2, 6, 12, -13,
9, -12, 10, 3, -8, 4, -7, 9, -11, 12, -4, -6, 1, 12, 2, -8,
6, -9, 7, -4, 2, 3, 3, -2, 6, 3, 11, 0, 3, -3, 8, -8,
7, 8, 9, 3, -11, -5, -6, -4, -10, 11, -5, 10, -5, -8, -3, 12,
-10, 5, -9, 0, 8, -1, 12, -6, 4, -6, 6, -11, -10, 12, -8, 7,
4, -2, 6, 7, -2, 0, -2, 12, -5, -8, -5, 2, 7, -6, 10, 12,
-9, -13, -8, -8, -5, -13, -5, -2, 8, -8, 9, -13, -9, -11, -9, 0,
1, -8, 1, -2, 7, -4, 9, 1, -2, 1, -1, -4, 11, -6, 12, -11,
-12, -9, -6, 4, 3, 7, 7, 12, 5, 5, 10, 8, 0, -4, 2, 8,
-9, 12, -5, -13, 0, 7, 2, 12, -1, 2, 1, 7, 5, 11, 7, -9,
3, 5, 6, -8, -13, -4, -8, 9, -5, 9, -3, -3, -4, -7, -3, -12,
6, 5, 8, 0, -7, 6, -6, 12, -13, 6, -5, -2, 1, -10, 3, 10,
4, 1, 8, -4, -2, -2, 2, -13, 2, -12, 12, 12, -2, -13, 0, -6,
4, 1, 9, 3, -6, -10, -3, -5, -3, -13, -1, 1, 7, 5, 12, -11,
4, -2, 5, -7, -13, 9, -9, -5, 7, 1, 8, 6, 7, -8, 7, 6,
-7, -4, -7, 1, -8, 11, -7, -8, -13, 6, -12, -8, 2, 4, 3, 9,
10, -5, 12, 3, -6, -5, -6, 7, 8, -3, 9, -8, 2, -12, 2, 8,
-11, -2, -10, 3, -12, -13, -7, -9, -11, 0, -10, -5, 5, -3, 11, 8,
-2, -13, -1, 12, -1, -8, 0, 9, -13, -11, -12, -5, -10, -2, -10, 11,
-3, 9, -2, -13, 2, -3, 3, 2, -9, -13, -4, 0, -4, 6, -3, -10,
-4, 12, -2, -7, -6, -11, -4, 9, 6, -3, 6, 11, -13, 11, -5, 5,
11, 11, 12, 6, 7, -5, 12, -2, -1, 12, 0, 7, -4, -8, -3, -2,
-7, 1, -6, 7, -13, -12, -8, -13, -7, -2, -6, -8, -8, 5, -6, -9,
-5, -1, -4, 5, -13, 7, -8, 10, 1, 5, 5, -13, 1, 0, 10, -13,
9, 12, 10, -1, 5, -8, 10, -9, -1, 11, 1, -13, -9, -3, -6, 2,
-1, -10, 1, 12, -13, 1, -8, -10, 8, -11, 10, -6, 2, -13, 3, -6,
7, -13, 12, -9, -10, -10, -5, -7, -10, -8, -8, -13, 4, -6, 8, 5,
3, 12, 8, -13, -4, 2, -3, -3, 5, -13, 10, -12, 4, -13, 5, -1,
-9, 9, -4, 3, 0, 3, 3, -9, -12, 1, -6, 1, 3, 2, 4, -8,
-10, -10, -10, 9, 8, -13, 12, 12, -8, -12, -6, -5, 2, 2, 3, 7,
10, 6, 11, -8, 6, 8, 8, -12, -7, 10, -6, 5, -3, -9, -3, 9,
-1, -13, -1, 5, -3, -7, -3, 4, -8, -2, -8, 3, 4, 2, 12, 12,
2, -5, 3, 11, 6, -9, 11, -13, 3, -1, 7, 12, 11, -1, 12, 4,
-3, 0, -3, 6, 4, -11, 4, 12, 2, -4, 2, 1, -10, -6, -8, 1,
-13, 7, -11, 1, -13, 12, -11, -13, 6, 0, 11, -13, 0, -1, 1, 4,
-13, 3, -9, -2, -9, 8, -6, -3, -13, -6, -8, -2, 5, -9, 8, 10,
2, 7, 3, -9, -1, -6, -1, -1, 9, 5, 11, -2, 11, -3, 12, -8,
3, 0, 3, 5, -1, 4, 0, 10, 3, -6, 4, 5, -13, 0, -10, 5,
5, 8, 12, 11, 8, 9, 9, -6, 7, -4, 8, -12, -10, 4, -10, 9,
7, 3, 12, 4, 9, -7, 10, -2, 7, 0, 12, -2, -1, -6, 0, -11};
namespace apexcv
{
// Helper function used to sort the keypoints
static bool CmpGreaterFeature(Orb::Corner aLeft, Orb::Corner aRight)
{
return(aLeft.strength > aRight.strength);
}
static inline void flushUMat(vsdk::SUMat& aTarget)
{
// Helper function used to flush the cache data into the DDR
uint8_t * pData = (uint8_t *)aTarget.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
int size = (int)(aTarget.total() * aTarget.elemSize());
OAL_MemoryFlushAndInvalidate((void *)pData, size);
return;
}
// Helper function that calculates Harris corner metric
float
HarrisScore(uint8_t *__restrict__ apCenter,
int aStep,
const int acBlockSize,
const float acHarrisK)
{
const int radius = (acBlockSize >> 1);
const float scale = 1.0f / ((1 << 2) * acBlockSize * 255.f);
const float sclPow2 = scale * scale;
const float sclPow4 = (sclPow2 * sclPow2);
register int a = 0, b = 0, c = 0;
for(int y = -radius; y < radius; y++)
{
// Point to the center of the image row
const uint8_t *__restrict__ pStartRow = (uint8_t * __restrict__) & apCenter[y * aStep];
for(int x = -radius; x < radius; x++)
{
// Row access
const uint8_t *__restrict__ ptr = (const uint8_t * __restrict__) & pStartRow[x];
// Compute dx and dy
// Data from first line
int mat00 = ptr[-aStep - 1];
int mat01 = ptr[-aStep + 0];
int mat02 = ptr[-aStep + 1];
// Data from the second line
int mat10 = ptr[-1];
int mat12 = ptr[+1];
// Data from the third line
int mat20 = ptr[aStep - 1];
int mat21 = ptr[aStep + 0];
int mat22 = ptr[aStep + 1];
// Image derivative for both x and y
int dx = (mat02 - mat00) + 2 * (mat12 - mat10) + (mat22 - mat20);
int dy = (mat20 - mat00) + 2 * (mat21 - mat01) + (mat22 - mat02);
// Compute the products of the derivation at each pixel
a += (dx * dx);
b += (dy * dy);
c += (dx * dy);
}
}
// H(x, y) = | Sx*x(x, y) Sx*y(x, y) | in our code = | a c |
// | Sy*x(x, y) Sy*y(x, y) | | c b |
// Harris Cornerness = Det(H) - k * trace(H) ^ 2
float score = ((float)a * b - (float)c * c - acHarrisK * ((float)a + b) * ((float)a + b)) * sclPow4;
// Return the Harris Corner Metric
return score;
}
APEXCV_LIB_RESULT CalcChunkOffsets(vsdk::SUMat &aInputImg, std::vector<Orb::Corner> &aKeypoints, int aNrOfkeypoints, int aPatchSize, vsdk::SUMat &aChunkOffsets)
{
// Each keypoint is place inside a chunk
// This helper function calculate the offset in bytes inside the image for each chunk
uint16_t span = aInputImg.step[0];
uint16_t halfPatch = aPatchSize >> 1;
int32_t *pChunkOffset = (int32_t *)aChunkOffsets.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
int32_t sizeBytes = aChunkOffsets.total() * aChunkOffsets.elemSize();
// Clear the buffer
memset((uint8_t *)pChunkOffset, 0, sizeBytes);
// Basic error checks
if(aPatchSize <= 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aNrOfkeypoints <= 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aKeypoints.size() == 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
// Loop all the keypoints
for(int kpntId = 0; kpntId < aNrOfkeypoints; kpntId++)
{
// Read the <x, y> coordinates of the keypoints
Orb::Corner data = aKeypoints[kpntId];
// Calculate the offset in bytes for the keypoint
uint16_t x = data.x;
uint16_t y = data.y;
uint16_t newX = (x - halfPatch);
uint16_t newY = (y - halfPatch);
int32_t offset = newX + newY * span;
pChunkOffset[kpntId] = offset;
}
OAL_MemoryFlushAndInvalidate((void *)pChunkOffset, sizeBytes);
return APEXCV_SUCCESS;
}
Orb::Orb() :
mpChunkOffsets(nullptr),
mpAngles(nullptr),
mpDescriptorCount(nullptr),
mpBinPatternOut(nullptr),
mInit(false),
mpProcessCalcOrientation(nullptr),
mpProcessCalcRbrief(nullptr)
{
}
Orb::~Orb()
{
// Class destructor
if(NULL != mpProcessCalcRbrief)
{
delete[] (APU_ORB_RBRIEF *) mpProcessCalcRbrief;
}
if (NULL != mpProcessCalcOrientation)
{
delete[](APU_ORB_ORIENTATION *) mpProcessCalcOrientation;
}
if (NULL != mpBinPatternOut)
{
delete[] mpBinPatternOut;
}
if (NULL != mpDescriptorCount)
{
delete[] mpDescriptorCount;
}
if (NULL != mpAngles)
{
delete[] mpAngles;
}
if (NULL != mpChunkOffsets)
{
delete[] mpChunkOffsets;
}
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
APEXCV_LIB_RESULT Orb::Create(unsigned char aApexId,
unsigned char aNrOfThreads,
unsigned int aBorderSize,
unsigned int aPatchSize,
unsigned int aRadius,
unsigned int aDescriptorSizeInBytes,
unsigned int aFastCircumference,
unsigned int aFastThreshold,
float aHarrisK,
unsigned int aNrOfKeypoints)
{
// Basic error checks
if(mInit != false)
{
return APEXCV_ERROR_OBJECT_ALREADY_INITIALIZED;
}
if(aBorderSize < aRadius)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aPatchSize < (2 * aRadius))
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aDescriptorSizeInBytes == 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aNrOfKeypoints == 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aNrOfThreads > 2)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aApexId >= 2)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
APEXCV_LIB_RESULT status;
const int pairXY = 2;
const int nrOfPairsForComparison = 2;
const int smpltPtrnApexDmaBytes = 2048;
const int maxNrOfKeypoints = FAST_MAX_LIST_ELEMENTS;
// Class parameters
mApexId = aApexId;
mNrOfThreads = aNrOfThreads;
mDistanceFromBorder = aBorderSize;
mFastCirc = aFastCircumference;
mFastTh = aFastThreshold;
mHarrisK = aHarrisK;
mNrOfFeatures = aNrOfKeypoints;
int descriptorSizeInBits = aDescriptorSizeInBytes * 8;
int samplingPoints = descriptorSizeInBits * nrOfPairsForComparison * pairXY;
// Allocate the buffer to maximum
// The sampling buffer is tagged as static_fixed inside the ACF
msmplBitPattern = vsdk::SUMat(1, smpltPtrnApexDmaBytes, VSDK_CV_8SC1);
if (!msmplBitPattern.empty())
{
// Fill-in the buffer that APEX will "see" as the sampling bit pattern
int8_t * pData = (int8_t *)msmplBitPattern.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
// Clear the buffer
memset(pData, 0, smpltPtrnApexDmaBytes);
for (int idx = 0; idx < samplingPoints; idx++)
{
pData[idx] = samplingPattern[idx];
}
}
// Dynamic allocation of APU processes
APU_ORB_ORIENTATION * pProcessCalcOrientation = new APU_ORB_ORIENTATION[mNrOfThreads];
if(NULL == pProcessCalcOrientation)
{
return APEXCV_ERROR_MEMORY_ALLOCATION_FAILED;
}
// Store to the class variables
mpProcessCalcOrientation = (void *) pProcessCalcOrientation;
{
for(int32_t i=0;i<mNrOfThreads;i++)
{
ApexcvHostBaseBaseClass::InfoCluster lInfo;
char lTemp[50];
sprintf(lTemp, "%s_THREAD[%d]","APU_ORB_ORIENTATION",i);
lInfo.set_ACF(lTemp, (void*) &pProcessCalcOrientation[i]);
lInfo.push_PortName("INPUT");
mvInfoClusters.push_back(lInfo);
}
}
APU_ORB_RBRIEF * pProcessCalcRbrief = new APU_ORB_RBRIEF[mNrOfThreads];
if(NULL == pProcessCalcRbrief)
{
return APEXCV_ERROR_MEMORY_ALLOCATION_FAILED;
}
// Store to the class variables
mpProcessCalcRbrief = (void *) pProcessCalcRbrief;
{
for(int32_t i=0;i<mNrOfThreads;i++)
{
ApexcvHostBaseBaseClass::InfoCluster lInfo;
char lTemp[50];
sprintf(lTemp, "%s_THREAD[%d]","APU_ORB_RBRIEF",i);
lInfo.set_ACF(lTemp, (void *) &pProcessCalcRbrief[i]);
lInfo.push_PortName("INPUT");
mvInfoClusters.push_back(lInfo);
}
}
// Dynamic allocation of the data structures linked to the parallel processes
mpChunkOffsets = new vsdk::SUMat[mNrOfThreads];
mpAngles = new vsdk::SUMat[mNrOfThreads];
mpDescriptorCount = new vsdk::SUMat[mNrOfThreads];
mpBinPatternOut = new vsdk::SUMat[mNrOfThreads];
// Allocating memory and filling in the parameters that will be sent to APEX
mPatchSizeInPixels = vsdk::SUMat(1, 1, VSDK_CV_8SC1);
mRadiusInPixels = vsdk::SUMat(1, 1, VSDK_CV_8SC1);
mDescrSizeBytes = vsdk::SUMat(1, 1, VSDK_CV_8SC1);
mFastCornerList = vsdk::SUMat(1, maxNrOfKeypoints, VSDK_CV_32SC1);
mDescrSizeBytes.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u) = (int8_t)aDescriptorSizeInBytes;
flushUMat(mDescrSizeBytes);
mRadiusInPixels.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u) = (int8_t)aRadius;
flushUMat(mRadiusInPixels);
mPatchSizeInPixels.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u) = (int8_t)aPatchSize;
flushUMat(mPatchSizeInPixels);
// Splitting the work between the APEXes
int nrOfElements = mNrOfFeatures / mNrOfThreads;
int descrSizeInBytes = (int)(mDescrSizeBytes.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u));
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
mpChunkOffsets[threadId] = vsdk::SUMat(1, nrOfElements, VSDK_CV_32SC1);
mpAngles[threadId] = vsdk::SUMat(1, nrOfElements, VSDK_CV_16UC1);
mpDescriptorCount[threadId] = vsdk::SUMat(1, 1, VSDK_CV_32SC1);
mpBinPatternOut[threadId] = vsdk::SUMat(1, nrOfElements * descrSizeInBytes, VSDK_CV_8UC1);
// IC Orientation Initialization
status = pProcessCalcOrientation[threadId].Initialize();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// Connecting the external buffers to the kernel graphs
status = pProcessCalcOrientation[threadId].ConnectIO("PATCH_SIZE", mPatchSizeInPixels);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Connecting the external buffers to the kernel graphs
status = pProcessCalcOrientation[threadId].ConnectIO("RADIUS", mRadiusInPixels);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Connecting the external buffers to the kernel graphs
status = pProcessCalcOrientation[threadId].ConnectIO("OUTPUT", mpAngles[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Initializing the Rotated Brief for APEX
status = pProcessCalcRbrief[threadId].Initialize();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// BIT_PATTERN - Connecting the sampling pattern to the APEX
// This buffer will indicate to the hw what samples to pick from the input chunk
status = pProcessCalcRbrief[threadId].ConnectIO("BIT_PATTERN", msmplBitPattern);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// ORIENTATION - Connecting the orientation of each chunk to the APEX
status = pProcessCalcRbrief[threadId].ConnectIO("ORIENTATION", mpAngles[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// PATCH_SIZE - Connecting the dimension of the patch
status = pProcessCalcRbrief[threadId].ConnectIO("PATCH_SIZE", mPatchSizeInPixels);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// PATCH_SIZE - Connecting the size of the descriptor in bytes
status = pProcessCalcRbrief[threadId].ConnectIO("DESCR_SIZE_B", mDescrSizeBytes);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// COUNT_DESCR - Connecting the number of output descriptors
status = pProcessCalcRbrief[threadId].ConnectIO("COUNT_DESCR", mpDescriptorCount[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
}
// Class is initialized correctly only if the code arrives at this point
mInit = true;
// Everythig is fine until this point
return APEXCV_SUCCESS;
}
APEXCV_LIB_RESULT Orb::Detect(vsdk::SUMat &aInImg)
{
APEXCV_LIB_RESULT status = EXIT_FAILURE;
mInGrayScale = aInImg;
mImgW = aInImg.cols;
mImgH = aInImg.rows;
mImgSpan = aInImg.step[0];
unsigned char *lpBaseImg = aInImg.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
int patchSize;
if(!mPatchSizeInPixels.empty())
{
patchSize = (int)(*((int8_t *)mPatchSizeInPixels.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data));
}
else
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
if(mDistanceFromBorder >= (unsigned int)aInImg.cols)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(mDistanceFromBorder >= (unsigned int)aInImg.rows)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
// Initializing Fast9 detector
status = mFast9.Initialize(mFastCornerList,
aInImg,
mFastTh,
false,
mFastCirc,
true);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// Configure APEX to run with 64 CUs
status = mFast9.SelectApuConfiguration(ACF_APU_CFG__APU_0_CU_0_63_SMEM_0_3, mApexId);
if(status != APEXCV_SUCCESS)
{
return status;
}
// Start crunching the data in the APEX
status = mFast9.Process();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
// Return the number of detected keypoints
mDetectedKeypoints = mFast9.GetNrOfFeatures();
// mDetectedKeypoints is to allocate intermediate buffers so it needs to exit
if(mDetectedKeypoints == 0)
{
return APEXCV_SUCCESS;
}
if(mDetectedKeypoints < 0)
{
// This is the special case when FAST9 has an internal error when running in serialize mode!
// Check FAST9 APU kernel code to see the status!
printf("Fast9 went crazy !\n Status is: %d\n", mDetectedKeypoints);
return APEXCV_ERROR_FAILURE;
}
APU_ORB_ORIENTATION * pProcessCalcOrientation = (APU_ORB_ORIENTATION *) mpProcessCalcOrientation;
// FAST9 outputs a list of coordinates in the form of <x, y>
uint16_t *pOutPackedList = (uint16_t *)(mFastCornerList.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data);
// Constant value
const int harrisWindowSize = 7;
const int pair = 2;
// The keypoint array is not sorted at the beginning
bool isSorted = false;
for(int idx = 0; idx < mDetectedKeypoints; idx++)
{
// Read the keypoint coordinates
unsigned int x = pOutPackedList[pair * idx + 0];
unsigned int y = pOutPackedList[pair * idx + 1];
// Filter out the keypoints that are outside of the borderline
if((x > mDistanceFromBorder) &&
(y > mDistanceFromBorder) &&
(x < (mImgW - mDistanceFromBorder)) &&
(y < (mImgH - mDistanceFromBorder)))
{
// Place the pointer to the center of the keypoint
uint8_t *__restrict__ pCenter = (uint8_t * __restrict__) & lpBaseImg[y * mImgSpan + x];
// This variable will be inserted in the keypoint array
Orb::Corner keypoint;
keypoint.x = x;
keypoint.y = y;
keypoint.strength = HarrisScore(pCenter, mImgSpan, harrisWindowSize, mHarrisK);
// Don't keep more keypoints than you need
if(mKeypoints.size() < mNrOfFeatures)
{
// Place the values into the vector in no particular order
mKeypoints.push_back(keypoint);
}
else
{
// "mKeypoints" is sorted only once when its size is equal to the desired nr of mKeypoints
if(isSorted == false)
{
// Sort the mKeypoints
std::sort(mKeypoints.begin(), mKeypoints.end(), CmpGreaterFeature);
isSorted = true;
}
// The new keypoint is compared to the last element in the vector which is also the smallest
// It's insert in the queue only if CmpGreaterFeature() returns bool true
if(CmpGreaterFeature(keypoint, mKeypoints.back()))
{
// Remove the last element
mKeypoints.pop_back();
// Place the new element in the vector
mKeypoints.insert(std::lower_bound(mKeypoints.begin(), mKeypoints.end(), keypoint, CmpGreaterFeature), keypoint);
}
}
}
}
// If fast detects a keypoint, find it's corresponding "cornerness" from Harris
// Orb needs the best FAST points based on the Harris score
// Sort only if fast did not find enough mKeypoints
if(isSorted == false)
{
std::sort(mKeypoints.begin(), mKeypoints.end(), CmpGreaterFeature);
}
// After detection update the number of keypoints
mNrOfFeatures = mKeypoints.size();
if(0 == mNrOfFeatures)
{
return APEXCV_SUCCESS;
}
// Calculate chunk offsets
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
ACF_APU_CFG apuConfig = ACF_APU_CFG__APU_0_CU_0_31_SMEM_0_1;
if(threadId)
{
apuConfig = ACF_APU_CFG__APU_1_CU_32_63_SMEM_2_3;
}
// Creating a subvector of keypoints for each APU
int nrOfElem = (mNrOfFeatures / mNrOfThreads);
int start = threadId * nrOfElem;
int stop = start + nrOfElem;
std::vector<Orb::Corner> keypointSubVector(mKeypoints.begin() + start, mKeypoints.begin() + stop);
// Calculating the chunk offsets for each of the detected keypoints
status = CalcChunkOffsets(mInGrayScale, keypointSubVector, nrOfElem, patchSize, mpChunkOffsets[threadId]);
// Exit with error
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_INTERNAL_ERROR;
}
// APUs must run only with 32 active CUs because of DMA size
status = pProcessCalcOrientation[threadId].SelectApuConfiguration(apuConfig, (int32_t) mApexId);
// Exit with error
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_SELECTAPUCONFIG;
}
status = pProcessCalcOrientation[threadId].ConnectIndirectInput("INPUT", aInImg, mpChunkOffsets[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Start all processes
status = pProcessCalcOrientation[threadId].Start();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Wait for the APU processes to finish
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
status = pProcessCalcOrientation[threadId].Wait();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Exit the function
return APEXCV_SUCCESS;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
APEXCV_LIB_RESULT Orb::SetBriefSamplingPattern(vsdk::SUMat &aInBitPattern)
{
// Helper function used to connect the sampling pattern to the apex graph
if(mInit == true)
{
APEXCV_LIB_RESULT status;
APU_ORB_RBRIEF * pProcessCalcRbrief = (APU_ORB_RBRIEF *) mpProcessCalcRbrief;
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
status = pProcessCalcRbrief[threadId].ConnectIO("BIT_PATTERN", aInBitPattern);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
}
}
else
{
// Exit with error
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// Exit the function
return APEXCV_SUCCESS;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
APEXCV_LIB_RESULT Orb::Compute(vsdk::SUMat &aInSmoothedImg,
vsdk::SUMat &aOutDescriptors)
{
APEXCV_LIB_RESULT status;
APU_ORB_RBRIEF * pProcessCalcRbrief = (APU_ORB_RBRIEF *) mpProcessCalcRbrief;
if ((0 == mNrOfFeatures) || (0 == mDetectedKeypoints))
{
return APEXCV_SUCCESS;
}
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
ACF_APU_CFG apuConfig = ACF_APU_CFG__APU_0_CU_0_31_SMEM_0_1;
if(threadId)
{
apuConfig = ACF_APU_CFG__APU_1_CU_32_63_SMEM_2_3;
}
status = pProcessCalcRbrief[threadId].ConnectIndirectInput("INPUT", aInSmoothedImg, mpChunkOffsets[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
status = pProcessCalcRbrief[threadId].ConnectIO("OUTPUT", mpBinPatternOut[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
status = pProcessCalcRbrief[threadId].SelectApuConfiguration(apuConfig, (int32_t)mApexId);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_SELECTAPUCONFIG;
}
status = pProcessCalcRbrief[threadId].Start();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Wait for the APU processes to finish
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
status = pProcessCalcRbrief[threadId].Wait();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Pointing to the base of the output container
uint8_t *pBase = (uint8_t *)aOutDescriptors.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
// Calculating the necessary offset to jump between thread output clusters
int descrSizeB = (int)(mDescrSizeBytes.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u));
int nrDescrToCopy = (mNrOfFeatures / mNrOfThreads);
int clusterSizeB = (descrSizeB * nrDescrToCopy);
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
uint8_t *pDst = (uint8_t *)(pBase + threadId * clusterSizeB);
uint8_t *pSrc = (uint8_t *)mpBinPatternOut[threadId].getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
memcpy(pDst, pSrc, clusterSizeB);
}
// Everything is fine until here
return APEXCV_SUCCESS;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetPatchSize()
{
return mPatchSizeInPixels;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetRadius()
{
return mRadiusInPixels;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetFastOut()
{
return mFastCornerList;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
int Orb::GetNrOfDetectedKeypoints()
{
return mDetectedKeypoints;
}
int Orb::GetNrOfValidKeypoints()
{
return mNrOfFeatures;
}
bool Orb::DataIsValid()
{
return ((mNrOfFeatures != 0) && (mDetectedKeypoints != 0));
}
vsdk::SUMat &Orb::GetChunkOffsets()
{
if(DataIsValid() == true)
{
// Allocating the container
mAllChunkOffsets = vsdk::SUMat(1, mNrOfFeatures, VSDK_CV_32S);
// Pointing to the base of the container
uint8_t *pBaseDst = (uint8_t *)mAllChunkOffsets.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
// Size of the cluster
int clusterSizeB = (int)(mpChunkOffsets[threadId].total() * mpChunkOffsets[threadId].elemSize());
uint8_t *pSrc = (uint8_t *)mpChunkOffsets[threadId].getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
uint8_t *pDst = (uint8_t *)(pBaseDst + threadId * clusterSizeB);
memcpy(pDst, pSrc, clusterSizeB);
}
}
return mAllChunkOffsets;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetIcoAngles()
{
if(DataIsValid() == true)
{
// Allocating the container
mAllAngles = vsdk::SUMat(1, mNrOfFeatures, VSDK_CV_16U);
// Pointing to the base of the container
uint8_t *pBaseDst = (uint8_t *)mAllAngles.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
// Size of the cluster
int clusterSizeB = (int)(mpAngles[threadId].total() * mpAngles[threadId].elemSize());
uint8_t *pSrc = (uint8_t *)mpAngles[threadId].getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
OAL_MemoryFlushAndInvalidate((void *)pSrc, clusterSizeB);
uint8_t *pDst = (uint8_t *)(pBaseDst + threadId * clusterSizeB);
memcpy(pDst, pSrc, clusterSizeB);
}
}
return mAllAngles;
}
std::vector<Orb::Corner> &Orb::GetKeypoints()
{
return mKeypoints;
}
} /* namespace apexcv */
| 34.735417
| 162
| 0.55314
|
intesight
|
16782b280ef5d9a2ade28b1763bfa3d83086b2bd
| 15,704
|
cpp
|
C++
|
src/main.cpp
|
HTLife/Logger2
|
0810e72b3b94eaf164ad98a70feae9ad80d61b79
|
[
"BSD-2-Clause"
] | null | null | null |
src/main.cpp
|
HTLife/Logger2
|
0810e72b3b94eaf164ad98a70feae9ad80d61b79
|
[
"BSD-2-Clause"
] | null | null | null |
src/main.cpp
|
HTLife/Logger2
|
0810e72b3b94eaf164ad98a70feae9ad80d61b79
|
[
"BSD-2-Clause"
] | null | null | null |
#include "main.h"
int find_argument(int argc, char** argv, const char* argument_name)
{
for(int i = 1; i < argc; ++i)
{
if(strcmp(argv[i], argument_name) == 0)
{
return (i);
}
}
return (-1);
}
int parse_argument(int argc, char** argv, const char* str, int &val)
{
int index = find_argument(argc, argv, str) + 1;
if(index > 0 && index < argc)
{
val = atoi(argv[index]);
}
return (index - 1);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
int width = 640;
int height = 480;
int fps = 30;
int tcp = 0;
parse_argument(argc, argv, "-w", width);
parse_argument(argc, argv, "-h", height);
parse_argument(argc, argv, "-f", fps);
tcp = find_argument(argc, argv, "-t") != -1;
MainWindow * window = new MainWindow(width, height, fps, tcp);
window->show();
return app.exec();
}
MainWindow::MainWindow(int width, int height, int fps, bool tcp)
: logger(0),
depthImage(width, height, QImage::Format_RGB888),
rgbImage(width, height, QImage::Format_RGB888),
recording(false),
lastDrawn(-1),
width(width),
height(height),
fps(fps),
tcp(tcp),
comms(tcp ? new Communicator : 0)
{
this->setMaximumSize(width * 2, height + 160);
this->setMinimumSize(width * 2, height + 160);
QVBoxLayout * wrapperLayout = new QVBoxLayout;
QHBoxLayout * mainLayout = new QHBoxLayout;
QHBoxLayout * fileLayout = new QHBoxLayout;
QHBoxLayout * optionLayout = new QHBoxLayout;
QHBoxLayout * buttonLayout = new QHBoxLayout;
wrapperLayout->addLayout(mainLayout);
depthLabel = new QLabel(this);
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
mainLayout->addWidget(depthLabel);
imageLabel = new QLabel(this);
imageLabel->setPixmap(QPixmap::fromImage(rgbImage));
mainLayout->addWidget(imageLabel);
wrapperLayout->addLayout(fileLayout);
wrapperLayout->addLayout(optionLayout);
QLabel * logLabel = new QLabel("Log file: ", this);
logLabel->setMaximumWidth(logLabel->fontMetrics().boundingRect(logLabel->text()).width());
fileLayout->addWidget(logLabel);
logFile = new QLabel(this);
logFile->setTextInteractionFlags(Qt::TextSelectableByMouse);
logFile->setStyleSheet("border: 1px solid grey");
fileLayout->addWidget(logFile);
#ifdef __APPLE__
int cushion = 25;
#else
int cushion = 10;
#endif
browseButton = new QPushButton("Browse", this);
browseButton->setMaximumWidth(browseButton->fontMetrics().boundingRect(browseButton->text()).width() + cushion);
connect(browseButton, SIGNAL(clicked()), this, SLOT(fileBrowse()));
fileLayout->addWidget(browseButton);
dateNameButton = new QPushButton("Date filename", this);
dateNameButton->setMaximumWidth(dateNameButton->fontMetrics().boundingRect(dateNameButton->text()).width() + cushion);
connect(dateNameButton, SIGNAL(clicked()), this, SLOT(dateFilename()));
fileLayout->addWidget(dateNameButton);
autoExposure = new QCheckBox("Auto Exposure");
autoExposure->setChecked(false);
autoWhiteBalance = new QCheckBox("Auto White Balance");
autoWhiteBalance->setChecked(false);
compressed = new QCheckBox("Compressed");
compressed->setChecked(true);
memoryRecord = new QCheckBox("Record to RAM");
memoryRecord->setChecked(false);
memoryStatus = new QLabel("");
connect(autoExposure, SIGNAL(stateChanged(int)), this, SLOT(setExposure()));
connect(autoWhiteBalance, SIGNAL(stateChanged(int)), this, SLOT(setWhiteBalance()));
connect(compressed, SIGNAL(released()), this, SLOT(setCompressed()));
connect(memoryRecord, SIGNAL(stateChanged(int)), this, SLOT(setMemoryRecord()));
optionLayout->addWidget(autoExposure);
optionLayout->addWidget(autoWhiteBalance);
optionLayout->addWidget(compressed);
optionLayout->addWidget(memoryRecord);
optionLayout->addWidget(memoryStatus);
wrapperLayout->addLayout(buttonLayout);
startStop = new QPushButton(tcp ? "Stream && Record" : "Record", this);
connect(startStop, SIGNAL(clicked()), this, SLOT(recordToggle()));
buttonLayout->addWidget(startStop);
QPushButton * quitButton = new QPushButton("Quit", this);
connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));
buttonLayout->addWidget(quitButton);
setLayout(wrapperLayout);
startStop->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
quitButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QFont currentFont = startStop->font();
currentFont.setPointSize(currentFont.pointSize() + 8);
startStop->setFont(currentFont);
quitButton->setFont(currentFont);
painter = new QPainter(&depthImage);
painter->setPen(Qt::green);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, "Attempting to start OpenNI2...");
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
#ifndef OS_WINDOWS
char * homeDir = getenv("HOME");
logFolder.append(homeDir);
logFolder.append("/");
#else
char * homeDrive = getenv("HOMEDRIVE");
char * homeDir = getenv("HOMEPATH");
logFolder.append(homeDrive);
logFolder.append("\\");
logFolder.append(homeDir);
logFolder.append("\\");
#endif
logFolder.append("Kinect_Logs");
boost::filesystem::path p(logFolder.c_str());
boost::filesystem::create_directory(p);
logFile->setText(QString::fromStdString(getNextFilename()));
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timerCallback()));
timer->start(15);
}
MainWindow::~MainWindow()
{
timer->stop();
delete logger;
}
std::string MainWindow::getNextFilename()
{
static char const* const fmt = "%Y-%m-%d";
std::ostringstream ss;
ss.imbue(std::locale(std::cout.getloc(), new boost::gregorian::date_facet(fmt)));
ss << boost::gregorian::day_clock::universal_day();
std::string dateFilename;
if(!lastFilename.length())
{
dateFilename = ss.str();
}
else
{
dateFilename = lastFilename;
}
std::string currentFile;
int currentNum = 0;
while(true)
{
std::stringstream strs;
strs << logFolder;
#ifndef OS_WINDOWS
strs << "/";
#else
strs << "\\";
#endif
strs << dateFilename << ".";
strs << std::setfill('0') << std::setw(2) << currentNum;
strs << ".klg";
if(!boost::filesystem::exists(strs.str().c_str()))
{
return strs.str();
}
currentNum++;
}
return "";
}
void MainWindow::dateFilename()
{
lastFilename.clear();
logFile->setText(QString::fromStdString(getNextFilename()));
}
void MainWindow::fileBrowse()
{
QString message = "Log file selection";
QString types = "All files (*)";
QString fileName = QFileDialog::getSaveFileName(this, message, ".", types);
if(!fileName.isEmpty())
{
if(!fileName.contains(".klg", Qt::CaseInsensitive))
{
fileName.append(".klg");
}
#ifndef OS_WINDOWS
logFolder = fileName.toStdString().substr(0, fileName.toStdString().rfind("/"));
lastFilename = fileName.toStdString().substr(fileName.toStdString().rfind("/") + 1, fileName.toStdString().rfind(".klg"));
#else
logFolder = fileName.toStdString().substr(0, fileName.toStdString().rfind("\\"));
lastFilename = fileName.toStdString().substr(fileName.toStdString().rfind("\\") + 1, fileName.toStdString().rfind(".klg"));
#endif
lastFilename = lastFilename.substr(0, lastFilename.size() - 4);
logFile->setText(QString::fromStdString(getNextFilename()));
}
}
void MainWindow::recordToggle()
{
if(!recording)
{
if(logFile->text().length() == 0)
{
QMessageBox::information(this, "Information", "You have not selected an output log file");
}
else
{
memoryRecord->setEnabled(false);
compressed->setEnabled(false);
logger->startWriting(logFile->text().toStdString());
startStop->setText("Stop");
recording = true;
}
}
else
{
logger->stopWriting(this);
memoryRecord->setEnabled(true);
compressed->setEnabled(true);
startStop->setText(tcp ? "Stream && Record" : "Record");
recording = false;
logFile->setText(QString::fromStdString(getNextFilename()));
}
}
void MainWindow::setExposure()
{
logger->getOpenNI2Interface()->setAutoExposure(autoExposure->isChecked());
}
void MainWindow::setWhiteBalance()
{
logger->getOpenNI2Interface()->setAutoWhiteBalance(autoWhiteBalance->isChecked());
}
void MainWindow::setCompressed()
{
if(compressed->isChecked())
{
logger->setCompressed(compressed->isChecked());
}
else if(!compressed->isChecked())
{
if(QMessageBox::question(this, "Compression?", "If you don't have a fast machine or an SSD hard drive you might drop frames, are you sure?", "&No", "&Yes", QString::null, 0, 1 ))
{
logger->setCompressed(compressed->isChecked());
}
else
{
compressed->setChecked(true);
logger->setCompressed(compressed->isChecked());
}
}
}
void MainWindow::setMemoryRecord()
{
logger->setMemoryRecord(memoryRecord->isChecked());
}
void MainWindow::quit()
{
if(QMessageBox::question(this, "Quit?", "Are you sure you want to quit?", "&No", "&Yes", QString::null, 0, 1 ))
{
if(recording)
{
recordToggle();
}
this->close();
}
}
void MainWindow::timerCallback()
{
int64_t usedMemory = MemoryBuffer::getUsedSystemMemory();
int64_t totalMemory = MemoryBuffer::getTotalSystemMemory();
int64_t processMemory = MemoryBuffer::getProcessMemory();
float usedGB = (usedMemory / (float)1073741824);
float totalGB = (totalMemory / (float)1073741824);
#ifdef __APPLE__
float processGB = (processMemory / (float)1073741824);
#else
float processGB = (processMemory / (float)1048576);
#endif
QString memoryInfo = QString::number(usedGB, 'f', 2) + "/" + QString::number(totalGB, 'f', 2) + "GB memory used, " + QString::number(processGB, 'f', 2) + "GB by Logger2";
memoryStatus->setText(memoryInfo);
if(!logger)
{
if(frameStats.size() >= 15)
{
logger = new Logger2(width, height, fps, tcp, this->logFolder);
if(!logger->getOpenNI2Interface()->ok())
{
memset(depthImage.bits(), 0, width * height * 3);
painter->setPen(Qt::red);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, "Attempting to start OpenNI2... failed!");
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
QMessageBox msgBox;
msgBox.setText("Sorry, OpenNI2 is having trouble (it's still in beta). Please try running Logger2 again.");
msgBox.setDetailedText(QString::fromStdString(logger->getOpenNI2Interface()->error()));
msgBox.exec();
exit(-1);
}
else
{
memset(depthImage.bits(), 0, width * height * 3);
painter->setPen(Qt::green);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, "Starting stream...");
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
}
return;
}
else
{
frameStats.push_back(0);
return;
}
}
int lastDepth = logger->getOpenNI2Interface()->latestDepthIndex.getValue();
if(lastDepth == -1)
{
return;
}
int bufferIndex = lastDepth % OpenNI2Interface::numBuffers;
if(bufferIndex == lastDrawn)
{
return;
}
if(lastFrameTime == logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second)
{
return;
}
memcpy(&depthBuffer[0], logger->getOpenNI2Interface()->frameBuffers[bufferIndex].first.first, width * height * 2);
if(!(tcp && recording))
{
memcpy(rgbImage.bits(), logger->getOpenNI2Interface()->frameBuffers[bufferIndex].first.second, width * height * 3);
}
cv::Mat1w depth(height, width, (unsigned short *)&depthBuffer[0]);
normalize(depth, tmp, 0, 255, cv::NORM_MINMAX, 0);
cv::Mat3b depthImg(height, width, (cv::Vec<unsigned char, 3> *)depthImage.bits());
cv::cvtColor(tmp, depthImg, CV_GRAY2RGB);
painter->setPen(recording ? Qt::red : Qt::green);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, recording ? (tcp ? "Streaming & Recording" : "Recording") : "Viewing");
frameStats.push_back(abs(logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second - lastFrameTime));
if(frameStats.size() > 15)
{
frameStats.erase(frameStats.begin());
}
int64_t speedSum = 0;
for(unsigned int i = 0; i < frameStats.size(); i++)
{
speedSum += frameStats[i];
}
int64_t avgSpeed = (float)speedSum / (float)frameStats.size();
float fps = 1.0f / ((float)avgSpeed / 1000000.0f);
fps = floor(fps * 10.0f);
fps /= 10.0f;
std::stringstream str;
str << (int)ceil(fps) << "fps";
lastFrameTime = logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second;
painter->setFont(QFont("Arial", 24));
#ifdef __APPLE__
int offset = 20;
#else
int offset = 10;
#endif
painter->drawText(10, height - offset, QString::fromStdString(str.str()));
if(tcp)
{
cv::Mat3b modelImg(height / 4, width / 4);
cv::Mat3b modelImgBig(height, width, (cv::Vec<unsigned char, 3> *)rgbImage.bits());
std::string dataStr = comms->tryRecv();
if(dataStr.length())
{
std::vector<char> data(dataStr.begin(), dataStr.end());
modelImg = cv::imdecode(cv::Mat(data), 1);
cv::Size bigSize(width, height);
cv::resize(modelImg, modelImgBig, bigSize, 0, 0);
}
}
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
imageLabel->setPixmap(QPixmap::fromImage(rgbImage));
if(logger->getMemoryBuffer().memoryFull.getValue())
{
assert(recording);
recordToggle();
QMessageBox msgBox;
msgBox.setText("Recording has been automatically stopped to prevent running out of system memory.");
msgBox.exec();
}
std::pair<bool, int64_t> dropping = logger->dropping.getValue();
if(!tcp && dropping.first)
{
assert(recording);
recordToggle();
std::stringstream strs;
strs << "Recording has been automatically stopped. Logging experienced a jump of " << dropping.second / 1000
<< "ms, indicating a drop below 10fps. Please try enabling compression or recording to RAM to prevent this.";
QMessageBox msgBox;
msgBox.setText(QString::fromStdString(strs.str()));
msgBox.exec();
}
}
| 29.969466
| 187
| 0.604687
|
HTLife
|
167b87db97246dbaeb9eb96becfa5211c30e744f
| 16,137
|
cpp
|
C++
|
src/gui/color.cpp
|
strandfield/yasl
|
d109eb3166184febfe48d1a2d1c96683c4a813f7
|
[
"MIT"
] | 1
|
2020-12-28T01:41:35.000Z
|
2020-12-28T01:41:35.000Z
|
src/gui/color.cpp
|
strandfield/yasl
|
d109eb3166184febfe48d1a2d1c96683c4a813f7
|
[
"MIT"
] | null | null | null |
src/gui/color.cpp
|
strandfield/yasl
|
d109eb3166184febfe48d1a2d1c96683c4a813f7
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2018 Vincent Chambrin
// This file is part of the Yasl project
// For conditions of distribution and use, see copyright notice in LICENSE
#include "yasl/gui/color.h"
#include "yasl/common/binding/class.h"
#include "yasl/common/binding/default_arguments.h"
#include "yasl/common/binding/namespace.h"
#include "yasl/common/enums.h"
#include "yasl/common/genericvarianthandler.h"
#include "yasl/core/datastream.h"
#include "yasl/core/enums.h"
#include "yasl/core/string.h"
#include "yasl/gui/color.h"
#include <script/classbuilder.h>
#include <script/enumbuilder.h>
static void register_color_spec_enum(script::Class color)
{
using namespace script;
Enum spec = color.newEnum("Spec").setId(script::Type::QColorSpec).get();
spec.addValue("Invalid", QColor::Invalid);
spec.addValue("Rgb", QColor::Rgb);
spec.addValue("Hsv", QColor::Hsv);
spec.addValue("Cmyk", QColor::Cmyk);
spec.addValue("Hsl", QColor::Hsl);
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
static void register_color_name_format_enum(script::Class color)
{
using namespace script;
Enum name_format = color.newEnum("NameFormat").setId(script::Type::QColorNameFormat).get();
name_format.addValue("HexRgb", QColor::HexRgb);
name_format.addValue("HexArgb", QColor::HexArgb);
}
#endif
static void register_color_class(script::Namespace ns)
{
using namespace script;
Class color = ns.newClass("Color").setId(script::Type::QColor).get();
register_color_spec_enum(color);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
register_color_name_format_enum(color);
#endif
// QColor();
bind::default_constructor<QColor>(color).create();
// ~QColor();
bind::destructor<QColor>(color).create();
// QColor(Qt::GlobalColor);
bind::constructor<QColor, Qt::GlobalColor>(color).create();
// QColor(int, int, int, int = 255);
bind::constructor<QColor, int, int, int, int>(color)
.apply(bind::default_arguments(255)).create();
// QColor(QRgb);
/// TODO: QColor(QRgb);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// QColor(QRgba64);
/// TODO: QColor(QRgba64);
#endif
// QColor(const QString &);
bind::constructor<QColor, const QString &>(color).create();
// QColor(QStringView);
/// TODO: QColor(QStringView);
// QColor(const char *);
/// TODO: QColor(const char *);
// QColor(QLatin1String);
/// TODO: QColor(QLatin1String);
// QColor(QColor::Spec);
bind::constructor<QColor, QColor::Spec>(color).create();
// QColor(const QColor &);
bind::constructor<QColor, const QColor &>(color).create();
// QColor(QColor &&);
bind::constructor<QColor, QColor &&>(color).create();
// QColor & operator=(QColor &&);
bind::memop_assign<QColor, QColor &&>(color);
// QColor & operator=(const QColor &);
bind::memop_assign<QColor, const QColor &>(color);
// QColor & operator=(Qt::GlobalColor);
bind::memop_assign<QColor, Qt::GlobalColor>(color);
// bool isValid() const;
bind::member_function<QColor, bool, &QColor::isValid>(color, "isValid").create();
// QString name() const;
bind::member_function<QColor, QString, &QColor::name>(color, "name").create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
// QString name(QColor::NameFormat) const;
bind::member_function<QColor, QString, QColor::NameFormat, &QColor::name>(color, "name").create();
#endif
// void setNamedColor(const QString &);
bind::void_member_function<QColor, const QString &, &QColor::setNamedColor>(color, "setNamedColor").create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
// void setNamedColor(QStringView);
/// TODO: void setNamedColor(QStringView);
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
// void setNamedColor(QLatin1String);
/// TODO: void setNamedColor(QLatin1String);
#endif
// static QStringList colorNames();
bind::static_member_function<QColor, QStringList, &QColor::colorNames>(color, "colorNames").create();
// QColor::Spec spec() const;
bind::member_function<QColor, QColor::Spec, &QColor::spec>(color, "spec").create();
// int alpha() const;
bind::member_function<QColor, int, &QColor::alpha>(color, "alpha").create();
// void setAlpha(int);
bind::void_member_function<QColor, int, &QColor::setAlpha>(color, "setAlpha").create();
// qreal alphaF() const;
bind::member_function<QColor, qreal, &QColor::alphaF>(color, "alphaF").create();
// void setAlphaF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setAlphaF>(color, "setAlphaF").create();
// int red() const;
bind::member_function<QColor, int, &QColor::red>(color, "red").create();
// int green() const;
bind::member_function<QColor, int, &QColor::green>(color, "green").create();
// int blue() const;
bind::member_function<QColor, int, &QColor::blue>(color, "blue").create();
// void setRed(int);
bind::void_member_function<QColor, int, &QColor::setRed>(color, "setRed").create();
// void setGreen(int);
bind::void_member_function<QColor, int, &QColor::setGreen>(color, "setGreen").create();
// void setBlue(int);
bind::void_member_function<QColor, int, &QColor::setBlue>(color, "setBlue").create();
// qreal redF() const;
bind::member_function<QColor, qreal, &QColor::redF>(color, "redF").create();
// qreal greenF() const;
bind::member_function<QColor, qreal, &QColor::greenF>(color, "greenF").create();
// qreal blueF() const;
bind::member_function<QColor, qreal, &QColor::blueF>(color, "blueF").create();
// void setRedF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setRedF>(color, "setRedF").create();
// void setGreenF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setGreenF>(color, "setGreenF").create();
// void setBlueF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setBlueF>(color, "setBlueF").create();
// void getRgb(int *, int *, int *, int *) const;
/// TODO: void getRgb(int *, int *, int *, int *) const;
// void setRgb(int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, &QColor::setRgb>(color, "setRgb")
.apply(bind::default_arguments(255)).create();
// void getRgbF(qreal *, qreal *, qreal *, qreal *) const;
/// TODO: void getRgbF(qreal *, qreal *, qreal *, qreal *) const;
// void setRgbF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, &QColor::setRgbF>(color, "setRgbF")
.apply(bind::default_arguments(qreal(1.0))).create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// QRgba64 rgba64() const;
/// TODO: QRgba64 rgba64() const;
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// void setRgba64(QRgba64);
/// TODO: void setRgba64(QRgba64);
#endif
// QRgb rgba() const;
/// TODO: QRgb rgba() const;
// void setRgba(QRgb);
/// TODO: void setRgba(QRgb);
// QRgb rgb() const;
/// TODO: QRgb rgb() const;
// void setRgb(QRgb);
/// TODO: void setRgb(QRgb);
// int hue() const;
bind::member_function<QColor, int, &QColor::hue>(color, "hue").create();
// int saturation() const;
bind::member_function<QColor, int, &QColor::saturation>(color, "saturation").create();
// int hsvHue() const;
bind::member_function<QColor, int, &QColor::hsvHue>(color, "hsvHue").create();
// int hsvSaturation() const;
bind::member_function<QColor, int, &QColor::hsvSaturation>(color, "hsvSaturation").create();
// int value() const;
bind::member_function<QColor, int, &QColor::value>(color, "value").create();
// qreal hueF() const;
bind::member_function<QColor, qreal, &QColor::hueF>(color, "hueF").create();
// qreal saturationF() const;
bind::member_function<QColor, qreal, &QColor::saturationF>(color, "saturationF").create();
// qreal hsvHueF() const;
bind::member_function<QColor, qreal, &QColor::hsvHueF>(color, "hsvHueF").create();
// qreal hsvSaturationF() const;
bind::member_function<QColor, qreal, &QColor::hsvSaturationF>(color, "hsvSaturationF").create();
// qreal valueF() const;
bind::member_function<QColor, qreal, &QColor::valueF>(color, "valueF").create();
// void getHsv(int *, int *, int *, int *) const;
/// TODO: void getHsv(int *, int *, int *, int *) const;
// void setHsv(int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, &QColor::setHsv>(color, "setHsv")
.apply(bind::default_arguments(255)).create();
// void getHsvF(qreal *, qreal *, qreal *, qreal *) const;
/// TODO: void getHsvF(qreal *, qreal *, qreal *, qreal *) const;
// void setHsvF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, &QColor::setHsvF>(color, "setHsvF")
.apply(bind::default_arguments(qreal(1.0))).create();
// int cyan() const;
bind::member_function<QColor, int, &QColor::cyan>(color, "cyan").create();
// int magenta() const;
bind::member_function<QColor, int, &QColor::magenta>(color, "magenta").create();
// int yellow() const;
bind::member_function<QColor, int, &QColor::yellow>(color, "yellow").create();
// int black() const;
bind::member_function<QColor, int, &QColor::black>(color, "black").create();
// qreal cyanF() const;
bind::member_function<QColor, qreal, &QColor::cyanF>(color, "cyanF").create();
// qreal magentaF() const;
bind::member_function<QColor, qreal, &QColor::magentaF>(color, "magentaF").create();
// qreal yellowF() const;
bind::member_function<QColor, qreal, &QColor::yellowF>(color, "yellowF").create();
// qreal blackF() const;
bind::member_function<QColor, qreal, &QColor::blackF>(color, "blackF").create();
// void getCmyk(int *, int *, int *, int *, int *);
/// TODO: void getCmyk(int *, int *, int *, int *, int *);
// void setCmyk(int, int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, int, &QColor::setCmyk>(color, "setCmyk")
.apply(bind::default_arguments(255)).create();
// void getCmykF(qreal *, qreal *, qreal *, qreal *, qreal *);
/// TODO: void getCmykF(qreal *, qreal *, qreal *, qreal *, qreal *);
// void setCmykF(qreal, qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, qreal, &QColor::setCmykF>(color, "setCmykF")
.apply(bind::default_arguments(qreal(1.0))).create();
// int hslHue() const;
bind::member_function<QColor, int, &QColor::hslHue>(color, "hslHue").create();
// int hslSaturation() const;
bind::member_function<QColor, int, &QColor::hslSaturation>(color, "hslSaturation").create();
// int lightness() const;
bind::member_function<QColor, int, &QColor::lightness>(color, "lightness").create();
// qreal hslHueF() const;
bind::member_function<QColor, qreal, &QColor::hslHueF>(color, "hslHueF").create();
// qreal hslSaturationF() const;
bind::member_function<QColor, qreal, &QColor::hslSaturationF>(color, "hslSaturationF").create();
// qreal lightnessF() const;
bind::member_function<QColor, qreal, &QColor::lightnessF>(color, "lightnessF").create();
// void getHsl(int *, int *, int *, int *) const;
/// TODO: void getHsl(int *, int *, int *, int *) const;
// void setHsl(int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, &QColor::setHsl>(color, "setHsl")
.apply(bind::default_arguments(255)).create();
// void getHslF(qreal *, qreal *, qreal *, qreal *) const;
/// TODO: void getHslF(qreal *, qreal *, qreal *, qreal *) const;
// void setHslF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, &QColor::setHslF>(color, "setHslF")
.apply(bind::default_arguments(qreal(1.0))).create();
// QColor toRgb() const;
bind::member_function<QColor, QColor, &QColor::toRgb>(color, "toRgb").create();
// QColor toHsv() const;
bind::member_function<QColor, QColor, &QColor::toHsv>(color, "toHsv").create();
// QColor toCmyk() const;
bind::member_function<QColor, QColor, &QColor::toCmyk>(color, "toCmyk").create();
// QColor toHsl() const;
bind::member_function<QColor, QColor, &QColor::toHsl>(color, "toHsl").create();
// QColor convertTo(QColor::Spec) const;
bind::member_function<QColor, QColor, QColor::Spec, &QColor::convertTo>(color, "convertTo").create();
// static QColor fromRgb(QRgb);
/// TODO: static QColor fromRgb(QRgb);
// static QColor fromRgba(QRgb);
/// TODO: static QColor fromRgba(QRgb);
// static QColor fromRgb(int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, &QColor::fromRgb>(color, "fromRgb")
.apply(bind::default_arguments(255)).create();
// static QColor fromRgbF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, &QColor::fromRgbF>(color, "fromRgbF")
.apply(bind::default_arguments(qreal(1.0))).create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// static QColor fromRgba64(ushort, ushort, ushort, ushort);
/// TODO: static QColor fromRgba64(ushort, ushort, ushort, ushort);
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// static QColor fromRgba64(QRgba64);
/// TODO: static QColor fromRgba64(QRgba64);
#endif
// static QColor fromHsv(int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, &QColor::fromHsv>(color, "fromHsv")
.apply(bind::default_arguments(255)).create();
// static QColor fromHsvF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, &QColor::fromHsvF>(color, "fromHsvF")
.apply(bind::default_arguments(qreal(1.0))).create();
// static QColor fromCmyk(int, int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, int, &QColor::fromCmyk>(color, "fromCmyk")
.apply(bind::default_arguments(255)).create();
// static QColor fromCmykF(qreal, qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, qreal, &QColor::fromCmykF>(color, "fromCmykF")
.apply(bind::default_arguments(qreal(1.0))).create();
// static QColor fromHsl(int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, &QColor::fromHsl>(color, "fromHsl")
.apply(bind::default_arguments(255)).create();
// static QColor fromHslF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, &QColor::fromHslF>(color, "fromHslF")
.apply(bind::default_arguments(qreal(1.0))).create();
// QColor light(int) const;
bind::member_function<QColor, QColor, int, &QColor::light>(color, "light").create();
// QColor lighter(int = 150) const;
bind::member_function<QColor, QColor, int, &QColor::lighter>(color, "lighter")
.apply(bind::default_arguments(150)).create();
// QColor dark(int) const;
bind::member_function<QColor, QColor, int, &QColor::dark>(color, "dark").create();
// QColor darker(int) const;
bind::member_function<QColor, QColor, int, &QColor::darker>(color, "darker").create();
// bool operator==(const QColor &) const;
bind::memop_eq<QColor, const QColor &>(color);
// bool operator!=(const QColor &) const;
bind::memop_neq<QColor, const QColor &>(color);
// static bool isValidColor(const QString &);
bind::static_member_function<QColor, bool, const QString &, &QColor::isValidColor>(color, "isValidColor").create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
// static bool isValidColor(QStringView);
/// TODO: static bool isValidColor(QStringView);
#endif
// static bool isValidColor(QLatin1String);
/// TODO: static bool isValidColor(QLatin1String);
yasl::registerVariantHandler<yasl::GenericVariantHandler<QColor, QMetaType::QColor>>();
}
void register_color_file(script::Namespace gui)
{
using namespace script;
Namespace ns = gui;
register_color_class(ns);
// QDebug operator<<(QDebug, const QColor &);
/// TODO: QDebug operator<<(QDebug, const QColor &);
// QDataStream & operator<<(QDataStream &, const QColor &);
bind::op_put_to<QDataStream &, const QColor &>(ns);
// QDataStream & operator>>(QDataStream &, QColor &);
bind::op_read_from<QDataStream &, QColor &>(ns);
}
| 47.60177
| 121
| 0.684576
|
strandfield
|
167d1a6a38f47e1add1967c79c3dcb161c3cf94f
| 2,821
|
cpp
|
C++
|
src/Common/TokenType.cpp
|
Morphlng/cploxplox
|
f7f64c535b76bdaab90d7ea7fd0377bf44595c71
|
[
"MIT"
] | null | null | null |
src/Common/TokenType.cpp
|
Morphlng/cploxplox
|
f7f64c535b76bdaab90d7ea7fd0377bf44595c71
|
[
"MIT"
] | null | null | null |
src/Common/TokenType.cpp
|
Morphlng/cploxplox
|
f7f64c535b76bdaab90d7ea7fd0377bf44595c71
|
[
"MIT"
] | null | null | null |
#include "Common/TokenType.h"
namespace CXX {
const char* TypeName(TokenType type)
{
switch (type)
{
case TokenType::PLUS: // +
return "PLUS";
case TokenType::MINUS: // -
return "MINUS";
case TokenType::MUL: // *
return "MUL";
case TokenType::DIV: // /
return "DIV";
case TokenType::MOD: // %
return "MOD";
case TokenType::LPAREN: // (
return "LPAREN";
case TokenType::RPAREN: // )
return "RPAREN";
case TokenType::LBRACE: // [
return "LBRACE";
case TokenType::RBRACE: // ]
return "RBRACE";
case TokenType::LBRACKET: // {
return "LBRACKET";
case TokenType::RBRACKET: // }
return "RBRACKET";
case TokenType::COMMA: // ,
return "COMMA";
case TokenType::DOT: // .
return "DOT";
case TokenType::COLON: //:
return "PLUS";
case TokenType::SEMICOLON: // ;
return "SEMICOLON";
case TokenType::PLUS_PLUS:
return "PLUS_PLUS";
case TokenType::MINUS_MINUS:
return "MINUS_MINUS";
case TokenType::PLUS_EQUAL:
return "PLUS_EQUAL";
case TokenType::MINUS_EQUAL:
return "MINUS_EQUAL";
case TokenType::MUL_EQUAL:
return "MUL_EQUAL";
case TokenType::DIV_EQUAL:
return "DIV_EQUAL";
case TokenType::QUESTION_MARK: // ?
return "QUESTION_MARK";
// bool
case TokenType::BANG: // !
return "BANG";
case TokenType::BANGEQ: // !=
return "BANGEQ";
case TokenType::EQ: // =
return "EQ";
case TokenType::EQEQ: // ==
return "EQEQ";
case TokenType::GT: // >
return "GT";
case TokenType::GTE: // >=
return "GTE";
case TokenType::LT: // LT
return "LT";
case TokenType::LTE: // <=
return "LTE";
// primary
case TokenType::NUMBER: // number
return "NUMBER";
case TokenType::STRING: // string
return "STRING";
case TokenType::IDENTIFIER: // identifier
return "IDENTIFIER";
// keyword
case TokenType::NIL: // nil, represent undefined variable
return "NIL";
case TokenType::TRUE: // true
return "TRUE";
case TokenType::FALSE: // false
return "FALSE";
case TokenType::VAR:
return "VAR";
case TokenType::CLASS:
return "CLASS";
case TokenType::THIS:
return "THIS";
case TokenType::SUPER:
return "IDENTIFIER";
case TokenType::IF:
return "IF";
case TokenType::ELSE:
return "ELSE";
case TokenType::FOR:
return "FOR";
case TokenType::WHILE:
return "WHILE";
case TokenType::BREAK:
return "BREAK";
case TokenType::CONTINUE:
return "CONTINUE";
case TokenType::FUNC:
return "FUNC";
case TokenType::RETURN:
return "RETURN";
case TokenType::AND:
return "AND";
case TokenType::OR:
return "OR";
case TokenType::IMPORT:
return "IMPORT";
case TokenType::AS:
return "AS";
case TokenType::FROM:
return "FROM";
case TokenType::END_OF_FILE:
return "EOF";
}
return "unreachable";
}
}
| 21.371212
| 59
| 0.631691
|
Morphlng
|
167e531f1fabb80e12c24ac291623b3e2646b1ce
| 304
|
cpp
|
C++
|
Main/P1615.cpp
|
qinyihao/Luogu_Problem_Solver
|
bb4675f045affe513613023394027c3359bb0876
|
[
"MIT"
] | null | null | null |
Main/P1615.cpp
|
qinyihao/Luogu_Problem_Solver
|
bb4675f045affe513613023394027c3359bb0876
|
[
"MIT"
] | null | null | null |
Main/P1615.cpp
|
qinyihao/Luogu_Problem_Solver
|
bb4675f045affe513613023394027c3359bb0876
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
long long a2,b2,c2,s2;
long long a1,b1,c1,s1;
long long k,ans;
int main()
{
scanf("%lld:%lld:%lld\n%lld:%lld:%lld",&a1,&b1,&c1,&a2,&b2,&c2);
s1=a1*3600+b1*60+c1;
s2=a2*3600+b2*60+c2;
scanf("%lld",&k);
ans=k*(s2-s1);
printf("%lld",ans);
return 0;
}
| 16.888889
| 65
| 0.605263
|
qinyihao
|
168098d4959918324edb9474d337f02c97e1b905
| 2,148
|
cpp
|
C++
|
src/Utils.cpp
|
lyftt/WebServer
|
adc2ef7f999e6c6e75cea46087161fe21116bd40
|
[
"MIT"
] | null | null | null |
src/Utils.cpp
|
lyftt/WebServer
|
adc2ef7f999e6c6e75cea46087161fe21116bd40
|
[
"MIT"
] | null | null | null |
src/Utils.cpp
|
lyftt/WebServer
|
adc2ef7f999e6c6e75cea46087161fe21116bd40
|
[
"MIT"
] | null | null | null |
#include "Utils.h"
#include <fcntl.h>
#include <sys/epoll.h>
#include "config.h"
#include "http_conn.h"
#include "TimerSortList.h"
#include "webserver.h"
/*静态遍历定义*/
int Utils::u_epollfd = -1;
/*
*
* 设置fd为非阻塞
*
*/
int Utils::setnonblocking(int fd)
{
int old_opt = fcntl(fd,F_GETFL);
int new_opt = old_opt | O_NONBLOCK;
fcntl(fd,F_SETFL,new_opt);
return old_opt;
}
/*
*
*重置文件描述的epolloneshot事件
*
*/
bool Utils::modfd(int epollfd, int fd, int ev, int trig_mode)
{
epoll_event event;
event.data.fd = fd;
if (ET == trig_mode)
{
event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP; //ET 触发模式
}
else
{
event.events = ev | EPOLLONESHOT | EPOLLRDHUP; //LT 触发模式
}
epoll_ctl(u_epollfd,EPOLL_CTL_MOD,fd,&event); //重置epolloneshot事件
}
/*
*将文件描述符注册到epoll内核事件表
*
*/
bool Utils::addfd(int epollfd, int fd, bool one_shot, int trig_mode)
{
epoll_event event;
event.data.fd = fd;
if (ET == trig_mode)
{
event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; //高效ET模式,监听可读事件和连接断开事件
}
else
{
event.events = EPOLLIN | EPOLLRDHUP; //普通LT模式,监听可读事件和连接断开事件
}
if (one_shot)
event.events |= EPOLLONESHOT;
epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event);
setnonblocking(fd);
return true;
}
/*
*
* 设置epollfd
*
**/
int Utils::set_epollfd(int epollfd)
{
int old_value = u_epollfd;
u_epollfd = epollfd;
return old_value;
}
/*
*
* 获取epollfd
*
**/
int Utils::get_epollfd()
{
return u_epollfd;
}
/*
*
* 定时器的回调函数
*
*/
void Utils::cb_func(client_data* user_data)
{
if (!user_data)
return;
epoll_ctl(u_epollfd,EPOLL_CTL_DEL,user_data->sockfd,0); //从监听的红黑树中删除这个连接
close(user_data->sockfd); //关闭连接
http_conn::m_user_count--; //连接数量减一
}
/*
*
* 还没绑定到定时器时,直接调用close关闭连接即可
*
*/
void Utils::show_error(int connfd,const char *info)
{
send(connfd,info,strlen(info),0);
close(connfd);
}
/*
*
* 超时的处理函数
*
*/
void Utils::timer_handler(TimerSortList* list)
{
list->tick();
alarm(TIMESLOT);
}
| 15.565217
| 77
| 0.604749
|
lyftt
|
1682841d20ba5c157c575c46c93dbb99c6bb5b30
| 2,972
|
cpp
|
C++
|
Ilya Bondarenko/EditedFinance.cpp
|
soomrack/MR2020
|
2de7289665dcdac4a436eb512f283780aa78cb76
|
[
"MIT"
] | 4
|
2020-09-22T12:04:07.000Z
|
2020-10-03T22:28:00.000Z
|
Ilya Bondarenko/EditedFinance.cpp
|
soomrack/MR2020
|
2de7289665dcdac4a436eb512f283780aa78cb76
|
[
"MIT"
] | null | null | null |
Ilya Bondarenko/EditedFinance.cpp
|
soomrack/MR2020
|
2de7289665dcdac4a436eb512f283780aa78cb76
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
using namespace std;
// Edited by Panteleev M. D.
int main()
{
setlocale(LC_ALL, "Rus");
float d1=0;
float x, y,z, t, n;
n = 0;
// программа для подсчета выполаты по ипотеке
//начало
float stavka, ttt, mstavka, os, emp, od, pch, och, x2, sk, pow1, time, total,total1;
int n1, n2;
cout << "Введите процентную ставку годовых: ";
cin >> stavka;
cout << "Введите количество лет ипотеки: ";
cin >> ttt;
cout << "Введите сумму кредита: ";
cin >> sk;
cout << endl << "Введите ежемесячный доход: ";
cin >> x2;
n1 = 0;
n2 = 0;
mstavka = stavka / 12 / 100; // находим ежемесячную ставку
ttt = ttt * 12; // срок ипотеки в месяцах
pow1 = 1 + mstavka;
os = pow(pow1, ttt); //находим общую ставку
emp = sk * mstavka * os / (os - 1);// находим ежемесячный платеж
od = sk;// приравниваем остаток долка к сумме кредита
total = emp * ttt;
total1 = total;
cout << "Ежемесячный платеж : " << emp << endl;
cout << "Количество долга : " << total << endl;
n1 = 0;
while (total >= 0 )
{
total = total - emp-x2;
n1 = n1 + 1;
n2 = n2 + 1;
}
n1 = n1/12;
n2 = n2 ;
n2 = n2 % 12;
cout << "Количество времени, через которое будет выплачена вся сумма: " << n1 <<" лет" << endl <<n2 <<" месяцев"<< endl;
cout << "остаток: " << (total1 - n1 * 12 * (emp + x2) - (n2) * (emp + x2)) * (-1) << endl << endl;
//конец
// программа для подсчета стоимости квартиры после инфляции
// начало
float ct, tt, a = 0, prozent;
cout << "Введите процент инфляции: ";
cin >> prozent;
cout << "Введите стоимость квартиры: ";
cin >> ct;
cout << "Введите количество лет: ";
cin >> tt;
int month = rand() % (int)tt+1;
while (a < tt)
{
if (a==month) //В один из месяцев недвижимость растет в цене (открыли рядом метро)
{
cout << "Wow! Your property greatly increased in price!" << '\n';
ct += 300000;
}
ct = ct * (1 + prozent / 100);
a = a + 1;
}
cout << "Стоимость квартиры через " << tt << " лет (года)" << ct << endl << endl;
//конец
// программа для подсчета средств при депозите
//начало
cout << "Введите начальный капитал: ";
cin >> d1;
cout << "Введите доход: ";
cin >> x;
cout << "Введите процент годовых депозита: ";
cin >> z;
cout << "Введите срок депозита: ";
cin >> t;
int probability = rand()%100+1;
int year = rand() % (int)t +1;
while (n<t)
{
if (probability >= 92 && year == n) //С определенной вероятностью в один из годов может обанкротиться банк
{
cout << "Bank went buckrupt! You lost some of your money" << '\n';
d1 -= 600000;
}
d1 = d1* (1 + z / 100);
d1 = d1 + x * 12;
n = n + 1;
}
cout << d1 << endl;
//конец
if (d1>=ct)
{
cout << endl << "Сумма,находящаяся в банке позволяет купить квартиру.";
}
else {
cout << "Сумма,находящаяся в банке не позволяет купить квартиру.";
}
}
| 24.97479
| 122
| 0.564266
|
soomrack
|
168340b0962936f89e2b4371955683ee49c3f378
| 3,871
|
cpp
|
C++
|
pgadmin/dlg/dlgSchema.cpp
|
cjayho/pgadmin3
|
df5f0b83175b4fb495bfcb4d4ce175def486c9df
|
[
"PostgreSQL"
] | 111
|
2015-01-02T15:39:46.000Z
|
2022-01-08T05:08:20.000Z
|
pgadmin/dlg/dlgSchema.cpp
|
cjayho/pgadmin3
|
df5f0b83175b4fb495bfcb4d4ce175def486c9df
|
[
"PostgreSQL"
] | 13
|
2015-07-08T20:26:20.000Z
|
2019-06-17T12:45:35.000Z
|
pgadmin/dlg/dlgSchema.cpp
|
cjayho/pgadmin3
|
df5f0b83175b4fb495bfcb4d4ce175def486c9df
|
[
"PostgreSQL"
] | 96
|
2015-03-11T14:06:44.000Z
|
2022-02-07T10:04:45.000Z
|
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2016, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// dlgSchema.cpp - PostgreSQL Schema Property
//
//////////////////////////////////////////////////////////////////////////
// wxWindows headers
#include <wx/wx.h>
// App headers
#include "pgAdmin3.h"
#include "utils/misc.h"
#include "dlg/dlgSchema.h"
#include "schema/pgSchema.h"
#include "ctl/ctlSeclabelPanel.h"
// pointer to controls
BEGIN_EVENT_TABLE(dlgSchema, dlgDefaultSecurityProperty)
END_EVENT_TABLE();
dlgProperty *pgSchemaBaseFactory::CreateDialog(frmMain *frame, pgObject *node, pgObject *parent)
{
return new dlgSchema(this, frame, (pgSchema *)node, parent);
}
dlgSchema::dlgSchema(pgaFactory *f, frmMain *frame, pgSchema *node, pgObject *parent)
: dlgDefaultSecurityProperty(f, frame, node, wxT("dlgSchema"), wxT("USAGE,CREATE"), "UC", node != NULL ? true : false)
{
schema = node;
seclabelPage = new ctlSeclabelPanel(nbNotebook);
}
pgObject *dlgSchema::GetObject()
{
return schema;
}
int dlgSchema::Go(bool modal)
{
wxString strDefPrivsOnTables, strDefPrivsOnSeqs, strDefPrivsOnFuncs, strDefPrivsOnTypes;
if (connection->BackendMinimumVersion(9, 1))
{
seclabelPage->SetConnection(connection);
seclabelPage->SetObject(schema);
this->Connect(EVT_SECLABELPANEL_CHANGE, wxCommandEventHandler(dlgSchema::OnChange));
}
else
seclabelPage->Disable();
if (schema)
{
if (connection->BackendMinimumVersion(9, 0))
{
strDefPrivsOnTables = schema->GetDefPrivsOnTables();
strDefPrivsOnSeqs = schema->GetDefPrivsOnSequences();
strDefPrivsOnFuncs = schema->GetDefPrivsOnFunctions();
}
if (connection->BackendMinimumVersion(9, 2))
strDefPrivsOnTypes = schema->GetDefPrivsOnTypes();
// edit mode
if (!connection->BackendMinimumVersion(7, 5))
cbOwner->Disable();
if (schema->GetMetaType() == PGM_CATALOG)
{
cbOwner->Disable();
txtName->Disable();
}
}
else
{
// create mode
}
return dlgDefaultSecurityProperty::Go(modal, true, strDefPrivsOnTables, strDefPrivsOnSeqs, strDefPrivsOnFuncs, strDefPrivsOnTypes);
}
pgObject *dlgSchema::CreateObject(pgCollection *collection)
{
wxString name = GetName();
pgObject *obj = schemaFactory.CreateObjects(collection, 0, wxT(" WHERE nspname=") + qtDbString(name) + wxT("\n"));
return obj;
}
#ifdef __WXMAC__
void dlgSchema::OnChangeSize(wxSizeEvent &ev)
{
SetPrivilegesLayout();
if (GetAutoLayout())
{
Layout();
}
}
#endif
void dlgSchema::CheckChange()
{
bool enable = true;
wxString name = GetName();
if (schema)
{
enable = name != schema->GetName()
|| txtComment->GetValue() != schema->GetComment()
|| cbOwner->GetValue() != schema->GetOwner();
if (seclabelPage && connection->BackendMinimumVersion(9, 1))
enable = enable || !(seclabelPage->GetSqlForSecLabels().IsEmpty());
}
else
{
CheckValid(enable, !name.IsEmpty(), _("Please specify name."));
}
EnableOK(enable);
}
wxString dlgSchema::GetSql()
{
wxString sql, name;
name = qtIdent(GetName());
if (schema)
{
// edit mode
AppendNameChange(sql);
AppendOwnerChange(sql, wxT("SCHEMA ") + name);
}
else
{
// create mode
sql = wxT("CREATE SCHEMA ") + name;
AppendIfFilled(sql, wxT("\n AUTHORIZATION "), qtIdent(cbOwner->GetValue()));
sql += wxT(";\n");
}
AppendComment(sql, wxT("SCHEMA"), 0, schema);
sql += GetGrant(wxT("UC"), wxT("SCHEMA ") + name);
if (connection->BackendMinimumVersion(9, 0) && defaultSecurityChanged)
sql += GetDefaultPrivileges(name);
if (seclabelPage && connection->BackendMinimumVersion(9, 1))
sql += seclabelPage->GetSqlForSecLabels(wxT("SCHEMA"), name);
return sql;
}
void dlgSchema::OnChange(wxCommandEvent &event)
{
CheckChange();
}
| 22.637427
| 132
| 0.676828
|
cjayho
|
1683814c6cc41a6ceed66a8ca49dc183f55e68c5
| 886
|
cpp
|
C++
|
elasticfusionpublic/GUI/src/Main.cpp
|
beichendexiatian/InstanceFusion
|
cd48e3f477595a48d845ce01302f564b6b3fc6f6
|
[
"Apache-2.0"
] | 27
|
2016-03-02T09:43:59.000Z
|
2021-12-01T06:30:31.000Z
|
elasticfusionpublic/GUI/src/Main.cpp
|
beichendexiatian/InstanceFusion
|
cd48e3f477595a48d845ce01302f564b6b3fc6f6
|
[
"Apache-2.0"
] | 1
|
2022-03-27T13:09:39.000Z
|
2022-03-27T13:09:39.000Z
|
GUI/src/Main.cpp
|
YabinXuTUD/HRBFFusion3D
|
20dbff99782f31844791b09824bbfd9370d4a0c4
|
[
"BSD-3-Clause"
] | 4
|
2016-03-02T05:52:59.000Z
|
2018-04-29T00:37:30.000Z
|
/*
* This file is part of ElasticFusion.
*
* Copyright (C) 2015 Imperial College London
*
* The use of the code within this file and all code within files that
* make up the software that is ElasticFusion is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.imperial.ac.uk/dyson-robotics-lab/downloads/elastic-fusion/elastic-fusion-license/>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email researchcontracts.engineering@imperial.ac.uk.
*
*/
#include "MainController.h"
int main(int argc, char * argv[])
{
MainController mainController(argc, argv);
mainController.launch();
return 0;
}
| 30.551724
| 111
| 0.732506
|
beichendexiatian
|
168a35a894b7e48f5b34bc5d0054435015ddd494
| 6,773
|
hpp
|
C++
|
SGXDNN/layers/maxpool2d.hpp
|
LukeZheZhu/slalom
|
96ff15977b7058b96d2a00a51c6aabbe729cc6d5
|
[
"MIT"
] | 128
|
2018-06-11T06:07:21.000Z
|
2022-03-30T19:33:29.000Z
|
SGXDNN/layers/maxpool2d.hpp
|
LukeZheZhu/slalom
|
96ff15977b7058b96d2a00a51c6aabbe729cc6d5
|
[
"MIT"
] | 41
|
2018-09-03T15:33:35.000Z
|
2022-02-09T23:40:03.000Z
|
SGXDNN/layers/maxpool2d.hpp
|
LukeZheZhu/slalom
|
96ff15977b7058b96d2a00a51c6aabbe729cc6d5
|
[
"MIT"
] | 46
|
2018-11-23T09:11:20.000Z
|
2022-03-21T08:38:39.000Z
|
#ifndef SGXDNN_MAXPOOL2D_H_
#define SGXDNN_MAXPOOL2D_H_
#include <iostream>
#include <string>
#include "../mempool.hpp"
#include "layer.hpp"
#include "eigen_maxpool.h"
using namespace tensorflow;
namespace SGXDNN
{
template<typename T>
void fast_maxpool(T* input, T* output,
int batch, int input_rows_, int input_cols_, int input_depth_, int out_rows_, int out_cols_,
int window_rows_, int window_cols_, int pad_rows_, int pad_cols_, int row_stride_, int col_stride_,
bool avg_pool = false)
{
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> ConstEigenMatrixMap;
typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> EigenMatrixMap;
ConstEigenMatrixMap in_mat(input, input_depth_,
input_cols_ * input_rows_ * batch);
EigenMatrixMap out_mat(output, input_depth_, out_rows_ * out_cols_ * batch);
// The following code basically does the following:
// 1. Flattens the input and output tensors into two dimensional arrays.
// tensor_in_as_matrix:
// depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)
// output_as_matrix:
// depth by (out_width * out_height * tensor_in_batch)
//
// 2. Walks through the set of columns in the flattened
// tensor_in_as_matrix,
// and updates the corresponding column(s) in output_as_matrix with the
// max value.
auto shard = [&in_mat, &out_mat, input_rows_, input_cols_, input_depth_, out_rows_, out_cols_,
window_rows_, window_cols_, pad_rows_, pad_cols_, row_stride_, col_stride_, avg_pool](long start, long limit) {
const int in_rows = input_rows_;
const int in_cols = input_cols_;
const int window_rows = window_rows_;
const int window_cols = window_cols_;
const int pad_rows = pad_rows_;
const int pad_cols = pad_cols_;
const int row_stride = row_stride_;
const int col_stride = col_stride_;
const int out_height = out_rows_;
const int out_width = out_cols_;
const int input_depth = input_depth_;
{
// Initializes the output tensor with MIN<T>.
const int output_image_size = out_height * out_width * input_depth;
EigenMatrixMap out_shard(out_mat.data() + start * output_image_size,
1, (limit - start) * output_image_size);
if (avg_pool) {
out_shard.setConstant((T) 0.0);
} else {
out_shard.setConstant(Eigen::NumTraits<T>::lowest());
}
}
for (int b = start; b < limit; ++b) {
const int out_offset_batch = b * out_height;
for (int h = 0; h < in_rows; ++h) {
for (int w = 0; w < in_cols; ++w) {
// (h_start, h_end) * (w_start, w_end) is the range that the input
// vector projects to.
const int hpad = h + pad_rows;
const int wpad = w + pad_cols;
const int h_start = (hpad < window_rows)
? 0
: (hpad - window_rows) / row_stride + 1;
const int h_end = std::min(hpad / row_stride + 1, out_height);
const int w_start = (wpad < window_cols)
? 0
: (wpad - window_cols) / col_stride + 1;
const int w_end = std::min(wpad / col_stride + 1, out_width);
// compute elementwise max
const int in_offset = (b * in_rows + h) * in_cols + w;
for (int ph = h_start; ph < h_end; ++ph) {
const int out_offset_base =
(out_offset_batch + ph) * out_width;
for (int pw = w_start; pw < w_end; ++pw) {
const int out_offset = out_offset_base + pw;
if (avg_pool) {
out_mat.col(out_offset) += in_mat.col(in_offset) / ((T)(window_rows * window_cols));
} else {
out_mat.col(out_offset) = out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));
}
}
}
}
}
}
};
shard(0, batch);
}
template <typename T> class MaxPool2D : public Layer<T>
{
public:
explicit MaxPool2D(
const std::string& name,
const array4d input_shape,
const int window_rows,
const int window_cols,
const int row_stride,
const int col_stride,
const Eigen::PaddingType& padding,
const bool avg_pool,
MemPool* mem_pool
): Layer<T>(name, input_shape),
window_rows_(window_rows),
window_cols_(window_cols),
row_stride_(row_stride),
col_stride_(col_stride),
padding_(padding),
avg_pool_(avg_pool),
mem_pool_(mem_pool)
{
input_rows_ = input_shape[1];
input_cols_ = input_shape[2];
input_depth_ = input_shape[3];
GetWindowedOutputSize(input_rows_, window_rows_, row_stride_,
padding_, &out_rows_, &pad_rows_);
GetWindowedOutputSize(input_cols_, window_cols_, col_stride_,
padding_, &out_cols_, &pad_cols_);
output_shape_ = {0, out_rows_, out_cols_, input_depth_};
output_size_ = out_rows_ * out_cols_ * input_depth_;
printf("in Pool2D with window = (%d, %d), stride = (%d, %d), padding = %d, out_shape = (%d, %d, %d), pad = (%d, %d)\n",
window_rows_, window_cols_, row_stride_, col_stride_, padding_, out_rows_, out_cols_, input_depth_, pad_rows_, pad_cols_);
}
array4d output_shape() override
{
return output_shape_;
}
int output_size() override
{
return output_size_;
}
protected:
TensorMap<T, 4> apply_impl(TensorMap<T, 4> input, void* device_ptr = NULL, bool release_input = true) override
{
int batch = input.dimension(0);
output_shape_[0] = batch;
T* output_mem_ = mem_pool_->alloc<T>(batch * output_size_);
auto output_map = TensorMap<T, 4>(output_mem_, output_shape_);
fast_maxpool(input.data(), output_map.data(),
batch, input_rows_, input_cols_, input_depth_, out_rows_, out_cols_,
window_rows_, window_cols_, pad_rows_, pad_cols_, row_stride_, col_stride_, avg_pool_);
mem_pool_->release(input.data());
return output_map;
}
TensorMap<T, 4> fwd_verify_impl(TensorMap<T, 4> input, float** aux_data, int linear_idx, void* device_ptr = NULL, bool release_input = true) override
{
auto output_map = apply_impl(input, device_ptr, release_input);
if (avg_pool_) {
output_map = output_map.round();
}
return output_map;
}
int input_rows_;
int input_cols_;
int input_depth_;
int out_rows_;
int out_cols_;
int pad_rows_;
int pad_cols_;
const Eigen::PaddingType padding_;
const int window_rows_;
const int window_cols_;
const int row_stride_;
const int col_stride_;
const bool avg_pool_;
MemPool* mem_pool_;
array4d output_shape_;
int output_size_;
};
}
#endif
| 32.878641
| 151
| 0.643142
|
LukeZheZhu
|
168f66ea15283d8a72bc9c195b260f907bb4b951
| 2,439
|
cpp
|
C++
|
src/day09/day09.cpp
|
alikoptan/adventofcode2020
|
2d1cb40dcbc35cfc24ba22e20fdb6df127b7a318
|
[
"Unlicense"
] | null | null | null |
src/day09/day09.cpp
|
alikoptan/adventofcode2020
|
2d1cb40dcbc35cfc24ba22e20fdb6df127b7a318
|
[
"Unlicense"
] | null | null | null |
src/day09/day09.cpp
|
alikoptan/adventofcode2020
|
2d1cb40dcbc35cfc24ba22e20fdb6df127b7a318
|
[
"Unlicense"
] | null | null | null |
#include "string"
#include "deque"
#include "vector"
#include "iostream"
#include "climits"
#include "unordered_map"
using namespace std;
class day9 {
private:
const int PERMABLE = 25;
long long anomaly = 0;
vector <long long> numberList, prefixSum;
deque <long long> window;
void readFile() {
freopen("input.txt", "r", stdin);
string line;
while (getline(cin, line)) {
numberList.push_back(stol(line));
}
}
bool exists(deque<long long> currentWindow, long long target) {
unordered_map <long long, bool> table;
while (!currentWindow.empty()) {
if (table[target - currentWindow.front()])
return true;
table[currentWindow.front()] = true;
currentWindow.pop_front();
}
return false;
}
void initSum() {
long long currentSum = 0;
for (auto element : numberList) {
currentSum += element;
prefixSum.push_back(currentSum);
}
}
long long getSum(int& i, int& j) {
if (!j)
return prefixSum[j];
return prefixSum[j] - prefixSum[i - 1];
}
public:
day9() {
readFile();
}
void part1() {
for (int i = 0; i < PERMABLE; i++)
window.push_back(numberList[i]);
for (int i = PERMABLE; i < numberList.size(); i++) {
if (exists(window, numberList[i])) {
window.pop_front();
window.push_back(numberList[i]);
}else {
this->anomaly = numberList[i];
break;
}
}
cout << "Part 1: " << this->anomaly << '\n';
}
void part2() {
initSum();
long long borderSum = 0, minimum = LONG_MAX, maximum = 0;
for (int i = 0; i < numberList.size(); i++) {
for (int j = i + 1; j < numberList.size(); j++) {
if (getSum(i, j) == anomaly) {
for (int k = i; k <= j; k++) {
minimum = min(minimum, numberList[k]);
maximum = max(maximum, numberList[k]);
}
borderSum = minimum + maximum;
break;
}
}
}
cout << "Part 2: " << borderSum << '\n';
}
};
int main() {
day9 solution;
solution.part1();
solution.part2();
return 0;
}
| 27.404494
| 67
| 0.481755
|
alikoptan
|
169229f94fc636e7c4b8b51c519734346a41cf4a
| 2,911
|
cpp
|
C++
|
Terminal/Source/LoadJPEG.cpp
|
Gravecat/BearLibTerminal
|
64fec04101350a99a71db872c513e17bdd2cc94d
|
[
"MIT"
] | 80
|
2020-06-17T15:26:27.000Z
|
2022-03-29T11:17:01.000Z
|
Terminal/Source/LoadJPEG.cpp
|
Gravecat/BearLibTerminal
|
64fec04101350a99a71db872c513e17bdd2cc94d
|
[
"MIT"
] | 11
|
2020-07-19T15:22:06.000Z
|
2022-03-31T03:33:13.000Z
|
Terminal/Source/LoadJPEG.cpp
|
Gravecat/BearLibTerminal
|
64fec04101350a99a71db872c513e17bdd2cc94d
|
[
"MIT"
] | 18
|
2020-09-16T01:29:46.000Z
|
2022-03-27T18:48:09.000Z
|
/*
* BearLibTerminal
* Copyright (C) 2013-2014 Cfyz
*
* 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 <NanoJPEG.h>
#include <functional>
#include <algorithm>
#include <stdexcept>
#include <istream>
#include <vector>
#include <memory>
#include "Geometry.hpp"
#include "Utility.hpp"
#include "Bitmap.hpp"
#include "Log.hpp"
namespace BearLibTerminal
{
std::string to_string(const Jpeg::Decoder::DecodeResult& value)
{
switch (value)
{
case Jpeg::Decoder::OK: return "OK";
case Jpeg::Decoder::NotAJpeg: return "not a JPEG";
case Jpeg::Decoder::Unsupported: return "unsupported format";
case Jpeg::Decoder::OutOfMemory: return "out of memory";
case Jpeg::Decoder::InternalError: return "internal error";
case Jpeg::Decoder::SyntaxError: return "syntax error";
default: return "unknown error";
}
}
Bitmap LoadJPEG(std::istream& stream)
{
std::istreambuf_iterator<char> eos;
std::string contents(std::istreambuf_iterator<char>(stream), eos);
std::unique_ptr<Jpeg::Decoder> decoder(new Jpeg::Decoder((const unsigned char*)contents.data(), contents.size()));
if (decoder->GetResult() != Jpeg::Decoder::OK)
{
throw std::runtime_error(std::string("Failed to load JPEG resource: ") + to_string(decoder->GetResult()));
}
Size size(decoder->GetWidth(), decoder->GetHeight());
if (size.width <= 0 || size.height <= 0)
{
throw std::runtime_error(std::string("Failed to load JPEG resource: internal loader error"));
}
Bitmap result(size, Color());
uint8_t* data = decoder->GetImage();
bool is_color = decoder->IsColor();
for (int y = 0; y < size.height; y++)
{
for (int x = 0; x < size.width; x++)
{
if (is_color)
{
result(x, y) = Color(0xFF, data[0], data[1], data[2]);
data += 3;
}
else
{
result(x, y) = Color(0xFF, data[0], data[0], data[0]);
data += 1;
}
}
}
return result;
}
}
| 31.301075
| 116
| 0.701134
|
Gravecat
|
169379be3d546912001d578df643de860221fa4b
| 335
|
hpp
|
C++
|
src/rsm/options.hpp
|
Nadrin/rsm
|
7cdeb4a17a4b01bfd135d81a97b6f9690f8700d9
|
[
"MIT"
] | 5
|
2019-01-29T03:56:56.000Z
|
2019-08-13T15:17:26.000Z
|
src/rsm/options.hpp
|
Nadrin/rsm
|
7cdeb4a17a4b01bfd135d81a97b6f9690f8700d9
|
[
"MIT"
] | null | null | null |
src/rsm/options.hpp
|
Nadrin/rsm
|
7cdeb4a17a4b01bfd135d81a97b6f9690f8700d9
|
[
"MIT"
] | 1
|
2019-03-28T08:48:31.000Z
|
2019-03-28T08:48:31.000Z
|
/*
* rsm :: Random Sampling Mathematics
* Copyright (c) 2018 Michał Siejak
* Released under the MIT license; see LICENSE file for details.
*/
#pragma once
#include <cstdint>
namespace rsm {
using options_t = uint8_t;
namespace opt {
enum option_bits {
none = 0,
jitter = 1,
shuffle = 2,
};
} // opt
} // rsm
| 13.4
| 64
| 0.638806
|
Nadrin
|
169725ec4d220cbd21892f14e6b98bce36409e80
| 30,147
|
cpp
|
C++
|
Samples/Win7Samples/netds/peertopeer/DRT/CAPIWrappers.cpp
|
windows-development/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 8
|
2017-04-30T17:38:27.000Z
|
2021-11-29T00:59:03.000Z
|
Samples/Win7Samples/netds/peertopeer/DRT/CAPIWrappers.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | null | null | null |
Samples/Win7Samples/netds/peertopeer/DRT/CAPIWrappers.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 2
|
2020-08-11T13:21:49.000Z
|
2021-09-01T10:41:51.000Z
|
// CAPIWrappers.cpp - Functions for dealing with certificates.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#endif
#include "CAPIWrappers.h"
#pragma comment(lib, "crypt32")
#pragma comment(lib, "rpcrt4")
#ifndef USES
#define USES(x) (x = x)
#endif
#define HRESULT_FROM_RPCSTATUS(x) \
(((x < 0) || (x == RPC_S_OK)) ? \
(HRESULT)x : \
(HRESULT) (((x) & 0x0000FFFF) | (FACILITY_RPC<< 16) | 0x80000000))
#define SECOND_IN_FILETIME (10i64 * 1000 * 1000)
const DWORD SIXTYFOUR_K = 64 * 1024;
const DWORD SIXTEEN_K = 16 * 1024;
const DWORD ONE_K = 1024;
BYTE s_keyDataBuf[SIXTEEN_K] = {0};
BYTE s_certBuf[SIXTEEN_K] = {0};
BYTE s_fileBuf[SIXTYFOUR_K] = {0};
/****************************************************************************++
Description :
This function creates a well known sid using User domain. CreateWellKnownSid requires
domain sid to be provided to generate such sids. This function first gets the domain sid
out of the user information in the token and then generate a well known sid.
Arguments:
hToken - [supplies] The token for which sid has to be generated
sidType - [supplies] The type of well known sid
pSid - [receives] The newly create sid
pdwSidSize - [Supplies/Receives] The size of the memory allocated for ppSid
Returns:
Errors returned by GetTokenInformation
Errors returned by CreateWellKnownSid
E_OUTOFMEMORY In case there is not enough memory
Errors returned by GetWindowsAccountDomainSid
--***************************************************************************/
HRESULT
CreateWellKnownSidForAccount(
__in_opt HANDLE hToken,
__in WELL_KNOWN_SID_TYPE sidType,
__out PSID pSid,
__inout DWORD * pdwSidSize)
{
HRESULT hr = S_OK;
TOKEN_USER * pUserToken = NULL;
DWORD dwTokenLen = 0;
PBYTE pDomainSid[SECURITY_MAX_SID_SIZE];
DWORD dwSidSize = SECURITY_MAX_SID_SIZE;
//
// Get the TokenUser, use this TokenUser to generate a well-known sid that requires a domain
//
if (!GetTokenInformation(
hToken,
TokenUser,
NULL,
dwTokenLen,
&dwTokenLen))
{
DWORD err = GetLastError();
if (err != ERROR_INSUFFICIENT_BUFFER)
{
hr = HRESULT_FROM_WIN32(err);
goto cleanup;
}
}
pUserToken = (TOKEN_USER *) new BYTE[dwTokenLen];
if (pUserToken == NULL)
{
hr = E_OUTOFMEMORY;
goto cleanup;
}
if (!GetTokenInformation(
hToken,
TokenUser,
pUserToken,
dwTokenLen,
&dwTokenLen))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanup;
}
//
// Now get the domain sid from the TokenUser
//
if (!GetWindowsAccountDomainSid(
pUserToken->User.Sid,
(PSID) pDomainSid,
&dwSidSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanup;
}
if(!CreateWellKnownSid(
sidType,
pDomainSid,
pSid,
pdwSidSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanup;
}
cleanup:
delete [] pUserToken;
return hr;
}
/****************************************************************************++
Routine Description:
Verifies whether specified well-known SID is in the current user token
Arguments:
sid - one of the WELL_KNOWN_SID_TYPE consts
hToken - Optional the token for which we want to test membership
pfMember - [Receives] TRUE if specified sid is a member of the user token, FALSE otherwise
Notes:
-
Return Value:
Errors returned by CreateWellKnownSid
Errors returned by CheckTokenMembership
--*****************************************************************************/
HRESULT
IsMemberOf(
__in WELL_KNOWN_SID_TYPE sid,
__in_opt HANDLE hToken,
__out BOOL * pfMember)
{
HRESULT hr = S_OK;
BOOL fMember = FALSE;
BYTE pSID[SECURITY_MAX_SID_SIZE] = {0};
DWORD dwSIDSize = sizeof(pSID);
//
// create SID for the authenticated users
//
if (!CreateWellKnownSid(
sid,
NULL, // not a domain sid
(SID*)pSID,
&dwSIDSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
if (FAILED(hr) && (hr != E_INVALIDARG))
{
goto Cleanup;
}
//
// In case of invalid-arg we might need to provide the domain, so create well known sid for domain
//
hr = CreateWellKnownSidForAccount(hToken, sid, pSID, &dwSIDSize);
if (hr == HRESULT_FROM_WIN32(ERROR_NON_ACCOUNT_SID))
{
//
// If it is a non account sid (for example Local Service). Ignore the error.
//
hr = S_OK;
fMember = FALSE;
goto Cleanup;
}
else if (FAILED(hr))
{
goto Cleanup;
}
}
//
// check whether token has this sid
//
if (!CheckTokenMembership(hToken,
(SID*)pSID, // sid for the authenticated user
&fMember))
{
hr = HRESULT_FROM_WIN32(GetLastError());
// just to be on the safe side (as we don't know that CheckTokenMembership
// does not modify fAuthenticated in case of error)
fMember = FALSE;
if (hr == E_ACCESSDENIED && hToken == NULL)
{
// unable to query the thread token. Open as self and try again
if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken))
{
if (CheckTokenMembership(hToken, (SID*)pSID, &fMember))
{
hr = S_OK;
}
else
{
// stick with the original error code, but ensure that fMember is correct
fMember = FALSE;
}
CloseHandle(hToken);
}
}
goto Cleanup;
}
Cleanup:
*pfMember = fMember;
return hr;
}
// helper used by CreateCryptProv
HRESULT
IsServiceAccount(
OUT BOOL * pfMember)
{
HRESULT hr = S_OK;
BOOL fMember = FALSE;
hr = IsMemberOf(WinLocalServiceSid, NULL, &fMember);
if (FAILED(hr) || fMember)
{
goto Cleanup;
}
hr = IsMemberOf(WinLocalSystemSid, NULL, &fMember);
if (FAILED(hr) || fMember)
{
goto Cleanup;
}
hr = IsMemberOf(WinNetworkServiceSid, NULL, &fMember);
if (FAILED(hr) || fMember)
{
goto Cleanup;
}
Cleanup:
*pfMember = fMember;
return hr;
}
/****************************************************************************++
Routine Description:
Deletes the key container and the keys
Arguments:
pwzContainer -
Notes:
-
Return Value:
- S_OK
- or -
- no other errors are expected
--*****************************************************************************/
HRESULT
DeleteKeys(
IN PCWSTR pwzContainer)
{
HRESULT hr = S_OK;
HCRYPTPROV hCryptProv = NULL;
BOOL fServiceAccount = FALSE;
hr = IsServiceAccount(&fServiceAccount);
if (FAILED(hr))
{
goto Cleanup;
}
//
// this is the most counter-intuitive API that i have seen in my life
// in order to delete the contanier and all the keys in it, i have to call CryptAcquireContext
//
if (!CryptAcquireContextW(&hCryptProv,
pwzContainer,
NULL,
DEFAULT_PROV_TYPE,
fServiceAccount ?
(CRYPT_DELETEKEYSET | CRYPT_MACHINE_KEYSET) :
(CRYPT_DELETEKEYSET)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
Cleanup:
return hr;
}
/****************************************************************************++
Routine Description:
Wrapper fro CryptDestroyKey
Arguments:
hKey - handle to the key to destroy
Notes:
-
Return Value:
- VOID
--*****************************************************************************/
VOID
DestroyKey(
IN HCRYPTKEY hKey)
{
if (NULL != hKey)
{
//
// this is quite counter-intuitive API
// CryptDestroyKey just releases the handle to the key, but only in case of
// private/public key pairs.
//
if (!CryptDestroyKey(hKey))
{
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
USES(hr);
//
// should never happen, unless handle is invalid
//
}
}
}
/****************************************************************************++
Routine Description:
Releases the handle to the CSP
Arguments:
hCryptProv - handle to the CSP
Notes:
- handles the NULL CSP gracefully
Return Value:
- VOID
--*****************************************************************************/
VOID
ReleaseCryptProv(
IN HCRYPTPROV hCryptProv)
{
if (NULL != hCryptProv)
{
if (!CryptReleaseContext(hCryptProv, 0))
{
//
// one reason why this could fail (at least it failed a couple of times already) i s
// that some certifcate store was opened using this CSP, but
// CERT_STORE_NO_CRYPT_RELEASE_FLAG was not specified, so that
// when cert store is released the provider is released as well.
//
// verify that all stores that were ever used, specify this flag
//
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
USES(hr);
}
}
}
/****************************************************************************++
Routine Description:
Creates a handle to the CSP
Arguments:
pwzContainerName - name of the container to be created. if NULL, GUID is generated
for the name of the container
fCreateNewKeys - forces new keys to be created
phCryptProv - pointer to the location, where handle should be returned
Notes:
-
Return Value:
- S_OK
- or -
- CAPI error returned by CryptAcquireContextW
--*****************************************************************************/
HRESULT
CreateCryptProv(
IN PCWSTR pwzContainerName,
IN BOOL fCreateNewKeys,
OUT HCRYPTPROV* phCryptProv)
{
HRESULT hr = S_OK;
HCRYPTKEY hKey = NULL;
RPC_STATUS status = RPC_S_OK;
BOOL fCreatedContainer = FALSE;
WCHAR* pwzNewContainerName = NULL;
*phCryptProv = NULL;
if (NULL == pwzContainerName)
{
UUID uuid;
BOOL fServiceAccount = FALSE;
//
// generate container name from the UUID
//
status = UuidCreate(&uuid);
hr = HRESULT_FROM_RPCSTATUS(status);
if (FAILED(hr))
{
goto Cleanup;
}
status = UuidToStringW(&uuid, (unsigned short**)&pwzNewContainerName);
hr = HRESULT_FROM_RPCSTATUS(status);
if (FAILED(hr))
{
goto Cleanup;
}
pwzContainerName = pwzNewContainerName;
hr = IsServiceAccount(&fServiceAccount);
if (FAILED(hr))
{
goto Cleanup;
}
//
// open the clean key container
//
// note: CRYPT_NEW_KEYSET is not creating new keys, it just
// creates new key container. duh.
//
if (!CryptAcquireContextW(phCryptProv,
pwzNewContainerName,
NULL, // default provider name
DEFAULT_PROV_TYPE,
fServiceAccount ?
(CRYPT_SILENT | CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET) :
(CRYPT_SILENT | CRYPT_NEWKEYSET)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
//
// we are seeing that CryptAcquireContextW returns NTE_FAIL under low
// memory condition, so we just mask the error
//
if (NTE_FAIL == hr)
{
hr = E_OUTOFMEMORY;
}
goto Cleanup;
}
fCreatedContainer = TRUE;
}
else
{
BOOL fServiceAccount = FALSE;
hr = IsServiceAccount(&fServiceAccount);
if (FAILED(hr))
{
goto Cleanup;
}
//
// open the provider first, create the keys too
//
if (!CryptAcquireContextW(phCryptProv,
pwzContainerName,
NULL, // default provider name
DEFAULT_PROV_TYPE,
fServiceAccount ?
(CRYPT_SILENT | CRYPT_MACHINE_KEYSET) :
(CRYPT_SILENT)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
//
// we are seeing that CryptAcquireContextW returns NTE_FAIL under low
// memory condition, so we just mask the error
//
if (NTE_FAIL == hr)
{
hr = E_OUTOFMEMORY;
}
goto Cleanup;
}
}
if (fCreateNewKeys)
{
//
// make sure keys exist
//
if (!CryptGetUserKey(*phCryptProv,
DEFAULT_KEY_SPEC,
&hKey))
{
hr = HRESULT_FROM_WIN32(GetLastError());
// if key does not exist, create it
if (HRESULT_FROM_WIN32((unsigned long)NTE_NO_KEY) == hr)
{
hr = S_OK;
if (!CryptGenKey(*phCryptProv,
DEFAULT_KEY_SPEC,
CRYPT_EXPORTABLE,
&hKey))
{
hr = HRESULT_FROM_WIN32(GetLastError());
//
// we are seeing that CryptGenKey returns ERROR_CANTOPEN under low
// memory condition, so we just mask the error
//
if (HRESULT_FROM_WIN32(ERROR_CANTOPEN) == hr)
{
hr = E_OUTOFMEMORY;
}
goto Cleanup;
}
}
else
{
// failed to get user key by some misterious reason, so bail out
goto Cleanup;
}
}
}
Cleanup:
DestroyKey(hKey);
if (FAILED(hr))
{
//
// release the context
//
ReleaseCryptProv(*phCryptProv);
*phCryptProv = NULL;
//
// delete the keys, if we created them
//
if (fCreatedContainer)
{
DeleteKeys(pwzContainerName);
}
}
if (NULL != pwzNewContainerName)
{
// this always returns RPC_S_OK
status = RpcStringFreeW((unsigned short**)&pwzNewContainerName);
USES(status);
}
return hr;
}
/****************************************************************************++
Routine Description:
Retrieves the name of the CSP container.
Arguments:
hCryptProv - handle to the CSP
pcChars - count of chars in the buffer on input. count of chars used on return
pwzContainerName - pointer to output buffer
Notes:
-
Return Value:
- S_OK
- or -
- NTE_BAD_UID, if hCryptProv handle is not valid
--*****************************************************************************/
HRESULT
GetContainerName(
IN HCRYPTPROV hCryptProv,
__inout ULONG* pcChars,
__out_ecount_opt(*pcChars) LPWSTR pwzContainerName)
{
HRESULT hr = S_OK;
CHAR * pszBuf = new CHAR[*pcChars];
ULONG cbBufSize = sizeof(CHAR) *(*pcChars);
if (NULL == pszBuf)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
//
// get the name of the key container
//
if (!CryptGetProvParam(hCryptProv,
PP_CONTAINER,
(BYTE*)pszBuf,
&cbBufSize,
0))
{
hr = HRESULT_FROM_WIN32(GetLastError());
// if buffer is not sufficiently large, just return with this error
if (HRESULT_FROM_WIN32(ERROR_MORE_DATA) == hr)
{
// if buffer was not sufficiently large return the number of characters needed
*pcChars = cbBufSize / sizeof(CHAR);
goto Cleanup;
}
else
{
goto Cleanup;
}
}
//
// convert the string to the wide character, since that's what needed for the key info
//
if (0 == MultiByteToWideChar(CP_ACP,
0, // dwFlags
pszBuf,
-1, // calculate the length
pwzContainerName,
*pcChars))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
Cleanup:
if (NULL != pszBuf)
{
delete [] pszBuf;
}
return hr;
}
// Read a single cert from a file
HRESULT ReadCertFromFile(LPCWSTR pwzFileName, CERT_CONTEXT** ppCert, HCRYPTPROV* phCryptProv)
{
BOOL bRet = FALSE;
FILE* pFile = NULL;
errno_t err;
// open cert file for local cert
err = _wfopen_s(&pFile, pwzFileName, L"rb");
if (err)
{
return CRYPT_E_FILE_ERROR;
}
// read local cert into *ppLocalCert, allocating memory
fread(s_fileBuf, sizeof(s_fileBuf), 1, pFile);
fclose(pFile);
CRYPT_DATA_BLOB blob;
blob.cbData = sizeof(s_fileBuf);
blob.pbData = s_fileBuf;
HCERTSTORE hCertStore = PFXImportCertStore(&blob, L"DRT Rocks!", CRYPT_EXPORTABLE);
if (NULL == hCertStore)
return HRESULT_FROM_WIN32(GetLastError());
// TODO: does this have to be a c style cast? I get compile errors if I try reinterpret or static cast
// the first cert is always the leaf cert (since we encoded it that way)
CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)CertEnumCertificatesInStore(hCertStore, NULL);
if (NULL == pCertContext)
return HRESULT_FROM_WIN32(GetLastError());
// retreive the crypt provider which has the private key for this certificate
DWORD dwKeySpec = 0;
HCRYPTPROV hCryptProv = NULL;
bRet = CryptAcquireCertificatePrivateKey(pCertContext,
CRYPT_ACQUIRE_SILENT_FLAG | CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
NULL, &hCryptProv, &dwKeySpec, NULL);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// make sure provider stays around for duration of the test run. We need hCryptProv of root cert to sign local certs
CryptContextAddRef(hCryptProv, NULL, 0);
// everything succeeded, safe to set outparam
*ppCert = pCertContext;
if (NULL != phCryptProv)
*phCryptProv = hCryptProv;
return S_OK;
}
// helper function to write the cert store out to a file
HRESULT WriteStoreToFile(__in HCERTSTORE hCertStore, __in PCWSTR pwzFileName)
{
BOOL bRet = FALSE;
FILE* pFile = NULL;
errno_t err;
CRYPT_DATA_BLOB blob = { sizeof(s_fileBuf), s_fileBuf};
bRet = PFXExportCertStore(hCertStore, &blob, L"DRT Rocks!", EXPORT_PRIVATE_KEYS);
if (!bRet)
{
return HRESULT_FROM_WIN32(GetLastError());
}
err = _wfopen_s(&pFile, pwzFileName, L"wb");
if (err)
{
return CRYPT_E_FILE_ERROR;
}
fwrite(blob.pbData, blob.cbData, 1, pFile);
fclose(pFile);
return S_OK;
}
// helper function used by make certs to encode a name for storage in a cert (modified from drt\test\drtcert\main.cpp)
HRESULT EncodeName(__in PCWSTR pwzName, DWORD* pcbEncodedName, BYTE* pbEncodedName)
{
CERT_NAME_INFO nameInfo = {0};
CERT_RDN rdn = {0};
CERT_RDN_ATTR rdnAttr = {0};
nameInfo.cRDN = 1;
nameInfo.rgRDN = &rdn;
rdn.cRDNAttr = 1;
rdn.rgRDNAttr = &rdnAttr;
rdnAttr.dwValueType = CERT_RDN_UNICODE_STRING;
rdnAttr.pszObjId = szOID_COMMON_NAME;
rdnAttr.Value.pbData = (BYTE*)pwzName;
rdnAttr.Value.cbData = sizeof(WCHAR) * (DWORD)(wcslen(pwzName) + 1);
if (!CryptEncodeObject(DEFAULT_ENCODING, X509_NAME, &nameInfo, pbEncodedName, pcbEncodedName))
{
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
// manufacture a single cert and export it to a file
HRESULT MakeAndExportACert(PCWSTR pwzSignerName, PCWSTR pwzCertName, PCWSTR pwzFileName, HCERTSTORE hCertStore,
HCRYPTPROV hCryptProvSigner, HCRYPTPROV hCryptProvThisCert,
CERT_CONTEXT* pIssuerCertContext)
{
HRESULT hr = S_OK;
BOOL bRet = FALSE;
BYTE byteBuf1[ONE_K] = {0};
BYTE byteBuf2[ONE_K] = {0};
DWORD cSignerName = sizeof(byteBuf1);
BYTE* pbSignerName = byteBuf1;
DWORD cCertName = sizeof(byteBuf2);
BYTE* pbCertName = byteBuf2;
CERT_INFO certInfo = {0};
BYTE serialNumberBuf[16];
ULONGLONG ullTime = 0;
XCERT_CONTEXT pCertContext;
ULONG cchContainer = 512;
WCHAR wzContainer[512];
CRYPT_KEY_PROV_INFO keyInfo = {0};
// encode the names for use in a cert
hr = EncodeName(pwzSignerName, &cSignerName, pbSignerName);
if (FAILED(hr))
return hr;
hr = EncodeName(pwzCertName, &cCertName, pbCertName);
if (FAILED(hr))
return hr;
// first retrieve the public key from the hCryptProv (which abstracts the key pair)
DWORD dwSize = sizeof(s_keyDataBuf);
bRet = CryptExportPublicKeyInfo(hCryptProvThisCert, DEFAULT_KEY_SPEC, DEFAULT_ENCODING,
reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(s_keyDataBuf), &dwSize);
if (FALSE == bRet)
return HRESULT_FROM_WIN32(GetLastError());
// set the cert properties
certInfo.dwVersion = CERT_V3;
certInfo.SerialNumber.cbData = sizeof(serialNumberBuf);
certInfo.SerialNumber.pbData = serialNumberBuf;
certInfo.SignatureAlgorithm.pszObjId = DEFAULT_ALGORITHM;
GetSystemTimeAsFileTime((FILETIME*)&ullTime);
ullTime -= SECOND_IN_FILETIME * 60 * 60 * 24;
CopyMemory(&certInfo.NotBefore, &ullTime, sizeof(FILETIME));
ullTime += SECOND_IN_FILETIME * 60 * 60 * 24 * 365;
CopyMemory(&certInfo.NotAfter, &ullTime, sizeof(FILETIME));
certInfo.Issuer.cbData = cSignerName;
certInfo.Issuer.pbData = pbSignerName;
certInfo.Subject.cbData = cCertName;
certInfo.Subject.pbData = pbCertName;
certInfo.SubjectPublicKeyInfo = *(reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(s_keyDataBuf));
// create the cert
DWORD cCertBuf = sizeof(s_certBuf);
bRet = CryptSignAndEncodeCertificate(hCryptProvSigner, // Crypto provider
DEFAULT_KEY_SPEC, // Key spec, we always use the same
DEFAULT_ENCODING, // Encoding type, default
X509_CERT_TO_BE_SIGNED, // Structure type - certificate
&certInfo, // Structure information
&certInfo.SignatureAlgorithm, // Signature algorithm
NULL, // reserved, must be NULL
s_certBuf, // hopefully it will fit in 1K
&cCertBuf);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// retrieve the cert context. pCertContext gets a pointer into the crypto api heap, we must treat it as read only.
// pCertContext must be freed with CertFreeCertificateContext(p); we use a smart pointer to do the free
pCertContext = (CERT_CONTEXT*)CertCreateCertificateContext(DEFAULT_ENCODING, s_certBuf, cCertBuf);
if (NULL == pCertContext)
return HRESULT_FROM_WIN32(GetLastError());
// next attach the private key
// =================
// retrieve container name
hr = GetContainerName(hCryptProvThisCert, &cchContainer, wzContainer);
if (FAILED(hr))
return hr;
// set up key info struct for CAPI call
keyInfo.pwszContainerName = wzContainer;
keyInfo.pwszProvName = NULL;
keyInfo.dwProvType = DEFAULT_PROV_TYPE;
keyInfo.dwKeySpec = DEFAULT_KEY_SPEC;
// attach private key
bRet = CertSetCertificateContextProperty(pCertContext, CERT_KEY_PROV_INFO_PROP_ID, 0, &keyInfo);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// put the cert into the store
bRet = CertAddCertificateContextToStore(hCertStore, pCertContext, CERT_STORE_ADD_NEW, NULL);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// make sure the issuer cert is also in the store, if we have an issuer for the cert (ie, the non self signed case)
if (pIssuerCertContext)
{
bRet = CertAddCertificateContextToStore(hCertStore, pIssuerCertContext, CERT_STORE_ADD_NEW, NULL);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
}
// now export the cert to a file
hr = WriteStoreToFile(hCertStore, pwzFileName);
return hr;
}
// using cryptoApi, make a cert and export it. If there is an existing root cert, this will
// use the existing root cert to sign the local cert.
// export a local cert to the file <currentdir>\LocalCert.cer
// export a root cert to the file <currentDir>\RootCert.cer (if one does not already exist)
HRESULT MakeCert(LPCWSTR pwzLocalCertFileName, LPCWSTR pwzLocalCertName,
LPCWSTR pwzIssuerCertFileName, LPCWSTR pwzIssuerCertName)
{
HRESULT hr = S_OK;
XHCERTSTORE hSelfCertStore;
XHCERTSTORE hSignedCertStore;
XHCRYPTPROV hCryptProvIssuer;
XHCRYPTPROV hCryptProvThis;
XCERT_CONTEXT pIssuerCert;
// If there is an issuer cert, make sure it exists
if (pwzIssuerCertFileName)
{
hr = ReadCertFromFile(pwzIssuerCertFileName, &pIssuerCert, &hCryptProvIssuer);
if (FAILED(hr))
return hr;
}
// create this cert key pair (util function from peernet\common)
hr = CreateCryptProv(NULL, TRUE, &hCryptProvThis);
if (FAILED(hr))
return hr;
// create cert store
hSelfCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL,
CERT_STORE_CREATE_NEW_FLAG | CERT_STORE_NO_CRYPT_RELEASE_FLAG, NULL);
if (NULL == hSelfCertStore)
return HRESULT_FROM_WIN32(GetLastError());
// Make the self signed cert, and save it to a file
hr = MakeAndExportACert(pwzLocalCertName, pwzLocalCertName, pwzLocalCertFileName, hSelfCertStore, hCryptProvThis, hCryptProvThis, NULL);
if (FAILED(hr))
return hr;
// then, sign it if an issuer name was supplied
// (surprisingly, the same function does both, since it adds a signing record to existing cert)
// FUTURE: this is a bit inefficient, since we write the file twice, we can add a fWrite paramater, and not write the file when it is false
if (pwzIssuerCertFileName)
{
// must create a separate store, or we end up with a single cert and a chain cert in same store, apps can pick wrong cert
hSignedCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL,
CERT_STORE_CREATE_NEW_FLAG | CERT_STORE_NO_CRYPT_RELEASE_FLAG, NULL);
if (NULL == hSignedCertStore)
return HRESULT_FROM_WIN32(GetLastError());
hr = MakeAndExportACert(pwzIssuerCertName, pwzLocalCertName, pwzLocalCertFileName, hSignedCertStore, hCryptProvIssuer, hCryptProvThis, pIssuerCert);
}
return hr;
}
| 30.086826
| 157
| 0.533983
|
windows-development
|
1697eb193469b75698534159d177bde187a7da96
| 67
|
hpp
|
C++
|
3rdparty/kapok/Kapok.hpp
|
wohaaitinciu/zpublic
|
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
|
[
"Unlicense"
] | 202
|
2015-04-12T14:06:10.000Z
|
2022-02-28T15:08:33.000Z
|
3rdparty/kapok/Kapok.hpp
|
sinmx/ZPublic
|
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
|
[
"Unlicense"
] | 7
|
2015-04-12T14:17:57.000Z
|
2018-05-29T01:43:28.000Z
|
3rdparty/kapok/Kapok.hpp
|
sinmx/ZPublic
|
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
|
[
"Unlicense"
] | 93
|
2015-04-12T08:25:10.000Z
|
2020-11-05T02:57:03.000Z
|
#pragma once
#include "Serializer.hpp"
#include "DeSerializer.hpp"
| 16.75
| 27
| 0.776119
|
wohaaitinciu
|
169973eeda99fb85b47b792f8215de8cc9c04a21
| 508
|
hpp
|
C++
|
src/classifier/svm/svm_binary_classifier.hpp
|
bububa/openvision
|
0864e48ec8e69ac13d6889d41f7e1171f53236dd
|
[
"Apache-2.0"
] | 1
|
2022-02-08T06:42:05.000Z
|
2022-02-08T06:42:05.000Z
|
src/classifier/svm/svm_binary_classifier.hpp
|
bububa/openvision
|
0864e48ec8e69ac13d6889d41f7e1171f53236dd
|
[
"Apache-2.0"
] | null | null | null |
src/classifier/svm/svm_binary_classifier.hpp
|
bububa/openvision
|
0864e48ec8e69ac13d6889d41f7e1171f53236dd
|
[
"Apache-2.0"
] | null | null | null |
#ifndef _CLASSIFIER_SVM_BINARY_CLASSIFIER_H_
#define _CLASSIFIER_SVM_BINARY_CLASSIFIER_H_
#include "svm_classifier.hpp"
namespace ovclassifier {
class SVMBinaryClassifier : public SVMClassifier {
public:
SVMBinaryClassifier();
~SVMBinaryClassifier();
int LoadModel(const char *modelfile);
double Predict(const float *vec);
int Classify(const float *vec, std::vector<float> &scores);
private:
MODEL *model_ = NULL;
};
} // namespace ovclassifier
#endif // !_CLASSIFIER_SVM_BINARY_CLASSIFIER_H_
| 25.4
| 61
| 0.787402
|
bububa
|
169a7726b883813a797f1edb1cafbf61c2138cc6
| 10,234
|
cpp
|
C++
|
Rise/src/Platform/OpenGL/OpenGLShader.cpp
|
Super-Shadow/Rise
|
38f0cfd1d63365958c6ff8252598ce871525c885
|
[
"Apache-2.0"
] | null | null | null |
Rise/src/Platform/OpenGL/OpenGLShader.cpp
|
Super-Shadow/Rise
|
38f0cfd1d63365958c6ff8252598ce871525c885
|
[
"Apache-2.0"
] | null | null | null |
Rise/src/Platform/OpenGL/OpenGLShader.cpp
|
Super-Shadow/Rise
|
38f0cfd1d63365958c6ff8252598ce871525c885
|
[
"Apache-2.0"
] | null | null | null |
#include "rspch.h"
#include "OpenGLShader.h"
#include <fstream>
#include <utility>
#include <glad/glad.h>
#include "glm/gtc/type_ptr.hpp"
namespace Rise
{
static GLenum ShaderTypeFromString(const std::string& type)
{
if (type == "vertex")
return GL_VERTEX_SHADER;
if (type == "fragment" || type == "pixel")
return GL_FRAGMENT_SHADER;
RS_CORE_ASSERT(false, "Unknown shader type '" + type + "'!");
return NULL;
}
OpenGLShader::OpenGLShader(const std::string& filePath)
{
RS_PROFILE_FUNCTION();
const auto source = ReadFile(filePath);
const auto shaderSources = PreProcess(source);
Compile(shaderSources);
// File name from file path
auto lastSlash = filePath.find_last_of("/\\");
lastSlash = lastSlash == std::string::npos ? 0 : lastSlash + 1;
const auto lastDot = filePath.rfind('.');
const auto count = lastDot == std::string::npos ? filePath.size() - lastSlash : lastDot - lastSlash;
m_Name = filePath.substr(lastSlash, count);
}
OpenGLShader::OpenGLShader(std::string name, const std::string& vertexSrc, const std::string& fragmentSrc) : m_Name(std::move(name))
{
RS_PROFILE_FUNCTION();
std::unordered_map<GLenum, std::string> sources;
sources[GL_VERTEX_SHADER] = vertexSrc;
sources[GL_FRAGMENT_SHADER] = fragmentSrc;
Compile(sources);
}
OpenGLShader::~OpenGLShader()
{
RS_PROFILE_FUNCTION();
glDeleteProgram(m_RendererID);
}
std::string OpenGLShader::ReadFile(const std::string& filePath)
{
RS_PROFILE_FUNCTION();
std::string result;
std::ifstream in(filePath, std::ios::in | std::ios::binary);
if (in)
{
in.seekg(0, std::ios::end);
const auto size = in.tellg();
if (size != -1)
{
result.resize(size);
in.seekg(0, std::ios::beg);
in.read(&result[0], size);
in.close();
}
else
{
RS_CORE_ERROR("Could not read from file '{0}'", filePath);
}
}
else
{
RS_CORE_ERROR("Could not open file '{0}'", filePath);
}
return result;
}
std::unordered_map<GLenum, std::string> OpenGLShader::PreProcess(const std::string& source)
{
RS_PROFILE_FUNCTION();
std::unordered_map<GLenum, std::string> shaderSources;
constexpr auto typeToken = "#type";
//const auto typeTokenLength = strlen(typeToken);
auto pos = source.find(typeToken, 0);
RS_CORE_ASSERT(pos != std::string::npos, "Shader missing #type!");
while (pos != std::string::npos)
{
const auto endOfLine = source.find_first_of("\r\n", pos);
RS_CORE_ASSERT(endOfLine != std::string::npos, "Syntax error");
const auto begin = pos + /*typeTokenLength + 1 */ 6; // The plus 1 is how many whitespaces between '#type vertex'
auto type = source.substr(begin, endOfLine - begin);
RS_CORE_ASSERT(ShaderTypeFromString(type), "Invalid shader type specification!"); // TODO: This is useless due to exact same asset in ShaderTypeFromString
const auto nextLinePos = source.find_first_not_of("\r\n", endOfLine);
RS_CORE_ASSERT(nextLinePos != std::string::npos, "Syntax error");
pos = source.find(typeToken, nextLinePos);
shaderSources[ShaderTypeFromString(type)] = source.substr(nextLinePos, pos - (nextLinePos == std::string::npos ? source.size() - 1 : nextLinePos));
}
return shaderSources;
}
void OpenGLShader::Compile(const std::unordered_map<GLenum, std::string>& shaderSources)
{
RS_PROFILE_FUNCTION();
// Now time to link them together into a program.
// Get a program object.
const auto program = glCreateProgram();
RS_CORE_ASSERT(shaderSources.size() <= 2, "Unsupported amount of shaders!");
std::array<GLenum, 2> glShaderIDs{};
auto glShaderIDIndex = 0;
for (const auto& [first, second] : shaderSources) // Good use of structural binding!
{
const auto type = first;
const auto source = second;
// Create an empty vertex shader handle
const auto shader = glCreateShader(type);
// Send the vertex shader source code to GL
// Note that std::string's .c_str is NULL character terminated.
auto sourceCstr = source.c_str();
glShaderSource(shader, 1, &sourceCstr, nullptr);
// Compile the vertex shader
glCompileShader(shader);
GLint isCompiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(shader, maxLength, &maxLength, &infoLog[0]);
// Either of them. Don't leak shaders.
glDeleteShader(shader);
// Use the infoLog as you see fit.
RS_CORE_ERROR("{0}", infoLog.data());
RS_CORE_ASSERT(false, "Shader compilation failure!");
// In this simple program, we'll just leave
break;
}
// Vertex and fragment shaders are successfully compiled.
// Attach our shaders to our program
glAttachShader(program, shader);
glShaderIDs[glShaderIDIndex++] = shader;
}
// Link our program
glLinkProgram(program);
// Note the different functions here: glGetProgram* instead of glGetShader*.
GLint isLinked;
glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
if (isLinked == GL_FALSE)
{
GLint maxLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);
// We don't need the program anymore.
glDeleteProgram(program);
// Don't leak shaders either.
for (const auto shader : glShaderIDs)
{
glDeleteShader(shader);
}
// Use the infoLog as you see fit.
RS_CORE_ERROR("{0}", infoLog.data());
RS_CORE_ASSERT(false, "Shader link failure!");
// In this simple program, we'll just leave
return;
}
// Always detach shaders after a successful link.
for (const auto shader : glShaderIDs)
{
glDetachShader(program, shader);
}
m_RendererID = program;
}
void OpenGLShader::Bind() const
{
RS_PROFILE_FUNCTION();
glUseProgram(m_RendererID);
}
void OpenGLShader::Unbind() const
{
RS_PROFILE_FUNCTION();
glUseProgram(0);
}
void OpenGLShader::SetInt(const std::string& name, const int value) const
{
RS_PROFILE_FUNCTION();
UploadUniformInt(name, value);
}
void OpenGLShader::SetIntArray(const std::string& name, const int* values, const int count) const
{
RS_PROFILE_FUNCTION();
UploadUniformIntArray(name, values, count);
}
void OpenGLShader::SetFloat(const std::string& name, const float value) const
{
RS_PROFILE_FUNCTION();
UploadUniformFloat(name, value);
}
void OpenGLShader::SetFloat3(const std::string& name, const glm::vec3& value) const
{
RS_PROFILE_FUNCTION();
UploadUniformFloat3(name, value);
}
void OpenGLShader::SetFloat4(const std::string& name, const glm::vec4& value) const
{
RS_PROFILE_FUNCTION();
UploadUniformFloat4(name, value);
}
void OpenGLShader::SetMat4(const std::string& name, const glm::mat4& value) const
{
RS_PROFILE_FUNCTION();
UploadUniformMat4(name, value);
}
void OpenGLShader::UploadUniformInt(const std::string& name, const int value) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if(location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform int named {1}.", m_Name, name);
glUniform1i(location, value);
}
void OpenGLShader::UploadUniformIntArray(const std::string& name, const int* values, const int count) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform int array named {1}.", m_Name, name);
glUniform1iv(location, count, values);
}
void OpenGLShader::UploadUniformFloat(const std::string& name, const float value) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform float named {1}.", m_Name, name);
glUniform1f(location, value);
}
void OpenGLShader::UploadUniformFloat2(const std::string& name, const glm::vec2& values) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform vec2 named {1}.", m_Name, name);
glUniform2f(location, values.x, values.y);
}
void OpenGLShader::UploadUniformFloat3(const std::string& name, const glm::vec3& values) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform vec3 named {1}.", m_Name, name);
glUniform3f(location, values.x, values.y, values.z);
}
void OpenGLShader::UploadUniformFloat4(const std::string& name, const glm::vec4& values) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform vec4 named {1}.", m_Name, name);
glUniform4f(location, values.x, values.y, values.z, values.w);
}
void OpenGLShader::UploadUniformMat3(const std::string& name, const glm::mat3& matrix) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform mat3 named {1}.", m_Name, name);
// count means how many matrices are we giving, so we put 1. If we used DirectX maths (column-major order) we would need to say GL_TRUE for auto transpose to OpenGL maths (row-major order).
glUniformMatrix3fv(location, 1, GL_FALSE, value_ptr(matrix)); // f means float and v means an array as it is 16 floats
}
void OpenGLShader::UploadUniformMat4(const std::string& name, const glm::mat4& matrix) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform mat4 named {1}.", m_Name, name);
// count means how many matrices are we giving, so we put 1. If we used DirectX maths (column-major order) we would need to say GL_TRUE for auto transpose to OpenGL maths (row-major order).
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix)); // f means float and v means an array as it is 16 floats
}
}
| 30.188791
| 191
| 0.707543
|
Super-Shadow
|
169b5d902e718a2729be42c7c2d447d5a6eef8f7
| 4,362
|
cpp
|
C++
|
luogu/APIO-fun/fun.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
luogu/APIO-fun/fun.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
luogu/APIO-fun/fun.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#include "fun.h"
using namespace std;
typedef vector<int> V;
const int N=120000;
int dep[N],sz[N],rt=0,n,cnt=0,id[3],nowpos=-1;
vector<int> son[N],ans;
bool cmp(int x,int y){return dep[x]<dep[y];}
void solver2(int idx,int idy){//X first
while(!son[idx].empty()||!son[idy].empty()){
if(son[idx].empty()) break;
ans.push_back(son[idx].back());
son[idx].pop_back(); swap(idx,idy);
}
ans.push_back(rt);
if(!son[idx].empty()) ans.push_back(son[idx][0]);
if(!son[idy].empty()) ans.push_back(son[idy][0]);
}
typedef pair<int,int> pii;
#define mk make_pair
set<pii> st[N];
void solver3(){
int mx=0,ID;
for(int i=0;i<=2;i++)
if((int)son[id[i]].size()>mx) mx=(int)son[id[i]].size(), ID=i;
if(mx*2==n){
if(ID!=0) swap(id[ID],id[0]);
for(int i=0;i<(int)son[id[2]].size();i++)
son[id[1]].push_back(son[id[2]][i]);
sort(son[id[1]].begin(),son[id[1]].end(),cmp);
solver2(id[0],id[1]);
return;
}
for(int i=0;i<=2;i++) {
for(int j=0;j<(int)son[id[i]].size();j++){
int to=son[id[i]][j];
st[id[i]].insert(mk(dep[to],to));
}
}
int PRE=-1,rest=n,pre=1000000,predep=-1;
while('M'+'Y'+'Y'+'A'+'N'+'D'+'H'+'C'+'Y'+'A'+'K'+'I'+'O'+'I'){
int mx1=((st[id[0]].empty()||PRE==id[0]) ? -1 : st[id[0]].rbegin()->second);
int mx2=((st[id[1]].empty()||PRE==id[1]) ? -1 : st[id[1]].rbegin()->second);
int mx3=((st[id[2]].empty()||PRE==id[2]) ? -1 : st[id[2]].rbegin()->second);
mx=0; int iid;
if(mx1!=-1&&mx<dep[mx1]) mx=dep[mx1],ID=0,iid=mx1;
if(mx2!=-1&&mx<dep[mx2]) mx=dep[mx2],ID=1,iid=mx2;
if(mx3!=-1&&mx<dep[mx3]) mx=dep[mx3],ID=2,iid=mx3;
assert(mx1!=-1||mx2!=-1||mx3!=-1);
st[id[ID]].erase(mk(dep[iid],iid));
ans.push_back(iid); rest--;
assert(rest==n-2||predep+dep[iid]<=pre);
pre=predep+dep[iid]; predep=dep[iid];
PRE=id[ID];
mx=0,ID;
for(int i=0;i<=2;i++)
if((int)st[id[i]].size()>mx) mx=(int)st[id[i]].size(), ID=i;
if(mx*2==rest){
int tmpid=ID;
mx1=((st[id[0]].empty()||PRE==id[0]) ? -1 : st[id[0]].rbegin()->second);
mx2=((st[id[1]].empty()||PRE==id[1]) ? -1 : st[id[1]].rbegin()->second);
mx3=((st[id[2]].empty()||PRE==id[2]) ? -1 : st[id[2]].rbegin()->second);
mx=0;
if(mx1!=-1&&mx<dep[mx1]) mx=dep[mx1],ID=0,iid=mx1;
if(mx2!=-1&&mx<dep[mx2]) mx=dep[mx2],ID=1,iid=mx2;
if(mx3!=-1&&mx<dep[mx3]) mx=dep[mx3],ID=2,iid=mx3;
int CH=0;
if(ID!=tmpid&&mx>predep) CH=1;
for(int i=0;i<=2;i++){
son[id[i]].clear();
while(!st[id[i]].empty()) {
if(CH!=1||st[id[i]].begin()->second!=iid)
son[id[i]].push_back(st[id[i]].begin()->second);
st[id[i]].erase(st[id[i]].begin());
}
}
if(tmpid!=0) swap(id[tmpid],id[0]);
for(int i=0;i<(int)son[id[2]].size();i++)
son[id[1]].push_back(son[id[2]][i]);
sort(son[id[0]].begin(),son[id[0]].end(),cmp);
sort(son[id[1]].begin(),son[id[1]].end(),cmp);
if(CH) son[id[1]].push_back(iid);
if(!CH) solver2(id[0],id[1]);
else solver2(id[1],id[0]);
return;
}
}
}
void init()
{
sz[0]=n;
for(int i=1;i<n;i++) sz[i]=attractionsBehind(0,i);
for(int i=1;i<n;i++)
if(sz[i]<sz[rt]&&sz[i]>=(n+1)/2) rt=i;
for(int i=0;i<n;i++) if(i!=rt){
dep[i]=hoursRequired(rt,i);
if(dep[i]==1) id[cnt++]=i, son[i].push_back(i);
}
for(int i=0;i<n;i++) if(i!=rt&&dep[i]!=1){
int dis1=hoursRequired(id[0],i),dis2=hoursRequired(id[1],i);
if(dis1==dep[i]-1) son[id[0]].push_back(i);
else if(dis2==dep[i]-1) son[id[1]].push_back(i);
else son[id[2]].push_back(i);
}
for(int i=0;i<cnt;i++) sort(son[id[i]].begin(),son[id[i]].end(),cmp);
}
std::vector<int> createFunTour(int NN, int Q)
{
n=NN;
if(NN==2) {vector<int> TMP; TMP.push_back(0); TMP.push_back(1); return TMP;}
init();
if(cnt==2) solver2(id[0],id[1]);
else solver3();
return ans;
}
| 36.655462
| 84
| 0.475928
|
jinzhengyu1212
|
169fd335a59b3723d4d21ba0e9d773c14d5bee16
| 10,690
|
hpp
|
C++
|
tests/test_queue.hpp
|
bcfrutuozo/Data-Structures-C-Plus-Plus
|
decd87c89380dbd98445411772567706cfa1e9b4
|
[
"MIT"
] | null | null | null |
tests/test_queue.hpp
|
bcfrutuozo/Data-Structures-C-Plus-Plus
|
decd87c89380dbd98445411772567706cfa1e9b4
|
[
"MIT"
] | null | null | null |
tests/test_queue.hpp
|
bcfrutuozo/Data-Structures-C-Plus-Plus
|
decd87c89380dbd98445411772567706cfa1e9b4
|
[
"MIT"
] | null | null | null |
//
// Created by bcfrutuozo on 18/03/2022.
//
#ifndef CPPDATASTRUCTURES_TEST_QUEUE_HPP
#define CPPDATASTRUCTURES_TEST_QUEUE_HPP
#include <catch2/catch.hpp>
#include <cstring>
#include "../Queue.h"
TEST_CASE("Queue<T>")
{
SECTION("Instantiation")
{
SECTION("Primitive types")
{
SECTION("Queue<uint8_t>")
{
Queue<uint8_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1u);
c.Enqueue(2u);
c.Enqueue(3u);
c.Enqueue(4u);
c.Enqueue(5u);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint8_t>{1u, 2u, 3u, 4u, 5u});
}
SECTION("Queue<uint16_t>")
{
Queue<uint16_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1u);
c.Enqueue(2u);
c.Enqueue(3u);
c.Enqueue(4u);
c.Enqueue(5u);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint16_t>{1u, 2u, 3u, 4u, 5u});
}
SECTION("Queue<uint32_t>")
{
Queue<uint32_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1u);
c.Enqueue(2u);
c.Enqueue(3u);
c.Enqueue(4u);
c.Enqueue(5u);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint32_t>{1u, 2u, 3u, 4u, 5u});
}
SECTION("Queue<uint64_t>")
{
Queue<uint64_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1ul);
c.Enqueue(2ul);
c.Enqueue(3ul);
c.Enqueue(4ul);
c.Enqueue(5ul);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint64_t>{1ul, 2ul, 3ul, 4ul, 5ul});
}
SECTION("Queue<int8_t>")
{
Queue<int8_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1);
c.Enqueue(2);
c.Enqueue(3);
c.Enqueue(4);
c.Enqueue(5);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int8_t>{1, 2, 3, 4, 5});
}
SECTION("Queue<int16_t>")
{
Queue<int16_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1);
c.Enqueue(2);
c.Enqueue(3);
c.Enqueue(4);
c.Enqueue(5);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int16_t>{1, 2, 3, 4, 5});
}
SECTION("Queue<int32_t>")
{
Queue<int32_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1);
c.Enqueue(2);
c.Enqueue(3);
c.Enqueue(4);
c.Enqueue(5);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int32_t>{1, 2, 3, 4, 5});
}
SECTION("Queue<int64_t>")
{
Queue<int64_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1l);
c.Enqueue(2l);
c.Enqueue(3l);
c.Enqueue(4l);
c.Enqueue(5l);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int64_t>{1l, 2l, 3l, 4l, 5l});
}
SECTION("Queue<char>")
{
Queue<char> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue('1');
c.Enqueue('2');
c.Enqueue('3');
c.Enqueue('4');
c.Enqueue('5');
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<char>{'1', '2', '3', '4', '5'});
}
SECTION("Queue<unsigned char>")
{
Queue<unsigned char> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue('1');
c.Enqueue('2');
c.Enqueue('3');
c.Enqueue('4');
c.Enqueue('5');
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<unsigned char>{'1', '2', '3', '4', '5'});
}
SECTION("Queue<float>")
{
Queue<float> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1.0f);
c.Enqueue(2.0f);
c.Enqueue(3.0f);
c.Enqueue(4.0f);
c.Enqueue(5.0);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
}
SECTION("Queue<double>")
{
Queue<double> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1.0f);
c.Enqueue(2.0f);
c.Enqueue(3.0f);
c.Enqueue(4.0f);
c.Enqueue(5.0);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<double>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
}
}
SECTION("Non-primitive types")
{
SECTION("Queue<const char*> Array")
{
Queue<const char *> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue("ABC");
c.Enqueue("BRUNO");
c.Enqueue("FRUTUOZO");
REQUIRE(c.GetLength() == 3);
REQUIRE(c == Queue<const char*>{"ABC", "BRUNO", "FRUTUOZO"});
}
}
SECTION("Copy constructor")
{
Queue<int> a{1, 2, 3, 4, 5, 6};
Queue<int> b(a);
REQUIRE(a == b);
a.Enqueue(7);
REQUIRE(a != b);
REQUIRE(a.Dequeue() == 1);
REQUIRE(a == Queue<int>{2, 3, 4, 5, 6, 7});
a.Dequeue();
a.Enqueue(10);
REQUIRE(a != b);
}
SECTION("Copy assignment constructor")
{
Queue<int> a{1, 2, 3, 4, 5, 6};
Queue<int> b = a;
REQUIRE(a == b);
a.Enqueue(7);
REQUIRE(a != b);
Queue<int> c{2, 3, 4, 5, 6, 7};
REQUIRE(a.Dequeue() == 1);
REQUIRE(a == c);
a.Dequeue();
a.Enqueue(10);
REQUIRE(a != b);
}
SECTION("Move constructor")
{
Queue<int> a{1, 2, 3, 4};
Queue<int> b = std::move(a);
REQUIRE(a.IsEmpty());
REQUIRE(b == Queue<int>({1, 2, 3, 4}));
}
SECTION("Move assignment")
{
Queue<int> a{1, 2, 3, 4};
Queue<int> b{5, 6};
b = std::move(a);
REQUIRE(a.IsEmpty());
REQUIRE(b == Queue<int>({1, 2, 3, 4}));
}
}
SECTION("Comparison")
{
SECTION("Queue<T> == Queue<T>")
{
REQUIRE(Queue<int>{1, 2, 3, 4, 5, 6} == Queue<int>{1, 2, 3, 4, 5, 6});
}
SECTION("Queue<T> != Queue<T>")
{
REQUIRE(Queue<int>{1, 2, 3, 4, 5, 6} != Queue<int>{1, 2, 3, 0, 5, 6});
}
}
SECTION("Push elements")
{
SECTION("Single element")
{
Queue<const char *> c = {"A", "TEST", "LOREM"};
c.Enqueue("ZZZZZ");
REQUIRE(c.GetLength() == 4);
REQUIRE(strcmp(c.Dequeue(), "A") == 0);
}
SECTION("Array of elements")
{
SECTION("Single element")
{
Queue<const char *> c = {"A", "TEST", "LOREM"};
Array<const char *> a = {"ABC", "DEF", "ZZZ"};
c.Enqueue(a);
REQUIRE(c.GetLength() == 6);
REQUIRE(strcmp(c.Dequeue(), "A") == 0);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<const char *> {"TEST", "LOREM", "ABC", "DEF", "ZZZ"});
}
SECTION("Array of elements")
{
Queue<const char *> c = {"A", "TEST", "LOREM", "TEST", "TEST2", "TEST3"};
REQUIRE(c.GetLength() == 6);
Array<const char *> a = c.Dequeue(3);
REQUIRE(a.GetLength() == 3);
REQUIRE(c.GetLength() == 3);
REQUIRE(strcmp(a[0], "A") == 0);
REQUIRE(strcmp(a[1], "TEST") == 0);
REQUIRE(strcmp(a[2], "LOREM") == 0);
}
}
}
SECTION("Pop elements")
{
Queue<int> c = {4, 99, -37, 0, 2};
REQUIRE(c.Dequeue() == 4);
REQUIRE(c.Dequeue() == 99);
REQUIRE(c.Dequeue() == -37);
REQUIRE(c.Dequeue() == 0);
REQUIRE(c.Dequeue() == 2);
CHECK_THROWS(c.Dequeue());
}
SECTION("Check peek")
{
Queue<int> c = {4, 99, -37, 0, 2};
REQUIRE(c.Peek() == 4);
REQUIRE(c.GetLength() == 5);
while (!c.IsEmpty())
c.Dequeue();
CHECK_THROWS(c.Peek());
}
SECTION("Clear container")
{
Queue<const char *> a{"ABC", "DEF", "GHIJKLM"};
a.Clear();
REQUIRE(a == Queue<const char*>{});
}
SECTION("Swap container")
{
Queue<int> a{0, 1, 2, 3};
Queue<int> b{9, 8, 7, 6};
a.Swap(b);
REQUIRE(a.Dequeue() == 9);
REQUIRE(a.Dequeue() == 8);
REQUIRE(a.Dequeue() == 7);
REQUIRE(a.Dequeue() == 6);
CHECK_THROWS(a.Dequeue());
REQUIRE(b.Dequeue() == 0);
REQUIRE(b.Dequeue() == 1);
REQUIRE(b.Dequeue() == 2);
REQUIRE(b.Dequeue() == 3);
CHECK_THROWS(b.Dequeue());
}
SECTION("Conversion to Array<T>") {
Queue<int> a{1, 2, 3, 4, 5};
Array<int> b = a.ToArray();
REQUIRE(a == Queue<int>{1, 2, 3, 4, 5});
REQUIRE(b == Array<int>{1, 2, 3, 4, 5});
}
SECTION("CopyTo(Array<T>)") {
Queue<int> a{1, 2, 3, 4, 5, 6};
Array<int> b{0, 0, 0, 0, 0, 0, 0, 0};
a.CopyTo(b, 2);
REQUIRE(b == Array<int>{0, 0, 1, 2, 3, 4, 5, 6});
Array<int> c;
CHECK_THROWS(a.CopyTo(c, 0));
Array<int> d{1, 2, 3};
a.CopyTo(d, 2);
REQUIRE(d == Array<int>{1, 2, 1, 2, 3, 4, 5, 6});
Array<int> e{1};
CHECK_THROWS(a.CopyTo(e, 1));
Array<int> f{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
a.CopyTo(f, 2);
REQUIRE(f == Array<int>{0, 0, 1, 2, 3, 4, 5, 6, 0, 0});
}
}
#endif //CPPDATASTRUCTURES_TEST_QUEUE_HPP
| 29.449036
| 89
| 0.389429
|
bcfrutuozo
|
16a1b63592a799349ae4ceee6923bc274609e766
| 1,800
|
cpp
|
C++
|
aws-cpp-sdk-workspaces-web/source/model/CreatePortalRequest.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-workspaces-web/source/model/CreatePortalRequest.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-workspaces-web/source/model/CreatePortalRequest.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/workspaces-web/model/CreatePortalRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::WorkSpacesWeb::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreatePortalRequest::CreatePortalRequest() :
m_additionalEncryptionContextHasBeenSet(false),
m_clientToken(Aws::Utils::UUID::RandomUUID()),
m_clientTokenHasBeenSet(true),
m_customerManagedKeyHasBeenSet(false),
m_displayNameHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Aws::String CreatePortalRequest::SerializePayload() const
{
JsonValue payload;
if(m_additionalEncryptionContextHasBeenSet)
{
JsonValue additionalEncryptionContextJsonMap;
for(auto& additionalEncryptionContextItem : m_additionalEncryptionContext)
{
additionalEncryptionContextJsonMap.WithString(additionalEncryptionContextItem.first, additionalEncryptionContextItem.second);
}
payload.WithObject("additionalEncryptionContext", std::move(additionalEncryptionContextJsonMap));
}
if(m_clientTokenHasBeenSet)
{
payload.WithString("clientToken", m_clientToken);
}
if(m_customerManagedKeyHasBeenSet)
{
payload.WithString("customerManagedKey", m_customerManagedKey);
}
if(m_displayNameHasBeenSet)
{
payload.WithString("displayName", m_displayName);
}
if(m_tagsHasBeenSet)
{
Array<JsonValue> tagsJsonList(m_tags.size());
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
}
payload.WithArray("tags", std::move(tagsJsonList));
}
return payload.View().WriteReadable();
}
| 24
| 130
| 0.757778
|
perfectrecall
|
16a8a92be01e8f75ab13847343727400919aa1bf
| 234
|
hpp
|
C++
|
chaine/src/topology/vertex/vertex_topology.hpp
|
the-last-willy/id3d
|
dc0d22e7247ac39fbc1fd8433acae378b7610109
|
[
"MIT"
] | null | null | null |
chaine/src/topology/vertex/vertex_topology.hpp
|
the-last-willy/id3d
|
dc0d22e7247ac39fbc1fd8433acae378b7610109
|
[
"MIT"
] | null | null | null |
chaine/src/topology/vertex/vertex_topology.hpp
|
the-last-willy/id3d
|
dc0d22e7247ac39fbc1fd8433acae378b7610109
|
[
"MIT"
] | null | null | null |
#pragma once
#include "index.hpp"
#include "mesh_topology.hpp"
#include "proxy.hpp"
namespace face_vertex {
inline
VertexTopology& vertex_topology(VertexTopologyProxy vtp) {
return mesh_topology(vtp).vertices[index(vtp)];
}
}
| 15.6
| 58
| 0.760684
|
the-last-willy
|
16a96378d705e59dea9725ce272640df3a1753d2
| 799
|
cpp
|
C++
|
test/training_data/plag_original_codes/01_000_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | 13
|
2021-01-20T19:53:16.000Z
|
2021-11-14T16:30:32.000Z
|
test/training_data/plag_original_codes/01_000_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | null | null | null |
test/training_data/plag_original_codes/01_000_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | null | null | null |
// 引用元 : https://atcoder.jp/contests/abc122/submissions/5997478
// 得点 : 300
// コード長 : 695
// 実行時間 : 70
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
typedef long long ll;
int main() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
vector<int> l(q), r(q);
rep(i, q) {
cin >> l[i] >> r[i];
}
vector<int> sum(n+1, 0);
for(int i = 1; i < n; i++) {
sum[i+1] = sum[i];
if(s[i-1] == 'A' && s[i] == 'C') {
sum[i+1]++;
}
}
rep(i, q) { int ans = sum[r[i]] - sum[l[i]];
cout << ans << "\n";
}
cout << endl;
return 0;
}
| 17.755556
| 64
| 0.439299
|
xryuseix
|
16a9bfb5be620f91ef04c39ba3805580f30c4aff
| 308
|
cpp
|
C++
|
C7Editing/data/c7framedata.cpp
|
xshanlin/c7es
|
520ab5b7efe54521aeb930e6baf60b8bb62a8027
|
[
"MIT"
] | null | null | null |
C7Editing/data/c7framedata.cpp
|
xshanlin/c7es
|
520ab5b7efe54521aeb930e6baf60b8bb62a8027
|
[
"MIT"
] | null | null | null |
C7Editing/data/c7framedata.cpp
|
xshanlin/c7es
|
520ab5b7efe54521aeb930e6baf60b8bb62a8027
|
[
"MIT"
] | null | null | null |
#include "c7framedata.h"
PO1_IMPLEMENTATION_BEGIN(C7FrameData, RIID_C7FRAME_DATA)
//PO1_ITEM_IMPLEMENTATION(C7BufferIO2D, RIID_C7BUFFER_IO_2D)
PO1_IMPLEMENTATION_END(C7Obj)
C7FrameData::C7FrameData(std::weak_ptr<C7Obj> outerObj) : C7Obj(outerObj) {
//ctor
}
C7FrameData::~C7FrameData() {
//dtor
}
| 22
| 75
| 0.782468
|
xshanlin
|
16b57a15a8897b655aa2d8b37f92ea3b7bbf4cf3
| 5,047
|
cpp
|
C++
|
code/wxWidgets/src/mac/classic/metafile.cpp
|
Bloodknight/NeuTorsion
|
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
|
[
"MIT"
] | 38
|
2016-02-20T02:46:28.000Z
|
2021-11-17T11:39:57.000Z
|
code/wxWidgets/src/mac/classic/metafile.cpp
|
Dwarf-King/TorsionEditor
|
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
|
[
"MIT"
] | 17
|
2016-02-20T02:19:55.000Z
|
2021-02-08T15:15:17.000Z
|
code/wxWidgets/src/mac/classic/metafile.cpp
|
Dwarf-King/TorsionEditor
|
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
|
[
"MIT"
] | 46
|
2016-02-20T02:47:33.000Z
|
2021-01-31T15:46:05.000Z
|
/////////////////////////////////////////////////////////////////////////////
// Name: metafile.cpp
// Purpose: wxMetaFile, wxMetaFileDC etc. These classes are optional.
// Author: Stefan Csomor
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id: metafile.cpp,v 1.4 2005/07/28 22:08:23 VZ Exp $
// Copyright: (c) Stefan Csomor
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "metafile.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/setup.h"
#endif
#if wxUSE_METAFILE
#ifndef WX_PRECOMP
#include "wx/utils.h"
#include "wx/app.h"
#endif
#include "wx/metafile.h"
#include "wx/clipbrd.h"
#include "wx/mac/private.h"
#include <stdio.h>
#include <string.h>
extern bool wxClipboardIsOpen;
IMPLEMENT_DYNAMIC_CLASS(wxMetafile, wxObject)
IMPLEMENT_ABSTRACT_CLASS(wxMetafileDC, wxDC)
/*
* Metafiles
* Currently, the only purpose for making a metafile is to put
* it on the clipboard.
*/
wxMetafileRefData::wxMetafileRefData(void)
{
m_metafile = 0;
}
wxMetafileRefData::~wxMetafileRefData(void)
{
if (m_metafile)
{
KillPicture( (PicHandle) m_metafile ) ;
m_metafile = 0;
}
}
wxMetaFile::wxMetaFile(const wxString& file)
{
m_refData = new wxMetafileRefData;
M_METAFILEDATA->m_metafile = 0;
wxASSERT_MSG( file.IsEmpty() , wxT("no file based metafile support yet") ) ;
/*
if (!file.IsNull() && (file.Cmp("") == 0))
M_METAFILEDATA->m_metafile = (WXHANDLE) GetMetaFile(file);
*/
}
wxMetaFile::~wxMetaFile()
{
}
bool wxMetaFile::SetClipboard(int width, int height)
{
#if wxUSE_DRAG_AND_DROP
//TODO finishi this port , we need the data obj first
if (!m_refData)
return FALSE;
bool alreadyOpen=wxTheClipboard->IsOpened() ;
if (!alreadyOpen)
{
wxTheClipboard->Open();
wxTheClipboard->Clear();
}
wxDataObject *data =
new wxMetafileDataObject( *this) ;
bool success = wxTheClipboard->SetData(data);
if (!alreadyOpen)
wxTheClipboard->Close();
return (bool) success;
#endif
return TRUE ;
}
void wxMetafile::SetHMETAFILE(WXHMETAFILE mf)
{
if (!m_refData)
m_refData = new wxMetafileRefData;
if ( M_METAFILEDATA->m_metafile )
KillPicture( (PicHandle) M_METAFILEDATA->m_metafile ) ;
M_METAFILEDATA->m_metafile = mf;
}
bool wxMetaFile::Play(wxDC *dc)
{
if (!m_refData)
return FALSE;
if (!dc->Ok() )
return FALSE;
{
wxMacPortSetter helper( dc ) ;
PicHandle pict = (PicHandle) GetHMETAFILE() ;
DrawPicture( pict , &(**pict).picFrame ) ;
}
return TRUE;
}
wxSize wxMetaFile::GetSize() const
{
wxSize size = wxDefaultSize ;
if ( Ok() )
{
PicHandle pict = (PicHandle) GetHMETAFILE() ;
Rect &r = (**pict).picFrame ;
size.x = r.right - r.left ;
size.y = r.bottom - r.top ;
}
return size;
}
/*
* Metafile device context
*
*/
// New constructor that takes origin and extent. If you use this, don't
// give origin/extent arguments to wxMakeMetaFilePlaceable.
wxMetaFileDC::wxMetaFileDC(const wxString& filename ,
int width , int height ,
const wxString& WXUNUSED(description) )
{
wxASSERT_MSG( width == 0 || height == 0 , _T("no arbitration of metafilesize supported") ) ;
wxASSERT_MSG( filename.IsEmpty() , _T("no file based metafile support yet")) ;
m_metaFile = new wxMetaFile(filename) ;
Rect r={0,0,height,width} ;
RectRgn( (RgnHandle) m_macBoundaryClipRgn , &r ) ;
CopyRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
m_metaFile->SetHMETAFILE( OpenPicture( &r ) ) ;
::GetPort( (GrafPtr*) &m_macPort ) ;
m_ok = TRUE ;
SetMapMode(wxMM_TEXT);
}
wxMetaFileDC::~wxMetaFileDC()
{
}
void wxMetaFileDC::DoGetSize(int *width, int *height) const
{
wxCHECK_RET( m_metaFile , _T("GetSize() doesn't work without a metafile") );
wxSize sz = m_metaFile->GetSize() ;
if (width) (*width) = sz.x;
if (height) (*height) = sz.y;
}
wxMetaFile *wxMetaFileDC::Close()
{
ClosePicture() ;
return m_metaFile;
}
#if wxUSE_DATAOBJ
size_t wxMetafileDataObject::GetDataSize() const
{
return GetHandleSize( (Handle) (*((wxMetafile*)&m_metafile)).GetHMETAFILE() ) ;
}
bool wxMetafileDataObject::GetDataHere(void *buf) const
{
memcpy( buf , (*(PicHandle)(*((wxMetafile*)&m_metafile)).GetHMETAFILE()) ,
GetHandleSize( (Handle) (*((wxMetafile*)&m_metafile)).GetHMETAFILE() ) ) ;
return true ;
}
bool wxMetafileDataObject::SetData(size_t len, const void *buf)
{
Handle handle = NewHandle( len ) ;
SetHandleSize( handle , len ) ;
memcpy( *handle , buf , len ) ;
m_metafile.SetHMETAFILE( handle ) ;
return true ;
}
#endif
#endif
| 23.151376
| 96
| 0.626907
|
Bloodknight
|
16b5f2b5511dc3654c63a913753b1c2314fc2545
| 6,636
|
cc
|
C++
|
ch16/generic_programing/copy.cc
|
leschus/cpp_primer_plus_6th
|
1d0ca7e22d41e5039dd08befd451c2c339e854f1
|
[
"MIT"
] | 1
|
2022-03-04T08:34:18.000Z
|
2022-03-04T08:34:18.000Z
|
ch16/generic_programing/copy.cc
|
leschus/cpp_primer_plus_6th
|
1d0ca7e22d41e5039dd08befd451c2c339e854f1
|
[
"MIT"
] | null | null | null |
ch16/generic_programing/copy.cc
|
leschus/cpp_primer_plus_6th
|
1d0ca7e22d41e5039dd08befd451c2c339e854f1
|
[
"MIT"
] | null | null | null |
#include <iterator> // 提供多种迭代器模板: ostream_iterator, istream_iterator,
// reverse_iterator, back_insert_iterator,
// front_insert_iterator, insert_iterator
#include <algorithm> // 提供了copy()函数
#include <iostream>
#include <vector>
#include <list>
using std::copy;
using std::cout;
using std::endl;
using std::cin;
using std::vector;
using std::ostream_iterator;
using std::istream_iterator;
using std::reverse_iterator;
using std::back_insert_iterator;
using std::for_each;
using std::list;
using std::front_insert_iterator;
using std::insert_iterator;
void output(const int n) { cout << n << " "; }
int main() {
cout << "### Testing basic usage of copy().\n";
vector<int> vec = {1, 2, 3, 4, 5, 6 ,7 ,8}; // 使用列表初始化
int ints[4] = {4, 3, 2, 1};
copy(ints, ints + 4, vec.begin()); // 用ints内的元素替换vec开头的内容
// copy()前两个参数指定要复制的内容(由迭代器类型指定)
// copy()的第三个参数指明要将复制内容的第一个元素放到什么位置(由迭代器类型指定)
for (int x: vec) { // 使用基于范围的for循环
cout << x << " ";
} // 预期输出: 4 3 2 1 5 6 7 8
cout << endl;
cout << "### Testing ostream_iterator used in copy().\n";
// 创建一个ostream_iterator迭代器, 并使用copy()来完成向屏幕输出字符的工作
// 第一个模板参数指明被发送给输出流的数据类型(double)
// 第二个模板参数指明输出流使用的字符类型(char)
// 构造函数的第一个参数指定使用的输出流(cout)
// 构造函数的第二个参数指定输出流中每个数据项之间的分隔符(" ")
ostream_iterator<double, char> out_iter(cout, " ");
vector<double> vec2 = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6};
copy(vec2.begin(), vec2.end(), out_iter);
cout << endl;
// 另一种在copy()中使用ostream_iterator的方法: 使用匿名ostream_iterator
copy(vec2.begin(), vec2.end(), ostream_iterator<double, char>(cout, " "));
cout << endl;
cout << "### Testing istream_iterator used in copy().\n";
// 创建一个istream_iterator, 并使用copy()来完成从键盘读取字符的工作
// 第一个模板参数指明要读取的数据类型(int)
// 第二个模板参数指明输入流使用的字符类型(char)
// 构造函数接收的单一参数指明使用的输入流(cin)
// 省略构造函数的参数表示输入失败, 可以用于标识输入的结束(碰到文件尾/类型不匹配/其他故障)
/* {
istream_iterator<int, char> in_iter(cin);
// istream_iterator<int, char> in_iter_end();
// 上述语句, 编译器没有将in_iter_end识别为一个istream_iterator迭代器实例,
// 难道说, istream_iterator的无参构造函数只是一种特殊标记, 并不能用来创建一个具体的
// istream_iterator实例?
// 由此导致地, copy()的第二个参数也不能设置为in_iter_end, 而只能显式地使用
// istream_iterator<int, char>()的形式
vector<int> vec3(5); // 创建一个容量为10的空向量
cout << "Enter integers to initialize vec3: ";
// copy(in_iter, in_iter_end, vec.begin()); // 出错
copy(in_iter, istream_iterator<int, char>(), vec3.begin());
for (int x: vec3) cout << x << " ";
cout << endl;
} */
// 测试表明, 使用预先创建istream_iterator实例再将其作为copy()的参数的方式来
// 读取输入, 程序会在创建完in_iter实例后就进入等待输入状态, 而不是预想的那样: 在调用
// copy()函数时才等待用户输入.
// 为避免出现这种情况, 应该尽量避免预先创建istream_iterator实例, 而是在调用copy()
// 时再临时创建.
vector<int> vec3(5); // 创建一个容量为10的空向量
cout << "Enter integers to initialize vec3: ";
copy(istream_iterator<int, char>(cin), istream_iterator<int, char>(),
vec3.begin());
// 另外需要注意的, ostream_iterator和istream_iterator并不会扩展目标容器的容量,
// 因此, 如果写入数据后导致目标容器容量超限, 将会引发运行错误
// 例如, 这里vec3容量为5, 如果istream_iterator通过cin读取了6个整数, 就会导致程序崩溃.
for (int x: vec3) cout << x << " ";
cout << endl;
cout << "### Testing reverse_iterator used in copy().\n";
// 使用reverse_iterator反向迭代器来倒序输出向量中的元素
// 怎么创建一个用于vector<int>的reverse_iterator迭代器实例?
vector<int> vec4 = {1, 3, 5, 7, 9};
// reverse_iterator<vector<int> > ri(vec4); // 这样? ==> 不行, 编译不通过
vector<int>::reverse_iterator ri2; // 还是这样? ==> OK
// for (ri2 = vec4.end(); ri2 != vec4.begin(); ri2++) {
// cout << *ri2 << " ";
// } // 由于vec4.end()返回vector<int>::iterator类型, 与ri2类型不匹配,
//导致上面编译出错. 应该使用rbegin()和rend()成员
for (ri2 = vec4.rbegin(); ri2 != vec4.rend(); ri2++) {
cout << *ri2 << " ";
}
cout << endl;
// 使用copy()和ostream_iterator迭代器, 可以不需要显式创建reverse_iterator迭代器就
// 完成将向量内容逆序输出至屏幕的工作
ostream_iterator<int, char> out_iter2(cout, " ");
copy(vec4.rbegin(), vec4.rend(), out_iter2);
cout << endl;
// 前述的例子中, 如果copy()的目标容器的容量不够用来存储其接收到的数据, 将会引发运行错误.
// 通过使用插入迭代器, 可以使得目标容器自动调整容量以容纳新加入的数据.
// 有三种插入迭代器:
// back_insert_iterator将新数据插入到容器尾部(最后一个元素之后)
// front_insert_iterator将新数据插入到容器头部(第一个元素之前)
// insert_iterator将新数据插入到容器指定元素之前
cout << "### Testing back_insert_iterator used in copy().\n";
// 使用限制: back_insert_iterator要求它处理的容器有一个push_back()方法, 即该容器
// 应当允许在尾部进行快速插入. vector类符合要求.
int ints2[5] = {2, 4, 6, 8, 10};
vector<int> vec5;
// 创建一个具名的back_insert_iterator实例并在copy()中使用
back_insert_iterator<vector<int> > back_iter(vec5);
copy(ints2, ints2 + 2, back_iter);
// 使用for_each搭配output()输出向量元素
for_each(vec5.begin(), vec5.end(), output);
cout << endl;
// 使用匿名的back_insert_iterator实例并在copy()中使用
copy(ints2 + 2, ints2 + 5, back_insert_iterator<vector<int> >(vec5));
for_each(vec5.begin(), vec5.end(), output);
cout << endl;
cout << "### Testing front_insert_iterator used in copy().\n";
// 使用限制: front_insert_iterator要求它处理的容器有一个push_front()方法, 即该容器
// 应当允许在头部进行快速插入. vector类不满足该要求, list类满足.
// front_insert_iterator执行插入时类似于链表的头插法.
list<int> l1;
// 使用具名的front_insert_iterator实例
front_insert_iterator<list<int> > front_iter(l1);
copy(ints2, ints2 + 2, front_iter);
for (int x: l1) { cout << x << " "; } // 使用基于范围的for循环输出l1内容
cout << endl;
// 使用匿名的front_insert_iterator实例
copy(ints2 + 2, ints2 + 5, front_insert_iterator<list<int> >(l1));
for (int x: l1) { cout << x << " "; }
cout << endl;
cout << "### Testing insert_iterator used in copy().\n";
// 注: insert_iterator没有像前两者那样的使用限制. 在创建insert_iterator实例时,
// 需要用构造函数的第二个参数指示插入位置.
vector<int> vec6 = {100, 200, 300, 400, 500};
// 使用具名的insert_iterator实例
insert_iterator<vector<int> > ins_iter(vec6, vec6.begin() + 2);
copy(ints2, ints2 + 2, ins_iter);
for_each(vec6.begin(), vec6.end(), output);
cout << endl;
// 使用匿名的insert_iterator实例
copy(ints2 + 2, ints2 + 5,
insert_iterator<vector<int> >(vec6, vec6.begin() + 2));
for_each(vec6.begin(), vec6.end(), output);
cout << endl;
// 另: 注意比较front_insert_iterator<A>(a)和insert_iterator<A>(a, a.begin())的
// 的区别. 在copy()中使用它们时, 前者类似于头插法, 目标容器中的元素顺序将与插入序列的顺序
// 相反, 而后者的效果则是目标容器中的元素顺序和插入序列的顺序相同.
}
/*
测试输出:
### Testing basic usage of copy().
4 3 2 1 5 6 7 8
### Testing ostream_iterator used in copy().
1.1 2.2 3.3 4.4 5.5 6.6
1.1 2.2 3.3 4.4 5.5 6.6
### Testing istream_iterator used in copy().
Enter integers to initialize vec3: 1 2 3 ^Z
1 2 3 0 0
### Testing reverse_iterator used in copy().
9 7 5 3 1
9 7 5 3 1
### Testing back_insert_iterator used in copy().
2 4
2 4 6 8 10
### Testing front_insert_iterator used in copy().
4 2
10 8 6 4 2
### Testing insert_iterator used in copy().
100 200 2 4 300 400 500
100 200 6 8 10 2 4 300 400 500
*/
| 35.486631
| 76
| 0.673297
|
leschus
|
16ba4692823cbbf7a6af51d11079ba6959c5bd4b
| 1,165
|
cpp
|
C++
|
Core/Src/userInterface.cpp
|
xlord13/vescUserInterface
|
ff26bc1245ec35cb545042fe01ce3111c92ef80f
|
[
"MIT"
] | null | null | null |
Core/Src/userInterface.cpp
|
xlord13/vescUserInterface
|
ff26bc1245ec35cb545042fe01ce3111c92ef80f
|
[
"MIT"
] | null | null | null |
Core/Src/userInterface.cpp
|
xlord13/vescUserInterface
|
ff26bc1245ec35cb545042fe01ce3111c92ef80f
|
[
"MIT"
] | null | null | null |
#include <userInterface.h>
#include <stdio.h>
#include <gui/common/FrontendApplication.hpp>
#include <touchgfx/hal/OSWrappers.hpp>
#ifdef __cplusplus
extern "C" {
#endif
int ui_initialize(void)
{
return 0;
}
void ui_print_esc_values(mc_values *val)
{
// printf("Input voltage: %.2f V\r\n", val->v_in);
// printf("Temp: %.2f degC\r\n", val->temp_mos);
// printf("Current motor: %.2f A\r\n", val->current_motor);
// printf("Current in: %.2f A\r\n", val->current_in);
// printf("RPM: %.1f RPM\r\n", val->rpm);
// printf("Duty cycle: %.1f %%\r\n", val->duty_now * 100.0);
// printf("Ah Drawn: %.4f Ah\r\n", val->amp_hours);
// printf("Ah Regen: %.4f Ah\r\n", val->amp_hours_charged);
// printf("Wh Drawn: %.4f Wh\r\n", val->watt_hours);
// printf("Wh Regen: %.4f Wh\r\n", val->watt_hours_charged);
// printf("Tacho: %i counts\r\n", val->tachometer);
// printf("Tacho ABS: %i counts\r\n", val->tachometer_abs);
// printf("Fault Code: %s\r\n", bldc_interface_fault_to_string(val->fault_code));
}
void signal_vsync(void)
{
touchgfx::OSWrappers::signalVSync();
}
#ifdef __cplusplus
}
#endif
| 28.414634
| 85
| 0.623176
|
xlord13
|
16bf04bfeeb15804e59f194e27095c8ba412f58d
| 798
|
cpp
|
C++
|
1.5/1.5/Source.cpp
|
albusshin/CTCI
|
0794c9f78cc881a60daf883ba2caa5d82bb8833d
|
[
"CC0-1.0"
] | 2
|
2015-03-25T09:33:38.000Z
|
2016-05-23T06:57:31.000Z
|
1.5/1.5/Source.cpp
|
albusshin/CTCI
|
0794c9f78cc881a60daf883ba2caa5d82bb8833d
|
[
"CC0-1.0"
] | null | null | null |
1.5/1.5/Source.cpp
|
albusshin/CTCI
|
0794c9f78cc881a60daf883ba2caa5d82bb8833d
|
[
"CC0-1.0"
] | null | null | null |
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void compressStr(char *str) {
int len = strlen(str);
if (len == 0) return;
char prev = str[0], now = prev;
int count = 1;
int i = 1;
stringstream ss;
while ((now = str[i++]) != NULL) {
if (now == prev) count++;
else {
ss << prev << count;
count = 1;
}
prev = now;
}
ss << prev << count;
/* Find the length of stringstream */
ss.seekp(0, ios::end);
stringstream::pos_type newLen = ss.tellp();
if (len <= newLen) return;
else ss >> str;
}
void test(char *str) {
cout << str << " ";
compressStr(str);
cout << str << endl;
}
int main() {
char* str1 = new char[100];
strcpy(str1, "aabcccccaaa");
test(str1);
strcpy(str1, "abcdefg");
test(str1);
strcpy(str1, "abbbccdd");
test(str1);
}
| 18.55814
| 44
| 0.596491
|
albusshin
|
16c1362b29ffb0307af36b5a0702ca43dc1462de
| 1,808
|
cpp
|
C++
|
Exercise_3_16_springs/src/ofApp.cpp
|
ChongChongS/P52Of
|
1904f58e02f15b329c6c01c47e251bbadf427e5e
|
[
"MIT"
] | null | null | null |
Exercise_3_16_springs/src/ofApp.cpp
|
ChongChongS/P52Of
|
1904f58e02f15b329c6c01c47e251bbadf427e5e
|
[
"MIT"
] | null | null | null |
Exercise_3_16_springs/src/ofApp.cpp
|
ChongChongS/P52Of
|
1904f58e02f15b329c6c01c47e251bbadf427e5e
|
[
"MIT"
] | null | null | null |
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetWindowShape(640,360);
ofSetBackgroundColor(255);
m1 = new Mover(ofGetWindowWidth()/2,100);
m2 = new Mover(ofGetWindowWidth()/2,50);
m3 = new Mover(ofGetWindowWidth()/2,150);
s1 = new Spring(m1,m2,100);
s2 = new Spring(m1,m3,100);
s3 = new Spring(m3,m2,100);
}
//--------------------------------------------------------------
void ofApp::update(){
s1->update();
s2->update();
s3->update();
m1->update();
m2->update();
m3->update();
}
//--------------------------------------------------------------
void ofApp::draw(){
s1->display();
s2->display();
s3->display();
m1->display();
m2->display();
m3->display();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
m1->drag(x,y);
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
m1->clicked(x,y);
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
m1->stopDragging();
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 22.320988
| 64
| 0.369469
|
ChongChongS
|
16c4fa6645d5e1b0d521c7a1db5e3307559f7841
| 3,247
|
cpp
|
C++
|
tests/Graphics/Renderer/AbstractFramebufferRenderer.cpp
|
danielealbano/rpi4-status-display
|
8ee56844715fb02e3070baa815e25e05f06d93f4
|
[
"BSD-2-Clause"
] | 1
|
2021-01-09T17:38:08.000Z
|
2021-01-09T17:38:08.000Z
|
tests/Graphics/Renderer/AbstractFramebufferRenderer.cpp
|
danielealbano/rpi4-status-display
|
8ee56844715fb02e3070baa815e25e05f06d93f4
|
[
"BSD-2-Clause"
] | 2
|
2021-01-09T17:32:52.000Z
|
2021-01-09T17:42:32.000Z
|
tests/Graphics/Renderer/AbstractFramebufferRenderer.cpp
|
danielealbano/rpi4-status-display
|
8ee56844715fb02e3070baa815e25e05f06d93f4
|
[
"BSD-2-Clause"
] | null | null | null |
/**
* Copyright 2020-2021 Albano Daniele Salvatore
*
* 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.
*/
#include <cstdint>
#include <iostream>
#include "Graphics/Color.h"
#include "Graphics/Point2D.h"
#include "Graphics/Size2D.h"
#include "Graphics/Line2D.h"
#include "Graphics/Rect2D.h"
#include "Graphics/Framebuffer.h"
#include "Graphics/Renderer/RendererInterface.h"
#include "Graphics/Renderer/AbstractFramebufferRenderer.h"
#include <catch2/catch.hpp>
using namespace std;
using namespace Rpi4StatusDisplay::Graphics;
using namespace Rpi4StatusDisplay::Graphics::Renderer;
#define EMPTY_OVERRIDDEN_CLASS_METHOD(CLASS_NAME, METHOD_NAME, ...) \
CLASS_NAME &METHOD_NAME(__VA_ARGS__) override { \
return *this; \
}
class AbstractRendererTestWrapper : public AbstractFramebufferRenderer {
public:
explicit AbstractRendererTestWrapper(Framebuffer &framebuffer) : AbstractFramebufferRenderer(framebuffer) {
// do nothing
}
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, setColor, Color &c);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, flush);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, clear);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, text, Point2D &p, std::string &text);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, line, Line2D &l);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, rectOutline, Rect2D &r);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, rectFilled, Rect2D &r);
};
TEST_CASE("Graphics::Renderer::AbstractFramebufferRenderer", "[Graphics][Renderer][AbstractFramebufferRenderer]") {
Size2D s0(20, 40);
Framebuffer f0(s0, 3, s0.width() * 3);
AbstractRendererTestWrapper abstractRendererTestWrapper0(f0);
SECTION("AbstractFramebufferRenderer(Framebuffer(Size2D(20, 40)))") {
REQUIRE(&abstractRendererTestWrapper0.framebuffer() == &f0);
}
}
| 46.385714
| 121
| 0.767478
|
danielealbano
|
16c5869e8b00276ebede32bfb0df9f5ff40bd596
| 214
|
cpp
|
C++
|
CluVRPsol.cpp
|
christofdefryn/CluVRP
|
42c037f4c54eca461128efdcb8a574be8903da5f
|
[
"Apache-2.0"
] | 6
|
2018-11-30T04:04:25.000Z
|
2021-04-22T14:14:15.000Z
|
CluVRPsol.cpp
|
RunningPhoton/CluVRP
|
42c037f4c54eca461128efdcb8a574be8903da5f
|
[
"Apache-2.0"
] | 1
|
2017-12-28T02:43:50.000Z
|
2018-10-01T08:45:48.000Z
|
CluVRPsol.cpp
|
RunningPhoton/CluVRP
|
42c037f4c54eca461128efdcb8a574be8903da5f
|
[
"Apache-2.0"
] | 6
|
2019-09-19T08:59:09.000Z
|
2020-06-12T19:43:36.000Z
|
#include "CluVRPsol.h"
CluVRPsol::CluVRPsol(ClusterSolution* sCluster, NodeSolution* sNode)
{
sCluster_ = sCluster;
sNode_ = sNode;
}
CluVRPsol::~CluVRPsol()
{
delete sNode_;
delete sCluster_;
}
| 15.285714
| 69
| 0.691589
|
christofdefryn
|
16c78f9486ec6537376e122aef5ec3f3fa39bf7c
| 621
|
hpp
|
C++
|
obsoleted/old/lib-obsolete/device/include/device.hpp
|
cppcoder123/led-server
|
8ebac31e1241bb203d2cedfd644fe52619007cd6
|
[
"MIT"
] | 1
|
2021-12-23T13:50:53.000Z
|
2021-12-23T13:50:53.000Z
|
obsoleted/old/lib-obsolete/device/include/device.hpp
|
cppcoder123/led-server
|
8ebac31e1241bb203d2cedfd644fe52619007cd6
|
[
"MIT"
] | null | null | null |
obsoleted/old/lib-obsolete/device/include/device.hpp
|
cppcoder123/led-server
|
8ebac31e1241bb203d2cedfd644fe52619007cd6
|
[
"MIT"
] | null | null | null |
//
//
//
#ifndef DEVICE_DEVICE_HPP
#define DEVICE_DEVICE_HPP
#include "device-codec.hpp"
#include "device-id.h"
#include "matrix.hpp"
namespace device
{
class device_t
{
public:
virtual ~device_t () {}
using codec_t = core::device::codec_t;
using msg_t = codec_t::msg_t;
using char_t = codec_t::char_t;
// do not throw
virtual bool write (const msg_t &msg) = 0;
virtual bool read (msg_t &msg, bool block) = 0;
// throws
virtual void write_status (const msg_t &msg) = 0;
virtual void read_status (char_t status = ID_STATUS_OK) = 0;
};
} // namespace device
#endif
| 16.783784
| 64
| 0.653784
|
cppcoder123
|
16c7906f922a315fa5e35d709cacfa8b2c6491cc
| 411
|
cpp
|
C++
|
Vortex/src/Vortex/Core/Input.cpp
|
olleh-dlrow/Vortex
|
f52574bcf33f53c7ed21dabf54aa91e70fde9060
|
[
"Apache-2.0"
] | null | null | null |
Vortex/src/Vortex/Core/Input.cpp
|
olleh-dlrow/Vortex
|
f52574bcf33f53c7ed21dabf54aa91e70fde9060
|
[
"Apache-2.0"
] | null | null | null |
Vortex/src/Vortex/Core/Input.cpp
|
olleh-dlrow/Vortex
|
f52574bcf33f53c7ed21dabf54aa91e70fde9060
|
[
"Apache-2.0"
] | null | null | null |
#include "vtpch.h"
#include "Vortex/Core/Input.h"
#ifdef VT_PLATFORM_WINDOWS
#include "Platform/Windows/WindowsInput.h"
#endif
namespace Vortex {
Scope<Input> Input::s_Instance = Input::Create();
Scope<Input> Input::Create()
{
#ifdef VT_PLATFORM_WINDOWS
return CreateScope<WindowsInput>();
#else
VT_CORE_ASSERT(false, "Unknown platform!");
return nullptr;
#endif
}
}
| 18.681818
| 53
| 0.683698
|
olleh-dlrow
|
16c991fffd6c4aa1a1ae2485e5577a89c7eab0e7
| 1,647
|
hpp
|
C++
|
src/org/apache/poi/poifs/storage/SmallBlockTableReader.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/poifs/storage/SmallBlockTableReader.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/poifs/storage/SmallBlockTableReader.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /POI/java/org/apache/poi/poifs/storage/SmallBlockTableReader.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/poifs/common/fwd-POI.hpp>
#include <org/apache/poi/poifs/property/fwd-POI.hpp>
#include <org/apache/poi/poifs/storage/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::poifs::storage::SmallBlockTableReader final
: public ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static BlockList* prepareSmallDocumentBlocks(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
static BlockAllocationTableReader* prepareReader(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, BlockList* list, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
public:
static BlockAllocationTableReader* _getSmallDocumentBlockReader(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
static BlockList* getSmallDocumentBlocks(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
// Generated
SmallBlockTableReader();
protected:
SmallBlockTableReader(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 41.175
| 243
| 0.757741
|
pebble2015
|
16cda066b93ddef1f3818fdc45ced2af72b6a220
| 1,308
|
cpp
|
C++
|
sourcecode/02_hello_triangle/maths_funcs.cpp
|
FahrenheitKid/OpenGLAmbientOcclusion
|
6fd0fbda5338d818d6156c6b1fc85fa51799f97f
|
[
"MIT"
] | null | null | null |
sourcecode/02_hello_triangle/maths_funcs.cpp
|
FahrenheitKid/OpenGLAmbientOcclusion
|
6fd0fbda5338d818d6156c6b1fc85fa51799f97f
|
[
"MIT"
] | null | null | null |
sourcecode/02_hello_triangle/maths_funcs.cpp
|
FahrenheitKid/OpenGLAmbientOcclusion
|
6fd0fbda5338d818d6156c6b1fc85fa51799f97f
|
[
"MIT"
] | null | null | null |
/******************************************************************************\
| OpenGL 4 Example Code. |
| Accompanies written series "Anton's OpenGL 4 Tutorials" |
| Email: anton at antongerdelan dot net |
| First version 27 Jan 2014 |
| Copyright Dr Anton Gerdelan, Trinity College Dublin, Ireland. |
| See individual libraries' separate legal notices |
|******************************************************************************|
| Commonly-used maths structures and functions |
| Simple-as-possible. No disgusting templates. |
| Structs vec3, mat4, versor. just hold arrays of floats called "v","m","q", |
| respectively. So, for example, to get values from a mat4 do: my_mat.m |
| A versor is the proper name for a unit quaternion. |
\******************************************************************************/
#include "maths_funcs.h"
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
// lerp function
float lerp(float a, float b, float f)
{
return a + f * (b - a);
}
| 50.307692
| 80
| 0.417431
|
FahrenheitKid
|
16d0ccf659fdcbb29fb75618ca5b4d978def871b
| 5,179
|
hh
|
C++
|
tamer/websocket.hh
|
kohler/tamer
|
0953029ad7fc5c3fd58869227976c359674c670f
|
[
"BSD-3-Clause"
] | 23
|
2015-04-11T06:41:04.000Z
|
2021-11-06T21:34:14.000Z
|
tamer/websocket.hh
|
kohler/tamer
|
0953029ad7fc5c3fd58869227976c359674c670f
|
[
"BSD-3-Clause"
] | 2
|
2015-04-15T07:00:31.000Z
|
2016-08-16T13:46:22.000Z
|
tamer/websocket.hh
|
kohler/tamer
|
0953029ad7fc5c3fd58869227976c359674c670f
|
[
"BSD-3-Clause"
] | 5
|
2015-08-18T19:24:07.000Z
|
2021-04-18T04:35:35.000Z
|
#ifndef TAMER_WEBSOCKET_HH
#define TAMER_WEBSOCKET_HH 1
#include "http.hh"
namespace tamer {
class websocket_handshake {
public:
static bool request(http_message& req, std::string& key);
static bool is_request(const http_message& req);
static bool response(http_message& resp, const http_message& req);
static bool is_response(const http_message& resp, const std::string& key);
};
enum websocket_opcode {
WEBSOCKET_CONTINUATION = 0,
WEBSOCKET_TEXT = 1,
WEBSOCKET_BINARY = 2,
WEBSOCKET_CLOSE = 8,
WEBSOCKET_PING = 9,
WEBSOCKET_PONG = 10
};
class websocket_message {
public:
inline websocket_message();
inline bool ok() const;
inline bool operator!() const;
inline enum http_errno error() const;
inline enum websocket_opcode opcode() const;
inline bool text() const;
inline bool binary() const;
inline bool incomplete() const;
inline const std::string& body() const;
inline std::string& body();
inline websocket_message& clear();
inline websocket_message& error(enum http_errno e);
inline websocket_message& incomplete(bool c);
inline websocket_message& opcode(enum websocket_opcode o);
inline websocket_message& body(std::string body);
inline websocket_message& text(std::string body);
inline websocket_message& binary(std::string body);
private:
unsigned error_ : 8;
unsigned incomplete_ : 4;
unsigned opcode_ : 4;
std::string body_;
};
class websocket_parser : public tamed_class {
public:
inline websocket_parser(enum http_parser_type type);
inline bool ok() const;
inline bool operator!() const;
inline bool closed() const;
void receive_any(fd f, websocket_message& ctrl, websocket_message& data, event<int> done);
void receive(fd f, event<websocket_message> done);
void send(fd f, websocket_message m, event<> done);
inline void send_text(fd f, std::string text, event<> done);
inline void send_binary(fd f, std::string text, event<> done);
void close(fd f, uint16_t code, std::string reason, event<> done);
inline void close(fd f, uint16_t code, event<> done);
private:
enum http_parser_type type_;
uint8_t closed_;
uint16_t close_code_;
std::string close_reason_;
class closure__receive_any__2fdR17websocket_messageR17websocket_messageQi_;
void receive_any(closure__receive_any__2fdR17websocket_messageR17websocket_messageQi_&);
class closure__receive__2fdQ17websocket_message_;
void receive(closure__receive__2fdQ17websocket_message_&);
class closure__send__2fd17websocket_messageQ_;
void send(closure__send__2fd17websocket_messageQ_&);
};
inline websocket_message::websocket_message()
: error_(0), incomplete_(0), opcode_(0) {
}
inline bool websocket_message::ok() const {
return error_ == 0;
}
inline bool websocket_message::operator!() const {
return !ok();
}
inline enum http_errno websocket_message::error() const {
return http_errno(error_);
}
inline enum websocket_opcode websocket_message::opcode() const {
return websocket_opcode(opcode_);
}
inline bool websocket_message::text() const {
return websocket_opcode(opcode_) == WEBSOCKET_TEXT;
}
inline bool websocket_message::binary() const {
return websocket_opcode(opcode_) == WEBSOCKET_BINARY;
}
inline bool websocket_message::incomplete() const {
return incomplete_;
}
inline const std::string& websocket_message::body() const {
return body_;
}
inline std::string& websocket_message::body() {
return body_;
}
inline websocket_message& websocket_message::clear() {
error_ = 0;
incomplete_ = 0;
opcode_ = 0;
body_.clear();
return *this;
}
inline websocket_message& websocket_message::error(enum http_errno e) {
error_ = e;
return *this;
}
inline websocket_message& websocket_message::incomplete(bool c) {
incomplete_ = c;
return *this;
}
inline websocket_message& websocket_message::opcode(enum websocket_opcode o) {
opcode_ = o;
return *this;
}
inline websocket_message& websocket_message::body(std::string s) {
body_ = TAMER_MOVE(s);
return *this;
}
inline websocket_message& websocket_message::text(std::string s) {
opcode_ = WEBSOCKET_TEXT;
body_ = TAMER_MOVE(s);
return *this;
}
inline websocket_message& websocket_message::binary(std::string s) {
opcode_ = WEBSOCKET_BINARY;
body_ = TAMER_MOVE(s);
return *this;
}
inline websocket_parser::websocket_parser(enum http_parser_type type)
: type_(type), closed_(0), close_code_(0) {
}
inline bool websocket_parser::ok() const {
return !closed_;
}
inline bool websocket_parser::operator!() const {
return closed_;
}
inline bool websocket_parser::closed() const {
return closed_;
}
inline void websocket_parser::send_text(fd f, std::string s, event<> done) {
send(f, websocket_message().text(s), done);
}
inline void websocket_parser::send_binary(fd f, std::string s, event<> done) {
send(f, websocket_message().binary(s), done);
}
inline void websocket_parser::close(fd f, uint16_t close_code, event<> done) {
close(f, close_code, std::string(), done);
}
}
#endif
| 26.695876
| 94
| 0.720409
|
kohler
|
16d317e517655bc2b5010c6d9b60af3667acc089
| 7,112
|
cpp
|
C++
|
source/MultiLibrary/Media/SoundStream.cpp
|
danielga/multilibrary
|
3d1177dd3affa875e06015f5e3e42dda525f3336
|
[
"BSD-3-Clause"
] | 2
|
2018-06-22T12:43:57.000Z
|
2019-05-31T21:56:27.000Z
|
source/MultiLibrary/Media/SoundStream.cpp
|
danielga/multilibrary
|
3d1177dd3affa875e06015f5e3e42dda525f3336
|
[
"BSD-3-Clause"
] | 1
|
2017-09-09T01:21:31.000Z
|
2017-11-12T17:52:56.000Z
|
source/MultiLibrary/Media/SoundStream.cpp
|
danielga/multilibrary
|
3d1177dd3affa875e06015f5e3e42dda525f3336
|
[
"BSD-3-Clause"
] | 1
|
2022-03-30T18:57:41.000Z
|
2022-03-30T18:57:41.000Z
|
/*************************************************************************
* MultiLibrary - https://danielga.github.io/multilibrary/
* A C++ library that covers multiple low level systems.
*------------------------------------------------------------------------
* Copyright (c) 2014-2022, Daniel Almeida
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include <MultiLibrary/Media/SoundStream.hpp>
#include <MultiLibrary/Media/AudioDevice.hpp>
#include <MultiLibrary/Media/OpenAL.hpp>
namespace MultiLibrary
{
SoundStream::SoundStream( ) :
thread_active( true ),
stream_thread( &SoundStream::DataStreamer, this ),
is_streaming( false ),
should_loop( false ),
samples_processed( 0 ),
channel_count( 0 ),
sample_rate( 0 ),
audio_format( 0 ),
minimum_bufsize( 0 )
{ }
SoundStream::~SoundStream( )
{
Stop( );
thread_active = false;
stream_thread.join( );
}
void SoundStream::Play( )
{
if( is_streaming )
{
alCheck( alSourcePlay( audio_source ) );
return;
}
Seek( std::chrono::milliseconds::zero( ) );
samples_processed = 0;
is_streaming = true;
}
void SoundStream::Pause( )
{
alCheck( alSourcePause( audio_source ) );
}
void SoundStream::Stop( )
{
is_streaming = false;
}
uint32_t SoundStream::GetChannelCount( ) const
{
return channel_count;
}
uint32_t SoundStream::GetSampleRate( ) const
{
return sample_rate;
}
std::chrono::microseconds SoundStream::GetDuration( ) const
{
return audio_duration;
}
SoundStatus SoundStream::GetStatus( ) const
{
SoundStatus status = SoundSource::GetStatus( );
if( status == Stopped && is_streaming )
status = Playing;
return status;
}
void SoundStream::SetPlayingOffset( const std::chrono::microseconds &time_offset )
{
Stop( );
Seek( time_offset );
samples_processed = static_cast<uint64_t>( time_offset.count( ) / 1000000.0 * sample_rate * channel_count );
is_streaming = true;
}
std::chrono::microseconds SoundStream::GetPlayingOffset( ) const
{
ALfloat secs = 0.0f;
alCheck( alGetSourcef( audio_source, AL_SEC_OFFSET, &secs ) );
return std::chrono::microseconds( static_cast<int64_t>( secs + static_cast<double>( samples_processed ) / sample_rate / channel_count ) );
}
void SoundStream::SetLoop( bool looping )
{
should_loop = looping;
}
bool SoundStream::GetLoop( )
{
return should_loop;
}
void SoundStream::Initialize( uint32_t channels, uint32_t sampleRate, const std::chrono::microseconds &duration )
{
channel_count = channels;
sample_rate = sampleRate;
audio_duration = duration;
audio_format = AudioDevice::GetFormatFromChannelCount( channels );
minimum_bufsize = sample_rate * channel_count * sizeof( int16_t ) / 10;
temp_buffer.resize( minimum_bufsize );
std::vector<int16_t>( temp_buffer ).swap( temp_buffer );
temp_buffer.resize( 0 );
}
void SoundStream::DataStreamer( )
{
std::chrono::milliseconds millisecs = std::chrono::milliseconds( 1 );
while( thread_active )
{
if( !is_streaming )
{
std::this_thread::sleep_for( millisecs );
continue;
}
alCheck( alGenBuffers( MAX_AUDIO_BUFFERS, audio_buffers ) );
bool requestStop = false;
for( uint8_t i = 0; i < MAX_AUDIO_BUFFERS; ++i )
{
end_buffer[i] = false;
if( !requestStop && FillAndPushBuffer( i ) )
requestStop = true;
}
alCheck( alSourcePlay( audio_source ) );
while( is_streaming )
{
if( SoundSource::GetStatus( ) == Stopped )
{
if( !requestStop )
alCheck( alSourcePlay( audio_source ) );
else
is_streaming = false;
}
ALint nbProcessed = 0;
alCheck( alGetSourcei( audio_source, AL_BUFFERS_PROCESSED, &nbProcessed ) );
while( nbProcessed-- )
{
ALuint buffer;
alCheck( alSourceUnqueueBuffers( audio_source, 1, &buffer ) );
uint32_t bufferNum = 0;
for( uint8_t i = 0; i < MAX_AUDIO_BUFFERS; ++i )
if( audio_buffers[i] == buffer )
{
bufferNum = i;
break;
}
if( end_buffer[bufferNum] )
{
samples_processed = 0;
end_buffer[bufferNum] = false;
}
else
{
ALint size, bits;
alCheck( alGetBufferi( buffer, AL_SIZE, &size ) );
alCheck( alGetBufferi( buffer, AL_BITS, &bits ) );
samples_processed += size / ( bits / 8 );
}
if( !requestStop )
if( FillAndPushBuffer( bufferNum ) )
requestStop = true;
}
if( SoundSource::GetStatus( ) != Stopped )
std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
}
alCheck( alSourceStop( audio_source ) );
ALint nbQueued = 0;
alCheck( alGetSourcei( audio_source, AL_BUFFERS_QUEUED, &nbQueued ) );
ALuint buffer = 0;
for( ALint i = 0; i < nbQueued; ++i )
alCheck( alSourceUnqueueBuffers( audio_source, 1, &buffer ) );
alCheck( alSourcei( audio_source, AL_BUFFER, 0 ) );
alCheck( alDeleteBuffers( MAX_AUDIO_BUFFERS, audio_buffers ) );
}
}
bool SoundStream::FillAndPushBuffer( uint32_t buffer_num )
{
bool requestStop = false;
if( !GetData( temp_buffer, minimum_bufsize ) )
{
end_buffer[buffer_num] = true;
if( should_loop )
{
Seek( std::chrono::milliseconds::zero( ) );
if( temp_buffer.size( ) == 0 )
return FillAndPushBuffer( buffer_num );
}
else
{
requestStop = true;
}
}
if( temp_buffer.size( ) > 0 )
{
uint32_t buffer = audio_buffers[buffer_num];
ALsizei size = static_cast<ALsizei>( temp_buffer.size( ) * sizeof( int16_t ) );
alCheck( alBufferData( buffer, audio_format, &temp_buffer[0], size, sample_rate ) );
alCheck( alSourceQueueBuffers( audio_source, 1, &buffer ) );
}
temp_buffer.resize( 0 );
return requestStop;
}
} // namespace MultiLibrary
| 25.768116
| 139
| 0.683493
|
danielga
|
16d32c4153cac0729484ff226a9ea64ef4791e77
| 311
|
cpp
|
C++
|
ros/src/computing/perception/localization/packages/vmml/src/bin/lidar_mapper/ScanOdometry.cpp
|
sujiwo/autoware
|
435869592aa98a6fcb2b0a24594c27ee85bb27fe
|
[
"Apache-2.0"
] | null | null | null |
ros/src/computing/perception/localization/packages/vmml/src/bin/lidar_mapper/ScanOdometry.cpp
|
sujiwo/autoware
|
435869592aa98a6fcb2b0a24594c27ee85bb27fe
|
[
"Apache-2.0"
] | null | null | null |
ros/src/computing/perception/localization/packages/vmml/src/bin/lidar_mapper/ScanOdometry.cpp
|
sujiwo/autoware
|
435869592aa98a6fcb2b0a24594c27ee85bb27fe
|
[
"Apache-2.0"
] | null | null | null |
/*
* ScanOdometry.cpp
*
* Created on: Jun 4, 2019
* Author: sujiwo
*/
#include "LidarMapper.h"
#include "ScanOdometry.h"
ScanOdometry::ScanOdometry(const LidarMapper &parent)
{
// TODO Auto-generated constructor stub
}
ScanOdometry::~ScanOdometry() {
// TODO Auto-generated destructor stub
}
| 14.136364
| 53
| 0.694534
|
sujiwo
|
16d7de132ae061d3a4c8d66292cf5f887b3f685d
| 3,495
|
cpp
|
C++
|
arch/drisc/AncillaryRegisterFile.cpp
|
svp-dev/mgsim
|
0abd708f3c48723fc233f6c53f3e638129d070fa
|
[
"MIT"
] | 7
|
2016-03-01T13:16:59.000Z
|
2021-08-20T07:41:43.000Z
|
arch/drisc/AncillaryRegisterFile.cpp
|
svp-dev/mgsim
|
0abd708f3c48723fc233f6c53f3e638129d070fa
|
[
"MIT"
] | null | null | null |
arch/drisc/AncillaryRegisterFile.cpp
|
svp-dev/mgsim
|
0abd708f3c48723fc233f6c53f3e638129d070fa
|
[
"MIT"
] | 5
|
2015-04-20T14:29:38.000Z
|
2018-12-29T11:09:17.000Z
|
#include "AncillaryRegisterFile.h"
#include <sim/config.h>
#include <iomanip>
using namespace std;
namespace Simulator
{
namespace drisc
{
void AncillaryRegisterFile::Cmd_Info(std::ostream& out, const std::vector<std::string>& /*arguments*/) const
{
out << "The ancillary registers hold information common to all threads on a processor.\n";
}
void AncillaryRegisterFile::Cmd_Read(std::ostream& out, const std::vector<std::string>& /*arguments*/) const
{
out << " Register | Value" << endl
<< "----------+----------------------" << endl;
for (size_t i = 0; i < m_numRegisters; ++i)
{
Integer value = ReadRegister(i);
out << setw(9) << setfill(' ') << right << i << left
<< " | "
<< setw(16 - sizeof(Integer) * 2) << setfill(' ') << ""
<< setw( sizeof(Integer) * 2) << setfill('0') << hex << right << value << left
<< endl;
}
}
size_t AncillaryRegisterFile::GetSize() const
{
return m_numRegisters * sizeof(Integer);
}
Integer AncillaryRegisterFile::ReadRegister(ARAddr addr) const
{
if (addr >= m_numRegisters)
{
throw exceptf<InvalidArgumentException>(*this, "Invalid ancillary register number: %u", (unsigned)addr);
}
return m_registers[addr];
}
void AncillaryRegisterFile::WriteRegister(ARAddr addr, Integer data)
{
if (addr >= m_numRegisters)
{
throw exceptf<InvalidArgumentException>(*this, "Invalid ancillary register number: %u", (unsigned)addr);
}
m_registers[addr] = data;
}
Result AncillaryRegisterFile::Read (MemAddr addr, void* data, MemSize size, LFID /*fid*/, TID /*tid*/, const RegAddr& /*writeback*/)
{
if (addr % sizeof(Integer) != 0 || (size != sizeof(Integer)) || (addr > m_numRegisters * sizeof(Integer)))
throw exceptf<InvalidArgumentException>(*this, "Invalid read from ancillary register: %#016llx (%u)", (unsigned long long)addr, (unsigned)size);
ARAddr raddr = addr / sizeof(Integer);
Integer value = ReadRegister(raddr);
COMMIT{
SerializeRegister(RT_INTEGER, value, data, size);
}
return SUCCESS;
}
Result AncillaryRegisterFile::Write(MemAddr addr, const void *data, MemSize size, LFID /*fid*/, TID /*tid*/)
{
if (addr % sizeof(Integer) != 0 || (size != sizeof(Integer)) || (addr > m_numRegisters * sizeof(Integer)))
throw exceptf<InvalidArgumentException>(*this, "Invalid write to ancillary register: %#016llx (%u)", (unsigned long long)addr, (unsigned)size);
addr /= sizeof(Integer);
Integer value = UnserializeRegister(RT_INTEGER, data, size);
COMMIT{
WriteRegister(addr, value);
}
return SUCCESS;
}
AncillaryRegisterFile::AncillaryRegisterFile(const std::string& name, Object& parent)
: MMIOComponent(name, parent),
m_numRegisters(name == "aprs" ? GetConf("NumAncillaryRegisters", size_t) : NUM_ASRS),
m_registers()
{
if (m_numRegisters == 0)
{
throw InvalidArgumentException(*this, "NumAncillaryRegisters must be 1 or larger");
}
m_registers.resize(m_numRegisters, 0);
if (name == "asrs")
{
WriteRegister(ASR_SYSTEM_VERSION, ASR_SYSTEM_VERSION_VALUE);
}
}
}
}
| 33.932039
| 156
| 0.589413
|
svp-dev
|
16d989b03f8829b29b5e973e716ba08d4b59ff59
| 130
|
cpp
|
C++
|
dependencies/physx-4.1/source/geomutils/src/mesh/GuMeshQuery.cpp
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
dependencies/physx-4.1/source/geomutils/src/mesh/GuMeshQuery.cpp
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
dependencies/physx-4.1/source/geomutils/src/mesh/GuMeshQuery.cpp
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
version https://git-lfs.github.com/spec/v1
oid sha256:b02719bdb687f6f2a0ec35ad50b06f79819681104750d72ed46969554055bd46
size 11165
| 32.5
| 75
| 0.884615
|
realtehcman
|
16da084f143d809d68cc50f25d7e61ca8e896f3e
| 28
|
cpp
|
C++
|
run/Builder.cpp
|
hzx/run
|
ed8c77ab0aae7ab4d1362f48ccd22a7f36e2ddcc
|
[
"MIT"
] | null | null | null |
run/Builder.cpp
|
hzx/run
|
ed8c77ab0aae7ab4d1362f48ccd22a7f36e2ddcc
|
[
"MIT"
] | null | null | null |
run/Builder.cpp
|
hzx/run
|
ed8c77ab0aae7ab4d1362f48ccd22a7f36e2ddcc
|
[
"MIT"
] | null | null | null |
class Builder {
public:
};
| 5.6
| 15
| 0.642857
|
hzx
|
16dbd308625bbaefd7670bfd290af308b019cd3f
| 721
|
cpp
|
C++
|
server/Common/Packets/GCLeaveScene.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 3
|
2018-06-19T21:37:38.000Z
|
2021-07-31T21:51:40.000Z
|
server/Common/Packets/GCLeaveScene.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | null | null | null |
server/Common/Packets/GCLeaveScene.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 13
|
2015-01-30T17:45:06.000Z
|
2022-01-06T02:29:34.000Z
|
#include "stdafx.h"
#include "GCLeaveScene.h"
BOOL GCLeaveScene::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_ObjID), sizeof(ObjID_t));
iStream.Read( (CHAR*)(&m_byLeaveCode), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GCLeaveScene::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_ObjID), sizeof(ObjID_t) ) ;
oStream.Write( (CHAR*)(&m_byLeaveCode), sizeof(BYTE) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GCLeaveScene::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GCLeaveSceneHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 16.767442
| 60
| 0.700416
|
viticm
|
16dd3f927778627cd5faedcaebc1c2b5b069b778
| 399
|
cpp
|
C++
|
CppImport/src/ClangFrontendActionFactory.cpp
|
patrick-luethi/Envision
|
b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a
|
[
"BSD-3-Clause"
] | null | null | null |
CppImport/src/ClangFrontendActionFactory.cpp
|
patrick-luethi/Envision
|
b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a
|
[
"BSD-3-Clause"
] | null | null | null |
CppImport/src/ClangFrontendActionFactory.cpp
|
patrick-luethi/Envision
|
b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a
|
[
"BSD-3-Clause"
] | null | null | null |
#include "ClangFrontendActionFactory.h"
#include "TranslateFrontendAction.h"
#include "manager/TranslateManager.h"
namespace CppImport {
ClangFrontendActionFactory::ClangFrontendActionFactory(ClangAstVisitor* visitor, CppImportLogger* log)
: visitor_{visitor}, log_{log}
{}
clang::FrontendAction* ClangFrontendActionFactory::create()
{
return new TranslateFrontendAction(visitor_, log_);
}
}
| 21
| 102
| 0.809524
|
patrick-luethi
|
16dec42dd1a8804c5551a1d3a5ee68feda5cd6b7
| 3,790
|
hpp
|
C++
|
apps/constellation/settings.hpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 1
|
2019-09-23T07:58:16.000Z
|
2019-09-23T07:58:16.000Z
|
apps/constellation/settings.hpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | null | null | null |
apps/constellation/settings.hpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 1
|
2019-12-06T10:02:35.000Z
|
2019-12-06T10:02:35.000Z
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// 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 "core/feature_flags.hpp"
#include "network/uri.hpp"
#include "settings/setting.hpp"
#include "settings/setting_collection.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace fetch {
/**
* Command line / Environment variable settings
*/
class Settings : private settings::SettingCollection
{
public:
using PeerList = std::vector<network::Uri>;
// Construction / Destruction
Settings();
Settings(Settings const &) = delete;
Settings(Settings &&) = delete;
~Settings() = default;
bool Update(int argc, char **argv);
/// @name High Level Network Settings
/// @{
settings::Setting<uint32_t> num_lanes;
settings::Setting<uint32_t> num_slices;
settings::Setting<uint32_t> block_interval;
/// @}
/// @name Network Mode
/// @{
settings::Setting<bool> standalone;
settings::Setting<bool> private_network;
/// @}
/// @name Standalone parameters
/// @{
settings::Setting<std::string> initial_address;
/// @}
/// @name Shards
/// @{
settings::Setting<std::string> db_prefix;
/// @}
/// @name Networking / P2P Manifest
/// @{
settings::Setting<uint16_t> port;
settings::Setting<PeerList> peers;
settings::Setting<std::string> external;
settings::Setting<std::string> config;
settings::Setting<uint32_t> max_peers;
settings::Setting<uint32_t> transient_peers;
settings::Setting<uint32_t> peer_update_interval;
settings::Setting<bool> disable_signing;
settings::Setting<bool> kademlia_routing;
/// @}
/// @name Bootstrap Config
/// @{
settings::Setting<bool> bootstrap;
settings::Setting<bool> discoverable;
settings::Setting<std::string> hostname;
settings::Setting<std::string> network_name;
settings::Setting<std::string> token;
/// @}
/// @name Threading Settings
/// @{
settings::Setting<uint32_t> num_processor_threads;
settings::Setting<uint32_t> num_verifier_threads;
settings::Setting<uint32_t> num_executors;
/// @}
/// @name Genesis File
/// @{
settings::Setting<std::string> genesis_file_location;
/// @}
/// @name Experimental
/// @{
settings::Setting<core::FeatureFlags> experimental_features;
/// @}
/// @name Proof of Stake
/// @{
settings::Setting<bool> proof_of_stake;
settings::Setting<uint64_t> max_cabinet_size;
settings::Setting<uint64_t> stake_delay_period;
settings::Setting<uint64_t> aeon_period;
/// @}
/// @name Error handling
/// @{
settings::Setting<bool> graceful_failure;
settings::Setting<bool> fault_tolerant;
/// @}
/// @name Agent support functionality
/// @{
settings::Setting<bool> enable_agents;
settings::Setting<uint16_t> messenger_port;
/// @}
// Operators
Settings &operator=(Settings const &) = delete;
Settings &operator=(Settings &&) = delete;
friend std::ostream &operator<<(std::ostream &stream, Settings const &settings);
private:
bool Validate();
};
} // namespace fetch
| 27.071429
| 82
| 0.648813
|
chr15murray
|
16e3d26ca33464a0d4d0996c433ace93dc93fc6f
| 386
|
hpp
|
C++
|
src/singleton.hpp
|
TulioAbreu/game-project
|
24367a8abe982a022354b0586f95d78f3d851c8d
|
[
"MIT"
] | null | null | null |
src/singleton.hpp
|
TulioAbreu/game-project
|
24367a8abe982a022354b0586f95d78f3d851c8d
|
[
"MIT"
] | 20
|
2020-04-26T12:09:56.000Z
|
2020-09-25T23:30:12.000Z
|
src/singleton.hpp
|
TulioAbreu/game-project
|
24367a8abe982a022354b0586f95d78f3d851c8d
|
[
"MIT"
] | null | null | null |
#ifndef SINGLETON_HPP
#define SINGLETON_HPP
template <typename T>
class Singleton {
protected:
static T* mInstance;
Singleton() {}
public:
virtual ~Singleton() {
}
static T* getInstance() {
if (!mInstance) {
mInstance = new T();
}
return mInstance;
}
};
template <typename T>
T* Singleton<T>::mInstance = nullptr;
#endif
| 14.846154
| 37
| 0.598446
|
TulioAbreu
|
16e47215b684537f73a94d6b21173d6927967319
| 25,494
|
hpp
|
C++
|
stf-inc/stf_buffered_reader.hpp
|
sparcians/stf_lib
|
9e4933bff0c956dba464ced72e311e73507342dc
|
[
"MIT"
] | 1
|
2022-02-17T00:48:44.000Z
|
2022-02-17T00:48:44.000Z
|
stf-inc/stf_buffered_reader.hpp
|
sparcians/stf_lib
|
9e4933bff0c956dba464ced72e311e73507342dc
|
[
"MIT"
] | null | null | null |
stf-inc/stf_buffered_reader.hpp
|
sparcians/stf_lib
|
9e4933bff0c956dba464ced72e311e73507342dc
|
[
"MIT"
] | null | null | null |
/**
* \brief This file defines a buffered STF trace reader class
*
*/
#ifndef __STF_BUFFERED_READER_HPP__
#define __STF_BUFFERED_READER_HPP__
#include <sys/stat.h>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include "stf_enums.hpp"
#include "stf_exception.hpp"
#include "stf_item.hpp"
#include "stf_reader.hpp"
#include "stf_record.hpp"
#include "stf_record_pointers.hpp"
#include "stf_record_types.hpp"
/**
* \namespace stf
* \brief Defines all STF related classes
*
*/
namespace stf {
/**
* \class STFBufferedReader
* \brief The STFBufferedReader provides an iterator to a buffered stream of objects constructed from a trace
*/
template<typename ItemType, typename FilterType, typename ReaderType>
class STFBufferedReader: public STFReader {
protected:
/**
* \typedef IntDescriptor
* \brief Internal descriptor type
*/
using IntDescriptor = descriptors::internal::Descriptor;
static constexpr size_t DEFAULT_BUFFER_SIZE_ = 1024; /**< Default buffer size */
const size_t buffer_size_; /**< Size of the buffer */
const size_t buffer_mask_; /**< Mask value used to index into the buffer */
bool last_item_read_ = false; /**< If true, we have read to the end of the trace */
/**
* \typedef BufferT
* \brief Underlying buffer type
*/
using BufferT = ItemType[]; // NOLINT: Use C-array here so we can use [] operator on the unique_ptr
std::unique_ptr<BufferT> buf_; /**< Circular buffer */
size_t head_; /**< index of head of current item in circular buffer */
size_t tail_; /**< index of tail of current item in circular buffer */
size_t num_items_read_ = 0; /**< Counts number of items read from the buffer */
bool buffer_is_empty_ = true; /**< True if the buffer contains no items */
size_t num_skipped_items_ = 0; /**< Counts number of skipped items so that item indices can be adjusted */
FilterType filter_; /**< Filter type used to skip over certain record types */
/**
* Default skipped_ method
* \param item Item to check for skipping
*/
__attribute__((always_inline))
static inline bool skipped_(const ItemType& item) {
return false;
}
/**
* Checks whether an item should be skipped. Delegates the check to subclass if it defines a skipped_ method.
* \param item Item to check for skipping
*/
__attribute__((always_inline))
inline bool itemSkipped_(const ItemType& item) const {
return ReaderType::skipped_(item);
}
/**
* Increments the skipped item counter
* \param skip_item If true, increment skipped item counter
*/
__attribute__((always_inline))
inline void countSkipped_(const bool skip_item) {
num_skipped_items_ += skip_item;
}
/**
* Default item skipping cleanup callback. Does nothing.
*/
__attribute__((always_inline))
inline void skippedCleanup_() {
}
/**
* Invokes subclass callback to clean up any addtional state when an item is skipped
*/
__attribute__((always_inline))
inline void skippedItemCleanup_() {
static_cast<ReaderType*>(this)->skippedCleanup_();
}
/**
* Initializes the internal buffer
*/
bool initItemBuffer_() {
buf_ = std::make_unique<BufferT>(static_cast<size_t>(buffer_size_));
size_t i = 0;
while(i < buffer_size_) {
try {
readNextItem_(buf_[i]);
if(STF_EXPECT_FALSE(itemSkipped_(buf_[i]))) {
skippedItemCleanup_();
continue;
}
}
catch(const EOFException&) {
last_item_read_ = true;
break;
}
++tail_;
++i;
}
// no items in the file;
if (STF_EXPECT_FALSE(tail_ == 0)) {
buffer_is_empty_ = true;
return false;
}
buffer_is_empty_ = false;
--tail_; // Make tail_ point to the last item read instead of one past the last item
head_ = 0;
return true;
}
/**
* Internal function to validate item by index to prevent buffer under/overrun
* \param index Index value to check
*/
__attribute__((always_inline))
inline void validateItemIndex_(const uint64_t index) const {
const auto& tail = buf_[tail_];
stf_assert(index >= buf_[head_].index() && (itemSkipped_(tail) || index <= tail.index()),
"sliding window index out of range");
}
/**
* Gets item based on index and buffer location
* \param index Index of item (used only for validation)
* \param loc Location of item within the buffer
*/
__attribute__((always_inline))
inline const ItemType* getItem_(const uint64_t index, const size_t loc) const {
validateItemIndex_(index);
return &buf_[loc];
}
/**
* Gets item based on index and buffer location
* \param index Index of item (used only for validation)
* \param loc Location of item within the buffer
*/
__attribute__((always_inline))
inline ItemType* getItem_(const uint64_t index, const size_t loc) {
validateItemIndex_(index);
return &buf_[loc];
}
/**
* Checks if the specified item is the last one in the trace
* \param index Index of item (used only for validation)
* \param loc Location of item within the buffer
*/
inline bool isLastItem_(const uint64_t index, const size_t loc) {
validateItemIndex_(index);
if(STF_EXPECT_TRUE(!last_item_read_)) {
return false;
}
return loc == tail_;
}
/**
* Returns whether the reader decided to skip the specified item. Can be overridden by a subclass.
* \param index Item index
* \param loc Item buffer location
*/
__attribute__((always_inline))
inline bool readerSkipCallback_(uint64_t& index, size_t& loc) const {
return false;
}
/**
* Calls the subclass implementation of readerSkipCallback_
* \param index Item index
* \param loc Item buffer location
*/
__attribute__((always_inline))
inline bool callReaderSkipCallback_(uint64_t& index, size_t& loc) const {
return static_cast<const ReaderType*>(this)->readerSkipCallback_(index, loc);
}
/**
* Helper function for item iteration. The function does the following work;
* - refill the circular buffer if iterates to 2nd last item in the buffer;
* - handle buffer location crossing boundary;
* - pair the item index and buffer location;
* \param index Item index
* \param loc Item buffer location
*/
__attribute__((always_inline))
inline bool moveToNextItem_(uint64_t &index, size_t &loc) {
bool skip_item = false;
do {
// validate the item index;
validateItemIndex_(index);
// if current location is the 2nd last item in buffer;
// refill the half of the buffer;
if (STF_EXPECT_FALSE(loc == tail_ -1)) {
fillHalfBuffer_();
}
// since 2nd last is used for refill;
// the tail is absolute the end of trace;
if (STF_EXPECT_FALSE(loc == tail_)) {
return false;
}
index++;
loc = (loc + 1) & buffer_mask_;
// Check to see if the subclass decided to skip this item
skip_item = callReaderSkipCallback_(index, loc);
}
while(skip_item);
num_items_read_ = index;
return true;
}
/**
* Returns the number of items read so far without filtering
*/
__attribute__((always_inline))
inline size_t rawNumItemsRead_() const {
return static_cast<const ReaderType*>(this)->rawNumRead_();
}
/**
* Returns the number of items read from the reader so far with filtering
*/
__attribute__((always_inline))
inline size_t numItemsReadFromReader_() const {
return rawNumItemsRead_() - num_skipped_items_;
}
/**
* Initializes item index
*/
__attribute__((always_inline))
inline void initItemIndex_(ItemType& item) const {
delegates::STFItemDelegate::setIndex_(item, numItemsReadFromReader_());
}
/**
* Returns the number of items read from the buffer so far with filtering
*/
inline size_t numItemsRead_() const {
return num_items_read_;
}
/**
* Fill item into the half of the circular buffer;
*/
size_t fillHalfBuffer_() {
size_t pos = tail_;
const size_t init_item_cnt = numItemsReadFromReader_();
const size_t max_item_cnt = init_item_cnt + (buffer_size_ / 2);
while(numItemsReadFromReader_() < max_item_cnt) {
pos = (pos + 1) & buffer_mask_;
try {
readNextItem_(buf_[pos]);
if(STF_EXPECT_FALSE(itemSkipped_(buf_[pos]))) {
skippedItemCleanup_();
pos = (pos - 1) & buffer_mask_;
}
}
catch(const EOFException&) {
last_item_read_ = true;
break;
}
}
const size_t item_cnt = numItemsReadFromReader_() - init_item_cnt;
// adjust head and tail;
if (STF_EXPECT_TRUE(item_cnt != 0)) {
tail_ = (tail_ + item_cnt) & buffer_mask_;
head_ = (head_ + item_cnt) & buffer_mask_;
}
return item_cnt;
}
/**
* read STF records to construct a ItemType instance. readNext_ must be implemented by subclass
* \param item Item to modify with the record
*/
__attribute__((hot, always_inline))
inline void readNextItem_(ItemType &item) {
static_cast<ReaderType*>(this)->readNext_(item);
}
/**
* Calls handleNewRecord_ callback in subclass
* \param item Item to modify
* \param urec Record used to modify item
*/
__attribute__((hot, always_inline))
inline const STFRecord* handleNewItemRecord_(ItemType& item, STFRecord::UniqueHandle&& urec) {
return static_cast<ReaderType*>(this)->handleNewRecord_(item, std::move(urec));
}
/**
* \brief Read the next STF record, optionally using it to modify the specified item
* \param item Item to modify
* \return pointer to record if it is valid; otherwise nullptr
*/
__attribute__((hot, always_inline))
inline const STFRecord* readRecord_(ItemType& item) {
STFRecord::UniqueHandle urec;
operator>>(urec);
if(STF_EXPECT_FALSE(filter_.isFiltered(urec->getDescriptor()))) {
return nullptr;
}
return handleNewItemRecord_(item, std::move(urec));
}
/**
* Gets the index of the first item in the buffer
*/
inline uint64_t getFirstIndex_() {
return buf_[head_].index();
}
/**
* Returns whether the subclass thinks we should seek the slow way
*/
inline bool slowSeek_() const {
return false;
}
/**
* Returns whether we should seek the slow way
*/
inline bool slowItemSeek_() const {
return static_cast<const ReaderType*>(this)->slowSeek_();
}
/**
* \class base_iterator
* \brief iterator of the item stream that hides the sliding window.
* Decrement is not implemented. Rewinding is done by copying or assigning
* an existing iterator, with range limited by the sliding window size.
*
* Using the iterator ++ operator may advance the underlying trace stream,
* which is un-rewindable if the trace is compressed or via STDIN
*
*/
class base_iterator {
friend class STFBufferedReader;
private:
STFBufferedReader *sir_ = nullptr; // the reader
uint64_t index_ = 1; // index to the item stream
size_t loc_ = 0; // location in the sliding window buffer;
// keep it to speed up casting;
bool end_ = true; // whether this is an end iterator
protected:
/**
* \brief whether pointing to the last item
* \return true if last item
*/
inline bool isLastItem_() const {
return sir_->isLastItem_(index_, loc_);
}
public:
/**
* \typedef difference_type
* Type used for finding difference between two iterators
*/
using difference_type = std::ptrdiff_t;
/**
* \typedef value_type
* Type pointed to by this iterator
*/
using value_type = ItemType;
/**
* \typedef pointer
* Pointer to a value_type
*/
using pointer = const ItemType*;
/**
* \typedef reference
* Reference to a value_type
*/
using reference = const value_type&;
/**
* \typedef iterator_category
* Iterator type - using forward_iterator_tag because backwards iteration is not currently supported
*/
using iterator_category = std::forward_iterator_tag;
/**
* \brief Default constructor
*
*/
base_iterator() = default;
/**
* \brief Constructor
* \param sir The STF reader to iterate
* \param end Whether this is an end iterator
*
*/
explicit base_iterator(STFBufferedReader *sir, const bool end = false) :
sir_(sir),
end_(end)
{
if(!end) {
if (!sir_->buf_) {
if(!sir_->initItemBuffer_()) {
end_ = true;
}
loc_ = 0;
}
else {
end_ = sir_->buffer_is_empty_;
}
index_ = sir_->getFirstIndex_();
}
}
/**
* \brief Copy constructor
* \param rv The existing iterator to copy from
*
*/
base_iterator(const base_iterator & rv) = default;
/**
* \brief Assignment operator
* \param rv The existing iterator to copy from
*
*/
base_iterator & operator=(const base_iterator& rv) = default;
/**
* \brief Pre-increment operator
*/
__attribute__((always_inline))
inline base_iterator & operator++() {
stf_assert(!end_, "Can't increment the end iterator");
// index_ and loc_ are increased in moveToNextItem_;
if(STF_EXPECT_FALSE(!sir_->moveToNextItem_(index_, loc_))) {
end_ = true;
}
return *this;
}
/**
* \brief Post-increment operator
*/
__attribute__((always_inline))
inline base_iterator operator++(int) {
auto temp = *this;
operator++();
return temp;
}
/**
* \brief Return the ItemType pointer the iterator points to
*/
inline pointer current() const {
if (STF_EXPECT_FALSE(end_)) {
return nullptr;
}
return sir_->getItem_(index_, loc_);
}
/**
* \brief Returns whether the iterator is still valid
*/
inline bool valid() const {
try {
// Try to get a valid pointer
return current();
}
catch(const STFException&) {
// The item is outside the current window, so it's invalid
return false;
}
}
/**
* \brief Return the ItemType pointer the iterator points to
*/
inline const value_type& operator*() const { return *current(); }
/**
* \brief Return the ItemType pointer the iterator points to
*/
inline pointer operator->() const { return current(); }
/**
* \brief The equal operator to check ending
* \param rv The iterator to compare with
*/
inline bool operator==(const base_iterator& rv) const {
if (end_ || rv.end_) {
return end_ && rv.end_;
}
return index_ == rv.index_;
}
/**
* \brief The unequal operator to check ending
* \param rv The iterator to compare with
*/
inline bool operator!=(const base_iterator& rv) const {
return !operator==(rv);
}
};
public:
/**
* \brief Constructor
* \param buffer_size The size of the buffer sliding window
*/
explicit STFBufferedReader(const size_t buffer_size = DEFAULT_BUFFER_SIZE_) :
buffer_size_(buffer_size),
buffer_mask_(buffer_size_ - 1)
{
// Does NOT call open() automatically! Must be handled by derived classes.
}
/**
* \brief The beginning of the item stream
*
*/
template<typename U = ReaderType>
inline typename U::iterator begin() { return typename U::iterator(static_cast<U*>(this)); }
/**
* \brief The beginning of the item stream
* \param skip Skip this many items at the beginning
*
*/
template<typename U = ReaderType>
inline typename U::iterator begin(const size_t skip) {
if(skip) {
return seekFromBeginning(skip);
}
return typename U::iterator(static_cast<U*>(this));
}
/**
* \brief The end of the item stream
*
*/
template<typename U = ReaderType>
inline const typename U::iterator& end() {
static const auto end_it = typename U::iterator(static_cast<U*>(this), true);
return end_it;
}
/**
* \brief Opens a file
* \param filename The trace file name
* \param force_single_threaded_stream If true, forces single threaded mode in reader
*/
void open(const std::string_view filename,
const bool force_single_threaded_stream = false) {
STFReader::open(filename, force_single_threaded_stream);
buf_.reset();
head_ = 0;
tail_ = 0;
}
/**
* \brief Closes the file
*/
int close() {
buf_.reset();
head_ = 0;
tail_ = 0;
return STFReader::close();
}
/**
* Seeks the reader by the specified number of items and returns an iterator to that point
* \note Intended for seeking the reader prior to reading any items. For seeking in a reader that
* has already been iterated over, use the seek() method.
* \param num_items Number of items to skip
*/
template<typename U = ReaderType>
inline typename U::iterator seekFromBeginning(const size_t num_items) {
auto it = begin();
seek(it, num_items);
return it;
}
/**
* \brief Seeks an iterator by the given number of items
* \param it Iterator to seek
* \param num_items Number of items to seek by
*/
template<typename U = ReaderType>
inline void seek(typename U::iterator& it, const size_t num_items) {
const size_t num_buffered = tail_ - it.loc_ + 1;
// If the items are already buffered or skipping mode is enabled,
// we have to seek the slow way
if(slowItemSeek_() || num_items <= num_buffered) {
const auto end_it = end();
for(size_t i = 0; i < num_items && it != end_it; ++i) {
++it;
}
}
else {
// We don't need to seek the reader past items we've already read
const size_t num_to_skip = num_items - num_buffered;
STFReader::seek(num_to_skip);
head_ = 0;
tail_ = 0;
initItemBuffer_();
it = begin();
}
}
/**
* Returns the number of records read so far
*/
inline size_t numRecordsRead() const {
return STFReader::numRecordsRead();
}
/**
* Gets the filter object for this reader
*/
FilterType& getFilter() {
return filter_;
}
};
} //end namespace stf
// __STF_INST_READER_HPP__
#endif
| 37.491176
| 121
| 0.467169
|
sparcians
|
16e5c3adc2b7f9f761b415edb4a098df465cd777
| 5,463
|
cpp
|
C++
|
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dswapchainwithswdc.cpp
|
txlos/wpf
|
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
|
[
"MIT"
] | 5,937
|
2018-12-04T16:32:50.000Z
|
2022-03-31T09:48:37.000Z
|
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dswapchainwithswdc.cpp
|
txlos/wpf
|
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
|
[
"MIT"
] | 4,151
|
2018-12-04T16:38:19.000Z
|
2022-03-31T18:41:14.000Z
|
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dswapchainwithswdc.cpp
|
txlos/wpf
|
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
|
[
"MIT"
] | 1,084
|
2018-12-04T16:24:21.000Z
|
2022-03-30T13:52:03.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
//
//
// Description:
// Contains CD3DSwapChainWithSwDC implementation
//
// This class overrides the GetDC method of CD3DSwapChain to implement
// GetDC using GetRenderTargetData. This approach acheived phenominal perf
// wins in WDDM.
//
#include "precomp.hpp"
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::CD3DSwapChainWithSwDC
//
// Synopsis:
// ctor
//
#pragma warning( push )
#pragma warning( disable : 4355 )
CD3DSwapChainWithSwDC::CD3DSwapChainWithSwDC(
__in HDC hdcPresentVia,
__in_range(>, 0) /*__out_range(==, this->m_cBackBuffers)*/ UINT cBackBuffers,
__inout_ecount(1) IDirect3DSwapChain9 *pD3DSwapChain
) : CD3DSwapChain(
pD3DSwapChain,
cBackBuffers,
reinterpret_cast<CD3DSurface **>(reinterpret_cast<BYTE *>(this) + sizeof(*this))
),
m_hdcCopiedBackBuffer(hdcPresentVia),
m_hbmpCopiedBackBuffer(NULL),
m_pBuffer(NULL)
{
}
#pragma warning( pop )
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::~CD3DSwapChainWithSwDC
//
// Synopsis:
// dtor
//
CD3DSwapChainWithSwDC::~CD3DSwapChainWithSwDC()
{
if (m_hdcCopiedBackBuffer)
{
DeleteDC(m_hdcCopiedBackBuffer);
}
if (m_hbmpCopiedBackBuffer)
{
DeleteObject(m_hbmpCopiedBackBuffer);
}
}
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::Init
//
// Synopsis:
// Inits the swap chain and creates the sysmem present surface
//
//-----------------------------------------------------------------------------
HRESULT
CD3DSwapChainWithSwDC::Init(
__inout_ecount(1) CD3DResourceManager *pResourceManager
)
{
HRESULT hr = S_OK;
// The base class must be initialized first
IFC(CD3DSwapChain::Init(pResourceManager));
Assert(m_cBackBuffers >= 1);
D3DSURFACE_DESC const &surfDesc = m_rgBackBuffers[0]->Desc();
// We don't handle anything else yet
Assert( surfDesc.Format == D3DFMT_A8R8G8B8
|| surfDesc.Format == D3DFMT_X8R8G8B8
);
BITMAPINFO bmi;
bmi.bmiHeader.biSize = sizeof(bmi);
bmi.bmiHeader.biWidth = surfDesc.Width;
bmi.bmiHeader.biHeight = -INT(surfDesc.Height);
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
bmi.bmiHeader.biXPelsPerMeter = 10000;
bmi.bmiHeader.biYPelsPerMeter = 10000;
bmi.bmiHeader.biClrUsed = 0;
bmi.bmiHeader.biClrImportant = 0;
IFCW32_CHECKOOH(GR_GDIOBJECTS, m_hbmpCopiedBackBuffer = CreateDIBSection(
m_hdcCopiedBackBuffer,
&bmi,
DIB_RGB_COLORS,
&m_pBuffer,
NULL,
0
));
MilPixelFormat::Enum milFormat = D3DFormatToPixelFormat(surfDesc.Format, TRUE);
IFC(HrCalcDWordAlignedScanlineStride(surfDesc.Width, milFormat, OUT m_stride));
IFC(HrGetRequiredBufferSize(
milFormat,
m_stride,
surfDesc.Width,
surfDesc.Height,
&m_cbBuffer));
IFCW32(SelectObject(
m_hdcCopiedBackBuffer,
m_hbmpCopiedBackBuffer
));
Cleanup:
RRETURN(hr);
}
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::GetDC
//
// Synopsis:
// Gets a DC that refers to a system memory bitmap.
//
// The system memory bitmap is updated during this call. The dirty rect is
// used to determine how much of it needs updating.
//
HRESULT
CD3DSwapChainWithSwDC::GetDC(
/*__in_range(<, this->m_cBackBuffers)*/ UINT iBackBuffer,
__in_ecount(1) const CMilRectU& rcDirty,
__deref_out HDC *phdcBackBuffer
) const
{
HRESULT hr = S_OK;
ENTER_USE_CONTEXT_FOR_SCOPE(Device());
Assert(iBackBuffer < m_cBackBuffers);
D3DSURFACE_DESC const &surfDesc = m_rgBackBuffers[iBackBuffer]->Desc();
UINT cbBufferInset =
m_stride * rcDirty.top
+ D3DFormatSize(surfDesc.Format) * rcDirty.left;
BYTE *pbBuffer = reinterpret_cast<BYTE*>(m_pBuffer) + cbBufferInset;
IFC(m_rgBackBuffers[iBackBuffer]->ReadIntoSysMemBuffer(
rcDirty,
0,
NULL,
D3DFormatToPixelFormat(surfDesc.Format, TRUE),
m_stride,
DBG_ANALYSIS_PARAM_COMMA(m_cbBuffer - cbBufferInset)
pbBuffer
));
*phdcBackBuffer = m_hdcCopiedBackBuffer;
Cleanup:
RRETURN(hr);
}
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::ReleaseDC
//
// Synopsis:
// Releases the DC returned by GetDC if necessary
//
HRESULT
CD3DSwapChainWithSwDC::ReleaseDC(
/*__in_range(<, this->m_cBackBuffers)*/ UINT iBackBuffer,
__in HDC hdcBackBuffer
) const
{
//
// Do nothing- GetDC just hands out the DC so release is not necessary.
//
UNREFERENCED_PARAMETER(iBackBuffer);
UNREFERENCED_PARAMETER(hdcBackBuffer);
return S_OK;
}
| 25.059633
| 92
| 0.601135
|
txlos
|
16e9faef1b0f81f6d70040eb863b7ffe84e61718
| 347
|
cpp
|
C++
|
OOP/stuclass.cpp
|
PranavDherange/Data_Structures
|
9962b5145f6b42d9317e2c328c2b3124f028ca70
|
[
"MIT"
] | 2
|
2021-02-25T11:54:50.000Z
|
2021-02-25T11:54:54.000Z
|
OOP/stuclass.cpp
|
PranavDherange/Data_Structures
|
9962b5145f6b42d9317e2c328c2b3124f028ca70
|
[
"MIT"
] | null | null | null |
OOP/stuclass.cpp
|
PranavDherange/Data_Structures
|
9962b5145f6b42d9317e2c328c2b3124f028ca70
|
[
"MIT"
] | 1
|
2021-10-03T17:39:10.000Z
|
2021-10-03T17:39:10.000Z
|
#include <bits/stdc++.h>
using namespace std;
#include "Studentclass.cpp"
int main()
{
char name[] = "abcd";
Student s1(20, name);
s1.display();
Student s2(s1);
s2.name[0] = 'x';
s2.display();
s1.display();
// name[3] = 'e';
// Student s2(24, name);
// s2.display();
// s1.display();
return 0;
}
| 15.772727
| 28
| 0.521614
|
PranavDherange
|
16ead209c586f2e074f1d4422af59ed6684e6b06
| 12,201
|
cc
|
C++
|
src/expression/typechecking.cc
|
pictavien/tchecker
|
5db2430b5b75a5b94cfbbe885840a4809b267be8
|
[
"MIT"
] | null | null | null |
src/expression/typechecking.cc
|
pictavien/tchecker
|
5db2430b5b75a5b94cfbbe885840a4809b267be8
|
[
"MIT"
] | null | null | null |
src/expression/typechecking.cc
|
pictavien/tchecker
|
5db2430b5b75a5b94cfbbe885840a4809b267be8
|
[
"MIT"
] | null | null | null |
/*
* This file is a part of the TChecker project.
*
* See files AUTHORS and LICENSE for copyright details.
*
*/
#include <tuple>
#include "tchecker/expression/type_inference.hh"
#include "tchecker/expression/typechecking.hh"
namespace tchecker {
namespace details {
/*!
\class expression_typechecker_t
\brief Expression typechecking visitor
*/
class expression_typechecker_t : public tchecker::expression_visitor_t {
public:
/*!
\brief Constructor
\param intvars : integer variables
\param clocks : clock variables
\param log : logging facility
*/
expression_typechecker_t(tchecker::integer_variables_t const & intvars,
tchecker::clock_variables_t const & clocks,
std::function<void(std::string const &)> error)
: _typed_expr(nullptr),
_intvars(intvars),
_clocks(clocks),
_error(error)
{}
/*!
\brief Copy constructor (DELETED)
*/
expression_typechecker_t(tchecker::details::expression_typechecker_t const &) = delete;
/*!
\brief Move constructor (DELETED)
*/
expression_typechecker_t(tchecker::details::expression_typechecker_t &&) = delete;
/*!
\brief Destructor
*/
virtual ~expression_typechecker_t()
{
delete _typed_expr;
}
/*!
\brief Assignment operator (DELETED)
*/
tchecker::details::expression_typechecker_t & operator= (tchecker::details::expression_typechecker_t const &) = delete;
/*!
\brief Move assignment operator (DELETED)
*/
tchecker::details::expression_typechecker_t & operator= (tchecker::details::expression_typechecker_t &&) = delete;
/*!
\brief Accessor
\return typed expression computed by this visitor
\note the expression is released by the call, and should be handled by the
caller
*/
tchecker::typed_expression_t * release()
{
auto p = _typed_expr;
_typed_expr = nullptr;
return p;
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::int_expression_t const & expr)
{
_typed_expr = new tchecker::typed_int_expression_t(tchecker::EXPR_TYPE_INTTERM, expr.value());
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::var_expression_t const & expr)
{
// variable type, id and size
auto type_id_size = typecheck_variable(expr.name());
enum tchecker::expression_type_t const type = std::get<0>(type_id_size);
tchecker::variable_id_t const id = std::get<1>(type_id_size);
tchecker::variable_size_t const size = std::get<2>(type_id_size);
// bounded integer variable
if ((type == tchecker::EXPR_TYPE_INTVAR) || (type == tchecker::EXPR_TYPE_INTARRAY)) {
auto const & infos = _intvars.info(id);
_typed_expr = new tchecker::typed_bounded_var_expression_t(type, expr.name(), id, size, infos.min(), infos.max());
}
// clock variable
else if ((type == tchecker::EXPR_TYPE_CLKVAR) || (type == tchecker::EXPR_TYPE_CLKARRAY))
_typed_expr = new tchecker::typed_var_expression_t(type, expr.name(), id, size);
// otherwise (BAD)
else
_typed_expr = new tchecker::typed_var_expression_t(tchecker::EXPR_TYPE_BAD, expr.name(), id, size);
if (type == tchecker::EXPR_TYPE_BAD)
_error("in expression " + expr.to_string() + ", undeclared variable");
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
\note array expression on variables of size 1 are well typed
\note out-of-bounds access are not checked
*/
virtual void visit(tchecker::array_expression_t const & expr)
{
// Typecheck variable
expr.variable().visit(*this);
auto const * const typed_variable = dynamic_cast<tchecker::typed_var_expression_t const *>(this->release());
auto const variable_type = typed_variable->type();
// Typecheck offset
expr.offset().visit(*this);
auto const * const typed_offset = this->release();
auto const offset_type = typed_offset->type();
// Typed expression
enum tchecker::expression_type_t expr_type;
if (integer_dereference(variable_type) && integer_valued(offset_type))
expr_type = tchecker::EXPR_TYPE_INTLVALUE;
else if (clock_dereference(variable_type) && integer_valued(offset_type))
expr_type = tchecker::EXPR_TYPE_CLKLVALUE;
else
expr_type = tchecker::EXPR_TYPE_BAD;
_typed_expr = new tchecker::typed_array_expression_t(expr_type, typed_variable, typed_offset);
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if (offset_type != tchecker::EXPR_TYPE_BAD) {
if (! integer_valued(offset_type))
_error("in expression " + expr.to_string() +
", array subscript " + expr.offset().to_string() +
" does not have an integral value");
else
_error("in expression " + expr.to_string() +
", invalid array variable " + expr.variable().to_string());
}
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::par_expression_t const & expr)
{
// Sub expression
expr.expr().visit(*this);
tchecker::typed_expression_t * typed_sub_expr = this->release();
// Typed expression
enum tchecker::expression_type_t expr_type = type_par(typed_sub_expr->type());
_typed_expr = new tchecker::typed_par_expression_t(expr_type, typed_sub_expr);
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if (typed_sub_expr->type() != tchecker::EXPR_TYPE_BAD)
_error("in expression " + expr.to_string() + ", invalid parentheses around " + expr.expr().to_string());
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::binary_expression_t const & expr)
{
// Operands
expr.left_operand().visit(*this);
tchecker::typed_expression_t * typed_left_operand = this->release();
expr.right_operand().visit(*this);
tchecker::typed_expression_t * typed_right_operand = this->release();
// Typed expression
enum tchecker::expression_type_t expr_type = type_binary(expr.binary_operator(), typed_left_operand->type(),
typed_right_operand->type());
switch (expr_type) {
case tchecker::EXPR_TYPE_CLKCONSTR_SIMPLE:
_typed_expr = new tchecker::typed_simple_clkconstr_expression_t(expr_type, expr.binary_operator(), typed_left_operand,
typed_right_operand);
break;
case tchecker::EXPR_TYPE_CLKCONSTR_DIAGONAL:
_typed_expr = new tchecker::typed_diagonal_clkconstr_expression_t(expr_type, expr.binary_operator(), typed_left_operand,
typed_right_operand);
break;
default: // either EXPR_TYPE_ATOMIC_PREDICATE or EXPR_TYPE_BAD
_typed_expr = new tchecker::typed_binary_expression_t(expr_type, expr.binary_operator(), typed_left_operand,
typed_right_operand);
break;
}
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if ((typed_left_operand->type() != tchecker::EXPR_TYPE_BAD) && (typed_right_operand->type() != tchecker::EXPR_TYPE_BAD))
_error("in expression " + expr.to_string() + ", invalid composition of expressions " + expr.left_operand().to_string() +
" and " + expr.right_operand().to_string());
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::unary_expression_t const & expr)
{
// Operand
expr.operand().visit(*this);
tchecker::typed_expression_t * typed_operand = this->release();
// Typed expression
enum tchecker::expression_type_t expr_type = type_unary(expr.unary_operator(), typed_operand->type());
_typed_expr = new tchecker::typed_unary_expression_t(expr_type, expr.unary_operator(), typed_operand);
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if (typed_operand->type() != tchecker::EXPR_TYPE_BAD)
_error("in expression " + expr.to_string() + ", invalid operand " + expr.operand().to_string());
}
protected:
/*!
\brief Accessor
\param name : variable name
\return tchecker::EXPR_TYPE_INTARRAY if name is an array of integer
variables,
tchecker::EXPR_TYPE_INTVAR if name is an integer variable of size 1,
tchecker::EXPR_TYPE_CLKARRAY if name is an array of clock variables,
tchecker::EXPR_TYPE_CLKVAR if name is a clock variable of size 1
tchecker::EXPR_TYPE_BAD otherwise (name is not a declared variable)
\pre name is a declared integer or clock variable
*/
std::tuple<enum tchecker::expression_type_t, tchecker::variable_id_t, tchecker::variable_size_t>
typecheck_variable(std::string const & name)
{
// Integer variable ?
try {
auto id = _intvars.id(name);
auto size = _intvars.info(id).size();
if (size > 1)
return std::make_tuple(tchecker::EXPR_TYPE_INTARRAY, id, size);
else
return std::make_tuple(tchecker::EXPR_TYPE_INTVAR, id, size);
}
catch (...)
{}
// Clock variable ?
try {
auto id = _clocks.id(name);
auto size = _clocks.info(id).size();
if (size > 1)
return std::make_tuple(tchecker::EXPR_TYPE_CLKARRAY, id, size);
else
return std::make_tuple(tchecker::EXPR_TYPE_CLKVAR, id, size);
}
catch (...)
{}
// Not a variable name
return std::make_tuple(tchecker::EXPR_TYPE_BAD, std::numeric_limits<tchecker::variable_id_t>::max(), 1);
}
tchecker::typed_expression_t * _typed_expr; /*!< Typed expression */
tchecker::integer_variables_t const & _intvars; /*!< Integer variables */
tchecker::clock_variables_t const & _clocks; /*!< Clock variables */
std::function<void(std::string const &)> _error; /*!< Error logging func */
};
} // end of namespace details
tchecker::typed_expression_t * typecheck(tchecker::expression_t const & expr,
tchecker::integer_variables_t const & intvars,
tchecker::clock_variables_t const & clocks,
std::function<void(std::string const &)> error)
{
tchecker::details::expression_typechecker_t v(intvars, clocks, error);
expr.visit(v);
return v.release();
}
} // end of namespace tchecker
| 36.861027
| 132
| 0.58823
|
pictavien
|
16edb80f7661e00b275c94644380bfaf2f291740
| 318
|
cpp
|
C++
|
smb2/cpp/GUI/Wrapper/Controls/ctrackbar.cpp
|
loginsinex/smb2
|
fd1347e8d730edd092df19a3d388684944016522
|
[
"MIT"
] | 8
|
2018-02-23T20:39:02.000Z
|
2022-02-14T23:57:36.000Z
|
smb2/cpp/GUI/Wrapper/Controls/ctrackbar.cpp
|
loginsinex/smb2
|
fd1347e8d730edd092df19a3d388684944016522
|
[
"MIT"
] | 1
|
2020-02-25T22:57:44.000Z
|
2020-02-27T02:07:17.000Z
|
smb2/cpp/GUI/Wrapper/Controls/ctrackbar.cpp
|
loginsinex/smb2
|
fd1347e8d730edd092df19a3d388684944016522
|
[
"MIT"
] | 1
|
2017-06-08T00:56:42.000Z
|
2017-06-08T00:56:42.000Z
|
#include "precomp.h"
VOID CTrackBar::SetMinMax(UINT min, UINT max)
{
cSendMessage(TBM_SETRANGEMIN, TRUE, min);
cSendMessage(TBM_SETRANGEMAX, TRUE, max);
}
VOID CTrackBar::Pos(UINT uPos)
{
cSendMessage(TBM_SETPOS, TRUE, uPos);
}
UINT CTrackBar::Pos()
{
return (UINT) cSendMessage(TBM_GETPOS);
}
| 17.666667
| 46
| 0.694969
|
loginsinex
|
16ef060d11c261a958069e8da8881267b134d95c
| 1,412
|
cpp
|
C++
|
src/m581expT.cpp
|
CardinalModules/TheXOR
|
910b76622c9100d9755309adf76542237c6d3a77
|
[
"CC0-1.0"
] | 1
|
2021-12-12T22:08:23.000Z
|
2021-12-12T22:08:23.000Z
|
src/m581expT.cpp
|
CardinalModules/TheXOR
|
910b76622c9100d9755309adf76542237c6d3a77
|
[
"CC0-1.0"
] | null | null | null |
src/m581expT.cpp
|
CardinalModules/TheXOR
|
910b76622c9100d9755309adf76542237c6d3a77
|
[
"CC0-1.0"
] | 1
|
2021-12-12T22:08:29.000Z
|
2021-12-12T22:08:29.000Z
|
#include "../include/m581expT.hpp"
void m581expT::process(const ProcessArgs &args)
{
int curStp = getStep();
if(curStp >= 0)
{
float v = params[Z8PULSE_TIME].getValue();
if(curStp != prevStep)
{
pulses[curStp].trigger(v/1000.f);
prevStep=curStp;
}
}
float deltaTime = 1.0 / args.sampleRate;
// 1 = in process; -1 = terminato; 0 = no operation
for(int k = 0; k < 16; k++)
{
int c = pulses[k].process(deltaTime);
if(c == 1)
outputs[OUT_1 + k].setVoltage(LVL_ON);
else if(c == -1)
outputs[OUT_1 + k].setVoltage(LVL_OFF);
}
}
m581expTWidget::m581expTWidget(m581expT *module)
{
CREATE_PANEL(module, this, 18, "res/modules/m581expT.svg");
if(module != NULL)
module->createWidget(this);
addParam(createParam<Davies1900hFixRedKnobSmall>(Vec(mm2px(79.067), yncscape(9.058, 8.0)), module, m581expT::Z8PULSE_TIME));
float dist_h = 14.52 - 3.559;
float dist_v = 97.737 - 86.980;
float y = 23.016;
float dled = 10.064 - 3.559;
float dledY = 102.571 - 97.737;
for (int c = 0; c < 8; c++)
{
for(int r = 0; r < 8; r++)
{
int n = c * 8 + r;
int posx = 3.559 + dist_h * c;
addOutput(createOutput<portBLUSmall>(Vec(mm2px(posx), yncscape(y + dist_v * r, 5.885)), module, m581expT::OUT_1 + n));
if(module != NULL)
addChild(createLight<TinyLight<RedLight>>(Vec(mm2px(dled + posx), yncscape(y + dledY + dist_v * r, 1.088)), module, module->ledID(n)));
}
}
}
| 25.672727
| 139
| 0.634561
|
CardinalModules
|
16efa27a12f51ec1eaac9620496887e857ae7aba
| 612
|
hpp
|
C++
|
mod/memlite/src/interface/instancer.hpp
|
kniz/worldlang
|
78701ab003c158211d42d129f91259d17febbb22
|
[
"MIT"
] | 7
|
2019-03-12T03:04:32.000Z
|
2021-12-26T04:33:44.000Z
|
mod/memlite/src/interface/instancer.hpp
|
kniz/worldlang
|
78701ab003c158211d42d129f91259d17febbb22
|
[
"MIT"
] | 7
|
2019-02-13T14:01:43.000Z
|
2020-11-20T11:09:06.000Z
|
mod/memlite/src/interface/instancer.hpp
|
kniz/worldlang
|
78701ab003c158211d42d129f91259d17febbb22
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../pool/pool.hpp"
#include "../watcher/watcher.hpp"
namespace wrd {
class instancer {
WRD_DECL_ME(instancer)
WRD_INIT_META(me)
friend class instance;
public:
wbool bind(const instance& new1);
wbool rel(const instance& old);
const pool& getPool() const;
const watcher& getWatcher() const;
static WRD_SINGLETON_GETTER(me)
private:
void* _new1(size_t sz);
void _del(void* pt, wcnt sz);
wbool _hasBindTag(const instance& it) const;
pool _pool;
watcher _watcher;
};
}
| 21.103448
| 52
| 0.601307
|
kniz
|
16f0cd1949c0c93b84ebe4ce1972566fcd01344e
| 5,134
|
hpp
|
C++
|
stan/math/opencl/kernel_generator/select.hpp
|
kedartal/math
|
77248cf73c1110660006c9700f78d9bb7c02be1d
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/opencl/kernel_generator/select.hpp
|
kedartal/math
|
77248cf73c1110660006c9700f78d9bb7c02be1d
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/opencl/kernel_generator/select.hpp
|
kedartal/math
|
77248cf73c1110660006c9700f78d9bb7c02be1d
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/as_operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/is_valid_expression.hpp>
#include <stan/math/opencl/kernel_generator/common_return_scalar.hpp>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
namespace stan {
namespace math {
/**
* Represents a selection operation in kernel generator expressions. This is
* element wise ternary operator <code>condition ? then : els</code>, also
* equivalent to Eigen's \c .select().
* @tparam Derived derived type
* @tparam T_condition type of condition
* @tparam T_then type of then expression
* @tparam T_else type of else expression
*/
template <typename T_condition, typename T_then, typename T_else>
class select_ : public operation_cl<select_<T_condition, T_then, T_else>,
common_scalar_t<T_then, T_else>,
T_condition, T_then, T_else> {
public:
using Scalar = common_scalar_t<T_then, T_else>;
using base = operation_cl<select_<T_condition, T_then, T_else>, Scalar,
T_condition, T_then, T_else>;
using base::var_name;
protected:
using base::arguments_;
public:
/**
* Constructor
* @param condition condition expression
* @param then then expression
* @param els else expression
*/
select_(T_condition&& condition, T_then&& then, T_else&& els) // NOLINT
: base(std::forward<T_condition>(condition), std::forward<T_then>(then),
std::forward<T_else>(els)) {
if (condition.rows() != base::dynamic && then.rows() != base::dynamic) {
check_size_match("select", "Rows of ", "condition", condition.rows(),
"rows of ", "then", then.rows());
}
if (condition.cols() != base::dynamic && then.cols() != base::dynamic) {
check_size_match("select", "Columns of ", "condition", condition.cols(),
"columns of ", "then", then.cols());
}
if (condition.rows() != base::dynamic && els.rows() != base::dynamic) {
check_size_match("select", "Rows of ", "condition", condition.rows(),
"rows of ", "else", els.rows());
}
if (condition.cols() != base::dynamic && els.cols() != base::dynamic) {
check_size_match("select", "Columns of ", "condition", condition.cols(),
"columns of ", "else", els.cols());
}
}
/**
* generates kernel code for this (select) operation.
* @param i row index variable name
* @param j column index variable name
* @param var_name_condition variable name of the condition expression
* @param var_name_else variable name of the then expression
* @param var_name_then variable name of the else expression
* @return part of kernel with code for this expression
*/
inline kernel_parts generate(const std::string& i, const std::string& j,
const std::string& var_name_condition,
const std::string& var_name_then,
const std::string& var_name_else) const {
kernel_parts res{};
res.body = type_str<Scalar>() + " " + var_name + " = " + var_name_condition
+ " ? " + var_name_then + " : " + var_name_else + ";\n";
return res;
}
/**
* View of a matrix that would be the result of evaluating this expression.
* @return view
*/
inline matrix_cl_view view() const {
matrix_cl_view condition_view = std::get<0>(arguments_).view();
matrix_cl_view then_view = std::get<1>(arguments_).view();
matrix_cl_view else_view = std::get<2>(arguments_).view();
return both(either(then_view, else_view), both(condition_view, then_view));
}
};
/**
* Selection operation on kernel generator expressions. This is element wise
* ternary operator <code> condition ? then : els </code>.
* @tparam T_condition type of condition expression
* @tparam T_then type of then expression
* @tparam T_else type of else expression
* @param condition condition expression
* @param then then expression
* @param els else expression
* @return selection operation expression
*/
template <typename T_condition, typename T_then, typename T_else,
typename
= require_all_valid_expressions_t<T_condition, T_then, T_else>>
inline select_<as_operation_cl_t<T_condition>, as_operation_cl_t<T_then>,
as_operation_cl_t<T_else>>
select(T_condition&& condition, T_then&& then, T_else&& els) { // NOLINT
return {as_operation_cl(std::forward<T_condition>(condition)),
as_operation_cl(std::forward<T_then>(then)),
as_operation_cl(std::forward<T_else>(els))};
}
} // namespace math
} // namespace stan
#endif
#endif
| 39.79845
| 79
| 0.668679
|
kedartal
|
16f23bb4e00852d5112a4b9b4fe9b892a39c7bdc
| 6,159
|
cpp
|
C++
|
RayEngine/Source/System/Application.cpp
|
Mumsfilibaba/RayEngine
|
68496966c1d7b91bc8fbdd305226ece9b9f596b2
|
[
"Apache-2.0"
] | null | null | null |
RayEngine/Source/System/Application.cpp
|
Mumsfilibaba/RayEngine
|
68496966c1d7b91bc8fbdd305226ece9b9f596b2
|
[
"Apache-2.0"
] | null | null | null |
RayEngine/Source/System/Application.cpp
|
Mumsfilibaba/RayEngine
|
68496966c1d7b91bc8fbdd305226ece9b9f596b2
|
[
"Apache-2.0"
] | null | null | null |
/*////////////////////////////////////////////////////////////
Copyright 2018 Alexander Dahlin
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
THIS SOFTWARE IS PROVIDED "AS IS". MEANING NO WARRANTY
OR SUPPORT IS PROVIDED OF ANY KIND.
In event of any damages, direct or indirect that can
be traced back to the use of this software, shall no
contributor be held liable. This includes computer
failure and or malfunction of any kind.
////////////////////////////////////////////////////////////*/
#include <RayEngine.h>
#include <System/Application.h>
#include <Graphics/IShader.h>
#include <Graphics/IPipelineState.h>
#include <Graphics/IRenderer.h>
#include <Graphics/Viewport.h>
namespace RayEngine
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application::Application(GRAPHICS_API api)
: m_pWindow(nullptr),
m_pDevice(nullptr),
m_pRenderer(nullptr),
m_pPipeline(nullptr),
m_Api(api)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application::~Application()
{
ReRelease_S(m_pPipeline);
ReRelease_S(m_pRenderer);
ReRelease_S(m_pDevice);
if (m_pWindow != nullptr)
{
m_pWindow->Destroy();
m_pWindow = nullptr;
}
LOG_INFO("Destroying Application");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Application::OnUpdate()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Application::OnRender()
{
using namespace Graphics;
m_pRenderer->Begin();
float color[] = { 0.392f, 0.584f, 0.929f, 1.0f };
m_pRenderer->Clear(color);
m_pRenderer->Draw();
m_pRenderer->End();
m_pRenderer->Present();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int32 Application::Run()
{
OnCreate();
LOG_INFO("Starting RayEngine");
m_pWindow->Show();
Event event = {};
while (event.Type != EVENT_TYPE_CLOSE)
{
if (m_pWindow->PeekEvent(&event))
{
if (event.Type == EVENT_TYPE_RESIZE)
{
}
}
OnUpdate();
OnRender();
}
LOG_INFO("Exiting RayEngine");
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Application::OnCreate()
{
using namespace Graphics;
LOG_INFO("Initializing RayEngine");
WindowDesc wnd = {};
wnd.Style = WINDOW_STYLE_STANDARD;
wnd.Width = 1024;
wnd.Height = 768;
wnd.pTitle = "RayEngine";
wnd.BackgroundColor.r = 127;
wnd.BackgroundColor.g = 127;
wnd.BackgroundColor.b = 127;
wnd.x = 0;
wnd.y = 0;
wnd.pIcon = nullptr;
wnd.Cursor.pImage = nullptr;
DeviceDesc dev = {};
dev.DeviceFlags = DEVICE_FLAG_DEBUG;
dev.SamplerDescriptorCount = 8;
dev.ResourceDescriptorCount = 8;
dev.RendertargetDescriptorCount = 4;
dev.DepthStencilDescriptorCount = 4;
dev.SampleCount = 1;
dev.BackBuffer.Count = 2;
dev.BackBuffer.Format = FORMAT_R8G8B8A8_UNORM;
dev.DepthStencil.Format = FORMAT_D24_UNORM_S8_UINT;
dev.Width = wnd.Width;
dev.Height = wnd.Height;
InitGraphics(&m_pWindow, wnd, &m_pDevice, dev, m_Api);
m_pRenderer = m_pDevice->CreateRenderer();
std::string vs;
std::string ps;
ShaderDesc shader = {};
shader.Flags = SHADER_FLAGS_DEBUG;
shader.pEntryPoint = "main";
shader.Type = SHADER_TYPE_VERTEX;
if (m_Api == GRAPHICS_API_OPENGL)
{
shader.SrcLang = SHADER_SOURCE_LANG_GLSL;
vs =
"#version 330\n"
"\n"
"void main()\n"
"{\n"
" vec4 pos = vec4(0.0);\n"
" if (gl_VertexID == 0) { pos = vec4(0.0f, 0.5f, 0.0f, 1.0f); }\n"
" else if (gl_VertexID == 1) { pos = vec4(0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else if (gl_VertexID == 2) { pos = vec4(-0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else { pos = vec4(0.0f, 0.0f, 0.0f, 1.0f); }\n"
" gl_Position = pos;\n"
"}\n";
ps =
"#version 330\n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n"
"}\n";
}
else
{
shader.SrcLang = SHADER_SOURCE_LANG_HLSL;
vs =
"struct VS_OUT\n"
"{\n"
" float4 pos : SV_Position;\n"
"};\n"
"\n"
"VS_OUT main(uint id : SV_VertexID)\n"
"{\n"
" VS_OUT output;\n"
" if (id == 0) { output.pos = float4(0.0f, 0.5f, 0.0f, 1.0f); }\n"
" else if (id == 1) { output.pos = float4(0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else if (id == 2) { output.pos = float4(-0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else { output.pos = float4(0.0f, 0.0f, 0.0f, 1.0f); }\n"
" return output;\n"
"}\n";
ps =
"struct PS_IN\n"
"{\n"
" float4 pos : SV_Position;\n"
"};\n"
"\n"
"float4 main(PS_IN input) : SV_Target0\n"
"{\n"
" return float4(1.0f, 1.0f, 1.0f, 1.0f);\n"
"}\n";
}
shader.pSource = vs.c_str();
IShader* pVS = nullptr;
m_pDevice->CreateShader(&pVS, &shader);
shader.pSource = ps.c_str();
shader.Type = SHADER_TYPE_PIXEL;
IShader* pPS = nullptr;
m_pDevice->CreateShader(&pPS, &shader);
PipelineStateDesc pipeline = PipelineStateDesc::DefaultGraphicsPipeline();
pipeline.Type = PIPELINE_TYPE_GRAPHICS;
pipeline.Graphics.pVertexShader = pVS;
pipeline.Graphics.pPixelShader = pPS;
pipeline.Graphics.RenderTargetCount = 1;
pipeline.Graphics.RenderTargetFormats[0] = dev.BackBuffer.Format;
pipeline.Graphics.DepthStencilFormat = dev.DepthStencil.Format;
pipeline.Graphics.SampleCount = dev.SampleCount;
pipeline.Graphics.Topology = PRIMITIVE_TOPOLOGY_TRIANGLELIST;
pipeline.Graphics.InputLayout.ElementCount = 0;
pipeline.Graphics.InputLayout.pElements = nullptr;
pipeline.Graphics.DepthStencilState.DepthEnable = true;
m_pDevice->CreatePipelineState(&m_pPipeline, &pipeline);
ReRelease_S(pVS);
ReRelease_S(pPS);
}
}
| 25.878151
| 123
| 0.562267
|
Mumsfilibaba
|
16f4e67cff58e7112c1221c466841c08adc38c2f
| 486
|
cpp
|
C++
|
Game/JMath.cpp
|
Jdasi/DXTK-Boids
|
9612de4f91846ec9c5307ac6d675c0c07b373a7d
|
[
"MIT"
] | null | null | null |
Game/JMath.cpp
|
Jdasi/DXTK-Boids
|
9612de4f91846ec9c5307ac6d675c0c07b373a7d
|
[
"MIT"
] | null | null | null |
Game/JMath.cpp
|
Jdasi/DXTK-Boids
|
9612de4f91846ec9c5307ac6d675c0c07b373a7d
|
[
"MIT"
] | null | null | null |
#include "JMath.h"
// Clamps a float. I.e. returns _min when _min is exceeded.
float JMath::clampf(float _curr, float _min, float _max)
{
if (_curr < _min)
return _min;
if (_curr > _max)
return _max;
return _curr;
}
// Inversely clamps a float. I.e. returns _min when _max is exceeded.
float JMath::iclampf(float _curr, float _min, float _max)
{
if (_curr < _min)
return _max;
if (_curr > _max)
return _min;
return _curr;
}
| 18.692308
| 69
| 0.623457
|
Jdasi
|
a84398d66f3c34c7da355a05051940f65ba14609
| 2,888
|
hxx
|
C++
|
include/cstddef.hxx
|
K-Wu/libcxx.doc
|
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
|
[
"Apache-2.0"
] | null | null | null |
include/cstddef.hxx
|
K-Wu/libcxx.doc
|
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
|
[
"Apache-2.0"
] | null | null | null |
include/cstddef.hxx
|
K-Wu/libcxx.doc
|
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
|
[
"Apache-2.0"
] | null | null | null |
// -*- C++ -*-
//===--------------------------- cstddef ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_CSTDDEF
#define _LIBCPP_CSTDDEF
/*
cstddef synopsis
Macros:
offsetof(type,member-designator)
NULL
namespace std
{
Types:
ptrdiff_t
size_t
max_align_t
nullptr_t
byte // C++17
} // std
*/
#ifndef __simt__
#include <__config.hxx>
#include <version.hxx>
#endif //__simt__
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifndef __simt__
// Don't include our own <stddef.h>; we don't want to declare ::nullptr_t.
#ifdef _MSC_VER
#include <../ucrt/stddef.h>
#else
#include_next <stddef.h>
#endif
#include <__nullptr.hxx>
#endif //__simt__
_LIBCPP_BEGIN_NAMESPACE_STD
using ::ptrdiff_t;
using ::size_t;
#if defined(__CLANG_MAX_ALIGN_T_DEFINED) || defined(_GCC_MAX_ALIGN_T) || \
defined(__DEFINED_max_align_t) || defined(__NetBSD__)
// Re-use the compiler's <stddef.h> max_align_t where possible.
using ::max_align_t;
#else
typedef long double max_align_t;
#endif
_LIBCPP_END_NAMESPACE_STD
#if _LIBCPP_STD_VER > 14
#ifdef _LIBCPP_BEGIN_NAMESPACE_STD_NOVERSION
_LIBCPP_BEGIN_NAMESPACE_STD_NOVERSION
#else
namespace std // purposefully not versioned
{
#endif //_LIBCPP_BEGIN_NAMESPACE_STD_NOVERSION
enum class byte : unsigned char {};
constexpr byte operator| (byte __lhs, byte __rhs) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
static_cast<unsigned int>(__lhs) | static_cast<unsigned int>(__rhs)
));
}
constexpr byte& operator|=(byte& __lhs, byte __rhs) noexcept
{ return __lhs = __lhs | __rhs; }
constexpr byte operator& (byte __lhs, byte __rhs) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
static_cast<unsigned int>(__lhs) & static_cast<unsigned int>(__rhs)
));
}
constexpr byte& operator&=(byte& __lhs, byte __rhs) noexcept
{ return __lhs = __lhs & __rhs; }
constexpr byte operator^ (byte __lhs, byte __rhs) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
static_cast<unsigned int>(__lhs) ^ static_cast<unsigned int>(__rhs)
));
}
constexpr byte& operator^=(byte& __lhs, byte __rhs) noexcept
{ return __lhs = __lhs ^ __rhs; }
constexpr byte operator~ (byte __b) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
~static_cast<unsigned int>(__b)
));
}
#ifdef _LIBCPP_END_NAMESPACE_STD_NOVERSION
_LIBCPP_END_NAMESPACE_STD_NOVERSION
#else
}
#endif //_LIBCPP_END_NAMESPACE_STD_NOVERSION
#endif
#endif // _LIBCPP_CSTDDEF
| 22.387597
| 80
| 0.686981
|
K-Wu
|
a84442cee063dad11d5a9cad2c5d748f9fcc3c46
| 4,971
|
cc
|
C++
|
src/actions/transformations/js_decode.cc
|
Peercraft/deb-modsecurity
|
6d608c3ea5d762b370bf682ba24e2febffd4f382
|
[
"Apache-2.0"
] | null | null | null |
src/actions/transformations/js_decode.cc
|
Peercraft/deb-modsecurity
|
6d608c3ea5d762b370bf682ba24e2febffd4f382
|
[
"Apache-2.0"
] | null | null | null |
src/actions/transformations/js_decode.cc
|
Peercraft/deb-modsecurity
|
6d608c3ea5d762b370bf682ba24e2febffd4f382
|
[
"Apache-2.0"
] | null | null | null |
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/actions/transformations/js_decode.h"
#include <string.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include "modsecurity/transaction.h"
#include "src/actions/transformations/transformation.h"
#include "src/utils/string.h"
namespace modsecurity {
namespace actions {
namespace transformations {
std::string JsDecode::evaluate(std::string value,
Transaction *transaction) {
std::string ret;
unsigned char *input = NULL;
input = reinterpret_cast<unsigned char *>
(malloc(sizeof(char) * value.length()+1));
if (input == NULL) {
return "";
}
memcpy(input, value.c_str(), value.length()+1);
size_t i = inplace(input, value.length());
ret.assign(reinterpret_cast<char *>(input), i);
free(input);
return ret;
}
int JsDecode::inplace(unsigned char *input, u_int64_t input_len) {
unsigned char *d = (unsigned char *)input;
int64_t i, count;
i = count = 0;
while (i < input_len) {
if (input[i] == '\\') {
/* Character is an escape. */
if ((i + 5 < input_len) && (input[i + 1] == 'u')
&& (VALID_HEX(input[i + 2])) && (VALID_HEX(input[i + 3]))
&& (VALID_HEX(input[i + 4])) && (VALID_HEX(input[i + 5]))) {
/* \uHHHH */
/* Use only the lower byte. */
*d = utils::string::x2c(&input[i + 4]);
/* Full width ASCII (ff01 - ff5e) needs 0x20 added */
if ((*d > 0x00) && (*d < 0x5f)
&& ((input[i + 2] == 'f') || (input[i + 2] == 'F'))
&& ((input[i + 3] == 'f') || (input[i + 3] == 'F'))) {
(*d) += 0x20;
}
d++;
count++;
i += 6;
} else if ((i + 3 < input_len) && (input[i + 1] == 'x')
&& VALID_HEX(input[i + 2]) && VALID_HEX(input[i + 3])) {
/* \xHH */
*d++ = utils::string::x2c(&input[i + 2]);
count++;
i += 4;
} else if ((i + 1 < input_len) && ISODIGIT(input[i + 1])) {
/* \OOO (only one byte, \000 - \377) */
char buf[4];
int j = 0;
while ((i + 1 + j < input_len) && (j < 3)) {
buf[j] = input[i + 1 + j];
j++;
if (!ISODIGIT(input[i + 1 + j])) break;
}
buf[j] = '\0';
if (j > 0) {
/* Do not use 3 characters if we will be > 1 byte */
if ((j == 3) && (buf[0] > '3')) {
j = 2;
buf[j] = '\0';
}
*d++ = (unsigned char)strtol(buf, NULL, 8);
i += 1 + j;
count++;
}
} else if (i + 1 < input_len) {
/* \C */
unsigned char c = input[i + 1];
switch (input[i + 1]) {
case 'a' :
c = '\a';
break;
case 'b' :
c = '\b';
break;
case 'f' :
c = '\f';
break;
case 'n' :
c = '\n';
break;
case 'r' :
c = '\r';
break;
case 't' :
c = '\t';
break;
case 'v' :
c = '\v';
break;
/* The remaining (\?,\\,\',\") are just a removal
* of the escape char which is default.
*/
}
*d++ = c;
i += 2;
count++;
} else {
/* Not enough bytes */
while (i < input_len) {
*d++ = input[i++];
count++;
}
}
} else {
*d++ = input[i++];
count++;
}
}
*d = '\0';
return count;
}
} // namespace transformations
} // namespace actions
} // namespace modsecurity
| 29.414201
| 79
| 0.396097
|
Peercraft
|
a859ffcda73443198aa4f1e6f89bd3a2501e2e90
| 2,541
|
hpp
|
C++
|
ivarp/include/ivarp/math_fn/eval/custom.hpp
|
phillip-keldenich/squares-in-disk
|
501ebeb00b909b9264a9611fd63e082026cdd262
|
[
"MIT"
] | null | null | null |
ivarp/include/ivarp/math_fn/eval/custom.hpp
|
phillip-keldenich/squares-in-disk
|
501ebeb00b909b9264a9611fd63e082026cdd262
|
[
"MIT"
] | null | null | null |
ivarp/include/ivarp/math_fn/eval/custom.hpp
|
phillip-keldenich/squares-in-disk
|
501ebeb00b909b9264a9611fd63e082026cdd262
|
[
"MIT"
] | null | null | null |
// The code is open source under the MIT license.
// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group
// https://ibr.cs.tu-bs.de/alg
//
// 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.
//
// Created by Phillip Keldenich on 22.11.19.
//
#pragma once
namespace ivarp {
namespace impl {
template<typename Context, typename FnType, typename... Args_, typename ArgArray>
struct EvaluateImpl<Context, MathCustomFunction<FnType,Args_...>, ArgArray>
{
using CalledType = MathCustomFunction<FnType,Args_...>;
using NumberType = typename Context::NumberType;
using ArgsType = typename CalledType::Args;
IVARP_HD_OVERLOAD_ON_CUDA_NT(NumberType,
static NumberType eval(const CalledType& c, const ArgArray& args) noexcept(AllowsCUDA<NumberType>::value)
{
return do_eval(c, args, IndexRange<0,sizeof...(Args_)>{});
}
)
private:
IVARP_HD_OVERLOAD_TEMPLATE_ON_CUDA_NT(IVARP_TEMPLATE_PARAMS(std::size_t... Inds), NumberType,
static NumberType do_eval(const CalledType& c, const ArgArray& args, IndexPack<Inds...>)
noexcept(AllowsCUDA<NumberType>::value)
{
return c.functor.template eval<Context>(
(PredicateEvaluateImpl<Context, TupleElementType<Inds,ArgsType>, ArgArray>::eval(
get<Inds>(c.args), args
))...
);
}
)
};
}
}
| 43.067797
| 117
| 0.681621
|
phillip-keldenich
|
a85be22b7ff30f9baa398b2a425d727c6faf163b
| 14,129
|
cpp
|
C++
|
test/range/test-any_range.cpp
|
rogiervd/range
|
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
|
[
"Apache-2.0"
] | null | null | null |
test/range/test-any_range.cpp
|
rogiervd/range
|
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
|
[
"Apache-2.0"
] | null | null | null |
test/range/test-any_range.cpp
|
rogiervd/range
|
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2013, 2015 Rogier van Dalen.
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.
*/
#define BOOST_TEST_MODULE test_range_any_range
#include "utility/test/boost_unit_test.hpp"
#include "range/any_range.hpp"
#include <list>
#include <vector>
#include <tuple>
#include "range/std.hpp"
#include "range/tuple.hpp"
#include "range/function_range.hpp"
#include "weird_count.hpp"
#include "unique_range.hpp"
using range::front;
using range::back;
using range::default_direction;
using range::empty;
using range::size;
using range::first;
using range::drop;
using range::chop;
using range::chop_in_place;
using range::has;
namespace callable = range::callable;
using range::any_range;
using range::make_any_range;
BOOST_AUTO_TEST_SUITE(test_range_any_range)
BOOST_AUTO_TEST_CASE (test_any_range_has) {
{
typedef any_range <int, range::capability::unique_capabilities> range;
// first and drop only available for rvalue references.
static_assert (has <callable::empty (range const &)>::value, "");
static_assert (!has <callable::first (range const &)>::value, "");
static_assert (!has <callable::size (range const &)>::value, "");
static_assert (!has <callable::drop (range const &)>::value, "");
static_assert (!has <callable::drop (range const &, int)>::value, "");
static_assert (has <callable::chop (range &&)>::value, "");
static_assert (has <callable::chop_in_place (range &)>::value, "");
static_assert (has <
callable::empty (range const &, direction::back)>::value, "");
static_assert (!has <
callable::first (range const &, direction::back)>::value, "");
static_assert (!has <
callable::size (range const &, direction::back)>::value, "");
static_assert (!has <
callable::drop (range const &, direction::back)>::value, "");
static_assert (!has <
callable::drop (range const &, int, direction::back)>::value, "");
static_assert (!has <
callable::chop (range &&, direction::back)>::value, "");
static_assert (!has <
callable::chop_in_place (range &, direction::back)>::value, "");
}
{
typedef any_range <int, range::capability::forward_capabilities> range;
static_assert (has <callable::empty (range const &)>::value, "");
static_assert (has <callable::first (range const &)>::value, "");
static_assert (!has <callable::size (range const &)>::value, "");
static_assert (has <callable::drop (range const &)>::value, "");
static_assert (!has <callable::drop (range const &, int)>::value, "");
static_assert (has <callable::chop (range &&)>::value, "");
static_assert (has <callable::chop_in_place (range &)>::value, "");
static_assert (has <
callable::empty (range const &, direction::back)>::value, "");
static_assert (!has <
callable::first (range const &, direction::back)>::value, "");
static_assert (!has <
callable::size (range const &, direction::back)>::value, "");
static_assert (!has <
callable::drop (range const &, direction::back)>::value, "");
static_assert (!has <
callable::drop (range const &, int, direction::back)>::value, "");
static_assert (!has <
callable::chop (range &&, direction::back)>::value, "");
static_assert (!has <
callable::chop_in_place (range &, direction::back)>::value, "");
}
{
typedef any_range <int, range::capability::bidirectional_capabilities>
range;
static_assert (has <callable::empty (range const &)>::value, "");
static_assert (has <callable::first (range const &)>::value, "");
static_assert (!has <callable::size (range const &)>::value, "");
static_assert (has <callable::drop (range const &)>::value, "");
static_assert (!has <callable::drop (range const &, int)>::value, "");
static_assert (has <callable::chop (range &&)>::value, "");
static_assert (has <callable::chop_in_place (range &)>::value, "");
static_assert (has <
callable::empty (range const &, direction::back)>::value, "");
static_assert (has <
callable::first (range const &, direction::back)>::value, "");
static_assert (!has <
callable::size (range const &, direction::back)>::value, "");
static_assert (has <
callable::drop (range const &, direction::back)>::value, "");
static_assert (!has <
callable::drop (range const &, int, direction::back)>::value, "");
static_assert (has <
callable::chop (range &&, direction::back)>::value, "");
static_assert (has <
callable::chop_in_place (range &, direction::back)>::value, "");
}
{
typedef any_range <int, range::capability::random_access_capabilities>
range;
static_assert (has <callable::empty (range const &)>::value, "");
static_assert (has <callable::first (range const &)>::value, "");
static_assert (has <callable::size (range const &)>::value, "");
static_assert (has <callable::drop (range const &)>::value, "");
static_assert (has <callable::drop (range const &, int)>::value, "");
static_assert (has <callable::chop (range &&)>::value, "");
static_assert (has <callable::chop_in_place (range &)>::value, "");
static_assert (has <
callable::empty (range const &, direction::back)>::value, "");
static_assert (has <
callable::first (range const &, direction::back)>::value, "");
static_assert (has <
callable::size (range const &, direction::back)>::value, "");
static_assert (has <
callable::drop (range const &, direction::back)>::value, "");
static_assert (has <
callable::drop (range const &, int, direction::back)>::value, "");
static_assert (has <
callable::chop (range &&, direction::back)>::value, "");
static_assert (has <
callable::chop_in_place (range &, direction::back)>::value, "");
}
}
BOOST_AUTO_TEST_CASE (test_any_range_homogeneous) {
std::vector <int> v;
v.push_back (4);
v.push_back (5);
v.push_back (6);
v.push_back (7);
{
any_range <int &> a (v);
BOOST_CHECK (!range::empty (a));
BOOST_CHECK_EQUAL (range::first (a), 4);
a = range::drop (a);
BOOST_CHECK (!range::empty (a));
auto chopped = range::chop (a);
BOOST_CHECK_EQUAL (chopped.first(), 5);
BOOST_CHECK (!range::empty (chopped.rest()));
a = chopped.move_rest();
BOOST_CHECK (!range::empty (a));
BOOST_CHECK_EQUAL (range::first (a), 6);
int & e = range::chop_in_place (a);
BOOST_CHECK_EQUAL (e, 6);
BOOST_CHECK_EQUAL (&e, &v [2]);
BOOST_CHECK (!range::empty (a));
BOOST_CHECK_EQUAL (range::first (a), 7);
a = range::drop (a);
BOOST_CHECK (range::empty (a));
}
{
auto a = range::make_any_range (v);
BOOST_MPL_ASSERT ((
range::has <callable::empty (decltype (a), direction::back)>));
BOOST_MPL_ASSERT ((
range::has <callable::first (decltype (a), direction::front)>));
BOOST_MPL_ASSERT ((
range::has <callable::size (decltype (a), direction::back)>));
BOOST_MPL_ASSERT ((
range::has <callable::drop (decltype (a), direction::back)>));
BOOST_MPL_ASSERT ((
range::has <callable::drop (decltype (a), int, direction::front)>));
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (size (a), 4u);
BOOST_CHECK_EQUAL (size (drop (a)), 3u);
BOOST_CHECK_EQUAL (first (drop (a)), 5);
BOOST_CHECK_EQUAL (first (drop (a, 2)), 6);
BOOST_CHECK_EQUAL (first (a, back), 7);
BOOST_CHECK_EQUAL (first (drop (a, back), back), 6);
BOOST_CHECK_EQUAL (first (drop (a, 2, back), back), 5);
BOOST_CHECK (empty (drop (a, 4), back));
first (drop (a)) = 14;
BOOST_CHECK_EQUAL (v[1], 14);
// Convert to default capabilities
any_range <int &> a2 (a);
BOOST_CHECK (!empty (a2));
a2 = drop (a2);
BOOST_CHECK (!empty (a2));
// Was 5, now 14.
BOOST_CHECK_EQUAL (first (a2), 14);
a2 = drop (a2);
BOOST_CHECK (!empty (a2));
BOOST_CHECK_EQUAL (first (a2), 6);
a2 = drop (a2);
BOOST_CHECK (!empty (a2));
BOOST_CHECK_EQUAL (first (a2), 7);
a2 = drop (a2);
BOOST_CHECK (empty (a2));
// Convert to different type: int & -> long should be fine.
any_range <long> al (a);
BOOST_CHECK (!empty (al));
BOOST_CHECK_EQUAL (first (al), 4l);
BOOST_CHECK_EQUAL (first (drop (al)), 14l);
al = drop (drop (al));
BOOST_CHECK (!empty (al));
BOOST_CHECK_EQUAL (first (al), 6l);
BOOST_CHECK (!empty (drop (al)));
BOOST_CHECK_EQUAL (first (drop (al)), 7l);
al = drop (drop (al));
BOOST_CHECK (empty (al));
}
}
BOOST_AUTO_TEST_CASE (test_any_range_unique) {
std::vector <int> v;
v.push_back (4);
v.push_back (5);
v.push_back (6);
v.push_back (7);
{
auto a = make_any_range (unique_view (v));
static_assert (!std::is_constructible <
decltype (a), decltype (a) const &>::value, "");
BOOST_CHECK_EQUAL (first (a), 4);
a = drop (std::move (a));
BOOST_CHECK_EQUAL (chop_in_place (a), 5);
auto b = std::move (a);
BOOST_CHECK_EQUAL (chop_in_place (b), 6);
BOOST_CHECK_EQUAL (chop_in_place (b), 7);
BOOST_CHECK (empty (b));
}
{
any_range <int, range::capability::unique_capabilities> a (
one_time_view (v));
// first and drop are not available.
BOOST_CHECK_EQUAL (chop_in_place (a), 4);
auto chopped = chop (std::move (a));
BOOST_CHECK_EQUAL (chopped.first(), 5);
a = chopped.move_rest();
BOOST_CHECK_EQUAL (chop_in_place (a), 6);
auto b = std::move (a);
BOOST_CHECK_EQUAL (chop_in_place (b), 7);
BOOST_CHECK (empty (b));
}
{
struct count {
int i;
count() : i (0) {}
int operator() () { return ++i; }
};
any_range <int, range::capability::unique_capabilities> a (
range::make_function_range (count()));
BOOST_CHECK_EQUAL (chop_in_place (a), 1);
BOOST_CHECK_EQUAL (chop_in_place (a), 2);
}
}
BOOST_AUTO_TEST_CASE (test_any_range_heterogeneous) {
{
std::tuple <> t;
any_range <int> a (t);
BOOST_CHECK (empty (a));
}
{
std::tuple <int> t (7);
any_range <int> a (t);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (first (a), 7);
any_range <int> a_next = drop (a);
BOOST_CHECK (empty (a_next));
}
{
std::tuple <int, char, long> t (7, 'a', 294l);
any_range <long> a (t);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (first (a), 7l);
a = drop (a);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (first (a), long ('a'));
a = drop (a);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (first (a), 294l);
a = drop (a);
BOOST_CHECK (empty (a));
}
{
std::tuple <int, char, long> t (7, 'a', 294l);
any_range <long, range::capability::bidirectional_capabilities> a (t);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (chop_in_place (a), 7l);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (chop_in_place (a, back), 294l);
BOOST_CHECK (!empty (a));
BOOST_CHECK_EQUAL (chop_in_place (a, back), long ('a'));
BOOST_CHECK (empty (a));
}
}
BOOST_AUTO_TEST_CASE (test_any_range_copy_move) {
typedef any_range <int, meta::map <
meta::map_element <range::capability::default_direction,
direction::front>,
meta::map_element <direction::front, meta::set <
range::capability::empty, range::capability::size,
range::capability::first>>>>
range_with_size;
typedef any_range <int, meta::map <
meta::map_element <range::capability::default_direction,
direction::front>,
meta::map_element <direction::front, meta::set <
range::capability::empty, range::capability::first>>>>
range_without_size;
std::vector <int> v;
v.push_back (26);
static_assert (
!std::is_constructible <range_with_size, range_with_size const &
>::value, "The range cannot be copied so it is not copy-constructible");
static_assert (
!std::is_constructible <range_without_size, range_with_size const &
>::value, "The range cannot be copied so it is not copy-constructible");
static_assert (
std::is_constructible <range_with_size, range_with_size &&>::value,
"Moving to the same type is a pointer operation.");
static_assert (
!std::is_constructible <range_without_size, range_with_size &&>::value,
"The range cannot be copied so it is not move-constructible "
"with different capabilities.");
range_with_size r (v);
range_with_size r2 (std::move (r));
BOOST_CHECK_EQUAL (size (r2), 1);
}
BOOST_AUTO_TEST_SUITE_END()
| 36.228205
| 80
| 0.583764
|
rogiervd
|
a85df51766a4e04ecc4d4dff6e50cdae3d006497
| 13,423
|
cc
|
C++
|
DRsim/src/DRsimDetectorConstruction.cc
|
kyHwangs/DRC_generic
|
efb5a791c57706ac1848907af5bef36cb8480ca2
|
[
"Apache-2.0"
] | null | null | null |
DRsim/src/DRsimDetectorConstruction.cc
|
kyHwangs/DRC_generic
|
efb5a791c57706ac1848907af5bef36cb8480ca2
|
[
"Apache-2.0"
] | null | null | null |
DRsim/src/DRsimDetectorConstruction.cc
|
kyHwangs/DRC_generic
|
efb5a791c57706ac1848907af5bef36cb8480ca2
|
[
"Apache-2.0"
] | 1
|
2022-03-28T04:06:32.000Z
|
2022-03-28T04:06:32.000Z
|
#include "DRsimDetectorConstruction.hh"
#include "DRsimCellParameterisation.hh"
#include "DRsimFilterParameterisation.hh"
#include "DRsimMirrorParameterisation.hh"
#include "DRsimSiPMSD.hh"
#include "G4VPhysicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4PVParameterised.hh"
#include "G4IntersectionSolid.hh"
#include "G4SDManager.hh"
#include "G4LogicalSkinSurface.hh"
#include "G4LogicalBorderSurface.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4SolidStore.hh"
#include "G4PhysicalVolumeStore.hh"
#include "G4GeometryManager.hh"
#include "G4Colour.hh"
#include "G4SystemOfUnits.hh"
#include "Randomize.hh"
using namespace std;
G4ThreadLocal DRsimMagneticField* DRsimDetectorConstruction::fMagneticField = 0;
G4ThreadLocal G4FieldManager* DRsimDetectorConstruction::fFieldMgr = 0;
int DRsimDetectorConstruction::fNofRow = 7;
int DRsimDetectorConstruction::fNofModules = fNofRow * fNofRow;
DRsimDetectorConstruction::DRsimDetectorConstruction()
: G4VUserDetectorConstruction(), fMessenger(0), fMaterials(NULL) {
DefineCommands();
DefineMaterials();
clad_C_rMin = 0.49*mm;
clad_C_rMax = 0.50*mm;
clad_C_Dz = 2.5*m;
clad_C_Sphi = 0.;
clad_C_Dphi = 2.*M_PI;
core_C_rMin = 0.*mm;
core_C_rMax = 0.49*mm;
core_C_Dz = 2.5*m;
core_C_Sphi = 0.;
core_C_Dphi = 2.*M_PI;
clad_S_rMin = 0.485*mm;
clad_S_rMax = 0.50*mm;
clad_S_Dz = 2.5*m;
clad_S_Sphi = 0.;
clad_S_Dphi = 2.*M_PI;
core_S_rMin = 0.*mm;
core_S_rMax = 0.485*mm;
core_S_Dz = 2.5*m;
core_S_Sphi = 0.;
core_S_Dphi = 2.*M_PI;
PMTT = 0.3*mm;
filterT = 0.01*mm;
reflectorT = 0.03*mm;
fVisAttrOrange = new G4VisAttributes(G4Colour(1.0,0.5,0.,1.0));
fVisAttrOrange->SetVisibility(true);
fVisAttrBlue = new G4VisAttributes(G4Colour(0.,0.,1.0,1.0));
fVisAttrBlue->SetVisibility(true);
fVisAttrGray = new G4VisAttributes(G4Colour(0.3,0.3,0.3,0.3));
fVisAttrGray->SetVisibility(true);
fVisAttrGreen = new G4VisAttributes(G4Colour(0.3,0.7,0.3));
fVisAttrGreen->SetVisibility(true);
}
DRsimDetectorConstruction::~DRsimDetectorConstruction() {
delete fMessenger;
delete fMaterials;
delete fVisAttrOrange;
delete fVisAttrBlue;
delete fVisAttrGray;
delete fVisAttrGreen;
}
void DRsimDetectorConstruction::DefineMaterials() {
fMaterials = DRsimMaterials::GetInstance();
}
G4VPhysicalVolume* DRsimDetectorConstruction::Construct() {
G4GeometryManager::GetInstance()->OpenGeometry();
G4PhysicalVolumeStore::GetInstance()->Clean();
G4LogicalVolumeStore::GetInstance()->Clean();
G4SolidStore::GetInstance()->Clean();
checkOverlaps = false;
G4VSolid* worldSolid = new G4Box("worldBox",10.*m,10.*m,10.*m);
worldLogical = new G4LogicalVolume(worldSolid,FindMaterial("G4_Galactic"),"worldLogical");
G4VPhysicalVolume* worldPhysical = new G4PVPlacement(0,G4ThreeVector(),worldLogical,"worldPhysical",0,false,0,checkOverlaps);
fFrontL = 1500.; // NOTE :: Length from the center of world box to center of module
fTowerDepth = 2500.;
fModuleH = 90;
fModuleW = 90;
fFiberUnitH = 1.;
// fRandomSeed = 1;
doFiber = true;
doReflector = false;
doPMT = true;
fiberUnit = new G4Box("fiber_SQ", (fFiberUnitH/2) *mm, (1./2) *mm, (fTowerDepth/2) *mm);
fiberClad = new G4Tubs("fiber", 0, clad_C_rMax, fTowerDepth/2., 0 *deg, 360. *deg); // S is the same
fiberCoreC = new G4Tubs("fiberC", 0, core_C_rMax, fTowerDepth/2., 0 *deg, 360. *deg);
fiberCoreS = new G4Tubs("fiberS", 0, core_S_rMax, fTowerDepth/2., 0 *deg, 360. *deg);
dimCalc = new dimensionCalc();
dimCalc->SetFrontL(fFrontL);
dimCalc->SetTower_height(fTowerDepth);
dimCalc->SetPMTT(PMTT+filterT);
dimCalc->SetReflectorT(reflectorT);
dimCalc->SetNofModules(fNofModules);
dimCalc->SetNofRow(fNofRow);
ModuleBuild(ModuleLogical,PMTGLogical,PMTfilterLogical,PMTcellLogical,PMTcathLogical,ReflectorMirrorLogical,fiberUnitIntersection,fiberCladIntersection,fiberCoreIntersection,fModuleProp);
delete dimCalc;
return worldPhysical;
}
void DRsimDetectorConstruction::ConstructSDandField() {
G4SDManager* SDman = G4SDManager::GetSDMpointer();
G4String SiPMName = "SiPMSD";
// ! Not a memory leak - SDs are deleted by G4SDManager. Deleting them manually will cause double delete!
if ( doPMT ) {
for (int i = 0; i < fNofModules; i++) {
DRsimSiPMSD* SiPMSDmodule = new DRsimSiPMSD("Module"+std::to_string(i), "ModuleC"+std::to_string(i), fModuleProp.at(i));
SDman->AddNewDetector(SiPMSDmodule);
PMTcathLogical[i]->SetSensitiveDetector(SiPMSDmodule);
}
}
}
void DRsimDetectorConstruction::ModuleBuild(G4LogicalVolume* ModuleLogical_[],
G4LogicalVolume* PMTGLogical_[], G4LogicalVolume* PMTfilterLogical_[], G4LogicalVolume* PMTcellLogical_[], G4LogicalVolume* PMTcathLogical_[],
G4LogicalVolume* ReflectorMirrorLogical_[],
std::vector<G4LogicalVolume*> fiberUnitIntersection_[], std::vector<G4LogicalVolume*> fiberCladIntersection_[], std::vector<G4LogicalVolume*> fiberCoreIntersection_[],
std::vector<DRsimInterface::DRsimModuleProperty>& ModuleProp_) {
for (int i = 0; i < fNofModules; i++) {
moduleName = setModuleName(i);
dimCalc->SetisModule(true);
module = new G4Box("Mudule", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (fTowerDepth/2.) *mm );
ModuleLogical_[i] = new G4LogicalVolume(module,FindMaterial("Copper"),moduleName);
// G4VPhysicalVolume* modulePhysical = new G4PVPlacement(0,dimCalc->GetOrigin(i),ModuleLogical_[i],moduleName,worldLogical,false,0,checkOverlaps);
new G4PVPlacement(0,dimCalc->GetOrigin(i),ModuleLogical_[i],moduleName,worldLogical,false,0,checkOverlaps);
if ( doPMT ) {
dimCalc->SetisModule(false);
pmtg = new G4Box("PMTG", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (PMTT+filterT)/2. *mm );
PMTGLogical_[i] = new G4LogicalVolume(pmtg,FindMaterial("G4_AIR"),moduleName);
new G4PVPlacement(0,dimCalc->GetOrigin_PMTG(i),PMTGLogical_[i],moduleName,worldLogical,false,0,checkOverlaps);
}
FiberImplement(i,ModuleLogical_,fiberUnitIntersection_,fiberCladIntersection_,fiberCoreIntersection_);
DRsimInterface::DRsimModuleProperty ModulePropSingle;
ModulePropSingle.towerXY = fTowerXY;
ModulePropSingle.ModuleNum = i;
ModuleProp_.push_back(ModulePropSingle);
if ( doPMT ) {
G4VSolid* SiPMlayerSolid = new G4Box("SiPMlayerSolid", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (PMTT/2.) *mm );
G4LogicalVolume* SiPMlayerLogical = new G4LogicalVolume(SiPMlayerSolid,FindMaterial("G4_AIR"),"SiPMlayerLogical");
new G4PVPlacement(0,G4ThreeVector(0.,0.,filterT/2.),SiPMlayerLogical,"SiPMlayerPhysical",PMTGLogical_[i],false,0,checkOverlaps);
G4VSolid* filterlayerSolid = new G4Box("filterlayerSolid", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (filterT/2.) *mm );
G4LogicalVolume* filterlayerLogical = new G4LogicalVolume(filterlayerSolid,FindMaterial("Glass"),"filterlayerLogical");
new G4PVPlacement(0,G4ThreeVector(0.,0.,-PMTT/2.),filterlayerLogical,"filterlayerPhysical",PMTGLogical_[i],false,0,checkOverlaps);
G4VSolid* PMTcellSolid = new G4Box("PMTcellSolid", 1.2/2. *mm, 1.2/2. *mm, PMTT/2. *mm );
PMTcellLogical_[i] = new G4LogicalVolume(PMTcellSolid,FindMaterial("Glass"),"PMTcellLogical_");
DRsimCellParameterisation* PMTcellParam = new DRsimCellParameterisation(fTowerXY.first,fTowerXY.second);
G4PVParameterised* PMTcellPhysical = new G4PVParameterised("PMTcellPhysical",PMTcellLogical_[i],SiPMlayerLogical,kXAxis,fTowerXY.first*fTowerXY.second,PMTcellParam);
G4VSolid* PMTcathSolid = new G4Box("PMTcathSolid", 1.2/2. *mm, 1.2/2. *mm, filterT/2. *mm );
PMTcathLogical_[i] = new G4LogicalVolume(PMTcathSolid,FindMaterial("Silicon"),"PMTcathLogical_");
new G4PVPlacement(0,G4ThreeVector(0.,0.,(PMTT-filterT)/2.*mm),PMTcathLogical_[i],"PMTcathPhysical",PMTcellLogical_[i],false,0,checkOverlaps);
new G4LogicalSkinSurface("Photocath_surf",PMTcathLogical_[i],FindSurface("SiPMSurf"));
G4VSolid* filterSolid = new G4Box("filterSolid", 1.2/2. *mm, 1.2/2. *mm, filterT/2. *mm );
PMTfilterLogical_[i] = new G4LogicalVolume(filterSolid,FindMaterial("Gelatin"),"PMTfilterLogical_");
DRsimFilterParameterisation* filterParam = new DRsimFilterParameterisation(fTowerXY.first,fTowerXY.second);
G4PVParameterised* filterPhysical = new G4PVParameterised("filterPhysical",PMTfilterLogical_[i],filterlayerLogical,kXAxis,fTowerXY.first*fTowerXY.second/2,filterParam);
new G4LogicalBorderSurface("filterSurf",filterPhysical,PMTcellPhysical,FindSurface("FilterSurf"));
PMTcathLogical_[i]->SetVisAttributes(fVisAttrGreen);
PMTfilterLogical_[i]->SetVisAttributes(fVisAttrOrange);
}
if ( doReflector ) {
G4VSolid* ReflectorlayerSolid = new G4Box("ReflectorlayerSolid", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (reflectorT/2.) *mm );
G4LogicalVolume* ReflectorlayerLogical = new G4LogicalVolume(ReflectorlayerSolid,FindMaterial("G4_Galactic"),"ReflectorlayerLogical");
new G4PVPlacement(0,dimCalc->GetOrigin_Reflector(i),ReflectorlayerLogical,"ReflectorlayerPhysical",worldLogical,false,0,checkOverlaps);
G4VSolid* mirrorSolid = new G4Box("mirrorSolid", 1.2/2. *mm, 1.2/2. *mm, reflectorT/2. *mm );
ReflectorMirrorLogical_[i] = new G4LogicalVolume(mirrorSolid,FindMaterial("Aluminum"),"ReflectorMirrorLogical_");
DRsimMirrorParameterisation* mirrorParam = new DRsimMirrorParameterisation(fTowerXY.first,fTowerXY.second);
G4PVParameterised* mirrorPhysical = new G4PVParameterised("mirrorPhysical",ReflectorMirrorLogical_[i],ReflectorlayerLogical,kXAxis,fTowerXY.first*fTowerXY.second/2,mirrorParam);
// new G4LogicalBorderSurface("MirrorSurf",mirrorPhysical,modulePhysical,FindSurface("MirrorSurf"));
new G4LogicalSkinSurface("MirrorSurf",ReflectorMirrorLogical_[i],FindSurface("MirrorSurf"));
ReflectorMirrorLogical_[i]->SetVisAttributes(fVisAttrGray);
}
}
}
void DRsimDetectorConstruction::DefineCommands() {}
void DRsimDetectorConstruction::FiberImplement(G4int i, G4LogicalVolume* ModuleLogical__[],
std::vector<G4LogicalVolume*> fiberUnitIntersection__[], std::vector<G4LogicalVolume*> fiberCladIntersection__[],
std::vector<G4LogicalVolume*> fiberCoreIntersection__[]) {
fFiberX.clear();
fFiberY.clear();
fFiberWhich.clear();
int NofFiber = 60;
int NofPlate = 60;
double randDeviation = 0.; // double randDeviation = fFiberUnitH - 1.;
fTowerXY = std::make_pair(NofPlate,NofFiber);
G4bool fWhich = false;
for (int k = 0; k < NofPlate; k++) {
for (int j = 0; j < NofFiber; j++) {
/*
? fX : # of plate , fY : # of fiber in the plate
*/
G4float fX = -90.*mm/2 + k*1.5*mm + 0.75*mm;
G4float fY = -90.*mm/2 + j*1.5*mm + 0.75*mm;
fWhich = !fWhich;
fFiberX.push_back(fX);
fFiberY.push_back(fY);
fFiberWhich.push_back(fWhich);
}
if ( NofFiber%2==0 ) { fWhich = !fWhich; }
}
if ( doFiber ) {
for (unsigned int j = 0; j<fFiberX.size(); j++) {
if ( !fFiberWhich.at(j) ) { //c fibre
tfiberCladIntersection = new G4IntersectionSolid("fiberClad",fiberClad,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.));
fiberCladIntersection__[i].push_back(new G4LogicalVolume(tfiberCladIntersection,FindMaterial("FluorinatedPolymer"),name));
new G4PVPlacement(0,G4ThreeVector(fFiberX.at(j),fFiberY.at(j),0),fiberCladIntersection__[i].at(j),name,ModuleLogical__[i],false,j,checkOverlaps);
tfiberCoreIntersection = new G4IntersectionSolid("fiberCore",fiberCoreC,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.));
fiberCoreIntersection__[i].push_back(new G4LogicalVolume(tfiberCoreIntersection,FindMaterial("PMMA"),name));
new G4PVPlacement(0,G4ThreeVector(0.,0.,0.),fiberCoreIntersection__[i].at(j),name,fiberCladIntersection__[i].at(j),false,j,checkOverlaps);
fiberCladIntersection__[i].at(j)->SetVisAttributes(fVisAttrGray);
fiberCoreIntersection__[i].at(j)->SetVisAttributes(fVisAttrBlue);
} else { // s fibre
tfiberCladIntersection = new G4IntersectionSolid("fiberClad",fiberClad,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.));
fiberCladIntersection__[i].push_back(new G4LogicalVolume(tfiberCladIntersection,FindMaterial("PMMA"),name));
new G4PVPlacement(0,G4ThreeVector(fFiberX.at(j),fFiberY.at(j),0),fiberCladIntersection__[i].at(j),name,ModuleLogical__[i],false,j,checkOverlaps);
tfiberCoreIntersection = new G4IntersectionSolid("fiberCore",fiberCoreS,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.));
fiberCoreIntersection__[i].push_back(new G4LogicalVolume(tfiberCoreIntersection,FindMaterial("Polystyrene"),name));
new G4PVPlacement(0,G4ThreeVector(0.,0.,0.),fiberCoreIntersection__[i].at(j),name,fiberCladIntersection__[i].at(j),false,j,checkOverlaps);
fiberCladIntersection__[i].at(j)->SetVisAttributes(fVisAttrGray);
fiberCoreIntersection__[i].at(j)->SetVisAttributes(fVisAttrOrange);
}
}
}
}
| 46.286207
| 212
| 0.716606
|
kyHwangs
|
a85e22945433eba2ae0840f32b9c59fbc589962a
| 10,259
|
hpp
|
C++
|
chat_room/ChatRoom_multithreads/cpp_headers/aws_s3.hpp
|
LiaoWC/cpp_programs
|
da78030d02cb916466ad5f0b0794f5c443cc05b4
|
[
"MIT"
] | null | null | null |
chat_room/ChatRoom_multithreads/cpp_headers/aws_s3.hpp
|
LiaoWC/cpp_programs
|
da78030d02cb916466ad5f0b0794f5c443cc05b4
|
[
"MIT"
] | null | null | null |
chat_room/ChatRoom_multithreads/cpp_headers/aws_s3.hpp
|
LiaoWC/cpp_programs
|
da78030d02cb916466ad5f0b0794f5c443cc05b4
|
[
"MIT"
] | null | null | null |
#ifndef _AWS_S3_HPP_
#define _AWS_S3_HPP_
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <fstream>
#include <string>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/CreateBucketRequest.h>
#define getObjectBuffer 5120
using namespace std;
// //snippet-start:[s3.cpp.list_buckets.inc]
// #include <aws/core/Aws.h>
// #include <aws/s3/S3Client.h>
// #include <aws/s3/model/Bucket.h>
// //snippet-end:[s3.cpp.list_buckets.inc]
// /**
// * List your Amazon S3 buckets.
// */
// int main(int argc, char** argv)
// {
// Aws::SDKOptions options;
// Aws::InitAPI(options);
// {
// // snippet-start:[s3.cpp.list_buckets.code]
// Aws::S3::S3Client s3_client;
// auto outcome = s3_client.ListBuckets();
// if (outcome.IsSuccess())
// {
// std::cout << "Your Amazon S3 buckets:" << std::endl;
// Aws::Vector<Aws::S3::Model::Bucket> bucket_list =
// outcome.GetResult().GetBuckets();
// for (auto const &bucket : bucket_list)
// {
// std::cout << " * " << bucket.GetName() << std::endl;
// }
// }
// else
// {
// std::cout << "ListBuckets error: "
// << outcome.GetError().GetExceptionName() << " - "
// << outcome.GetError().GetMessage() << std::endl;
// }
// // snippet-end:[s3.cpp.list_buckets.code]
// }
// Aws::ShutdownAPI(options);
// }
// //snippet-start:[s3.cpp.delete_bucket.inc]
// #include <aws/core/Aws.h>
// #include <aws/s3/S3Client.h>
// #include <aws/s3/model/DeleteBucketRequest.h>
// //snippet-end:[s3.cpp.delete_bucket.inc]
// /**
// * Delete an Amazon S3 bucket.
// *
// * ++ Warning ++ This code will actually delete the bucket that you specify!
// */
// int main(int argc, char** argv)
// {
// if (argc < 2)
// {
// std::cout << "delete_bucket - delete an S3 bucket" << std::endl
// << "\nUsage:" << std::endl
// << " delete_bucket <bucket> [region]" << std::endl
// << "\nWhere:" << std::endl
// << " bucket - the bucket to delete" << std::endl
// << " region - AWS region for the bucket" << std::endl
// << " (optional, default: us-east-1)" << std::endl
// << "\nNote! This will actually delete the bucket that you specify!"
// << std::endl
// << "\nExample:" << std::endl
// << " delete_bucket testbucket\n" << std::endl << std::endl;
// exit(1);
// }
// Aws::SDKOptions options;
// Aws::InitAPI(options);
// {
// const Aws::String bucket_name = argv[1];
// const Aws::String user_region = (argc >= 3) ? argv[2] : "us-east-1";
// std::cout << "Deleting S3 bucket: " << bucket_name << std::endl;
// // snippet-start:[s3.cpp.delete_bucket.code]
// Aws::Client::ClientConfiguration config;
// config.region = user_region;
// Aws::S3::S3Client s3_client(config);
// Aws::S3::Model::DeleteBucketRequest bucket_request;
// bucket_request.SetBucket(bucket_name);
// auto outcome = s3_client.DeleteBucket(bucket_request);
// if (outcome.IsSuccess())
// {
// std::cout << "Done!" << std::endl;
// }
// else
// {
// std::cout << "DeleteBucket error: "
// << outcome.GetError().GetExceptionName() << " - "
// << outcome.GetError().GetMessage() << std::endl;
// }
// // snippet-end:[s3.cpp.delete_bucket.code]
// }
// Aws::ShutdownAPI(options);
// }
// //snippet-end:[s3.cpp.create_bucket.inc]
namespace awsS3
{
bool create_bucket(const Aws::String &bucket_name,
const Aws::S3::Model::BucketLocationConstraint ®ion = Aws::S3::Model::BucketLocationConstraint::us_east_1)
{
// Set up the request
Aws::S3::Model::CreateBucketRequest request;
request.SetBucket(bucket_name);
// Is the region other than us-east-1 (N. Virginia)?
if (region != Aws::S3::Model::BucketLocationConstraint::us_east_1)
{
// Specify the region as a location constraint
Aws::S3::Model::CreateBucketConfiguration bucket_config;
bucket_config.SetLocationConstraint(region);
request.SetCreateBucketConfiguration(bucket_config);
}
// Create the bucket
Aws::S3::S3Client s3_client;
auto outcome = s3_client.CreateBucket(request);
if (!outcome.IsSuccess())
{
auto err = outcome.GetError();
std::cout << "ERROR: CreateBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
return false;
}
return true;
}
inline bool file_exists(const std::string &name)
{
struct stat buffer;
return (stat(name.c_str(), &buffer) == 0);
}
bool put_s3_object(const Aws::String &s3_bucket_name,
const Aws::String &s3_object_name,
const std::string &file_name,
const Aws::String ®ion = "")
{
// Verify file_name exists
if (!file_exists(file_name))
{
std::cout << "ERROR: NoSuchFile: The specified file does not exist"
<< std::endl;
return false;
}
// If region is specified, use it
Aws::Client::ClientConfiguration clientConfig;
if (!region.empty())
clientConfig.region = region;
// Set up request
// snippet-start:[s3.cpp.put_object.code]
Aws::S3::S3Client s3_client(clientConfig);
Aws::S3::Model::PutObjectRequest object_request;
object_request.SetBucket(s3_bucket_name);
object_request.SetKey(s3_object_name);
const std::shared_ptr<Aws::IOStream> input_data =
Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
file_name.c_str(),
std::ios_base::in | std::ios_base::binary);
object_request.SetBody(input_data);
// Put the object
auto put_object_outcome = s3_client.PutObject(object_request);
if (!put_object_outcome.IsSuccess())
{
auto error = put_object_outcome.GetError();
std::cout << "ERROR: " << error.GetExceptionName() << ": "
<< error.GetMessage() << std::endl;
return false;
}
return true;
// snippet-end:[s3.cpp.put_object.code]
}
/**
* Get an object from an Amazon S3 bucket.
*/
string get_object(const Aws::String &bucket_name, const Aws::String &object_name)
{
// Set up the request
Aws::S3::S3Client s3_client;
Aws::S3::Model::GetObjectRequest object_request;
object_request.SetBucket(bucket_name);
object_request.SetKey(object_name);
// Get the object
auto get_object_outcome = s3_client.GetObject(object_request);
if (get_object_outcome.IsSuccess())
{
// Get an Aws::IOStream reference to the retrieved file
auto &retrieved_file = get_object_outcome.GetResultWithOwnership().GetBody();
//#if 1
// Output the first line of the retrieved text file
char file_data[getObjectBuffer] = {0};
retrieved_file.getline(file_data, getObjectBuffer - 1);
//std::cout << file_data << std::endl;
string rt(file_data);
return file_data;
// #else
// // Alternatively, read the object's contents and write to a file
// const char *filename = "/PATH/FILE_NAME";
// std::ofstream output_file(filename, std::ios::binary);
// output_file << retrieved_file.rdbuf();
// #endif
}
else
{
auto error = get_object_outcome.GetError();
std::cout << "ERROR: " << error.GetExceptionName() << ": "
<< error.GetMessage() << std::endl;
string rt = "";
return rt;
}
// snippet-end:[s3.cpp.get_object.code]
}
/**
* Delete an object from an Amazon S3 bucket.
*
* ++ warning ++ This will actually delete the named object!
*/
bool delete_object(const Aws::String &bucket_name, const Aws::String key_name)
{
//std::cout << "Deleting" << key_name << " from S3 bucket: " << bucket_name << std::endl;
//cout << bucket_name << " ||| " << key_name << endl;
Aws::S3::S3Client s3_client;
Aws::S3::Model::DeleteObjectRequest object_request;
object_request.WithBucket(bucket_name).WithKey(key_name);
auto delete_object_outcome = s3_client.DeleteObject(object_request);
return (delete_object_outcome.IsSuccess());
}
} // namespace awsS3
#endif
| 39.007605
| 136
| 0.499951
|
LiaoWC
|
a85ea5203a902486716faaf97cc4619262159d6c
| 1,530
|
cpp
|
C++
|
src/prod/src/Management/healthmanager/RequestContextKind.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 2,542
|
2018-03-14T21:56:12.000Z
|
2019-05-06T01:18:20.000Z
|
src/prod/src/Management/healthmanager/RequestContextKind.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 994
|
2019-05-07T02:39:30.000Z
|
2022-03-31T13:23:04.000Z
|
src/prod/src/Management/healthmanager/RequestContextKind.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 300
|
2018-03-14T21:57:17.000Z
|
2019-05-06T20:07:00.000Z
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
namespace Management
{
namespace HealthManager
{
namespace RequestContextKind
{
void WriteToTextWriter(__in Common::TextWriter & w, Enum e)
{
switch(e)
{
case Report: w << "Report"; return;
case SequenceStream: w << "SequenceStream"; return;
case QueryEntityDetail: w << "QueryEntityDetail"; return;
case QueryEntityChildren: w << "QueryEntityChildren"; return;
case Query: w << "Query"; return;
case QueryEntityHealthStateChunk: w << "QueryEntityHealthStateChunk"; return;
case QueryEntityHealthState: w << "QueryEntityHealthState"; return;
case QueryEntityUnhealthyChildren: w << "QueryEntityUnhealthyChildren"; return;
default: w << "RequestContextKind(" << static_cast<uint>(e) << ')'; return;
}
}
BEGIN_ENUM_STRUCTURED_TRACE( RequestContextKind )
ADD_CASTED_ENUM_MAP_VALUE_RANGE( RequestContextKind, Report, LAST_STATE)
END_ENUM_STRUCTURED_TRACE( RequestContextKind )
}
}
}
| 40.263158
| 99
| 0.538562
|
vishnuk007
|
a85f657b71cb0c42e060c9ab6f5cc1cd63fc78cb
| 617
|
hpp
|
C++
|
configuration/ConfigurationArgumentProcessor_test/ConfigurationArgumentProcessor_test.hpp
|
leighgarbs/toolbox
|
fd9ceada534916fa8987cfcb5220cece2188b304
|
[
"MIT"
] | null | null | null |
configuration/ConfigurationArgumentProcessor_test/ConfigurationArgumentProcessor_test.hpp
|
leighgarbs/toolbox
|
fd9ceada534916fa8987cfcb5220cece2188b304
|
[
"MIT"
] | null | null | null |
configuration/ConfigurationArgumentProcessor_test/ConfigurationArgumentProcessor_test.hpp
|
leighgarbs/toolbox
|
fd9ceada534916fa8987cfcb5220cece2188b304
|
[
"MIT"
] | null | null | null |
#if !defined CONFIGURATION_ARGUMENT_PROCESSOR_TEST
#define CONFIGURATION_ARGUMENT_PROCESSOR_TEST
#include "Test.hpp"
#include "TestCases.hpp"
#include "TestMacros.hpp"
namespace Configuration
{
TEST_CASES_BEGIN(ArgumentProcessor_test)
TEST(RegisterPositionalArgument)
TEST(RegisterOptionalArgument)
TEST_CASES_BEGIN(Process)
TEST(PositionalArgument)
TEST(OptionalArgument)
TEST(OptionalCountingArgument)
TEST(Combined)
TEST_CASES_END(Process)
TEST(IsRegistered)
TEST_CASES_END(ArgumentProcessor_test)
}
#endif
| 19.28125
| 50
| 0.71799
|
leighgarbs
|
a86b36606b70fd77b4b9118cc6e54bf4366c7dae
| 1,811
|
cpp
|
C++
|
mshp/algo/graphs/Dijkstra_dist_from_given_to_all.cpp
|
zer0main/problems
|
264dd359f74e0906b9b7505506d50c879c4fb737
|
[
"MIT"
] | 5
|
2015-12-25T20:53:39.000Z
|
2017-07-18T23:19:04.000Z
|
mshp/algo/graphs/Dijkstra_dist_from_given_to_all.cpp
|
zer0main/problems
|
264dd359f74e0906b9b7505506d50c879c4fb737
|
[
"MIT"
] | null | null | null |
mshp/algo/graphs/Dijkstra_dist_from_given_to_all.cpp
|
zer0main/problems
|
264dd359f74e0906b9b7505506d50c879c4fb737
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2015-2017 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <bits/stdc++.h>
#define MAX_LENGTH 1000000000
typedef std::vector<int> Ints;
typedef std::vector<bool> Bools;
typedef std::pair<int, int> IntPair;
typedef std::vector<IntPair> IntPairs;
typedef std::vector<IntPairs> IntPairsVect;
int N, edges_n, cities_n, start;
IntPairsVect g;
Ints dist, cities;
Bools used;
void Dijkstra() {
dist[start] = 0;
for (int i = 0; i < N; i++) {
int v = -1;
for (int j = 0; j < N; j++) {
if (!used[j] && ((v == -1) || (dist[j] < dist[v]))) {
v = j;
}
}
if (dist[v] == MAX_LENGTH) {
break;
}
used[v] = true;
for (int j = 0; j < g[v].size(); j++) {
if (dist[g[v][j].first] > (dist[v] + g[v][j].second)) {
dist[g[v][j].first] = dist[v] + g[v][j].second;
}
}
}
}
int main() {
std::cin >> N >> edges_n >> cities_n >> start;
start--;
g.resize(N);
used.resize(N, false);
dist.resize(N, MAX_LENGTH);
for (int i = 0; i < cities_n; i++) {
int city_n;
std::cin >> city_n;
cities.push_back(city_n - 1);
}
for (int i = 0; i < edges_n; i++) {
int n1, n2, weight;
std::cin >> n1 >> n2 >> weight;
g[n1 - 1].push_back(IntPair(n2 - 1, weight));
g[n2 - 1].push_back(IntPair(n1 - 1, weight));
}
Dijkstra();
IntPairs ans;
for (int i = 0; i < cities.size(); i++) {
int d = dist[cities[i]];
ans.push_back(IntPair(d, cities[i]));
}
std::sort(ans.begin(), ans.end());
for (int i = 0; i < ans.size(); i++) {
std::cout << ans[i].second + 1 << " " << ans[i].first << "\n";
}
return 0;
}
| 25.152778
| 70
| 0.484263
|
zer0main
|
a86b85be14ff439ef1872f123b2e6ed04ecfaa94
| 4,053
|
cpp
|
C++
|
src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp
|
JimmyCushnie/runtime
|
b7eb82871f1d742efb444873e11dd6241cea73d2
|
[
"MIT"
] | 3
|
2021-06-24T15:39:52.000Z
|
2021-11-04T02:13:43.000Z
|
src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp
|
JimmyCushnie/runtime
|
b7eb82871f1d742efb444873e11dd6241cea73d2
|
[
"MIT"
] | 18
|
2019-12-03T00:21:59.000Z
|
2022-01-30T04:45:58.000Z
|
src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp
|
JimmyCushnie/runtime
|
b7eb82871f1d742efb444873e11dd6241cea73d2
|
[
"MIT"
] | 2
|
2022-01-23T12:24:04.000Z
|
2022-02-07T15:44:03.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "standardpch.h"
#include "simpletimer.h"
#include "methodcontext.h"
#include "methodcontextiterator.h"
#include "verbdumpmap.h"
#include "verbildump.h"
#include "spmiutil.h"
#include "spmidumphelper.h"
// Dump the CSV format header for all the columns we're going to dump.
void DumpMapHeader()
{
printf("index,");
// printf("process name,");
printf("method name,");
printf("full signature,");
printf("jit flags\n");
}
void DumpMap(int index, MethodContext* mc)
{
CORINFO_METHOD_INFO cmi;
unsigned int flags = 0;
mc->repCompileMethod(&cmi, &flags);
const char* moduleName = nullptr;
const char* methodName = mc->repGetMethodName(cmi.ftn, &moduleName);
const char* className = mc->repGetClassName(mc->repGetMethodClass(cmi.ftn));
printf("%d,", index);
// printf("\"%s\",", mc->cr->repProcessName());
printf("%s:%s,", className, methodName);
// Also, dump the full method signature
printf("\"");
DumpAttributeToConsoleBare(mc->repGetMethodAttribs(cmi.ftn));
DumpPrimToConsoleBare(mc, cmi.args.retType, CastHandle(cmi.args.retTypeClass));
printf(" %s", methodName);
// Show class and method generic params, if there are any
CORINFO_SIG_INFO sig;
mc->repGetMethodSig(cmi.ftn, &sig, nullptr);
const unsigned classInst = sig.sigInst.classInstCount;
if (classInst > 0)
{
for (unsigned i = 0; i < classInst; i++)
{
CORINFO_CLASS_HANDLE ci = sig.sigInst.classInst[i];
className = mc->repGetClassName(ci);
printf("%s%s%s%s",
i == 0 ? "[" : "",
i > 0 ? ", " : "",
className,
i == classInst - 1 ? "]" : "");
}
}
const unsigned methodInst = sig.sigInst.methInstCount;
if (methodInst > 0)
{
for (unsigned i = 0; i < methodInst; i++)
{
CORINFO_CLASS_HANDLE ci = sig.sigInst.methInst[i];
className = mc->repGetClassName(ci);
printf("%s%s%s%s",
i == 0 ? "[" : "",
i > 0 ? ", " : "",
className,
i == methodInst - 1 ? "]" : "");
}
}
printf("(");
DumpSigToConsoleBare(mc, &cmi.args);
printf(")\"");
// Dump the jit flags
CORJIT_FLAGS corJitFlags;
mc->repGetJitFlags(&corJitFlags, sizeof(corJitFlags));
unsigned long long rawFlags = corJitFlags.GetFlagsRaw();
// Add in the "fake" pgo flags
bool hasEdgeProfile = false;
bool hasClassProfile = false;
bool hasLikelyClass = false;
ICorJitInfo::PgoSource pgoSource = ICorJitInfo::PgoSource::Unknown;
if (mc->hasPgoData(hasEdgeProfile, hasClassProfile, hasLikelyClass, pgoSource))
{
rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_PGO);
if (hasEdgeProfile)
{
rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_EDGE_PROFILE);
}
if (hasClassProfile)
{
rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_CLASS_PROFILE);
}
if (hasLikelyClass)
{
rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_LIKELY_CLASS);
}
if (pgoSource == ICorJitInfo::PgoSource::Static)
{
rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_STATIC_PROFILE);
}
if (pgoSource == ICorJitInfo::PgoSource::Dynamic)
{
rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_DYNAMIC_PROFILE);
}
}
printf(", %s\n", SpmiDumpHelper::DumpJitFlags(rawFlags).c_str());
}
int verbDumpMap::DoWork(const char* nameOfInput)
{
MethodContextIterator mci;
if (!mci.Initialize(nameOfInput))
return -1;
DumpMapHeader();
while (mci.MoveNext())
{
MethodContext* mc = mci.Current();
DumpMap(mci.MethodContextNumber(), mc);
}
if (!mci.Destroy())
return -1;
return 0;
}
| 27.760274
| 83
| 0.585986
|
JimmyCushnie
|
a87087d87447957d1ebad46267fb85baf7063457
| 1,930
|
cpp
|
C++
|
testing/visualizer/Main.cpp
|
ElliottSlingsby/ChunkPool
|
b4dd1bc5c8e88b2519029bca8329ef7092e8352f
|
[
"MIT"
] | null | null | null |
testing/visualizer/Main.cpp
|
ElliottSlingsby/ChunkPool
|
b4dd1bc5c8e88b2519029bca8329ef7092e8352f
|
[
"MIT"
] | null | null | null |
testing/visualizer/Main.cpp
|
ElliottSlingsby/ChunkPool
|
b4dd1bc5c8e88b2519029bca8329ef7092e8352f
|
[
"MIT"
] | null | null | null |
#include "ChunkPool.hpp"
#include <iostream>
#include <ctime>
#include <random>
#include <chrono>
// Testing code, shouldn't really be here
struct Test{
inline Test(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z){}
inline void print() const{
std::cout << x << ", " << y << ", " << z << "\n";
}
int x;
int y;
int z;
uint8_t filler[256]; // bytes
};
int main(int argc, char *argv[]){
srand((unsigned int)time(nullptr));
ChunkPool pool(32 * 1024); // 32 KB
unsigned int count = 100000;
for (unsigned int i = 0; i < count; i++){
Test& test = *((Test*)pool.get(pool.set(sizeof(Test))));
test = Test(rand(), rand(), rand());
}
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::duration dt = end - start;
float max = 5.f;
float seconds = max;
unsigned int counter = 0;
while (seconds > 0){
dt = end - start;
start = std::chrono::high_resolution_clock::now();
auto iter = pool.begin();
while (iter.valid()){
*((Test*)iter.get()) = Test(rand(), rand(), rand());
iter.next();
}
//std::cout << std::chrono::duration_cast<std::chrono::duration<float>>(dt).count() * 1000 << " ms\n";
seconds -= std::chrono::duration_cast<std::chrono::duration<float>>(dt).count();
counter++;
end = std::chrono::high_resolution_clock::now();
}
std::cout << "FPS : " << counter / max << "\n";
start = std::chrono::high_resolution_clock::now();
// Randomly remove half all elements
for (unsigned int i = 0; i < count; i++){
if (!(rand() % 100))
pool.erase(i);
}
end = std::chrono::high_resolution_clock::now();
dt = end - start;
std::cout << "Removing : " << std::chrono::duration_cast<std::chrono::duration<float>>(dt).count() * 1000 << " ms\n";
std::getchar();
return 0;
}
| 21.685393
| 118
| 0.614508
|
ElliottSlingsby
|
a871bc75a1f740ea9243e61d603db9554171f971
| 272
|
cpp
|
C++
|
PrintImageSizeUtil/PrintImageSizeUtil.cpp
|
myarichuk/HunterDemo
|
def3f9e2ef6dbef901249ff71724217a9137e744
|
[
"MIT"
] | null | null | null |
PrintImageSizeUtil/PrintImageSizeUtil.cpp
|
myarichuk/HunterDemo
|
def3f9e2ef6dbef901249ff71724217a9137e744
|
[
"MIT"
] | null | null | null |
PrintImageSizeUtil/PrintImageSizeUtil.cpp
|
myarichuk/HunterDemo
|
def3f9e2ef6dbef901249ff71724217a9137e744
|
[
"MIT"
] | null | null | null |
// PrintImageSizeUtil.cpp : Defines the entry point for the application.
//
#include "PrintImageSizeUtil.h"
using namespace std;
int main()
{
const auto img = cv::imread("e:\\Capture.JPG");
cout << "image size: " << img.cols << "x" << img.rows << endl;
return 0;
}
| 19.428571
| 73
| 0.654412
|
myarichuk
|
a879d12611f6ebd30250cdb311437014b97d3515
| 247
|
cpp
|
C++
|
src/test.cpp
|
Liuchang0812/leetcode
|
d71f87b0035e661d0009f4382b39c4787c355f89
|
[
"MIT"
] | 9
|
2015-09-09T20:28:31.000Z
|
2019-05-15T09:13:07.000Z
|
src/test.cpp
|
liuchang0812/leetcode
|
d71f87b0035e661d0009f4382b39c4787c355f89
|
[
"MIT"
] | 1
|
2015-02-25T13:10:09.000Z
|
2015-02-25T13:10:09.000Z
|
src/test.cpp
|
liuchang0812/leetcode
|
d71f87b0035e661d0009f4382b39c4787c355f89
|
[
"MIT"
] | 1
|
2016-08-31T19:14:52.000Z
|
2016-08-31T19:14:52.000Z
|
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque<int> dq;
dq.push(1);
dq.push(2);
dq.push(4);
for (auto i = dq.begin(); i != dq.end(); ++i)
{
cout << *i << endl;
}
return 0;
}
| 13
| 49
| 0.48583
|
Liuchang0812
|
a87ede10a7fddd75d660071f5973acce06b32bd8
| 4,892
|
cpp
|
C++
|
Source/main.cpp
|
RPKQ/OpenGL_scratchUp
|
cbe0268d6bb86bc0de49fafdcf078e5b85395964
|
[
"CC-BY-3.0"
] | null | null | null |
Source/main.cpp
|
RPKQ/OpenGL_scratchUp
|
cbe0268d6bb86bc0de49fafdcf078e5b85395964
|
[
"CC-BY-3.0"
] | null | null | null |
Source/main.cpp
|
RPKQ/OpenGL_scratchUp
|
cbe0268d6bb86bc0de49fafdcf078e5b85395964
|
[
"CC-BY-3.0"
] | null | null | null |
#include "Program.h"
#include "AssimpModel.h"
#include "Camera.h"
#include "../Source/GLIncludes.h"
using namespace glm;
using namespace std;
enum { MENU_TIMER_START, MENU_TIMER_STOP, MENU_EXIT,
MENU_SHADER_NORMAL, MENU_SHADER_LIGHTING, MENU_SHADER_TEXTURE,
MENU_SCENE_SPONZA, MENU_SCENE_EMPIRE};
const int windowW = 1024, windowH = 768;
glm::mat4 modelMat;
glm::mat4 perspectMat;
Program* programNormal;
Program* programTexture;
Program* programLight;
Program* program;
AssimpModel* model;
AssimpModel* model_sponza;
AssimpModel* model_lostEmpire;
Camera* cam;
GLubyte timer_cnt = 0;
bool timer_enabled = true;
unsigned int timer_speed = 16;
void DisplayFunc()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
program->use();
program->setMat4("pvMat", perspectMat * cam->getViewMat());
program->setMat4("modelMat", glm::mat4(1.0));
program->setVec3("lightPos", glm::vec3(100000.0, 100000.0, 200000.0));
program->setBool("useTex", true);
model->draw();
glutSwapBuffers();
}
void KeyboardFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'w':
cam->moveLocal(Camera::FRONT);
break;
case 's':
cam->moveLocal(Camera::BACK);
break;
case 'a':
cam->moveLocal(Camera::LEFT);
break;
case 'd':
cam->moveLocal(Camera::RIGHT);
break;
case 'z':
cam->moveLocal(Camera::UP);
break;
case 'x':
cam->moveLocal(Camera::DOWN);
break;
default:
break;
}
}
void MotionFunc(int moveX, int moveY)
{
cam->rotateWithMouse(moveX, moveY);
}
void MouseFunc(int button, int state, int x, int y) {
if (state == GLUT_UP)
{
cam->endOfRotate();
}
}
void TimerFunc(int val)
{
timer_cnt++;
glutPostRedisplay();
if (timer_enabled)
{
glutTimerFunc(timer_speed, TimerFunc, val);
}
}
void ReshapeFunc(int width, int height)
{
glViewport(0, 0, width, height);
float viewportAspect = (float)width / (float)height;
perspectMat = glm::perspective(glm::radians(60.0f), viewportAspect, 0.1f, 1500.0f);
}
void InitCallbackFuncs()
{
glutDisplayFunc(DisplayFunc);
glutKeyboardFunc(KeyboardFunc);
glutMotionFunc(MotionFunc);
glutMouseFunc(MouseFunc);
glutTimerFunc(timer_speed, TimerFunc, 0);
glutReshapeFunc(ReshapeFunc);
}
void MenuFunc(int id)
{
switch (id)
{
case MENU_TIMER_START:
if (!timer_enabled)
{
timer_enabled = true;
glutTimerFunc(timer_speed, TimerFunc, 0);
}
break;
case MENU_TIMER_STOP:
timer_enabled = false;
break;
case MENU_EXIT:
exit(0);
break;
case MENU_SHADER_NORMAL:
program = programNormal;
break;
case MENU_SHADER_TEXTURE:
program = programTexture;
break;
case MENU_SHADER_LIGHTING:
program = programLight;
break;
case MENU_SCENE_SPONZA:
model = model_sponza;
cam->setMoveSpeed(5.0);
break;
case MENU_SCENE_EMPIRE:
model = model_lostEmpire;
cam->setMoveSpeed(1.0);
break;
default:
break;
}
}
void InitMenu()
{
int menu_main = glutCreateMenu(MenuFunc);
int menu_timer = glutCreateMenu(MenuFunc);
int menu_shader = glutCreateMenu(MenuFunc);
int menu_scene = glutCreateMenu(MenuFunc);
glutSetMenu(menu_main);
glutAddSubMenu("Timer", menu_timer);
glutAddSubMenu("Shader", menu_shader);
glutAddSubMenu("Scene", menu_scene);
glutAddMenuEntry("Exit", MENU_EXIT);
glutSetMenu(menu_timer);
glutAddMenuEntry("Start", MENU_TIMER_START);
glutAddMenuEntry("Stop", MENU_TIMER_STOP);
glutSetMenu(menu_shader);
glutAddMenuEntry("normal", MENU_SHADER_NORMAL);
glutAddMenuEntry("texture", MENU_SHADER_TEXTURE);
glutAddMenuEntry("lighting", MENU_SHADER_LIGHTING);
glutSetMenu(menu_scene);
glutAddMenuEntry("lost empire", MENU_SCENE_EMPIRE);
glutAddMenuEntry("sponza", MENU_SCENE_SPONZA);
glutSetMenu(menu_main);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void InitObjects()
{
// setup camera
cam = new Camera(vec3(0.0f, 15.0f, 20.0f), vec3(0.0f, 15.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
// setup program
programTexture = new Program("vs.vs.glsl", "fs.fs.glsl");
programLight = new Program("vs.vs.glsl", "light.fs.glsl");
programNormal = new Program("vs.vs.glsl", "normal.fs.glsl");
program = programTexture;
// load models
model_sponza = new AssimpModel("sponza.obj");
model_lostEmpire = new AssimpModel("lost_empire.obj");
model = model_sponza;
}
void Init()
{
// Init Window and GLUT
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(windowW, windowH);
glutInitWindowPosition(100, 100);
glutCreateWindow("Window");
// Must be done after glut is initialized!
GLenum res = glewInit();
if (res != GLEW_OK) {
fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
system("pause");
exit(1);
}
glClearColor(1.0, 1.0, 1.0, 0.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
InitMenu();
InitObjects();
InitCallbackFuncs();
// init reshape window
ReshapeFunc(windowW, windowH);
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
Init();
glutMainLoop();
return 0;
}
| 20.817021
| 93
| 0.721382
|
RPKQ
|
a883b658b1e81dc4e10753441051c4208c03e1ba
| 4,332
|
cpp
|
C++
|
tests/pimpl_tests/pimpl_basic_header_only/heap_allocations.cpp
|
lubkoll/friendly-type-erasure
|
719830233a8652ccf18164653b466b0054a617f6
|
[
"MIT"
] | null | null | null |
tests/pimpl_tests/pimpl_basic_header_only/heap_allocations.cpp
|
lubkoll/friendly-type-erasure
|
719830233a8652ccf18164653b466b0054a617f6
|
[
"MIT"
] | 22
|
2016-08-03T16:51:10.000Z
|
2016-11-23T20:53:03.000Z
|
tests/pimpl_tests/pimpl_basic_header_only/heap_allocations.cpp
|
lubkoll/friendly-type-erasure
|
719830233a8652ccf18164653b466b0054a617f6
|
[
"MIT"
] | null | null | null |
//#include <gtest/gtest.h>
//#include "interface.hh"
//#include "../mock_fooable.hh"
//#include "../util.hh"
//using Fooable = Basic::Fooable;
//using Mock::MockFooable;
//TEST( TestBasicFooable_HeapAllocations, Empty )
//{
// auto expected_heap_allocations = 0u;
// CHECK_HEAP_ALLOC( Fooable fooable,
// expected_heap_allocations );
// CHECK_HEAP_ALLOC( Fooable copy(fooable),
// expected_heap_allocations );
// CHECK_HEAP_ALLOC( Fooable move( std::move(fooable) ),
// expected_heap_allocations );
// CHECK_HEAP_ALLOC( Fooable copy_assign;
// copy_assign = move,
// expected_heap_allocations );
// CHECK_HEAP_ALLOC( Fooable move_assign;
// move_assign = std::move(copy_assign),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, CopyFromValue )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable( mock_fooable ),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, CopyConstruction )
//{
// auto expected_heap_allocations = 1u;
// Fooable fooable = MockFooable();
// CHECK_HEAP_ALLOC( Fooable other( fooable ),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, CopyFromValueWithReferenceWrapper )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable( std::ref(mock_fooable) ),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, MoveFromValue )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable( std::move(mock_fooable) ),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, MoveConstruction )
//{
// auto expected_heap_allocations = 0u;
// Fooable fooable = MockFooable();
// CHECK_HEAP_ALLOC( Fooable other( std::move(fooable) ),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, MoveFromValueWithReferenceWrapper )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable( std::move(std::ref(mock_fooable)) ),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, CopyAssignFromValue )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable;
// fooable = mock_fooable,
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, CopyAssignment )
//{
// auto expected_heap_allocations = 1u;
// Fooable fooable = MockFooable();
// CHECK_HEAP_ALLOC( Fooable other;
// other = fooable,
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, CopyAssignFromValuenWithReferenceWrapper )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable;
// fooable = std::ref(mock_fooable),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, MoveAssignFromValue )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable;
// fooable = std::move(mock_fooable),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, MoveAssignment )
//{
// auto expected_heap_allocations = 0u;
// Fooable fooable = MockFooable();
// CHECK_HEAP_ALLOC( Fooable other;
// other = std::move(fooable),
// expected_heap_allocations );
//}
//TEST( TestBasicFooable_HeapAllocations, MoveAssignFromValueWithReferenceWrapper )
//{
// auto expected_heap_allocations = 1u;
// MockFooable mock_fooable;
// CHECK_HEAP_ALLOC( Fooable fooable;
// fooable = std::move(std::ref(mock_fooable)),
// expected_heap_allocations );
//}
| 29.671233
| 84
| 0.638273
|
lubkoll
|
a885f6f314b0365739ff6bfbe9cfb9a4a8394f54
| 962
|
hpp
|
C++
|
CodeRed/Vulkan/VulkanSwapChain.hpp
|
LinkClinton/Code-Red
|
491621144aba559f068c7f91d71e3d0d7c87761e
|
[
"MIT"
] | 34
|
2019-09-11T09:12:16.000Z
|
2022-02-13T12:50:25.000Z
|
CodeRed/Vulkan/VulkanSwapChain.hpp
|
LinkClinton/Code-Red
|
491621144aba559f068c7f91d71e3d0d7c87761e
|
[
"MIT"
] | 7
|
2019-09-22T14:21:26.000Z
|
2020-03-24T10:36:20.000Z
|
CodeRed/Vulkan/VulkanSwapChain.hpp
|
LinkClinton/Code-Red
|
491621144aba559f068c7f91d71e3d0d7c87761e
|
[
"MIT"
] | 6
|
2019-10-21T18:05:55.000Z
|
2021-04-22T05:07:30.000Z
|
#pragma once
#include "../Interface/GpuSwapChain.hpp"
#include "VulkanUtility.hpp"
#ifdef __ENABLE__VULKAN__
namespace CodeRed {
class VulkanSwapChain final : public GpuSwapChain {
public:
explicit VulkanSwapChain(
const std::shared_ptr<GpuLogicalDevice>& device,
const std::shared_ptr<GpuCommandQueue>& queue,
const WindowInfo& info,
const PixelFormat& format,
const size_t buffer_count = 2);
~VulkanSwapChain();
void resize(const size_t width, const size_t height) override;
void present() override;
auto currentBufferIndex() const -> size_t override;
auto swapChain() const noexcept -> vk::SwapchainKHR { return mSwapChain; }
auto surface() const noexcept -> vk::SurfaceKHR { return mSurface; }
private:
void initializeSwapChain();
void updateCurrentFrameIndex();
private:
vk::SwapchainKHR mSwapChain;
vk::SurfaceKHR mSurface;
vk::Semaphore mSemaphore;
uint32_t mCurrentBufferIndex = 0;
};
}
#endif
| 21.863636
| 76
| 0.740125
|
LinkClinton
|
a888391d77c4bf5c0886e107f0b4b35c0415904b
| 3,011
|
hpp
|
C++
|
include/jbkernel/IVoidEthernet.hpp
|
JohnnyB1290/jblib-platform-abstract-jbkernel
|
6e9e3e26e0ea4cbfdffc5cdde30e64ae78dc82a7
|
[
"Apache-2.0"
] | null | null | null |
include/jbkernel/IVoidEthernet.hpp
|
JohnnyB1290/jblib-platform-abstract-jbkernel
|
6e9e3e26e0ea4cbfdffc5cdde30e64ae78dc82a7
|
[
"Apache-2.0"
] | null | null | null |
include/jbkernel/IVoidEthernet.hpp
|
JohnnyB1290/jblib-platform-abstract-jbkernel
|
6e9e3e26e0ea4cbfdffc5cdde30e64ae78dc82a7
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file
* @brief Void Ethernet Interface
*
*
* @note
* Copyright © 2019 Evgeniy Ivanov. Contacts: <strelok1290@gmail.com>
* All rights reserved.
* @note
* 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
* @note
* 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.
*
* @note
* This file is a part of JB_Lib.
*/
#ifndef IVOIDETHERNET_HPP_
#define IVOIDETHERNET_HPP_
#include "jbkernel/jb_common.h"
#if USE_LWIP
#include "lwip/pbuf.h"
#endif
namespace jblib
{
namespace jbkernel
{
typedef enum
{
PARAMETER_MAC = 0,
PARAMETER_TX_UNLOCK,
PARAMETER_LINK,
PARAMETER_SPEED,
PARAMETER_NAME,
} IVoidEthernetParameters_t;
typedef enum
{
SPEED_10_M = 0,
SPEED_100_M = 1,
SPEED_AUTONEG = 2,
SPEED_1000_M = 3,
}IVoidEthernetSpeed_t;
class IVoidEthernet
{
public:
IVoidEthernet(void){}
virtual ~IVoidEthernet(void){}
virtual void initialize(void) = 0;
virtual void start(void) = 0;
virtual void reset(void) = 0;
virtual void getParameter(const uint8_t number, void* const value) = 0;
virtual void setParameter(const uint8_t number, void* const value) = 0;
virtual bool isTxQueueFull(void) = 0;
virtual void addToTxQueue(EthernetFrame* const frame, uint16_t frameSize) = 0;
#if USE_LWIP
virtual void addToTxQueue(struct pbuf* p) = 0;
#endif
virtual uint16_t pullOutRxFrame(EthernetFrame* const frame) = 0;
uint32_t getErrorsCounter() const { return errorsCounter_; }
void setErrorsCounter(uint32_t errorsCounter = 0) { errorsCounter_ = errorsCounter; }
uint32_t getRxBytesCounter() const { return rxBytesCounter_; }
void setRxBytesCounter(uint32_t rxBytesCounter = 0) { rxBytesCounter_ = rxBytesCounter; }
uint32_t getRxFramesCounter() const { return rxFramesCounter_; }
void setRxFramesCounter(uint32_t rxFramesCounter = 0) { rxFramesCounter_ = rxFramesCounter; }
uint32_t getTxBytesCounter() const { return txBytesCounter_; }
void setTxBytesCounter(uint32_t txBytesCounter = 0) { txBytesCounter_ = txBytesCounter; }
uint32_t getTxFramesCounter() const { return txFramesCounter_; }
void setTxFramesCounter(uint32_t txFramesCounter = 0) { txFramesCounter_ = txFramesCounter; }
protected:
uint32_t txFramesCounter_ = 0;
uint32_t txBytesCounter_ = 0;
uint32_t rxFramesCounter_ = 0;
uint32_t rxBytesCounter_ = 0;
uint32_t errorsCounter_ = 0;
};
class IEthernetListener
{
public:
IEthernetListener(void){ }
virtual ~IEthernetListener(void){ }
virtual void parseFrame(EthernetFrame* const frame,
uint16_t frameSize, IVoidEthernet* const source, void* parameter) = 0;
};
}
}
#endif /* IVOIDETHERNET_HPP_ */
| 29.23301
| 94
| 0.756891
|
JohnnyB1290
|
a888f5426dbaf33bdc3f32567acf49c1dd5e918a
| 10,364
|
cpp
|
C++
|
Remove_bad_split_good/Assign05P1.cpp
|
awagsta/Data-Structures-and-Algorithms
|
d32dc118ff7392421dd61c0ff8cca0eebb27747a
|
[
"MIT"
] | null | null | null |
Remove_bad_split_good/Assign05P1.cpp
|
awagsta/Data-Structures-and-Algorithms
|
d32dc118ff7392421dd61c0ff8cca0eebb27747a
|
[
"MIT"
] | null | null | null |
Remove_bad_split_good/Assign05P1.cpp
|
awagsta/Data-Structures-and-Algorithms
|
d32dc118ff7392421dd61c0ff8cca0eebb27747a
|
[
"MIT"
] | null | null | null |
#include "llcpInt.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void SeedRand();
int BoundedRandomInt(int lowerBound, int upperBound);
int ListLengthCheck(Node* head, int whatItShouldBe);
bool match(Node* head, const int procInts[], int procSize);
void PruneArray(int a[], int& size, char whichOne);
void ShowArray(const int a[], int size);
void DebugShowCase(int whichCase, int totalCasesToDo,
const int caseValues[], int caseSize);
int main()
{
int TEST_CASES_TO_DO = 900000,
testCasesDone = 0,
LO_SIZE = 1,
HI_SIZE = 20,
LO_VALUE = -3,
HI_VALUE = 12;
int numInts,
used_INI,
used,
used_LE5,
used_GE7,
intCount,
intHolder,
iLenChk,
iLenChk_LE5,
iLenChk_GE7;
int *intArr_INI = 0,
*intArr = 0,
*intArr_LE5 = 0,
*intArr_GE7 = 0;
Node *head = 0,
*head_LE5, // intentionally left uninitialized
*head_GE7; // intentionally left uninitialized
RemBadSplitGood(head, head_LE5, head_GE7);
cout << "================================" << endl;
if (head->data == -99 && head->link == 0 &&
head_LE5->data == -99 && head_LE5->link == 0 &&
head_GE7->data == -99 && head_GE7->link == 0)
{
ListClear(head, 1);
ListClear(head_LE5, 1);
ListClear(head_GE7, 1);
cout << "test with empty list ... passed" << endl;
}
else
{
cout << "test with empty list ... failed" << endl;
exit(EXIT_FAILURE);
}
cout << "================================" << endl;
// SeedRand(); // disabled for reproducible result
do
{
++testCasesDone;
numInts = BoundedRandomInt(LO_SIZE, HI_SIZE);
intArr_INI = new int [numInts];
intArr = new int [numInts];
intArr_LE5 = new int [numInts];
intArr_GE7 = new int [numInts];
used_INI = used = used_LE5 = used_GE7 = 0;
for (intCount = 0; intCount < numInts; ++intCount)
{
intHolder = BoundedRandomInt(LO_VALUE, HI_VALUE);
intArr_INI[used_INI++] = intHolder;
intArr[used++] = intHolder;
InsertAsTail(head, intHolder);
}
PruneArray(intArr, used, 'I');
if (testCasesDone % 45000 == 0)
{
cout << "================================" << endl;
clog << "testing case " << testCasesDone
<< " of " << TEST_CASES_TO_DO << endl;
clog << "================================" << endl;
ShowArray(intArr_INI, used_INI);
cout << "initial\"[09] list\": ";
ShowArray(intArr, used);
}
for (int i = 0; i < used; ++i)
{
intHolder = intArr[i];
intArr_LE5[used_LE5++] = intHolder;
intArr_GE7[used_GE7++] = intHolder;
}
PruneArray(intArr, used, 'O');
PruneArray(intArr_LE5, used_LE5, 'L');
PruneArray(intArr_GE7, used_GE7, 'G');
// DebugShowCase(testCasesDone, TEST_CASES_TO_DO, intArr_INI, used_INI);
RemBadSplitGood(head, head_LE5, head_GE7);
iLenChk = ListLengthCheck(head, used);
if (iLenChk != 0)
{
if (iLenChk == -1)
{
cout << "\"==6\" list node-count error ... too few" << endl;
cout << "test_case: ";
ShowArray(intArr_INI, used_INI);
cout << "#expected: " << used << endl;
cout << "#returned: " << FindListLength(head) << endl;
}
else
{
cout << "\"==6\" list node-count error ... too many (circular list?)" << endl;
cout << "test_case: ";
ShowArray(intArr_INI, used_INI);
cout << "#expected: " << used << endl;
cout << "returned # is higher (may be infinite)" << endl;
}
exit(EXIT_FAILURE);
}
iLenChk_LE5 = ListLengthCheck(head_LE5, used_LE5);
if (iLenChk_LE5 != 0)
{
if (iLenChk_LE5 == -1)
{
cout << "\"<=5\" list node-count error ... too few" << endl;
cout << "test_case: ";
ShowArray(intArr_INI, used_INI);
cout << "#expected: " << used_LE5 << endl;
cout << "#returned: " << FindListLength(head_LE5) << endl;
}
else
{
cout << "\"<=5\" list node-count error ... too many (circular list?)" << endl;
cout << "test_case: ";
ShowArray(intArr_INI, used_INI);
cout << "#expected: " << used_LE5 << endl;
cout << "returned # is higher (may be infinite)" << endl;
}
exit(EXIT_FAILURE);
}
iLenChk_GE7 = ListLengthCheck(head_GE7, used_GE7);
if (iLenChk_GE7 != 0)
{
if (iLenChk_GE7 == -1)
{
cout << "\">=7\" list node-count error ... too few" << endl;
cout << "test_case: ";
ShowArray(intArr_INI, used_INI);
cout << "#expected: " << used_GE7 << endl;
cout << "#returned: " << FindListLength(head_GE7) << endl;
}
else
{
cout << "\">=7\" list node-count error ... too many (circular list?)" << endl;
cout << "test_case: ";
ShowArray(intArr_INI, used_INI);
cout << "#expected: " << used_GE7 << endl;
cout << "returned # is higher (may be infinite)" << endl;
}
exit(EXIT_FAILURE);
}
if ( !match(head, intArr, used) || !match(head_LE5, intArr_LE5, used_LE5) || !match(head_GE7, intArr_GE7, used_GE7) )
{
cout << "Contents error ... mismatch found in value or order" << endl;
cout << "test case at issue: ";
ShowArray(intArr_INI, used_INI);
cout << "ought2b \"==6 list\": ";
ShowArray(intArr, used);
cout << " \"<=5 list\": ";
ShowArray(intArr_LE5, used_LE5);
cout << " \">=7 list\": ";
ShowArray(intArr_GE7, used_GE7);
cout << "outcome \"==6 list\": ";
ShowAll(cout, head);
cout << " \"<=5 list\": ";
ShowAll(cout, head_LE5);
cout << " \">=7 list\": ";
ShowAll(cout, head_GE7);
exit(EXIT_FAILURE);
}
if (testCasesDone % 45000 == 0)
{
//cout << "================================" << endl;
//clog << "testing case " << testCasesDone
// << " of " << TEST_CASES_TO_DO << endl;
//clog << "================================" << endl;
//ShowArray(intArr_INI, used_INI);
cout << "ought2b \"==6 list\": ";
ShowArray(intArr, used);
cout << " \"<=5 list\": ";
ShowArray(intArr_LE5, used_LE5);
cout << " \">=7 list\": ";
ShowArray(intArr_GE7, used_GE7);
cout << "outcome \"==6 list\": ";
ShowAll(cout, head);
cout << " \"<=5 list\": ";
ShowAll(cout, head_LE5);
cout << " \">=7 list\": ";
ShowAll(cout, head_GE7);
}
ListClear(head, 1);
ListClear(head_LE5, 1);
ListClear(head_GE7, 1);
delete [] intArr_INI;
delete [] intArr;
delete [] intArr_LE5;
delete [] intArr_GE7;
intArr_INI = intArr = intArr_LE5 = intArr_GE7 = 0;
}
while (testCasesDone < TEST_CASES_TO_DO);
cout << "================================" << endl;
cout << "test program terminated normally" << endl;
cout << "================================" << endl;
return EXIT_SUCCESS;
}
/////////////////////////////////////////////////////////////////////
// Function to seed the random number generator
// PRE: none
// POST: The random number generator has been seeded.
/////////////////////////////////////////////////////////////////////
void SeedRand()
{
srand( (unsigned) time(NULL) );
}
/////////////////////////////////////////////////////////////////////
// Function to generate a random integer between
// lowerBound and upperBound (inclusive)
// PRE: lowerBound is a positive integer.
// upperBound is a positive integer.
// upperBound is larger than lowerBound
// The random number generator has been seeded.
// POST: A random integer between lowerBound and upperBound
// has been returned.
/////////////////////////////////////////////////////////////////////
int BoundedRandomInt(int lowerBound, int upperBound)
{
return ( rand() % (upperBound - lowerBound + 1) ) + lowerBound;
}
/////////////////////////////////////////////////////////////////////
// Function to check # of nodes in list against what it should be
// POST: returns
// -1 if # of nodes is less than what it should be
// 0 if # of nodes is equal to what it should be
// 1 if # of nodes is more than what it should be
/////////////////////////////////////////////////////////////////////
int ListLengthCheck(Node* head, int whatItShouldBe)
{
int length = 0;
while (head != 0)
{
++length;
if (length > whatItShouldBe) return 1;
head = head->link;
}
return (length < whatItShouldBe) ? -1 : 0;
}
bool match(Node* head, const int procInts[], int procSize)
{
int iProc = 0;
while (head != 0)
{
if (iProc == procSize) return false;
if (head->data != procInts[iProc]) return false;
++iProc;
head = head->link;
}
return true;
}
void PruneArray(int a[], int& size, char whichOne)
{
int target, count = 0, i;
for (i = 0; i < size; ++i)
{
target = a[i];
if ( (whichOne == 'O' && target != 6) ||
(whichOne == 'L' && target > 5) ||
(whichOne == 'G' && target < 7) ||
( whichOne == 'I' && (target < 0 || target > 9) )
)
++count;
else if (count)
a[i - count] = a[i];
}
size -= count;
if (size == 0)
{
if (whichOne == 'O' || whichOne == 'L' || whichOne == 'G')
{
a[0] = -99;
++size;
}
}
}
void ShowArray(const int a[], int size)
{
for (int i = 0; i < size; ++i)
cout << a[i] << " ";
cout << endl;
}
void DebugShowCase(int whichCase, int totalCasesToDo,
const int caseValues[], int caseSize)
{
cout << "test case " << whichCase
<< " of " << totalCasesToDo << endl;
cout << "test case: ";
ShowArray(caseValues, caseSize);
}
| 31.987654
| 123
| 0.489579
|
awagsta
|
a88bc31a83c5f97d81192f7d0a59b0b995720750
| 720
|
cpp
|
C++
|
1-FMT_IO/number-comparer.cpp
|
lotcz/PJC_ukoly
|
33d4c8b32c78b6a0df26e05c47fef840aa08cfe3
|
[
"MIT"
] | null | null | null |
1-FMT_IO/number-comparer.cpp
|
lotcz/PJC_ukoly
|
33d4c8b32c78b6a0df26e05c47fef840aa08cfe3
|
[
"MIT"
] | null | null | null |
1-FMT_IO/number-comparer.cpp
|
lotcz/PJC_ukoly
|
33d4c8b32c78b6a0df26e05c47fef840aa08cfe3
|
[
"MIT"
] | null | null | null |
#include "number-comparer.hpp"
#include <iostream>
#include <stdexcept>
#include <sstream>
/**
* return true if str1 is bigger than str2.
*/
bool NumberComparer::compare(std::string& str1, std::string& str2) {
if (str1.length() > str2.length()) {
return true;
} else if (str1.length() < str2.length()) {
return false;
} else {
return (str1 > str2);
}
}
std::string NumberComparer::max_number(std::istream& in) {
std::string max = "";
std::string str = "";
char chr;
while (in.get(chr)) {
if (chr == ',') {
if (compare(str, max)) {
max = str;
}
str = "";
} else {
str += chr;
}
}
if (compare(str, max)) {
max = str;
}
return max;
}
| 17.560976
| 68
| 0.551389
|
lotcz
|
a89889a31d8cf760da02d84a186e39e997b683af
| 17,960
|
cpp
|
C++
|
src/common/settings.cpp
|
linquize/cppan
|
014d9604183360dfa0628f5ec71198b57f89d9fc
|
[
"Apache-2.0"
] | null | null | null |
src/common/settings.cpp
|
linquize/cppan
|
014d9604183360dfa0628f5ec71198b57f89d9fc
|
[
"Apache-2.0"
] | null | null | null |
src/common/settings.cpp
|
linquize/cppan
|
014d9604183360dfa0628f5ec71198b57f89d9fc
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2016-2017, Egor Pugin
*
* 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 "settings.h"
#include "access_table.h"
#include "config.h"
#include "database.h"
#include "directories.h"
#include "exceptions.h"
#include "hash.h"
#include "program.h"
#include "stamp.h"
#include <boost/algorithm/string.hpp>
#include <boost/nowide/fstream.hpp>
#include <primitives/hasher.h>
#include <primitives/templates.h>
#include <primitives/log.h>
DECLARE_STATIC_LOGGER(logger, "settings");
void BuildSettings::set_build_dirs(const String &name)
{
filename = name;
filename_without_ext = name;
source_directory = directories.build_dir;
if (directories.build_dir_type == SettingsType::Local ||
directories.build_dir_type == SettingsType::None)
{
source_directory /= (CPPAN_LOCAL_BUILD_PREFIX + filename);
}
else
{
source_directory_hash = sha256_short(name);
source_directory /= source_directory_hash;
}
binary_directory = source_directory / "build";
}
void BuildSettings::append_build_dirs(const path &p)
{
source_directory /= p;
binary_directory = source_directory / "build";
}
Settings::Settings()
{
build_dir = temp_directory_path() / "build";
storage_dir = get_root_directory() / STORAGE_DIR;
}
void Settings::load(const path &p, const SettingsType type)
{
auto root = load_yaml_config(p);
load(root, type);
}
void Settings::load(const yaml &root, const SettingsType type)
{
load_main(root, type);
auto get_storage_dir = [this](SettingsType type)
{
switch (type)
{
case SettingsType::Local:
return cppan_dir / STORAGE_DIR;
case SettingsType::User:
return Settings::get_user_settings().storage_dir;
case SettingsType::System:
return Settings::get_system_settings().storage_dir;
default:
{
auto d = fs::absolute(storage_dir);
fs::create_directories(d);
return fs::canonical(d);
}
}
};
auto get_build_dir = [this](const path &p, SettingsType type, const auto &dirs)
{
switch (type)
{
case SettingsType::Local:
return current_thread_path();
case SettingsType::User:
case SettingsType::System:
return dirs.storage_dir_tmp / "build";
default:
return p;
}
};
Directories dirs;
dirs.storage_dir_type = storage_dir_type;
auto sd = get_storage_dir(storage_dir_type);
dirs.set_storage_dir(sd);
dirs.build_dir_type = build_dir_type;
dirs.set_build_dir(get_build_dir(build_dir, build_dir_type, dirs));
directories.update(dirs, type);
}
void Settings::load_main(const yaml &root, const SettingsType type)
{
auto packages_dir_type_from_string = [](const String &s, const String &key)
{
if (s == "local")
return SettingsType::Local;
if (s == "user")
return SettingsType::User;
if (s == "system")
return SettingsType::System;
throw std::runtime_error("Unknown '" + key + "'. Should be one of [local, user, system]");
};
get_map_and_iterate(root, "remotes", [this](auto &kv)
{
auto n = kv.first.template as<String>();
bool o = n == DEFAULT_REMOTE_NAME; // origin
Remote rm;
Remote *prm = o ? &remotes[0] : &rm;
prm->name = n;
YAML_EXTRACT_VAR(kv.second, prm->url, "url", String);
YAML_EXTRACT_VAR(kv.second, prm->data_dir, "data_dir", String);
YAML_EXTRACT_VAR(kv.second, prm->user, "user", String);
YAML_EXTRACT_VAR(kv.second, prm->token, "token", String);
if (!o)
remotes.push_back(*prm);
});
YAML_EXTRACT_AUTO(disable_update_checks);
YAML_EXTRACT_AUTO(max_download_threads);
YAML_EXTRACT(storage_dir, String);
YAML_EXTRACT(build_dir, String);
YAML_EXTRACT(cppan_dir, String);
YAML_EXTRACT(output_dir, String);
/*#ifdef _WIN32
// correctly convert to utf-8
#define CONVERT_DIR(x) x = to_wstring(x.string())
CONVERT_DIR(storage_dir);
CONVERT_DIR(build_dir);
CONVERT_DIR(cppan_dir);
CONVERT_DIR(output_dir);
#endif*/
auto &p = root["proxy"];
if (p.IsDefined())
{
if (!p.IsMap())
throw std::runtime_error("'proxy' should be a map");
YAML_EXTRACT_VAR(p, proxy.host, "host", String);
YAML_EXTRACT_VAR(p, proxy.user, "user", String);
}
storage_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "storage_dir_type", "user"), "storage_dir_type");
if (root["storage_dir"].IsDefined())
storage_dir_type = SettingsType::None;
build_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "build_dir_type", "system"), "build_dir_type");
if (root["build_dir"].IsDefined())
build_dir_type = SettingsType::None;
// read these first from local settings
// and they'll be overriden in bs (if they exist there)
YAML_EXTRACT_AUTO(use_cache);
YAML_EXTRACT_AUTO(show_ide_projects);
YAML_EXTRACT_AUTO(add_run_cppan_target);
YAML_EXTRACT_AUTO(cmake_verbose);
YAML_EXTRACT_AUTO(build_system_verbose);
YAML_EXTRACT_AUTO(verify_all);
YAML_EXTRACT_AUTO(copy_all_libraries_to_output);
YAML_EXTRACT_AUTO(copy_import_libs);
YAML_EXTRACT_AUTO(rc_enabled);
YAML_EXTRACT_AUTO(short_local_names);
YAML_EXTRACT_AUTO(full_path_executables);
YAML_EXTRACT_AUTO(var_check_jobs);
YAML_EXTRACT_AUTO(install_prefix);
YAML_EXTRACT_AUTO(build_warning_level);
YAML_EXTRACT_AUTO(meta_target_suffix);
// read build settings
if (type == SettingsType::Local)
{
// at first, we load bs from current root
load_build(root);
// then override settings with specific (or default) config
yaml current_build;
if (root["builds"].IsDefined())
{
// yaml will not keep sorting of keys in map
// so we can take 'first' build in document
if (root["current_build"].IsDefined())
{
if (root["builds"][root["current_build"].template as<String>()].IsDefined())
current_build = root["builds"][root["current_build"].template as<String>()];
else
{
// on empty config name we build the first configuration
LOG_WARN(logger, "No such build config '" + root["current_build"].template as<String>() +
"' in builds directive. Trying to build the first configuration.");
current_build = root["builds"].begin()->second;
}
}
}
else if (root["build"].IsDefined())
current_build = root["build"];
load_build(current_build);
}
// read project settings (deps etc.)
if (type == SettingsType::Local && load_project)
{
Project p;
p.allow_relative_project_names = true;
p.allow_local_dependencies = true;
p.load(root);
dependencies = p.dependencies;
}
}
void Settings::load_build(const yaml &root)
{
if (root.IsNull())
return;
// extract
YAML_EXTRACT_AUTO(c_compiler);
YAML_EXTRACT_AUTO(cxx_compiler);
YAML_EXTRACT_AUTO(compiler);
YAML_EXTRACT_AUTO(c_compiler_flags);
if (c_compiler_flags.empty())
YAML_EXTRACT_VAR(root, c_compiler_flags, "c_flags", String);
YAML_EXTRACT_AUTO(cxx_compiler_flags);
if (cxx_compiler_flags.empty())
YAML_EXTRACT_VAR(root, cxx_compiler_flags, "cxx_flags", String);
YAML_EXTRACT_AUTO(compiler_flags);
YAML_EXTRACT_AUTO(link_flags);
YAML_EXTRACT_AUTO(link_libraries);
YAML_EXTRACT_AUTO(configuration);
YAML_EXTRACT_AUTO(generator);
YAML_EXTRACT_AUTO(system_version);
YAML_EXTRACT_AUTO(toolset);
YAML_EXTRACT_AUTO(use_shared_libs);
YAML_EXTRACT_VAR(root, use_shared_libs, "build_shared_libs", bool);
YAML_EXTRACT_AUTO(silent);
YAML_EXTRACT_AUTO(use_cache);
YAML_EXTRACT_AUTO(show_ide_projects);
YAML_EXTRACT_AUTO(add_run_cppan_target);
YAML_EXTRACT_AUTO(cmake_verbose);
YAML_EXTRACT_AUTO(build_system_verbose);
YAML_EXTRACT_AUTO(verify_all);
YAML_EXTRACT_AUTO(copy_all_libraries_to_output);
YAML_EXTRACT_AUTO(copy_import_libs);
YAML_EXTRACT_AUTO(rc_enabled);
YAML_EXTRACT_AUTO(short_local_names);
YAML_EXTRACT_AUTO(full_path_executables);
YAML_EXTRACT_AUTO(var_check_jobs);
YAML_EXTRACT_AUTO(install_prefix);
YAML_EXTRACT_AUTO(build_warning_level);
YAML_EXTRACT_AUTO(meta_target_suffix);
for (int i = 0; i < CMakeConfigurationType::Max; i++)
{
auto t = configuration_types[i];
boost::to_lower(t);
YAML_EXTRACT_VAR(root, c_compiler_flags_conf[i], "c_compiler_flags_" + t, String);
if (c_compiler_flags_conf[i].empty())
YAML_EXTRACT_VAR(root, c_compiler_flags_conf[i], "c_flags_" + t, String);
YAML_EXTRACT_VAR(root, cxx_compiler_flags_conf[i], "cxx_compiler_flags_" + t, String);
if (cxx_compiler_flags_conf[i].empty())
YAML_EXTRACT_VAR(root, cxx_compiler_flags_conf[i], "cxx_flags_" + t, String);
YAML_EXTRACT_VAR(root, compiler_flags_conf[i], "compiler_flags_" + t, String);
YAML_EXTRACT_VAR(root, link_flags_conf[i], "link_flags_" + t, String);
}
cmake_options = get_sequence<String>(root["cmake_options"]);
get_string_map(root, "env", env);
// process
if (c_compiler.empty())
c_compiler = cxx_compiler;
if (c_compiler.empty())
c_compiler = compiler;
if (cxx_compiler.empty())
cxx_compiler = compiler;
if (!compiler_flags.empty())
{
c_compiler_flags += " " + compiler_flags;
cxx_compiler_flags += " " + compiler_flags;
}
for (int i = 0; i < CMakeConfigurationType::Max; i++)
{
if (!compiler_flags_conf[i].empty())
{
c_compiler_flags_conf[i] += " " + compiler_flags_conf[i];
cxx_compiler_flags_conf[i] += " " + compiler_flags_conf[i];
}
}
}
bool Settings::is_custom_build_dir() const
{
return build_dir_type == SettingsType::Local || build_dir_type == SettingsType::None;
}
String Settings::get_hash() const
{
Hasher h;
h |= c_compiler;
h |= cxx_compiler;
h |= compiler;
h |= c_compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= c_compiler_flags_conf[i];
h |= cxx_compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= cxx_compiler_flags_conf[i];
h |= compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= compiler_flags_conf[i];
h |= link_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= link_flags_conf[i];
h |= link_libraries;
h |= generator;
h |= system_version;
h |= toolset;
h |= use_shared_libs;
h |= configuration;
h |= default_configuration;
// besides we track all valuable ENV vars
// to be sure that we'll load correct config
auto add_env = [&h](const char *var)
{
auto e = getenv(var);
if (!e)
return;
h |= String(e);
};
add_env("PATH");
add_env("Path");
add_env("FPATH");
add_env("CPATH");
// windows, msvc
add_env("VSCOMNTOOLS");
add_env("VS71COMNTOOLS");
add_env("VS80COMNTOOLS");
add_env("VS90COMNTOOLS");
add_env("VS100COMNTOOLS");
add_env("VS110COMNTOOLS");
add_env("VS120COMNTOOLS");
add_env("VS130COMNTOOLS");
add_env("VS140COMNTOOLS");
add_env("VS141COMNTOOLS"); // 2017?
add_env("VS150COMNTOOLS");
add_env("VS151COMNTOOLS");
add_env("VS160COMNTOOLS"); // for the future
add_env("INCLUDE");
add_env("LIB");
// gcc
add_env("COMPILER_PATH");
add_env("LIBRARY_PATH");
add_env("C_INCLUDE_PATH");
add_env("CPLUS_INCLUDE_PATH");
add_env("OBJC_INCLUDE_PATH");
//add_env("LD_LIBRARY_PATH"); // do we need these?
//add_env("DYLD_LIBRARY_PATH");
add_env("CC");
add_env("CFLAGS");
add_env("CXXFLAGS");
add_env("CPPFLAGS");
return h.hash;
}
bool Settings::checkForUpdates() const
{
if (disable_update_checks)
return false;
#ifdef _WIN32
String stamp_file = "/client/.service/win32.stamp";
#elif __APPLE__
String stamp_file = "/client/.service/macos.stamp";
#else
String stamp_file = "/client/.service/linux.stamp";
#endif
auto fn = fs::temp_directory_path() / fs::unique_path();
download_file(remotes[0].url + stamp_file, fn);
auto stamp_remote = boost::trim_copy(read_file(fn));
fs::remove(fn);
boost::replace_all(stamp_remote, "\"", "");
uint64_t s1 = std::stoull(cppan_stamp);
uint64_t s2 = std::stoull(stamp_remote);
if (!(s1 != 0 && s2 != 0 && s2 > s1))
return false;
LOG_INFO(logger, "New version of the CPPAN client is available!");
LOG_INFO(logger, "Feel free to upgrade it from website (https://cppan.org/) or simply run:");
LOG_INFO(logger, "cppan --self-upgrade");
#ifdef _WIN32
LOG_INFO(logger, "(or the same command but from administrator)");
#else
LOG_INFO(logger, "or");
LOG_INFO(logger, "sudo cppan --self-upgrade");
#endif
LOG_INFO(logger, "");
return true;
}
Settings &Settings::get(SettingsType type)
{
static Settings settings[toIndex(SettingsType::Max) + 1];
auto i = toIndex(type);
auto &s = settings[i];
switch (type)
{
case SettingsType::Local:
{
RUN_ONCE
{
s = get(SettingsType::User);
};
}
break;
case SettingsType::User:
{
std::exception_ptr eptr;
RUN_ONCE
{
try
{
s = get(SettingsType::System);
auto fn = get_config_filename();
if (!fs::exists(fn))
{
boost::system::error_code ec;
fs::create_directories(fn.parent_path(), ec);
if (ec)
throw std::runtime_error(ec.message());
auto ss = get(SettingsType::System);
ss.save(fn);
}
s.load(fn, SettingsType::User);
}
catch (...)
{
eptr = std::current_exception();
}
};
if (eptr)
std::rethrow_exception(eptr);
}
break;
case SettingsType::System:
{
RUN_ONCE
{
auto fn = CONFIG_ROOT "default";
if (!fs::exists(fn))
return;
s.load(fn, SettingsType::System);
};
}
break;
}
return s;
}
Settings &Settings::get_system_settings()
{
return get(SettingsType::System);
}
Settings &Settings::get_user_settings()
{
return get(SettingsType::User);
}
Settings &Settings::get_local_settings()
{
return get(SettingsType::Local);
}
void Settings::clear_local_settings()
{
get_local_settings() = get_user_settings();
}
void Settings::save(const path &p) const
{
boost::nowide::ofstream o(p.string());
if (!o)
throw std::runtime_error("Cannot open file: " + p.string());
yaml root;
root["remotes"][DEFAULT_REMOTE_NAME]["url"] = remotes[0].url;
root["storage_dir"] = storage_dir.string();
o << dump_yaml_config(root);
}
void cleanConfig(const String &c)
{
if (c.empty())
return;
auto h = hash_config(c);
auto remove_pair = [&](const auto &dir)
{
fs::remove_all(dir / c);
fs::remove_all(dir / h);
};
remove_pair(directories.storage_dir_bin);
remove_pair(directories.storage_dir_lib);
remove_pair(directories.storage_dir_exp);
#ifdef _WIN32
remove_pair(directories.storage_dir_lnk);
#endif
// for cfg we also remove xxx.cmake files (found with xxx.c.cmake files)
remove_pair(directories.storage_dir_cfg);
for (auto &f : boost::make_iterator_range(fs::directory_iterator(directories.storage_dir_cfg), {}))
{
if (!fs::is_regular_file(f) || f.path().extension() != ".cmake")
continue;
auto parts = split_string(f.path().string(), ".");
if (parts.size() == 2)
{
if (parts[0] == c || parts[0] == h)
fs::remove(f);
continue;
}
if (parts.size() == 3)
{
if (parts[1] == c || parts[1] == h)
{
fs::remove(parts[0] + ".cmake");
fs::remove(parts[1] + ".cmake");
fs::remove(f);
}
continue;
}
}
// obj
auto &sdb = getServiceDatabase();
for (auto &p : sdb.getInstalledPackages())
{
auto d = p.getDirObj() / "build";
if (!fs::exists(d))
continue;
for (auto &f : boost::make_iterator_range(fs::directory_iterator(d), {}))
{
if (!fs::is_directory(f))
continue;
if (f.path().filename() == c || f.path().filename() == h)
fs::remove_all(f);
}
}
// config hashes (in sdb)
sdb.removeConfigHashes(c);
sdb.removeConfigHashes(h);
}
void cleanConfigs(const Strings &configs)
{
for (auto &c : configs)
cleanConfig(c);
}
| 29.636964
| 127
| 0.619488
|
linquize
|
a899d8c1bf83a99b830acff1dad1e2b64c4eeba4
| 2,987
|
hpp
|
C++
|
modules/encode/src/video/video_stream/video_stream.hpp
|
HFauto/CNStream
|
1d4847327fff83eedbc8de6911855c5f7bb2bf22
|
[
"Apache-2.0"
] | null | null | null |
modules/encode/src/video/video_stream/video_stream.hpp
|
HFauto/CNStream
|
1d4847327fff83eedbc8de6911855c5f7bb2bf22
|
[
"Apache-2.0"
] | null | null | null |
modules/encode/src/video/video_stream/video_stream.hpp
|
HFauto/CNStream
|
1d4847327fff83eedbc8de6911855c5f7bb2bf22
|
[
"Apache-2.0"
] | null | null | null |
/*************************************************************************
* Copyright (C) [2020] by Cambricon, 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
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*************************************************************************/
#ifndef __VIDEO_STREAM_HPP__
#define __VIDEO_STREAM_HPP__
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#if (CV_MAJOR_VERSION >= 3)
#include <opencv2/imgcodecs/imgcodecs.hpp>
#endif
#include <string>
#include "tiler/tiler.hpp"
#include "../video_encoder/video_encoder.hpp"
#include "../video_common.hpp"
namespace cnstream {
namespace video { class VideoStream; }
class VideoStream {
public:
using PacketInfo = VideoEncoder::PacketInfo;
using Event = VideoEncoder::Event;
using EventCallback = VideoEncoder::EventCallback;
using ColorFormat = Tiler::ColorFormat;
using Buffer = Tiler::Buffer;
using Rect = Tiler::Rect;
struct Param {
int width;
int height;
int tile_cols;
int tile_rows;
double frame_rate;
int time_base;
int bit_rate;
int gop_size;
VideoPixelFormat pixel_format = VideoPixelFormat::NV21;
VideoCodecType codec_type = VideoCodecType::H264;
bool mlu_encoder = true;
bool resample = true;
int device_id = -1;
};
explicit VideoStream(const Param ¶m);
~VideoStream();
// no copying
VideoStream(const VideoStream &) = delete;
VideoStream &operator=(const VideoStream &) = delete;
VideoStream(VideoStream &&);
VideoStream &operator=(VideoStream &&);
bool Open();
bool Close(bool wait_finish = false);
bool Update(const cv::Mat &mat, ColorFormat color, int64_t timestamp, const std::string &stream_id,
void *user_data = nullptr);
bool Update(const Buffer *buffer, int64_t timestamp, const std::string &stream_id, void *user_data = nullptr);
bool Clear(const std::string &stream_id);
void SetEventCallback(EventCallback func);
int RequestFrameBuffer(VideoFrame *frame);
int GetPacket(VideoPacket *packet, PacketInfo *info = nullptr);
private:
video::VideoStream *stream_ = nullptr;
};
} // namespace cnstream
#endif // __VIDEO_STREAM_HPP__
| 31.776596
| 112
| 0.694342
|
HFauto
|
a89a3303c865f25d9aaeefc2ff9659cc08253660
| 2,035
|
cpp
|
C++
|
Daemon/ydotoold.cpp
|
StoneDot/ydotool
|
cf38f107bb998e938cdf8cd5cd5eafb88739a414
|
[
"MIT"
] | null | null | null |
Daemon/ydotoold.cpp
|
StoneDot/ydotool
|
cf38f107bb998e938cdf8cd5cd5eafb88739a414
|
[
"MIT"
] | null | null | null |
Daemon/ydotoold.cpp
|
StoneDot/ydotool
|
cf38f107bb998e938cdf8cd5cd5eafb88739a414
|
[
"MIT"
] | null | null | null |
/*
This file is part of ydotool.
Copyright (C) 2018-2019 ReimuNotMoe
This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "ydotoold.hpp"
using namespace ydotool;
//struct ep_ctx {
// size_t bufpos_read = 0;
// uint8_t buf_read[8];
//};
//
//void fd_set_nonblocking(int fd) {
// int flag = fcntl(fd, F_GETFL) | O_NONBLOCK;
// fcntl(fd, F_SETFL, flag);
//}
Instance instance;
static int client_handler(int fd) {
uInputRawData buf{0};
while (true) {
int rc = recv(fd, &buf, sizeof(buf), MSG_WAITALL);
if (rc == sizeof(buf)) {
instance.uInputContext->Emit(buf.type, buf.code, buf.value);
} else {
return 0;
}
}
}
int main(int argc, char **argv) {
const char path_socket[] = "/tmp/.ydotool_socket";
unlink(path_socket);
int fd_listener = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd_listener == -1) {
std::cerr << "ydotoold: " << "failed to create socket: " << strerror(errno) << "\n";
abort();
}
sockaddr_un addr{0};
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path_socket, sizeof(addr.sun_path)-1);
if (bind(fd_listener, (struct sockaddr *)&addr, sizeof(addr))) {
std::cerr << "ydotoold: " << "failed to bind to socket [" << path_socket << "]: " << strerror(errno) << "\n";
abort();
}
if (listen(fd_listener, 16)) {
std::cerr << "ydotoold: " << "failed to listen on socket [" << path_socket << "]: " << strerror(errno) << "\n";
abort();
}
chmod(path_socket, 0600);
std::cerr << "ydotoold: " << "listening on socket " << path_socket << "\n";
instance.Init("ydotoold virtual device");
while (int fd_client = accept(fd_listener, nullptr, nullptr)) {
std::cerr << "ydotoold: accepted client\n";
std::thread thd(client_handler, fd_client);
thd.detach();
}
}
| 23.662791
| 113
| 0.653071
|
StoneDot
|
a89b9d3fecc3cb13ea796b2a462af7d2ae414ca2
| 331
|
cpp
|
C++
|
Unreal4/FogOfWar/UnchartedWaters/Source/unchartedwaters/UI/UWGameHUD.cpp
|
fangguanya/study
|
4e0ae19d97c5665208657fdb280bd2c25ce05190
|
[
"MIT"
] | null | null | null |
Unreal4/FogOfWar/UnchartedWaters/Source/unchartedwaters/UI/UWGameHUD.cpp
|
fangguanya/study
|
4e0ae19d97c5665208657fdb280bd2c25ce05190
|
[
"MIT"
] | null | null | null |
Unreal4/FogOfWar/UnchartedWaters/Source/unchartedwaters/UI/UWGameHUD.cpp
|
fangguanya/study
|
4e0ae19d97c5665208657fdb280bd2c25ce05190
|
[
"MIT"
] | 1
|
2022-03-08T01:36:39.000Z
|
2022-03-08T01:36:39.000Z
|
#pragma once
// !< All right is reserved by HW-Storm Game Studio, Even not mentioned clearly with signature.
// !< This is not a free ware, Please do-not copy it outside of HW-Storm Game Studio
// !< File : UWGameState
// !< Date : 2/27/2017 12:03:53 PM
// !< Author : fanggang
#include "unchartedwaters.h"
#include "UWGameHUD.h"
| 33.1
| 95
| 0.700906
|
fangguanya
|
a89bd2a83e044b1bcaab8b2b6b77ecf6d8ca80bd
| 2,197
|
cc
|
C++
|
src/base-element.cc
|
banetl/bson-parser
|
b5c15c1f10863d7e4ea2aa6fc07188728ed2de04
|
[
"MIT"
] | null | null | null |
src/base-element.cc
|
banetl/bson-parser
|
b5c15c1f10863d7e4ea2aa6fc07188728ed2de04
|
[
"MIT"
] | null | null | null |
src/base-element.cc
|
banetl/bson-parser
|
b5c15c1f10863d7e4ea2aa6fc07188728ed2de04
|
[
"MIT"
] | 1
|
2018-04-05T11:53:23.000Z
|
2018-04-05T11:53:23.000Z
|
#include <map>
#include <string>
#include "base-element.hh"
#include "utils.hh"
namespace bson
{
BaseElement::BaseElement(BaseElement::Type type, const std::string key)
: type_(type),
key_(key)
{
}
std::string BaseElement::get_type_string(BaseElement::Type e) const
{
const std::map<BaseElement::Type, const std::string> type_to_str
{
{ BaseElement::Type::bfp, "64-bit binary floating point" },
{ BaseElement::Type::str, "UTF-8 string" },
{ BaseElement::Type::doc, "Embedded document" },
{ BaseElement::Type::array, "Array" },
{ BaseElement::Type::bdata, "Binary data" },
{ BaseElement::Type::undef, "Undefined (value) — Deprecated" },
{ BaseElement::Type::oid, "ObjectId" },
{ BaseElement::Type::bf, "Boolean \"false\"" },
{ BaseElement::Type::bt, "Boolean \"true\"" },
{ BaseElement::Type::date, "UTC datetime" },
{ BaseElement::Type::null, "Null value" },
{ BaseElement::Type::regex, "Regular expression" },
{ BaseElement::Type::dbp, "DBPointer" },
{ BaseElement::Type::jvs, "JavaScript code" },
{ BaseElement::Type::symbol, "Symbol" },
{ BaseElement::Type::jvsg, "JavaScript code w/ scope" },
{ BaseElement::Type::i32, "32-bit integer" },
{ BaseElement::Type::time, "Timestamp" },
{ BaseElement::Type::i64, "64-bit integer" },
{ BaseElement::Type::d128, "128-bit decimal floating point" },
{ BaseElement::Type::min, "Min key" },
{ BaseElement::Type::max, "Max key" },
};
auto it = type_to_str.find(e);
return (it != type_to_str.end()) ? it->second : "Error";
}
std::ostream& BaseElement::dump(std::ostream& ostr) const
{
ostr << "Element:" << utils::iendl
<< "type: " << this->get_type_string(type_) << utils::iendl
<< "key: " << key_ << utils::iendl;
return ostr;
}
std::ostream& operator<<(std::ostream& ostr, const BaseElement& elt)
{
return elt.dump(ostr);
}
}
| 35.435484
| 75
| 0.543013
|
banetl
|
a89c4847dfe0405d41b72a1e6dd932ef1b11774a
| 78
|
cpp
|
C++
|
Windows/VS2017/vtkCommonDataModel/vtkCommonDataModel.cpp
|
WinBuilds/VTK
|
508ab2644432973724259184f2cb83aced602484
|
[
"BSD-3-Clause"
] | null | null | null |
Windows/VS2017/vtkCommonDataModel/vtkCommonDataModel.cpp
|
WinBuilds/VTK
|
508ab2644432973724259184f2cb83aced602484
|
[
"BSD-3-Clause"
] | null | null | null |
Windows/VS2017/vtkCommonDataModel/vtkCommonDataModel.cpp
|
WinBuilds/VTK
|
508ab2644432973724259184f2cb83aced602484
|
[
"BSD-3-Clause"
] | null | null | null |
#include "vtkCommonDataModel.h"
vtkCommonDataModel::vtkCommonDataModel()
{
}
| 13
| 40
| 0.794872
|
WinBuilds
|
a89eef6e13458396ada343fe487e175568f46273
| 1,068
|
cpp
|
C++
|
1138/main.cpp
|
Heliovic/PAT_Solutions
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | 2
|
2019-03-18T12:55:38.000Z
|
2019-09-07T10:11:26.000Z
|
1138/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
1138/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#define MAX_N 51200
using namespace std;
int preorder[MAX_N];
int inorder[MAX_N];
int N;
bool flag = false;
struct node
{
int data;
node* lc;
node* rc;
node() {lc = rc = NULL;}
};
node* root = NULL;
node* rebuild(int pl, int pr, int il, int ir)
{
if (pl > pr || il > ir)
return NULL;
node* n = new node;
n->data = preorder[pl];
int k;
for (int i = il; i <= ir; i++)
{
if (n->data == inorder[i])
{
k = i;
break;
}
}
n->lc = rebuild(pl + 1, pl + k - il, il, k - 1);
n->rc = rebuild(pl + k - il + 1, pr, k + 1, ir);
return n;
}
void post(node* r)
{
if (r == NULL || flag)
return;
post(r->lc);
post(r->rc);
if (!flag)
printf("%d", r->data);
flag = true;
}
int main()
{
scanf("%d", &N);
for (int i = 1; i <= N; i++)
scanf("%d", &preorder[i]);
for (int i = 1; i <= N; i++)
scanf("%d", &inorder[i]);
root = rebuild(1, N, 1, N);
post(root);
return 0;
}
| 14.630137
| 52
| 0.449438
|
Heliovic
|
a8a15dd1bd099b9a6edfeeb0e0d7f1e8fe317f19
| 93
|
hpp
|
C++
|
lib/hwlib-extra/hwlib-extra.hpp
|
Fusion86/gesture-gloves
|
17ebff2c7ea63cffd4f78e9d7ec35a004cb457e2
|
[
"MIT"
] | null | null | null |
lib/hwlib-extra/hwlib-extra.hpp
|
Fusion86/gesture-gloves
|
17ebff2c7ea63cffd4f78e9d7ec35a004cb457e2
|
[
"MIT"
] | null | null | null |
lib/hwlib-extra/hwlib-extra.hpp
|
Fusion86/gesture-gloves
|
17ebff2c7ea63cffd4f78e9d7ec35a004cb457e2
|
[
"MIT"
] | null | null | null |
#pragma once
#include <hwlib.hpp>
hwlib::ostream& operator<<(hwlib::ostream& os, float f);
| 15.5
| 56
| 0.698925
|
Fusion86
|
a8a1843d2251bfd8946be5202b9fc309288531db
| 2,315
|
hpp
|
C++
|
src/seal/kernel/sum_seal.hpp
|
EvonneH/he-transformer
|
85b3b629e46a25795ffcd913c8c5ffe7e4d50afc
|
[
"Apache-2.0"
] | null | null | null |
src/seal/kernel/sum_seal.hpp
|
EvonneH/he-transformer
|
85b3b629e46a25795ffcd913c8c5ffe7e4d50afc
|
[
"Apache-2.0"
] | null | null | null |
src/seal/kernel/sum_seal.hpp
|
EvonneH/he-transformer
|
85b3b629e46a25795ffcd913c8c5ffe7e4d50afc
|
[
"Apache-2.0"
] | null | null | null |
//*****************************************************************************
// Copyright 2018-2020 Intel Corporation
//
// 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 <vector>
#include "he_type.hpp"
#include "ngraph/coordinate_transform.hpp"
#include "ngraph/type/element_type.hpp"
#include "seal/he_seal_backend.hpp"
#include "seal/kernel/add_seal.hpp"
namespace ngraph::runtime::he {
inline void sum_seal(std::vector<HEType>& arg, std::vector<HEType>& out,
const Shape& in_shape, const Shape& out_shape,
const AxisSet& reduction_axes,
const element::Type& element_type,
HESealBackend& he_seal_backend) {
NGRAPH_CHECK(he_seal_backend.is_supported_type(element_type),
"Unsupported type ", element_type);
CoordinateTransform output_transform(out_shape);
bool complex_packing = arg.size() > 0 ? arg[0].complex_packing() : false;
size_t batch_size = arg.size() > 0 ? arg[0].batch_size() : 1;
for (const Coordinate& output_coord : output_transform) {
// TODO(fboemer): batch size
const auto out_coord_idx = output_transform.index(output_coord);
out[out_coord_idx] = HEType(HEPlaintext(std::vector<double>(batch_size, 0)),
complex_packing);
}
CoordinateTransform input_transform(in_shape);
for (const Coordinate& input_coord : input_transform) {
Coordinate output_coord = reduce(input_coord, reduction_axes);
auto& input = arg[input_transform.index(input_coord)];
auto& output = out[output_transform.index(output_coord)];
scalar_add_seal(input, output, output, he_seal_backend);
}
}
} // namespace ngraph::runtime::he
| 39.237288
| 80
| 0.657451
|
EvonneH
|
a8a91abb8516aa351c075c34550896cbe193bb21
| 6,802
|
cpp
|
C++
|
src/imtjson/src/imtjson/array.cpp
|
martykadlcek/trading-bot
|
c2f34ef1e6746f02642dde3cb3d11010213f0121
|
[
"MIT"
] | 7
|
2017-01-12T08:56:33.000Z
|
2022-03-09T17:25:20.000Z
|
src/imtjson/src/imtjson/array.cpp
|
martykadlcek/trading-bot
|
c2f34ef1e6746f02642dde3cb3d11010213f0121
|
[
"MIT"
] | 1
|
2017-01-19T16:25:01.000Z
|
2017-01-19T16:25:01.000Z
|
src/imtjson/src/imtjson/array.cpp
|
martykadlcek/trading-bot
|
c2f34ef1e6746f02642dde3cb3d11010213f0121
|
[
"MIT"
] | 1
|
2016-10-14T06:24:16.000Z
|
2016-10-14T06:24:16.000Z
|
#include "array.h"
#include "arrayValue.h"
#include "object.h"
#include <time.h>
namespace json {
Array::Array(Value value): base(value),changes(value)
{
}
Array::Array() : base(AbstractArrayValue::getEmptyArray())
{
}
Array::Array(const std::initializer_list<Value> &v) {
reserve(v.size());
for (auto &&x : v) push_back(x);
}
Array & Array::push_back(const Value & v)
{
changes.push_back(v.v);
return *this;
}
Array & Array::add(const Value & v)
{
changes.push_back(v.v);
return *this;
}
Array & Array::addSet(const StringView<Value>& v)
{
changes.reserve(changes.size() + v.length);
for (std::size_t i = 0; i < v.length; i++)
changes.push_back(v.data[i].v);
return *this;
}
Array& json::Array::addSet(const Value& v) {
changes.reserve(changes.size() + v.size());
for (std::size_t i = 0, cnt = v.size(); i < cnt; i++)
changes.push_back(v[i].getHandle());
return *this;
}
Array & Array::insert(std::size_t pos, const Value & v)
{
extendChanges(pos);
changes.insert(changes.begin()+(pos - changes.offset), v.v);
return *this;
}
Array & Array::insertSet(std::size_t pos, const StringView<Value>& v)
{
extendChanges(pos);
changes.insert(changes.begin() + (pos - changes.offset), v.length, PValue());
for (std::size_t i = 0; i < v.length; i++) {
changes[pos + changes.offset + i] = v.data[i].v;
}
return *this;
}
Array& json::Array::insertSet(std::size_t pos, const Value& v) {
extendChanges(pos);
changes.insert(changes.begin() + (pos - changes.offset), v.size(), PValue());
for (std::size_t i = 0, cnt = v.size(); i < cnt; i++) {
changes[pos + changes.offset + i] = v[i].v;
}
return *this;
}
Array& json::Array::addSet(const std::initializer_list<Value>& v) {
return addSet(StringView<Value>(v));
}
Array& json::Array::insertSet(std::size_t pos,
const std::initializer_list<Value>& v) {
return insertSet(pos,StringView<Value>(v));
}
Array & Array::erase(std::size_t pos)
{
extendChanges(pos);
changes.erase(changes.begin() + (pos - changes.offset));
return *this;
}
Array & Array::eraseSet(std::size_t pos, std::size_t length)
{
extendChanges(pos);
auto b = changes.begin() + (pos - changes.offset);
auto e = b + length ;
changes.erase(b,e);
return *this;
}
Array & Array::trunc(std::size_t pos)
{
if (pos < changes.offset) {
changes.offset = pos;
changes.clear();
}
else {
changes.erase(changes.begin() + (pos - changes.offset), changes.end());
}
return *this;
}
Array &Array::clear() {
changes.offset = 0;
changes.clear();
return *this;
}
Array &Array::revert() {
changes.offset = base.size();
changes.clear();
return *this;
}
Array & Array::set(std::size_t pos, const Value & v)
{
extendChanges(pos);
changes[pos - changes.offset] = v.getHandle();
return *this;
}
Value Array::operator[](std::size_t pos) const
{
if (pos < changes.offset) return base[pos];
else {
pos -= changes.offset;
return changes.at(pos);
}
}
ValueRef Array::makeRef(std::size_t pos) {
return ValueRef(*this, pos);
}
std::size_t Array::size() const
{
return changes.offset + changes.size();
}
bool Array::empty() const
{
return size() == 0;
}
PValue Array::commit() const
{
if (empty()) return AbstractArrayValue::getEmptyArray();
if (!dirty()) return base.getHandle();
std::size_t needSz = changes.offset + changes.size();
RefCntPtr<ArrayValue> result = ArrayValue::create(needSz);
for (std::size_t x = 0; x < changes.offset; ++x) {
result->push_back(base[x].getHandle());
}
for (auto &&x : changes) {
if (x->type() != undefined) result->push_back(x);
}
return PValue::staticCast(result);
}
Object2Array Array::object(std::size_t pos)
{
return Object2Array((*this)[pos],*this,pos);
}
Array2Array Array::array(std::size_t pos)
{
return Array2Array((*this)[pos], *this, pos);
}
bool Array::dirty() const
{
return changes.offset != base.size() || !changes.empty();
}
void Array::extendChanges(size_t pos)
{
if (pos < changes.offset) {
changes.insert(changes.begin(), changes.offset - pos, PValue());
for (std::size_t x = pos; x < changes.offset; ++x) {
changes[x - pos] = base[x].v;
}
changes.offset = pos;
}
}
Array::~Array()
{
}
ArrayIterator Array::begin() const {
return ArrayIterator(this,0);
}
ArrayIterator Array::end() const {
return ArrayIterator(this,size());
}
Array &Array::reserve(std::size_t items) {
changes.reserve(items);
return *this;
}
Object2Array Array::addObject() {
std::size_t pos = size();
add(AbstractObjectValue::getEmptyObject());
return object(pos);
}
Array2Array Array::addArray() {
std::size_t pos = size();
add(AbstractArrayValue::getEmptyArray());
return array(pos);
}
StringView<PValue> Array::getItems(const Value& v) {
const IValue *pv = v.getHandle();
const ArrayValue *av = dynamic_cast<const ArrayValue *>(pv->unproxy());
if (av) return av->getItems(); else return StringView<PValue>();
}
Array::Array(const Array& other):base(other.base),changes(other.changes) {
}
Array::Array(Array&& other):base(std::move(other.base)),changes(std::move(other.changes)) {
}
Array& Array::operator =(const Array& other) {
if (this == &other) return *this;
base = other.base;
changes = other.changes;
return *this;
}
Array& Array::operator =(Array&& other) {
if (this == &other) return *this;
base = std::move(other.base);
changes = std::move(other.changes);
return *this;
}
Array::Changes::Changes(const Changes& base)
:std::vector<PValue>(base),offset(base.offset)
{
}
Array::Changes::Changes(Changes&& base)
:std::vector<PValue>(std::move(base)),offset(base.offset) {
}
Array::Changes& Array::Changes::operator =(const Changes& base) {
std::vector<PValue>::operator =(base);
offset = base.offset;
return *this;
}
Array::Changes& Array::Changes::operator =(Changes&& base) {
std::vector<PValue>::operator =(std::move(base));
offset = base.offset;
return *this;
}
Array& Array::reverse() {
Array out;
for (std::size_t x = size(); x > 0; x--)
out.add((*this)[x-1]);
*this = std::move(out);
return *this;
}
Array& Array::slice(Int start) {
if (start < 0) {
if (-start < (Int)size()) {
return slice(size()+start);
}
} else if (start >= (Int)size()) {
clear();
} else {
eraseSet(0,start);
}
return *this;
}
Array& Array::slice(Int start, Int end) {
if (end < 0) {
if (-end < (Int)size()) {
slice(start, (Int)size()+end);
} else {
clear();
}
} else if (end < (Int)size()) {
trunc(end);
}
return slice(start);
}
Array& json::Array::setSize(std::size_t length, Value fillVal) {
reserve(length);
if (size() > length) return trunc(length);
while (size() < length) add(fillVal);
return *this;
}
}
| 21.593651
| 91
| 0.636136
|
martykadlcek
|
a8a9a9b0eab95164006e56947f358a6338c08fac
| 7,014
|
hpp
|
C++
|
mesp/mesp_inner.hpp
|
KuceraMartin/mesp-fpt
|
295a6a65ba5aedde775eb57805d7a74124e63c66
|
[
"MIT"
] | null | null | null |
mesp/mesp_inner.hpp
|
KuceraMartin/mesp-fpt
|
295a6a65ba5aedde775eb57805d7a74124e63c66
|
[
"MIT"
] | null | null | null |
mesp/mesp_inner.hpp
|
KuceraMartin/mesp-fpt
|
295a6a65ba5aedde775eb57805d7a74124e63c66
|
[
"MIT"
] | null | null | null |
#ifndef IMPL_MESP_INNER_HPP
#define IMPL_MESP_INNER_HPP
#include <boost/dynamic_bitset.hpp>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "../common/common.hpp"
#include "../common/graph.hpp"
#include "constrained_set_cover.hpp"
class mesp_inner {
public:
int k;
int pi_first, pi_last;
std::shared_ptr<const graph> G;
std::shared_ptr<const std::unordered_set<int>> C;
path solution;
private:
std::unordered_set<int> L;
std::vector<int> pi;
std::unordered_map<int, int> e;
public:
mesp_inner(const std::shared_ptr<const graph> &G, const std::shared_ptr<const std::unordered_set<int>> &C, int k, int pi_first = -1, int pi_last = -1):
G(G),
C(C),
k(k),
pi_first(pi_first),
pi_last(pi_last)
{}
bool solve()
{
init_L();
do {
init_pi();
do {
if (!can_pi()) continue;
init_e();
do {
if (solve_inner()) return true;
} while (next_e());
} while (next_pi());
} while (next_L());
return false;
}
private:
bool solve_inner()
{
auto candidate_segments = get_segments();
if (!candidate_segments.has_value()) return false;
std::unordered_set<int> I(L.begin(), L.end());
std::vector<int> h_inv((*candidate_segments).size(), -1);
std::vector<std::vector<path>> candidates;
for (int i = 0; i < candidate_segments->size(); i++) {
if ((*candidate_segments)[i].size() == 1) {
for (int u : (*candidate_segments)[i][0]) I.insert(u);
continue;
}
candidates.emplace_back(std::move((*candidate_segments)[i]));
h_inv[i] = candidates.size() - 1;
}
std::unordered_set<int> U;
for (int v = 0; v < G->n; v++) {
if (C->count(v) || I.count(v)) continue;
if (estimate_path_dst(v) > k + 1) return false;
if (estimate_path_dst(v) == k + 1) U.insert(v);
}
if (U.size() > 2 * (pi.size() - 1)) return false;
std::vector<int> requirements;
for (int u = 0; u < G->n; u++) {
if (L.count(u)) continue;
if (!C->count(u) && !U.count(u)) continue;
int need_dst = e.count(u) ? e[u] : k;
if (G->distance(u, I) <= need_dst) continue;
requirements.push_back(u);
}
const std::function<boost::dynamic_bitset<>(const path &)> psi = [this, &requirements] (const path &segment) {
boost::dynamic_bitset<> res(requirements.size(), 0);
if (segment.empty()) return res;
for (int i = 0; i < requirements.size(); i++) {
int u = requirements[i];
int need_dst = e.count(u) ? e[u] : k;
if (G->distance(u, segment) <= need_dst) {
res[i] = true;
}
}
return res;
};
auto true_segment_id = constrained_set_cover(requirements, candidates, psi);
if (!true_segment_id.has_value()) return false;
solution.clear();
for (int i = 0; i < pi.size() - 1; i++) {
solution.push_back(pi[i]);
path &segment = h_inv[i] == -1 ? (*candidate_segments)[i][0] : candidates[h_inv[i]][(*true_segment_id)[h_inv[i]]];
for (int s : segment) solution.push_back(s);
}
solution.push_back(pi.back());
return G->ecc(solution) <= k;
}
std::optional<std::vector<std::vector<path>>> get_segments() const
{
std::vector<std::vector<path>> candidate_segments(pi.size() - 1);
for (int i = 0; i < pi.size() - 1; i++) {
std::queue<int> q;
q.push(pi[i + 1]);
std::unordered_map<int, int> dst = {{pi[i + 1], 0}};
while (!q.empty()) {
int u = q.front();
q.pop();
if (u == pi[i]) break;
for (int v : G->neighbors(u)) {
if (dst.count(v)) continue;
if (C->count(v) && v != pi[i]) continue;
dst[v] = dst[u] + 1;
q.push(v);
}
}
if (!dst.count(pi[i])) return std::nullopt;
if (dst[pi[i]] != G->distance(pi[i + 1], pi[i])) return std::nullopt;
std::vector<path> Sigma;
std::vector<int> K;
for (int u : G->neighbors(pi[i])) {
if (!dst.count(u) || dst[u] != dst[pi[i]] - 1) continue;
if (u == pi[i + 1]) {
Sigma.emplace_back();
break;
}
for (int v : G->neighbors(u)) {
if (!dst.count(v) || dst[v] != dst[u] - 1) continue;
Sigma.push_back({u});
int K_added = 0;
while (v != pi[i + 1]) {
int p = Sigma.back().back();
if (estimate_path_dst(v) > k) {
if (K_added++ < 2) K.push_back(v);
if (K.size() > 4) return std::nullopt;
}
Sigma.back().push_back(v);
for (int n : G->neighbors(v)) {
if (!dst.count(n) || dst[n] != dst[v] - 1) continue;
if (n == p) continue;
v = n;
break;
}
}
}
}
for (auto &segment : Sigma) {
std::vector<int> K_sat(K.size(), 0);
for (int j = 0; j < K.size(); j++) {
K_sat[j] |= G->distance(K[j], segment) <= k;
}
bool is_sat = true;
for (bool s : K_sat) is_sat |= s;
if (is_sat) {
candidate_segments[i].emplace_back(std::move(segment));
}
}
}
return candidate_segments;
}
void init_L()
{
L.clear();
auto C_iter = C->begin();
if (pi_first == -1) {
L.insert(*C_iter);
++C_iter;
} else {
L.insert(pi_first);
}
if (pi_last == -1) {
L.insert(*C_iter);
} else {
L.insert(pi_last);
}
}
bool next_L()
{
int max_size = C->size();
if (pi_first != -1) max_size++;
if (pi_last != -1) max_size++;
if (L.size() == max_size) return false;
do {
for (int v : *C) {
if (L.count(v)) {
L.erase(v);
} else {
L.insert(v);
break;
}
}
} while (L.size() < 2);
return true;
}
void init_pi()
{
pi.clear();
pi.reserve(L.size());
if (pi_first != -1) pi.push_back(pi_first);
for (int u : L) {
if (u == pi_first || u == pi_last) continue;
pi.push_back(u);
}
if (pi_last != -1) pi.push_back(pi_last);
std::sort(pi.begin() + (pi_first == -1 ? 0 : 1), pi.end() - (pi_last == -1 ? 0 : 1));
}
bool can_pi() const
{
int length = 0;
for (int i = 0; i < pi.size() - 1; i++) {
length += G->distance(pi[i], pi[i + 1]);
}
return length == G->distance(pi[0], pi.back());
}
bool next_pi()
{
int first = pi_first == -1 ? 0 : 1;
int last = (int) pi.size() - (pi_last == -1 ? 1 : 2);
if (first >= last) return false;
int m = last - 1;
while (m >= first && pi[m] > pi[m + 1]) m--;
if (m < first) return false;
int k = last;
while (pi[m] > pi[k]) k--;
std::swap(pi[m], pi[k]);
int p = m + 1;
int q = last;
while (p < q) {
std::swap(pi[p], pi[q]);
p++;
q--;
}
return true;
}
void init_e()
{
e.clear();
for (int v : *C) {
if (L.count(v)) continue;
e[v] = 1;
}
}
bool next_e()
{
int cnt = 0;
for (int v : *C) {
if (L.count(v)) continue;
if (e[v] < k) {
e[v]++;
break;
} else {
e[v] = 1;
cnt++;
}
}
return cnt < e.size();
}
int estimate_path_dst(int u) const
{
int res = INF;
if (pi_first != -1) {
res = std::min(res, G->distance(u, pi_first));
}
if (pi_last != -1) {
res = std::min(res, G->distance(u, pi_last));
}
for (int v : *C) {
int e_v = e.count(v) ? e.at(v) : 0;
res = std::min(res, G->distance(u, v) + e_v);
}
return res;
}
};
#endif //IMPL_MESP_INNER_HPP
| 22.699029
| 152
| 0.550613
|
KuceraMartin
|
a8aefe93bfad9ad7ea0f6ba41d5a8a505d0ab170
| 271
|
hh
|
C++
|
src/state/secondary_variable_field_evaluator_fromfunction_reg.hh
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 37
|
2017-04-26T16:27:07.000Z
|
2022-03-01T07:38:57.000Z
|
src/state/secondary_variable_field_evaluator_fromfunction_reg.hh
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 494
|
2016-09-14T02:31:13.000Z
|
2022-03-13T18:57:05.000Z
|
src/state/secondary_variable_field_evaluator_fromfunction_reg.hh
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 43
|
2016-09-26T17:58:40.000Z
|
2022-03-25T02:29:59.000Z
|
#include "secondary_variable_field_evaluator_fromfunction.hh"
namespace Amanzi {
Utils::RegisteredFactory<FieldEvaluator,SecondaryVariableFieldEvaluatorFromFunction> SecondaryVariableFieldEvaluatorFromFunction::fac_("secondary variable from function");
} // namespace
| 33.875
| 171
| 0.867159
|
fmyuan
|
a8b165b4934772d0c528880b4800c6b25ea181f7
| 352
|
cpp
|
C++
|
files/mnem_gen_abacaba.cpp
|
kborozdin/palindromic-length
|
2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2
|
[
"MIT"
] | null | null | null |
files/mnem_gen_abacaba.cpp
|
kborozdin/palindromic-length
|
2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2
|
[
"MIT"
] | null | null | null |
files/mnem_gen_abacaba.cpp
|
kborozdin/palindromic-length
|
2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2
|
[
"MIT"
] | null | null | null |
// abacaba
#include <stdio.h>
#include <string.h>
#define MAX 100000
char str[MAX];
int main(int argc,char *argv[]) {
int n,k,i;
sscanf(argv[1],"%d",&n);
str[0]='a';
k=1;
char c='a';
for(;n>1;--n) {
str[k]=++c;
for(i=0;i<k;++i)
str[k+1+i]=str[i];
k=k+k+1;
}
printf("%s\n",str);
return 0;
}
| 14.666667
| 34
| 0.465909
|
kborozdin
|
a8b269f1eddb55832cddc194dcb7ca705ca1e3d4
| 644
|
hpp
|
C++
|
Notemania/include/Screen.hpp
|
lunacys/Notemania
|
fcf314ea37fa3f5aa0ca7817708d0b5e8ec171ba
|
[
"MIT"
] | 1
|
2017-06-27T09:38:45.000Z
|
2017-06-27T09:38:45.000Z
|
Notemania/include/Screen.hpp
|
lunacys/Notemania
|
fcf314ea37fa3f5aa0ca7817708d0b5e8ec171ba
|
[
"MIT"
] | 1
|
2017-06-29T16:31:41.000Z
|
2017-06-29T16:31:41.000Z
|
Notemania/include/Screen.hpp
|
lunacys/Notemania
|
fcf314ea37fa3f5aa0ca7817708d0b5e8ec171ba
|
[
"MIT"
] | 3
|
2017-06-27T09:52:19.000Z
|
2017-07-20T13:35:12.000Z
|
#ifndef NOMA_SCREEN_HPP_
#define NOMA_SCREEN_HPP_
#include <string>
namespace noma
{
class IScreenManager;
class Screen
{
public:
Screen* find_screen();
Screen* find_screen(const std::string& name);
void show(const std::string& name, bool hideThis);
void show();
void hide();
virtual void initialize();
virtual void update(double dt);
virtual void render();
IScreenManager* screen_manager;
bool is_initialized;
bool is_visible;
protected:
Screen();
private:
};
} // namespace noma
#endif // NOMA_SCREEN_HPP_
| 16.512821
| 58
| 0.607143
|
lunacys
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.