blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b384c76b6a71004ca990700ca576519ee4148b01 | 26c05bda03a9134ca4a5d5a93549e2e2dc1d7d68 | /modules/editor/source/CodeEditor.cpp | 22688d1b7dd8f401fd546ee404b496a0043fe38c | [] | no_license | alxarsenault/eos | 19f97c94aca9dadfe4ae1c46cc087861742912f0 | d962c83a5af4022bd663695a1c699c1e5581dd30 | refs/heads/master | 2021-05-30T18:16:39.782464 | 2016-01-25T17:13:44 | 2016-01-25T17:13:44 | 41,336,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,574 | cpp | CodeEditor.cpp | #include "CodeEditor.h"
#include <algorithm>
#include "axLib/axButton.h"
/*******************************************************************************
* eos::TextEditor::Logic.
******************************************************************************/
TextEditor::Logic::Logic()
: _file_path("")
, _cursor_pos(0, 0)
{
}
bool TextEditor::Logic::OpenFile(const std::string& file_path)
{
_file_path = file_path;
std::ifstream t(file_path);
std::string file_str(
(std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
// Remove all tab for string.
ax::Utils::String::ReplaceCharWithString(file_str, '\t', " ");
_file_data = ax::Utils::String::Split(file_str, "\n");
_cursor_pos = ax::Point(0, 0);
return true;
}
bool TextEditor::Logic::SaveFile(const std::string& file_path)
{
_file_path = file_path;
std::ofstream out(file_path);
for (auto& n : _file_data) {
out << n << std::endl;
}
out.close();
return true;
}
ax::StringVector& TextEditor::Logic::GetFileData()
{
return _file_data;
}
const ax::StringVector& TextEditor::Logic::GetFileData() const
{
return _file_data;
}
std::string TextEditor::Logic::GetFilePath() const
{
return _file_path;
}
ax::Point TextEditor::Logic::GetCursorPosition() const
{
return _cursor_pos;
}
void TextEditor::Logic::MoveCursorRight()
{
int x_pos = _cursor_pos.x + 1;
// Block cursor position at the last char index + 1
// to allow append at the end of line.
if (x_pos > _file_data[_cursor_pos.y].size()) {
x_pos = (int)_file_data[_cursor_pos.y].size();
}
_cursor_pos.x = x_pos;
}
void TextEditor::Logic::MoveCursorLeft()
{
int x_pos = _cursor_pos.x - 1;
if (x_pos < 0) {
x_pos = 0;
}
_cursor_pos.x = x_pos;
}
void TextEditor::Logic::MoveCursorUp()
{
int x_pos = _cursor_pos.x;
int y_pos = _cursor_pos.y - 1;
// Block cursor at first line.
if (y_pos < 0) {
y_pos = 0;
}
// Block x cursor position at last char of line + 1.
if (x_pos > _file_data[y_pos].size()) {
x_pos = (int)_file_data[y_pos].size();
}
_cursor_pos.x = x_pos;
_cursor_pos.y = y_pos;
}
void TextEditor::Logic::MoveCursorDown()
{
int x_pos = _cursor_pos.x;
int y_pos = _cursor_pos.y + 1;
// Block cursor at last line.
if (y_pos > (int)_file_data.size() - 1) {
y_pos = (int)_file_data.size() - 1;
// ax::Print("Logic :: Cursor last line");
// Set cursor at the last char of last line.
x_pos = (int)_file_data[y_pos].size();
_cursor_pos.x = x_pos;
_cursor_pos.y = y_pos;
return;
}
// Block x cursor position at last char of line + 1.
if (x_pos > _file_data[y_pos].size()) {
x_pos = (int)_file_data[y_pos].size();
}
_cursor_pos.x = x_pos;
_cursor_pos.y = y_pos;
}
void TextEditor::Logic::AddChar(const char& c)
{
const char TAB = 9;
// Append at the end of the line.
if (_cursor_pos.x == _file_data[_cursor_pos.y].size()) {
// if(c == TAB)
// {
// _file_data[_cursor_pos.y].push_back(' ');
// _file_data[_cursor_pos.y].push_back(' ');
// _file_data[_cursor_pos.y].push_back(' ');
// _file_data[_cursor_pos.y].push_back(' ');
// _cursor_pos.x += 4;
// return;
// }
_file_data[_cursor_pos.y].push_back(c);
_cursor_pos.x++;
return;
}
// Insert char.
// if(c == TAB)
// {
// _file_data[_cursor_pos.y].insert(_cursor_pos.x, std::string(" "));
// _cursor_pos.x += 4;
// return;
// }
// char cc = c;
_file_data[_cursor_pos.y].insert(_cursor_pos.x, 1, c);
//_file_data[_cursor_pos.y].insert(_cursor_pos.x, std::string(&cc));
_cursor_pos.x++;
}
void TextEditor::Logic::Enter()
{
// Append at the end of the line.
if (_cursor_pos.x == _file_data[_cursor_pos.y].size()) {
_file_data.insert(
_file_data.begin() + _cursor_pos.y + 1, std::string(""));
_cursor_pos.x = 0;
_cursor_pos.y++;
return;
}
// Beginning of not empty line.
if (_cursor_pos.x == 0) {
_file_data.insert(_file_data.begin() + _cursor_pos.y, std::string(""));
_cursor_pos.y++;
return;
}
// Enter in middle of line.
std::string old_str = _file_data[_cursor_pos.y].substr(0, _cursor_pos.x);
std::string new_str = _file_data[_cursor_pos.y].substr(_cursor_pos.x);
_file_data[_cursor_pos.y] = old_str;
_file_data.insert(_file_data.begin() + _cursor_pos.y + 1, new_str);
_cursor_pos.x = 0;
_cursor_pos.y++;
}
void TextEditor::Logic::Delete()
{
// Nothing to do when delete on last char of last line.
if (_cursor_pos.x == _file_data[_cursor_pos.y].size()
&& _cursor_pos.y == _file_data.size() - 1) {
return;
}
// Delete at the end of line.
if (_cursor_pos.x == _file_data[_cursor_pos.y].size()) {
std::string next_line = _file_data[_cursor_pos.y + 1];
_file_data[_cursor_pos.y] += next_line;
// Delete old line.
_file_data.erase(_file_data.begin() + _cursor_pos.y + 1);
return;
}
// Remove char in middle of line.
_file_data[_cursor_pos.y].erase(
_file_data[_cursor_pos.y].begin() + _cursor_pos.x);
}
void TextEditor::Logic::BackSpace()
{
// Nothing to do when backspace at the begenning of first line.
if (_cursor_pos.x == 0 && _cursor_pos.y == 0) {
return;
}
// Backspace at the beginning of line.
if (_cursor_pos.x == 0) {
std::string line = _file_data[_cursor_pos.y];
int end_line_pos = (int)_file_data[_cursor_pos.y - 1].size();
// Append line to the line above.
_file_data[_cursor_pos.y - 1] += line;
// Delete old line.
_file_data.erase(_file_data.begin() + _cursor_pos.y);
_cursor_pos.x = end_line_pos;
_cursor_pos.y--;
return;
}
// Remove at the end of the line.
if (_cursor_pos.x == _file_data[_cursor_pos.y].size()) {
// ax::Print("POP");
_file_data[_cursor_pos.y].pop_back();
_cursor_pos.x--;
if (_cursor_pos.x < 0) {
_cursor_pos.x = 0;
}
return;
}
// Remove char in middle of line.
_file_data[_cursor_pos.y].erase(
_file_data[_cursor_pos.y].begin() + _cursor_pos.x - 1);
_cursor_pos.x--;
}
/*******************************************************************************
* eos::TextEditor.
******************************************************************************/
TextEditor::TextEditor(const ax::Rect& rect, const TextEditor::Info& info)
: _font("resources/VeraMono.ttf")
, _line_num_font("resources/DejaVuSansMono.ttf")
, _line_height(15)
, _file_start_index(0)
, _info(info)
{
_line_num_font.SetFontSize(10);
_n_line_shown = (rect.size.y - 20 - 1) / _line_height;
win = ax::Window::Create(rect);
_scrollPanel = ax::Window::Create(
ax::Rect(1, 1 + 20, rect.size.x - 1, rect.size.y - 20 - 1));
_scrollPanel->property.AddProperty("BlockDrawing");
_scrollPanel->event.OnPaint = ax::WBind<ax::GC>(this, &TextEditor::OnPaint);
_scrollPanel->event.OnMouseEnter
= ax::WBind<ax::Point>(this, &TextEditor::OnMouseEnter);
_scrollPanel->event.OnMouseLeftDown
= ax::WBind<ax::Point>(this, &TextEditor::OnMouseLeftDown);
_scrollPanel->event.OnMouseLeftUp
= ax::WBind<ax::Point>(this, &TextEditor::OnMouseLeftUp);
_scrollPanel->event.OnLeftArrowDown
= ax::WBind<char>(this, &TextEditor::OnLeftArrowDown);
_scrollPanel->event.OnRightArrowDown
= ax::WBind<char>(this, &TextEditor::OnRightArrowDown);
_scrollPanel->event.OnUpArrowDown
= ax::WBind<char>(this, &TextEditor::OnUpArrowDown);
_scrollPanel->event.OnDownArrowDown
= ax::WBind<char>(this, &TextEditor::OnDownArrowDown);
_scrollPanel->event.OnKeyDown
= ax::WBind<char>(this, &TextEditor::OnKeyDown);
_scrollPanel->event.OnEnterDown
= ax::WBind<char>(this, &TextEditor::OnEnterDown);
_scrollPanel->event.OnKeyDeleteDown
= ax::WBind<char>(this, &TextEditor::OnKeyDeleteDown);
_scrollPanel->event.OnBackSpaceDown
= ax::WBind<char>(this, &TextEditor::OnBackSpaceDown);
win->node.Add(_scrollPanel);
ax::ScrollBar::Info sInfo;
sInfo.normal = ax::Color(0.22);
sInfo.hover = ax::Color(0.23);
sInfo.clicking = ax::Color(0.21);
sInfo.slider_contour = ax::Color(0.0, 0.2);
sInfo.contour = ax::Color(0.0, 0.0);
sInfo.bg_top = ax::Color(0.8, 0.2);
sInfo.bg_bottom = ax::Color(0.82, 0.2);
//
ax::ScrollBar::Events scrollEvents;
scrollEvents.value_change = GetOnScroll();
win->node.Add(_scrollBar = ax::ScrollBar::Ptr(new ax::ScrollBar(
ax::Rect(rect.size.x - 11, 20, 10, rect.size.y - 1 - 20),
scrollEvents, sInfo)));
_logic.OpenFile("resources/draw.chai");
win->event.OnPaint = ax::WFunc<ax::GC>([&](ax::GC gc) {
ax::Rect rect(win->dimension.GetDrawingRect());
gc.SetColor(ax::Color(0.15));
gc.DrawRectangle(rect);
gc.DrawRectangleColorFade(ax::Rect(1, 1, rect.size.x - 1, 20),
ax::Color(0.15), ax::Color(0.25));
gc.SetColor(ax::Color(0.6));
gc.DrawString(_font, _logic.GetFilePath(), ax::Point(5, 1));
gc.SetColor(ax::Color(0.15));
gc.DrawRectangleContour(rect);
});
// Scrollbar is use without window handle, it behave just like a slider.
int h_size = (int)_logic.GetFileData().size() * _line_height;
_scrollBar->UpdateWindowSize(ax::Size(rect.size.x, h_size));
_number_cpp.insert("0");
_key_words_cpp.insert("class");
_key_words_cpp.insert("const");
_key_words_cpp.insert("return");
_key_words_cpp.insert("void");
_key_words_cpp.insert("virtual");
_key_words_cpp.insert("private");
_key_words_cpp.insert("public");
_key_words_cpp.insert("protected");
_key_words_cpp.insert("virtual");
_key_words_cpp.insert("if");
_key_words_cpp.insert("else");
_key_words_cpp.insert("while");
_key_words_cpp.insert("float");
_key_words_cpp.insert("double");
_key_words_cpp.insert("unsigned");
_key_words_cpp.insert("char");
_key_words_cpp.insert("for");
_key_words_cpp.insert("namespace");
_key_words_cpp.insert("new");
_key_words_cpp.insert("delete");
ax::Button::Info btn_info;
btn_info.normal = ax::Color(0.6, 1.0);
btn_info.hover = ax::Color(0.6, 1.0);
btn_info.clicking = ax::Color(0.6, 1.0);
btn_info.selected = ax::Color(0.6, 1.0);
btn_info.contour = ax::Color(0.3, 1.0);
btn_info.font_color = ax::Color(0.0);
ax::Button::Ptr save_btn(new ax::Button(
ax::Rect(rect.size.x - 25, 2, 20, 17),
ax::Event::Function([&](ax::Event::Msg* msg) {
// ax::Print("CLLICK");
_logic.SaveFile(_logic.GetFilePath());
win->PushEvent(10020, new ax::Event::StringMsg("Save"));
}),
btn_info, "", "S"));
win->node.Add(save_btn);
}
std::string TextEditor::GetStringContent() const
{
std::string content;
const ax::StringVector& data = _logic.GetFileData();
for (auto& n : data) {
content += (n + "\n");
}
return content;
}
std::string TextEditor::GetFilePath() const
{
return _logic.GetFilePath();
}
ax::Point TextEditor::FileCursorPosToNextPosIndex()
{
ax::Point file_cursor(_logic.GetCursorPosition());
// Cursor is above shown text.
if (file_cursor.y < _file_start_index) {
return ax::Point(-1, -1);
}
// Cursor is bellow shown text.
if (file_cursor.y > _file_start_index + _n_line_shown - 1) {
return ax::Point(-1, -1);
}
return ax::Point(file_cursor.x, file_cursor.y - _file_start_index);
}
void TextEditor::MoveToCursorPosition()
{
ax::Point cur_pos(_logic.GetCursorPosition());
// Cursor is bellow last shown line.
if (cur_pos.y > _file_start_index + _n_line_shown - 1) {
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Possible problem when file size is smaller than _n_line_shown.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
_file_start_index = cur_pos.y - _n_line_shown + 1;
}
else if (cur_pos.y < _file_start_index) {
_file_start_index = cur_pos.y;
}
// Move scroll bar.
int diff = (int)_logic.GetFileData().size() - _n_line_shown;
double scroll_ratio = _file_start_index / double(diff);
_scrollBar->SetZeroToOneValue(scroll_ratio);
}
void TextEditor::Resize(const ax::Size& size)
{
// _n_line_shown = size.y / _line_height;
//
// //_scrollBar->SetRect(ax::Rect(size.x - 11, 0, 10, size.y - 1));
//
// int h_size = (int)_logic.GetFileData().size() * _line_height;
// _scrollBar->UpdateWindowSize(ax::Size(size.x, h_size));
//
// // Move scroll bar.
// int diff = (int)_logic.GetFileData().size() - _n_line_shown;
// double scroll_ratio = _file_start_index / double(diff);
// _scrollBar->SetZeroToOneValue(scroll_ratio);
//
// win->dimension.SetSize(size);
}
void TextEditor::OnScroll(const ax::ScrollBar::Msg& msg)
{
int diff = (int)_logic.GetFileData().size() - _n_line_shown;
double scroll_ratio = _scrollBar->GetZeroToOneValue();
_file_start_index = scroll_ratio * diff;
_scrollPanel->Update();
}
void TextEditor::OnMouseEnter(const ax::Point& mouse)
{
_scrollPanel->event.GrabKey();
}
void TextEditor::OnLeftArrowDown(const char& key)
{
_logic.MoveCursorLeft();
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnRightArrowDown(const char& key)
{
_logic.MoveCursorRight();
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnUpArrowDown(const char& key)
{
_logic.MoveCursorUp();
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnDownArrowDown(const char& key)
{
_logic.MoveCursorDown();
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnKeyDown(const char& key)
{
_logic.AddChar(key);
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnEnterDown(const char& key)
{
_logic.Enter();
int h_size = (int)_logic.GetFileData().size() * _line_height;
_scrollBar->UpdateWindowSize(
ax::Size(_scrollPanel->dimension.GetRect().size.x, h_size));
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnBackSpaceDown(const char& key)
{
_logic.BackSpace();
int h_size = (int)_logic.GetFileData().size() * _line_height;
_scrollBar->UpdateWindowSize(
ax::Size(_scrollPanel->dimension.GetRect().size.x, h_size));
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnKeyDeleteDown(const char& key)
{
_logic.Delete();
int h_size = (int)_logic.GetFileData().size() * _line_height;
_scrollBar->UpdateWindowSize(
ax::Size(_scrollPanel->dimension.GetRect().size.x, h_size));
MoveToCursorPosition();
_scrollPanel->Update();
}
void TextEditor::OnMouseLeftDown(const ax::Point& mouse_pos)
{
}
void TextEditor::OnMouseLeftUp(const ax::Point& mouse_pos)
{
// ax::Point pos = mouse_pos - GetAbsoluteRect().position;
// ax::Size w_size(GetSize());
//
// int n_shown = w_size.y / 15;
//
// _selected_index = (pos.y / (double)w_size.y) * n_shown;
//
// int index = _file_start_index + _selected_index;
//
// const std::vector<ax::os::File>& content = _dir.GetContent();
//
// if(index < content.size())
// {
// if(content[index].type == ax::os::File::FOLDER)
// {
// _dir.Goto(_dir.GetPath() + _dir.GetContent()[index].name +
// "/");
// ResetParams();
// }
// }
//
// Update();
}
bool is_special(const char& x)
{
return x == '(' || x == ')' || x == ':' || x == '[' || x == ']' || x == ','
|| x == ';' || x == '{' || x == '}';
}
// bool is_number_char();
std::string RemoveSpecialChar(const std::string& str)
{
std::string r = str;
r.erase(std::remove_if(r.begin(), r.end(), [](char x) {
return is_special(x);
}), r.end());
return r;
}
// bool is_number(const std::string& s)
//{
// return !s.empty() && std::find_if(s.begin(), s.end(),
// [](char c)
// {
// return !std::isdigit(c);
// }) == s.end();
//}
bool is_number(const std::string& str)
{
char* p;
strtod(str.c_str(), &p); //, 10);
return *p == 0;
}
void TextEditor::OnPaint(ax::GC gc)
{
ax::Rect rect(_scrollPanel->dimension.GetDrawingRect());
gc.SetColor(_info.bg_color);
gc.DrawRectangle(ax::Rect(0, 0, rect.size.x, rect.size.y));
// Draw line number background.
gc.SetColor(_info.line_number_bg_color);
gc.DrawRectangle(ax::Rect(0, 0, 25, rect.size.y));
ax::Point num_pos(4, 2);
gc.SetColor(_info.line_number_color);
// Draw line number.
for (int i = 0; i < _n_line_shown; i++) {
int num = i + _file_start_index;
std::string num_str = std::to_string(num);
if (num < 10) {
num_str = " " + num_str;
}
else if (num < 100) {
num_str = " " + num_str;
}
gc.DrawString(_line_num_font, num_str, num_pos);
num_pos += ax::Point(0, 15);
}
// Text initial position.
// ax::Point line_pos(4, 0);
ax::Point line_pos(25 + 4, 0);
_next_pos_data.clear();
const ax::StringVector& data = _logic.GetFileData();
// Set text color.
gc.SetColor(_info.text_color);
// Draw text.
for (int i = 0, k = _file_start_index; k < data.size() && i < _n_line_shown;
i++, k++) {
const std::string& text = data[k];
std::vector<int> next_vec(text.size() + 1);
// Draw string.
if (_font) {
int x = line_pos.x;
next_vec[0] = x;
//
//----------------------------------------
// ax::StringVector words =
// ax::Utils::String::Split(text, " ");
//
// int index = 0;
//
// for(auto& w : words)
// {
// std::string clean_word =
//RemoveSpecialChar(w);
//
// ax::Color word_color = _info.text_color;
//
// if(_key_words_cpp.find(clean_word) !=
// _key_words_cpp.end())
// {
// word_color = ax::Color(0.6627451f,
//0.05098039f,
// 0.5686275f);
// }
//
// for (int i = 0; i < w.size(); i++)
// {
// gc.SetColor(word_color);
//
// if(text[index] == ' ')
// {
// i--;
// _font.SetChar(' ');
// }
// else
// {
// _font.SetChar(w[i]);
//
// if(is_special(w[i]))
// {
// gc.SetColor(_info.text_color);
// }
// else if(std::isdigit(w[i]))
// {
// gc.SetColor(ax::Color(0.0f,
//0.0f, 1.0f));
// }
// }
//
// ax::Point d = _font.GetDelta();
//
// ax::Point txtPos(x + d.x,
// line_pos.y - d.y +
// _font.GetFontSize());
//
// ax::Rect txtRect(txtPos,
//_font.GetSize());
// gc.DrawTexture(_font.GetTexture(),
//txtRect);
//
// x += _font.GetNextPosition();
//
// next_vec[index + 1] = x;
//
// index++;
//
// }
// }
//
// _font.SetChar(' ');
// ax::Point d = _font.GetDelta();
//
// while(index < text.size())
// {
// ax::Point txtPos(x + d.x,
// line_pos.y - d.y +
// _font.GetFontSize());
// ax::Rect txtRect(txtPos,
//_font.GetSize());
// gc.DrawTexture(_font.GetTexture(),
//txtRect);
// x += _font.GetNextPosition();
// next_vec[index + 1] = x;
// index++;
// }
//------------------------
for (int i = 0; i < text.size(); i++) {
_font.SetChar(text[i]);
ax::Point d = _font.GetDelta();
ax::Point txtPos(
x + d.x, line_pos.y - d.y + _font.GetFontSize());
ax::Rect txtRect(txtPos, _font.GetSize());
gc.DrawTexture(_font.GetTexture(), txtRect);
x += _font.GetNextPosition();
next_vec[i + 1] = x;
}
}
_next_pos_data.push_back(next_vec);
line_pos += ax::Point(0, 15);
}
// Line cursor.
ax::Point cursor_index = FileCursorPosToNextPosIndex();
if (cursor_index.x != -1 && cursor_index.y != -1) {
// ax::Print("Draw cursor");
int x = _next_pos_data[cursor_index.y][cursor_index.x];
int y = cursor_index.y * _line_height;
gc.SetColor(_info.cursor_color);
// gc.SetColor(ax::Color(1.0f, 0.0f, 0.0f));
gc.DrawLine(ax::Point(x, y), ax::Point(x, y + _line_height));
}
} |
3d7d9fa01703098c64de8df3e6baba150eaa455c | 7d23b7237a8c435c3c4324f1b59ef61e8b2bde63 | /include/win32/mmap/detail/file_mapping.hpp | d485283d15e35269773a3a5c0c08d19b0be695af | [] | no_license | chenyu2202863/smart_cpp_lib | af1ec275090bf59af3c29df72b702b94e1e87792 | 31de423f61998f3b82a14fba1d25653d45e4e719 | refs/heads/master | 2021-01-13T01:50:49.456118 | 2016-02-01T07:11:01 | 2016-02-01T07:11:01 | 7,198,248 | 4 | 3 | null | null | null | null | GB18030 | C++ | false | false | 4,348 | hpp | file_mapping.hpp | #ifndef __MMAP_FILEMAPPING_HPP
#define __MMAP_FILEMAPPING_HPP
#include "map_file.hpp"
#include "access_buffer.hpp"
namespace mmap
{
// -------------------------------------------------------------------------
// class HandleProxy
template < typename Owner >
class proxy_t
{
public:
typedef typename Owner::size_type size_type;
typedef typename Owner::pos_type pos_type;
typedef typename Owner::Utils Utils;
private:
Owner &owner_;
public:
enum { AllocationGranularityBits= Owner::AllocationGranularityBits };
enum { AllocationGranularity = Owner::AllocationGranularity };
enum { AllocationGranularityMask= Owner::AllocationGranularityMask };
public:
proxy_t(Owner &owner)
: owner_(owner)
{}
public:
char *view_segment(DWORD dwBasePage, DWORD dwPageCount)
{
return owner_.view_segment(dwBasePage, dwPageCount);
}
char *access_segment(DWORD dwBasePage, DWORD dwPageCount)
{
return owner_.access_segment(dwBasePage, dwPageCount);
}
char *alloc_segment(DWORD dwBasePage, DWORD dwPageCount)
{
return owner_.alloc_segment(dwBasePage, dwPageCount);
}
};
// -------------------------------------------------------------------------
// class FileMapping
// 对MapFile的一层包装,提供边界对齐的保护操作
template<typename ConfigT>
class file_mapping_t
: public map_file_t<ConfigT>
{
private:
typedef map_file_t<ConfigT> base_type;
public:
typedef typename base_type::size_type size_type;
typedef typename base_type::pos_type pos_type;
typedef proxy_t<file_mapping_t> HandleType;
typedef base_type Utils;
private:
DWORD total_pages_;
enum { _AGBits = 16 };
// 分配粒度
enum { _AllocationGranularityInvBits = sizeof(DWORD) * 8 - _AGBits };
public:
enum { AllocationGranularityBits = _AGBits };
enum { AllocationGranularity = (1 << _AGBits) };
enum { AllocationGranularityMask = (AllocationGranularity - 1) };
private:
file_mapping_t(const file_mapping_t &);
file_mapping_t &operator=(const file_mapping_t &);
public:
file_mapping_t()
: total_pages_(0)
{}
template < typename CharT >
file_mapping_t(const std::basic_string<CharT> &path, pos_type *offset = NULL)
{
open(path, offset);
}
public:
DWORD total_pages() const
{
return total_pages_;
}
void close()
{
base_type::close();
total_pages_ = 0;
}
bool resize(pos_type size)
{
total_pages_ = (size + AllocationGranularityMask) >> AllocationGranularityBits;
return base_type::resize(size);
}
template < typename CharT >
bool open(const std::basic_string<CharT> &path, pos_type *offset = 0)
{
if( ConfigT::GetSizeOnOpen )
{
pos_type size = 0;
bool hRes = base_type::open(path, &size);
total_pages_ = static_cast<DWORD>((size + AllocationGranularityMask) >> AllocationGranularityBits);
if( offset != 0 )
*offset = size;
return hRes;
}
else
{
total_pages_ = 0;
return base_type::open(path, 0);
}
}
char *view_segment(DWORD dwBasePage, DWORD dwPageCount)
{
assert(base_type::good());
if( dwBasePage + dwPageCount > total_pages_ )
{
if( dwBasePage >= total_pages_ )
return 0;
else
dwPageCount = total_pages_ - dwBasePage;
}
return reinterpret_cast<char *>(base_type::map(dwBasePage << AllocationGranularityBits, dwPageCount << AllocationGranularityBits));
}
char *access_segment(DWORD dwBasePage, DWORD dwPageCount)
{
assert(base_type::good());
if( dwBasePage + dwPageCount > total_pages_ )
{
total_pages_ = dwBasePage + dwPageCount;
base_type::resize(total_pages_ << AllocationGranularityBits);
}
return reinterpret_cast<char *>(base_type::map(dwBasePage << AllocationGranularityBits, dwPageCount << AllocationGranularityBits));
}
char *alloc_segment(DWORD dwBasePage, DWORD dwPageCount)
{
assert(base_type::good());
dwBasePage += total_pages_;
total_pages_ += dwPageCount;
base_type::resize(total_pages_ << AllocationGranularityBits);
return reinterpret_cast<char *>(base_type::map(dwBasePage << AllocationGranularityBits, dwPageCount << AllocationGranularityBits));
}
};
typedef file_mapping_t<mapping_readwrite> file_mapping_readwrite;
typedef file_mapping_t<mapping_readonly> file_mapping_readonly;
}
#endif |
61a0951ea1c1939f08660a565b4be212b78267d4 | c7273a49160e9413e85a91e36bc4a2fea7306db6 | /online/decoder_maindaq/DecoParam.h | fe72e502821891f7da8c2bfcef1e91b4206f0508 | [] | no_license | liuk/e1039-core | f04467e3ffdb0592528c48da069d96245cb7ff34 | 2bbff57544dc2bce70bfa0aa87129be2e719c63e | refs/heads/master | 2022-07-26T08:04:24.899781 | 2022-05-31T13:21:15 | 2022-05-31T13:21:15 | 195,715,486 | 0 | 1 | null | 2019-10-21T01:12:29 | 2019-07-08T01:27:24 | C++ | UTF-8 | C++ | false | false | 1,792 | h | DecoParam.h | #ifndef __DECO_PARAM_H__
#define __DECO_PARAM_H__
#include <geom_svc/ChanMapTaiwan.h>
#include <geom_svc/ChanMapV1495.h>
#include <geom_svc/ChanMapScaler.h>
//#include "assert.h"
class EventInfo;
/** This class contains all decoder parameters.
* Two types of parameters are included.
* - For controlling the decoder behavior.
* - For monitoring the condition of the decoder.
*/
struct DecoParam {
///
/// Control parameters
///
std::string fn_in;
std::string dir_param;
bool is_online;
int sampling;
int verb; ///< Verbosity. 0 = error, 1 = warning, 2 = info, 3 = debug, 4 = insane
int time_wait; ///< waiting time in second to pretend the online data flow.
ChanMapTaiwan chan_map_taiwan;
ChanMapV1495 chan_map_v1495;
ChanMapScaler chan_map_scaler;
///
/// Monitoring parameters
///
unsigned short int runID;
int spillID;
int spillID_cntr; // spillID from spill-counter event
int spillID_slow; // spillID from slow-control event
short targPos;
short targPos_slow; // from slow-control event
unsigned int event_count; ///< current event count
unsigned int codaID; ///< current Coda event ID
short spillType; ///< current spill type
short rocID; ///< current ROC ID
int eventIDstd; ///< current event ID of standard physics events
long int hitID; ///< current hit ID, commonly used by Hit and TriggerHit.
bool has_1st_bos; ///< Set 'true' at the 1st BOS event.
bool at_bos; ///< Set 'true' at BOS, which triggers parsing the data in one spill.
/// Max turnOnset in a spill. Used to drop NIM3 events that came after the beam stops. See elog 15010
unsigned int turn_id_max;
// Benchmarking Values
time_t timeStart, timeEnd;
DecoParam();
~DecoParam() {;}
int InitMapper();
};
#endif // __DECO_PARAM_H__
|
16bfa9c4c575bc4859a62db9694520b7338270eb | 174fb4289a0401c517ee2dd4fb8826f1cba4142a | /src/potentials/potential_harmonic.cpp | 05f283d8d77d832fc41118880cc6a553364dceb3 | [] | no_license | ansko/CppMd | cf1c800c0011476764c1238116915bea79143108 | 31d0fdba43eb6fbf14d2f81839d45345a232550c | refs/heads/master | 2021-08-23T09:03:02.670684 | 2017-12-04T12:13:07 | 2017-12-04T12:13:07 | 112,761,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | potential_harmonic.cpp | #include "potential_harmonic.hpp"
float PotentialHarmonic::E(std::shared_ptr<Bond> bond_ptr)
{
std::shared_ptr<Particle> par1_ptr = bond_ptr->getParticle1_ptr();
std::shared_ptr<Particle> par2_ptr = bond_ptr->getParticle2_ptr();
float x = par2_ptr->x() - par1_ptr->x();
float y = par2_ptr->y() - par1_ptr->y();
float z = par2_ptr->z() - par1_ptr->z();
float l = pow(pow(x, 2) + pow(y, 2) + pow(z, 2), 0.5);
float E = K_HAR * pow(bond_ptr->dl(), 2) / 2;
return E;
}
std::vector<float> PotentialHarmonic::F(std::shared_ptr<Bond> bond_ptr)
{
std::shared_ptr<Particle> par1_ptr = bond_ptr->getParticle1_ptr();
std::shared_ptr<Particle> par2_ptr = bond_ptr->getParticle2_ptr();
float x = par2_ptr->x() - par1_ptr->x();
float y = par2_ptr->y() - par1_ptr->y();
float z = par2_ptr->z() - par1_ptr->z();
float l = pow(pow(x, 2) + pow(y, 2) + pow(z, 2), 0.5);
float F = -K_HAR * bond_ptr->dl();
F_xyz[0] = F * x / l;
F_xyz[1] = F * y / l;
F_xyz[2] = F * z / l;
return F_xyz;
}
|
8ddfd7c6f7ed9b7ae38a897d1a27a37b2a052d8d | d046106c706374aea31449e757f9d0898684da18 | /APIMode/WithLibrary/XBeeLib/XBeeLib.h | bdf66700941ee744e05c55c3ab3bb1d6d89a12d6 | [] | no_license | leomr85/ArduinoTeam | c96a7175dda5c0620c038245880b7d78ed13833b | a965cfd40d9900403f33b036c4ee25bd743bd347 | refs/heads/master | 2016-09-01T19:46:16.199350 | 2014-11-27T12:24:09 | 2014-11-27T12:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | h | XBeeLib.h | /*
XBeeLib - Library for XBee Modules.
Created by Leonardo M. Rodrigues, July 17, 2014.
Released into the puclic domain.
*/
#ifndef XBeeLib_h
#define XBeeLib_h
#include "Arduino.h"
class XBeeLib
{
public:
XBeeLib(int coordinatorEnable);
void helloWorld();
void waitFor(long time);
void txRequest(String* message);
void rxPacket();
String getStatus();
void getBattVoltage(long *battVoltage);
void setPayload(String message);
String getPayload();
String* getPayloadAddress();
void setReceived(String message);
void addReceived(String item);
void clearReceived();
String getReceived();
int getCoordinatorEnabled();
void setCoordinatorEnabled(int type);
private:
// Coordinator Enable (0 = Device | 1 = Coordinator).
int _coordinatorEnabled;
// Frame payload.
String _payload;
// Payload received in the frame.
String _received;
};
#endif |
71fedd23020a12c5052d9aff0e4a6ed6ddd91911 | 1fdd12563de929f934fcdda811cad259f100b8b1 | /lab1Words/wordsparser.h | 6f4b9ce03d4bc750711cac63bd5f72a0ac86fe6b | [] | no_license | alexandrprotasenya/OOPLabs | 07d71189fb73030b1b8ad36c25e49f4e8f02ddff | b09106a61451d5b00dc948a7abc5f03304ef1592 | refs/heads/master | 2021-05-29T23:03:39.037404 | 2015-12-02T07:47:32 | 2015-12-02T07:47:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | h | wordsparser.h | #ifndef WORDSPARSER_H
#define WORDSPARSER_H
#include "pc_header.h"
class WordsParser
{
public:
WordsParser();
void printWords();
void printStr();
void setStr(char* str) {
m_str = str;
}
private:
char* m_str;
int get_word( const char *s, int &size, int start = 0 );
};
#endif // WORDSPARSER_H
|
a19ce3f69630130e2f20bc0b67a648a3632e0912 | 36e5c06883c0288dc48e3978ca9deaf6d6a9bffc | /src/assert/assert.hpp | 18acbb1806478ab2de4709e03f4aed5d362001ad | [
"MIT"
] | permissive | cwbaker/forge | 46271bc05311ce64b09e2c6e2311f51a124761c2 | 18b7ec97769354b28189d390474bd22473537f49 | refs/heads/main | 2022-11-19T17:13:46.367043 | 2022-11-11T07:23:23 | 2022-11-11T07:23:23 | 3,674,381 | 14 | 2 | MIT | 2022-09-07T04:20:33 | 2012-03-09T20:16:16 | C++ | UTF-8 | C++ | false | false | 1,767 | hpp | assert.hpp | #ifndef SWEET_ASSERT_ASSERT_HPP_INCLUDED
#define SWEET_ASSERT_ASSERT_HPP_INCLUDED
#if defined(BUILD_MODULE_ASSERT) && defined(BUILD_LIBRARY_TYPE_DYNAMIC)
#define SWEET_ASSERT_DECLSPEC __declspec(dllexport)
#elif defined(BUILD_LIBRARY_TYPE_DYNAMIC)
#define SWEET_ASSERT_DECLSPEC __declspec(dllimport)
#else
#define SWEET_ASSERT_DECLSPEC
#endif
#include <build.hpp>
/**
Assertion library.
The assert component provides the macro SWEET_ASSERT(<em>e</em>) for
asserting that assumptions are true at runtime. The macro compiles to code
to generate a __debugbreak() call if the expression is false when the macro
SWEET_ASSERT_ENABLED is defined and to nothing otherwise.
An assert function (sweet_assert()) is provided for situations where a macro
doesn't work. Lua code uses assertions in expressions in a way that requires
they be in a function.
*/
#ifdef __cplusplus
extern "C"
{
#endif
SWEET_ASSERT_DECLSPEC void sweet_break( void );
SWEET_ASSERT_DECLSPEC void sweet_assert( int expression, const char* description, const char* file, int line );
SWEET_ASSERT_DECLSPEC void sweet_assert_with_break( int expression, const char* description, const char* file, int line );
#ifdef __cplusplus
}
#endif
#ifdef _MSC_VER
#define SWEET_BREAK() __debugbreak()
#elif defined(BUILD_OS_MACOSX)
#define SWEET_BREAK() __asm__("int $3")
#else
#define SWEET_BREAK() sweet_break()
#endif
#ifdef SWEET_ASSERT_ENABLED
#define SWEET_ASSERT( x ) \
do { \
if ( !(x) ) \
{ \
sweet_assert( false, #x, __FILE__, __LINE__ ); \
SWEET_BREAK(); \
} \
} while ( false )
#else
#ifdef _MSC_VER
#pragma warning( disable: 4127 )
#endif
#define SWEET_ASSERT( x )
#endif
#endif
|
9c996981dc837755f6d5ccdc086250227dcb8e4a | 96b8e40f7a163c82dadc85b461cfd6342706c829 | /hashTableTest.cpp | 3cdf00523641d2596846e8fd7875bb0d723b6caf | [] | no_license | krisli210/Cheaters | 0048517c3dd24f65b5fcddc6c787a44533dc8c59 | da0722f51c962cf9b038bdfb5cfa7e99019782de | refs/heads/master | 2020-04-09T00:24:53.545854 | 2018-12-07T20:43:04 | 2018-12-07T20:43:04 | 159,865,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | cpp | hashTableTest.cpp | #include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "hashTable.h"
using namespace std;
int main() {
const int ts = 393241;
HASH_TABLE<int, ts> ht;
cout << ht.getTableSize() << endl;
string key1 = "hereisakey" ;
string key2 = "hereisalsoakey";
string key3 = "notlikeothers";
cout << ht.getKey(key1) << endl ;
cout << ht.getKey(key2) << endl ;
cout << ht.getKey(key3) << endl ;
ht.add(ht.getKey(key1), 42) ;
ht.add(ht.getKey(key2), 50) ;
ht.add(ht.getKey(key3), 3) ;
cout << ht.getKey(key3) << endl ;
vector<int> results = ht.getItemsAtKey(ht.getKey(key1)) ;
cout << "Added and retrieved: " << results[0] << endl ;
results = ht.getItemsAtKey(ht.getKey(key2)) ;
cout << "Added and retrieved: " << results[0] << endl ;
results = ht.getItemsAtKey(ht.getKey(key3));
cout << "Added and retrieved: " << results[0] << endl ;
/* int keys[] = {0, 1, 47, 99, 100, -1, 1, 3}; //8 Keys
int values[] = {42, 42, 42, 42, 42, 42, 56}; //7 Values
for(int i = 0; i < 7; i++){
ht.add(keys[i], values[i]);
}
for(int i = 0; i <8; i++){
cout << "Key " << keys[i] << ": ";
vector<int> results = ht.getItemsAtKey(keys[i]);
for(int j = 0; j < results.size(); j++) {
cout << results[j] << ", ";
}
cout << "(size " << ht.numItemsAtKey(i) << endl;
}
cout << ht.inTable(1, 32) << endl;
for(int i = 0; i <8; i++){
cout << "Key " << keys[i] << ": " << ht.inTable(keys[i], values[i]) << endl;
}
ht.remove(1, 42);
int i = 1;
vector<int> results = ht.getItemsAtKey(keys[i]);
for(int j = 0; j < results.size(); j++) {
cout << results[j] << ", ";
}
cout << "(size " << ht.numItemsAtKey(i) << endl;
for(int i = 0; i < 8; i++) {
ht.remove(keys[i], values[i]);
}
for(int i = 0; i <8; i++){
cout << "Key " << keys[i] << ": ";
vector<int> results = ht.getItemsAtKey(keys[i]);
for(int j = 0; j < results.size(); j++) {
cout << results[j] << ", ";
}
cout << "(size " << ht.numItemsAtKey(i) << endl;
}
ht.remove(1, 32);
*/
return 0;
}
|
5f83e22f80aab070c35c5a243dc18a6e8981d7a7 | 1a3fd15e9be7cf0ca6f0895e240f318043414da7 | /groups/1506-3/sannikova_vo/1-test-version/solver.cpp | 29aa6475168d3127b30bdb0d43ef7aa9ee22fe5f | [] | no_license | alvls/parprog-2018-1 | 09e2ea3d502165cdc6b9e1d50d4e17ab51b92628 | 293c76b89373669288b7cb454f32e3a7838f4758 | refs/heads/master | 2021-04-28T07:19:33.028962 | 2018-07-05T06:29:28 | 2018-07-05T06:29:28 | 122,221,726 | 0 | 52 | null | 2018-07-05T06:29:29 | 2018-02-20T16:09:14 | C++ | WINDOWS-1251 | C++ | false | false | 7,392 | cpp | solver.cpp | #include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <chrono>
#include <iostream>
#include <random>
#include "math.h"
#define MAXSTACK 2048
using namespace std;
void qSort_NO_recursion(vector<double>::iterator begin, vector<double>::iterator end)
{
long i, j; // указатели, участвующие в разделении
long lb, ub; // границы сортируемого в цикле фрагмента
long lbstack[MAXSTACK], ubstack[MAXSTACK]; // стек запросов
// каждый запрос задается парой значений,
// а именно: левой(lbstack) и правой(ubstack)
// границами промежутка
long stackpos = 1; // текущая позиция стека
long ppos; // середина массива
double pivot; // опорный элемент
//vector<double>::iterator temp;
double temp;
lbstack[1] = 0;
ubstack[1] = distance(begin, end)-1;
do {
// Взять границы lb и ub текущего массива из стека.
lb = lbstack[stackpos];
ub = ubstack[stackpos];
stackpos--;
do {
// Шаг 1. Разделение по элементу pivot
ppos = (lb + ub) >> 1; //середина
i = lb;
j = ub;
pivot = *(begin + ppos); // vec[ppos];
do {
while (/*a[i]*/ *(begin+i) < pivot)
i++;
while (pivot < /*a[j]*/ *(begin+j))
j--;
if (i <= j) {
temp = *(begin + i); // a[i];
*(begin + i) = *(begin + j); //a[i] = a[j];
*(begin + j) = temp; //a[j] = temp;
i++;
j--;
}
} while (i <= j);
// Сейчас указатель i указывает на начало правого подмассива,
// j - на конец левого (см. иллюстрацию выше), lb ? j ? i ? ub.
// Возможен случай, когда указатель i или j выходит за границу массива
// Шаги 2, 3. Отправляем большую часть в стек и двигаем lb,ub
if (i < ppos) { // правая часть больше
if (i < ub) { // если в ней больше 1 элемента - нужно
stackpos++; // сортировать, запрос в стек
lbstack[stackpos] = i;
ubstack[stackpos] = ub;
}
ub = j; // следующая итерация разделения
// будет работать с левой частью
}
else { // левая часть больше
if (j > lb) {
stackpos++;
lbstack[stackpos] = lb;
ubstack[stackpos] = j;
}
lb = i;
}
} while (lb < ub); // пока в меньшей части более 1 элемента
} while (stackpos != 0); // пока есть запросы в стеке
}
//главная функция для дальнейшей работы
void qSort(vector<double>::iterator begin, vector<double>::iterator end)
{
int first = 0;
int length = distance(begin, end);
int last = distance(begin, end) - 1;
double elem = *(begin + ((first + last) >> 1));
do {
while (*(begin + first) < elem)
first++;
while (*(begin + last) > elem)
last--;
if (first <= last) {
double temp = *(begin + first);
*(begin + first) = *(begin + last);
*(begin + last) = temp;
first++;
last--;
}
} while (first <= last);
if (last > 0)
qSort(begin, begin + last + 1);
if (first < distance(begin, end))
qSort(begin + first, end);
}
//обертка
void qSort(vector <double>* vec) {
vector<double>::iterator begin = vec->begin();
vector<double>::iterator end = vec->end();
qSort(begin, end);
}
void qSort_array_recursion(double* arr, int size)
{
int first = 0;
int last = size - 1;
double elem = arr[size / 2];
do {
while (arr[first] < elem)
first++;
while (arr[last] > elem)
last--;
if (first <= last) {
double tmp = arr[first];
arr[first] = arr[last];
arr[last] = tmp;
first++;
last--;
}
} while (first <= last);
if (last > 0)
qSort_array_recursion(arr, last + 1);
if (first < size)
qSort_array_recursion(&arr[first], size - first);
}
//печать массива для чека в мэйне
void printArray(double* arr, int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int Partition(double items[], int first, int last, double pivot) { //разделение по номеру элемента, слева будут все элементы < pivot
int j = first - 1;
for (int i = first; i <= last; ++i) {
if (items[i] < pivot) {
std::swap(items[++j], items[i]);
}
}
return j; //позиция pivot
}
int PartitionByIndex(double items[], int first, int last, int index) { //разделение по индексу
std::swap(items[index], items[last]);
int i = 1 + Partition(items, first, last, items[last]);
std::swap(items[i], items[last]);
return i; //позиция на которой стоит элемент который стоял на позиции index
}
void Select(double items[], int first, int last, int index) { //выбор участка массива
int i = PartitionByIndex(items, first, last, (first + last) / 2); //выбираем новую позицию медианы
if (i > index) { //если новая позиция медианы больше индекса
Select(items, first, i - 1, index); //то выбираем левую часть до нового индекса
}
else if (i < index) {
Select(items, i + 1, last, index); //выбираем правую часть после нового индекса
}
}
#pragma once
#include <iostream>
void QuickSort(double items[], int size/*int first, int last*/) { //быстрая рекурсивная сортировка
int i = PartitionByIndex(items, 0, size - 1, (size - 1) / 2);
if (i - 1 > 0/*first*/) {
QuickSort(items, i /*first, i - 1*/);
}
if (i + 1 < size - 1/*last*/) {
QuickSort(&items[i + 1], size - i - 1 /* i + 1, last*/);
}
}
#pragma once
#include <iostream>
#include <algorithm>
#include <cmath>
#include <omp.h>
using namespace std;
void QuickSort_OpenMP(double items[], int size /*int first, int last*/, int deep, int maxDeep) { //0, 8
if (deep >= maxDeep) { //если текушаю глубина больше максимальной
QuickSort(items, size /*first, last*/); //просто выполняем сортировку
}
else {
int i = /*(first + last)*/ (size - 1) / 2; //иначе мы выбираем серединный элемент
Select(items, 0, size - 1, i);
//Select(items, size/*first, last*/, i); //и выполняем выборку
#pragma omp parallel
{
#pragma omp sections nowait
{
#pragma omp section
if (i - 1 > 0/*first*/) {
QuickSort_OpenMP(items, i/*first, i - 1*/, deep + 1, maxDeep);
}
#pragma omp section
if (i + 1 < size - 1/*last*/) {
QuickSort_OpenMP(&items[i + 1], size - i - 1/*i + 1, last*/, deep + 1, maxDeep);
}
}
}
}
}
void QuickSort_OpenMP(double items[], int size /*int first, int last*/) {
int maxDeep = (int)(ceil(log((double)omp_get_num_procs()) / log(2.0))); //максимальная глубина рекурсиии если 8 потоков то 3
QuickSort_OpenMP(items, size /*first, last*/, 0, maxDeep);
}
|
95d1bc9e9a2f9c0b22d00e92fa0c2f76c1b67489 | bdf70a0995bf5251561c490a42a732950186fe06 | /Engine/Src/Ancona/Menu/Screens/MenuGameSystems.hpp | df2e2a86867cb85107ea4d1d54e0be3f2474fcc2 | [
"MIT"
] | permissive | ild-games/Ancona | f48761d0d069ee6d15cdf4ae3b661943e48931bb | 6a4f520f97d17648a6dd3ba0582cd51da4f9e809 | refs/heads/develop | 2023-03-05T06:33:59.538272 | 2021-11-24T20:05:40 | 2021-11-24T20:05:40 | 42,762,744 | 13 | 4 | MIT | 2021-11-24T20:05:57 | 2015-09-19T06:36:27 | C++ | UTF-8 | C++ | false | false | 2,312 | hpp | MenuGameSystems.hpp | #ifndef Anona_Menu_Systems_MenuGameSystems_H_
#define Anona_Menu_Systems_MenuGameSystems_H_
#include <Ancona/Core2D/Systems/CameraSystem.hpp>
#include <Ancona/Core2D/Systems/RotateSystem.hpp>
#include <Ancona/Core2D/Systems/Drawable/DrawableSystem.hpp>
#include <Ancona/Core2D/Systems/InputControlSystem.hpp>
#include <Ancona/Core2D/Systems/Collision/CollisionSystem.hpp>
#include <Ancona/Core2D/Systems/Audio/SoundSystem.hpp>
#include <Ancona/Core2D/Systems/Audio/MusicSystem.hpp>
#include <Ancona/Core2D/Systems/Audio/AutoStartMusicSystem.hpp>
#include <Ancona/Framework/EntityFramework/SystemManager.hpp>
#include <Ancona/Framework/Screens/ScreenManager.hpp>
#include <Ancona/Framework/Systems/ScreenSystemsContainer.hpp>
#include <Ancona/Platformer/Actions/ActionSystem.hpp>
#include "../Systems/ButtonSystem.hpp"
namespace ildmenu
{
/**
* @brief GameSystems used by the menu screen.
*/
class MenuGameSystems : public ild::ScreenSystemsContainer
{
public:
/**
* @brief Constructs the game systems for menu screen.
* @param screenManager Screen Manager for the game.
*/
MenuGameSystems(ild::ScreenManager & screenManager);
/* getters and setters */
ild::DrawableSystem & drawable() { return *_drawable; }
ild::InputControlSystem & input() { return *_input; }
ild::PositionSystem & position() { return *_position; }
ild::ActionSystem & action() { return *_action; }
ild::CameraSystem & camera() { return *_camera; }
ild::CollisionSystem & collision() { return *_collision; }
ild::SoundSystem & sound() { return *_sound; }
ild::MusicSystem & music() { return *_music; }
ild::AutoStartMusicSystem & autoStartMusic() { return *_autoStartMusic; }
ButtonSystem & button() { return *_button; }
ild::CollisionType nullCollision() { return 0; }
private:
ild::DrawableSystem * _drawable;
ild::InputControlSystem * _input;
ild::PositionSystem * _position;
ild::CameraSystem * _camera;
ild::CollisionSystem * _collision;
ild::ActionSystem * _action;
ild::SoundSystem * _sound;
ild::MusicSystem * _music;
ild::AutoStartMusicSystem * _autoStartMusic;
ButtonSystem * _button;
};
}
#endif
|
7ec4990744b56bf00b78c4903397f97922f58c96 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /remoting/host/audio_volume_filter_unittest.cc | d4d97c63e9166890493240338037fbe1f4afd188 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 2,427 | cc | audio_volume_filter_unittest.cc | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/audio_volume_filter.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
namespace {
class FakeAudioVolumeFilter : public AudioVolumeFilter {
public:
FakeAudioVolumeFilter(int silence_threshold)
: AudioVolumeFilter(silence_threshold) {}
~FakeAudioVolumeFilter() override = default;
void set_audio_level(float level) { level_ = level; }
protected:
float GetAudioLevel() override { return level_; }
private:
float level_ = 0;
};
} // namespace
TEST(AudioVolumeFilterTest, TwoChannels) {
int16_t samples[] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5,
6, 6, 7, 7, 8, 8, 9, 9, 10, 10};
FakeAudioVolumeFilter filter(0);
filter.set_audio_level(0.5f);
filter.Initialize(9, 2);
// After applying the audio volume, the |samples| should still pass the
// AudioSilenceDetector, AudioVolumeFilter::Apply() returns true under this
// condition. Ditto.
ASSERT_TRUE(filter.Apply(samples, std::size(samples) / 2));
}
TEST(AudioVolumeFilterTest, ThreeChannels) {
int16_t samples[] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6,
6, 7, 7, 8, 8, 9, 9, 10, 10, 11};
FakeAudioVolumeFilter filter(0);
filter.set_audio_level(0.5f);
filter.Initialize(6, 3);
ASSERT_TRUE(filter.Apply(samples, std::size(samples) / 3));
}
TEST(AudioVolumeFilterTest, SilentSamples) {
int16_t samples[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
FakeAudioVolumeFilter filter(0);
filter.set_audio_level(0.5f);
filter.Initialize(9, 2);
ASSERT_FALSE(filter.Apply(samples, std::size(samples) / 2));
}
TEST(AudioVolumeFilterTest, AudioLevel0) {
int16_t samples[] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5,
6, 6, 7, 7, 8, 8, 9, 9, 10, 10};
FakeAudioVolumeFilter filter(0);
filter.set_audio_level(0);
filter.Initialize(9, 2);
ASSERT_FALSE(filter.Apply(samples, std::size(samples) / 2));
}
TEST(AudioVolumeFilterTest, SilentAfterApplying) {
int16_t samples[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
FakeAudioVolumeFilter filter(0);
filter.set_audio_level(0.9f);
filter.Initialize(9, 2);
ASSERT_TRUE(filter.Apply(samples, std::size(samples) / 2));
}
} // namespace remoting
|
233b82ab4ef447f8d94d1fd6ddb952567cf63f7e | f3cd9679cb127414dfd9703659b4ea66ef10b7b6 | /die-tk/Surface.h | 51421f8a529e72eabeb36c6d4b61b72a13100a13 | [
"Artistic-2.0"
] | permissive | thinlizzy/die-tk | 04f0ea4b5ef5cd596fe37e5f7f09f22d21c32a6b | eba597d9453318b03e44f15753323be80ecb3a4e | refs/heads/master | 2021-07-04T10:44:25.246912 | 2021-06-03T22:26:45 | 2021-06-03T22:26:45 | 45,441,362 | 11 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,443 | h | Surface.h | #ifndef SURFACE_H_DIE_TK_2014_09_22_22_08
#define SURFACE_H_DIE_TK_2014_09_22_22_08
#include <memory>
#include "Callbacks.h"
#include "WindowObjects.h"
#include "custom/CustomControlImpl.h"
namespace tk {
class Canvas;
class NativeControlImpl;
/** Base class for all widgets, including windows. */
class Surface {
protected:
Surface() = default;
public:
Surface(Surface const &) = default;
Surface & operator=(Surface const &) = default;
Surface(Surface &&) = default;
Surface & operator=(Surface &&) = default;
virtual ~Surface();
explicit operator bool() const;
int x() const;
int y() const;
Point pos() const;
int width() const;
int height() const;
WDims dims() const;
Rect rect() const;
Surface & setPos(Point pos);
Surface & setDims(WDims dims);
Surface & setRect(Rect rect);
NativeString getText() const;
Surface & setText(NativeString const & text);
ClipboardType copyToClipboard() const;
void bringToFront();
void sendToBack();
bool enabled() const;
void enable();
void disable();
void setEnabled(bool enabled);
bool visible() const;
void show();
void hide();
void setVisible(bool visible);
Canvas & canvas();
void repaint();
void invalidate(Rect const & rect);
void setCursor(Cursor cursor);
void setBackground(RGBColor const & color);
void clear(RGBColor const & color = RGBColor());
Point screenToClient(Point const & point) const;
void addCustomControlImpl(std::shared_ptr<CustomControlImpl> const & controlImpl);
HandleMouseButton onMouseDown(HandleMouseButton callback);
HandleMouseButton onMouseUp(HandleMouseButton callback);
HandleMouseMove onMouseEnter(HandleMouseMove callback);
HandleMouseMove onMouseOver(HandleMouseMove callback);
HandleMouseMove onMouseLeave(HandleMouseMove callback);
protected:
std::shared_ptr<NativeControlImpl> impl;
// most used callbacks
ProcessKeyEvent onKeyDown(ProcessKeyEvent callback); // window, edit, memo
ProcessKeyEvent onKeyUp(ProcessKeyEvent callback); // window, edit, memo
ProcessKeypress onKeypress(ProcessKeypress callback); // window, edit, memo
// seldom used callbacks
HandlePaint onPaint(HandlePaint callback); // window, paintbox and custom controls
HandleOperation onFocus(HandleOperation callback); // window and controls that make sense to have focus
HandleOperation onLostFocus(HandleOperation callback); // window and controls that make sense to have focus
};
}
#endif
|
002ef48d5ac6f8cccd9d1c680c11a5259306635d | 39e4a82a5d9a35a2c7b73a9d3f3ce3f5d4793e23 | /filemanager apha 0.1(源码)/standard.h | 29d5e74ab45844a94f0a49a640722363e1f0029c | [] | no_license | jzy-byte-cmd/filemanager | 2fc13cf927c85398c0f3d9bc7a796e37b5e6a5b8 | f2942af903c90afc29e9dd9e5ad034fe2f06040a | refs/heads/master | 2023-08-17T14:37:04.150579 | 2021-10-03T16:06:19 | 2021-10-03T16:06:19 | 413,115,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | standard.h | #include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <tchar.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <algorithm>
//标准头文件
using std::cout;
using std::endl;
using std::cin;
using std::cerr;
using std::clog;
using std::abs;
using std::ios;
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::sort;
using std::fstream;
using std::find;
|
5c76c5c4a6dda315f48aba60527b442f698db650 | f08225aa3689ef23e68b0f516c12f4bda1f8280d | /complex/complex.cpp | 51b6704dc21e2e5ed48731b20cb0857395b6200f | [] | no_license | mind2cloud/MISiS_2nd_course_CPP_Tasks | 75782c26d8d1845def1f31c4e671646922814bd4 | 9b57b25b34e690b60296b2adb30b8e8ed4ee2622 | refs/heads/master | 2023-01-06T05:33:17.173392 | 2020-11-06T21:45:59 | 2020-11-06T21:45:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,206 | cpp | complex.cpp | #include "complex.h"
#include <iostream>
#include <cmath>
Complex::Complex(const double real)
: Complex(real, 0.0)
{
}
Complex::Complex(const double real, const double imaginary)
: re(real)
, im(imaginary)
{
}
Complex& Complex::operator=(const Complex& complex)
{
re = complex.re;
im = complex.im;
return *this;
}
bool Complex::operator==(const Complex& rhs) const
{
double eps0(0.0000001);
return (abs(re - rhs.re) < eps0 ) && (abs(im - rhs.im) < eps0);
}
bool Complex::operator!=(const Complex& rhs) const
{
return !operator==(rhs);
}
Complex& Complex::operator+=(const Complex& rhs)
{
re += rhs.re;
im += rhs.im;
return *this;
}
Complex& Complex::operator+=(const double number)
{
re += number;
im += number;
return *this;
}
Complex& Complex::operator-=(const Complex& rhs)
{
re -= rhs.re;
im -= rhs.im;
return *this;
}
Complex& Complex::operator-=(const double number)
{
re -= number;
im -= number;
return *this;
}
Complex& Complex::operator*=(const Complex& rhs)
{
re = re * rhs.re - im * rhs.im;
im = re * rhs.im + rhs.re * im;
return *this;
}
Complex& Complex::operator*=(const double number)
{
re *= number;
im *= number;
return *this;
}
Complex& Complex::operator/=(const Complex& rhs)
{
re = (re * rhs.re + im * rhs.im) / (rhs.re * rhs.re + rhs.im * rhs.im);
im = (im * rhs.re - re * rhs.im) / (rhs.re * rhs.re + rhs.im * rhs.im);
return *this;
}
Complex& Complex::operator/=(const double number)
{
re /= number;
im /= number;
return *this;
}
// Cопряженное комплексное число.
Complex Complex::conjugateNumber()
{
Complex complex;
complex.re = re;
complex.im = -im;
return complex;
}
Complex operator+(const Complex& lhs, const Complex& rhs)
{
Complex sum(lhs);
sum += rhs;
return sum;
}
Complex operator+(const double number, const Complex& rhs)
{
Complex sum(rhs);
sum += number;
return sum;
}
Complex operator+(const Complex& lhs, const double number)
{
Complex sum(lhs);
sum += number;
return sum;
}
Complex operator-(const Complex& lhs, const Complex& rhs)
{
return Complex(lhs.re - rhs.re, lhs.im - rhs.im);
}
Complex operator-(const double number, const Complex& rhs)
{
Complex sum(rhs);
sum -= number;
return sum;
}
Complex operator-(const Complex& lhs, const double number)
{
Complex sum(lhs);
sum -= number;
return sum;
}
Complex operator*(const Complex& lhs, const Complex& rhs)
{
Complex complex(lhs);
complex *= rhs;
return complex;
}
Complex operator*(const Complex& lhs, const double number)
{
Complex complex(lhs);
complex *= number;
return complex;
}
Complex operator*(const double number, const Complex& rhs)
{
Complex complex(rhs);
complex *= number;
return complex;
}
Complex operator/(const Complex& lhs, const Complex& rhs)
{
Complex complex(lhs);
complex /= rhs;
return complex;
}
Complex operator/(const double number, const Complex& rhs)
{
Complex complex(rhs);
complex /= number;
return complex;
}
Complex operator/(const Complex& lhs, const double number)
{
Complex complex(lhs);
complex /= number;
return complex;
}
std::ostream& operator<<(std::ostream& ostrm, const Complex& rhs)
{
return rhs.writeTo(ostrm);
}
std::istream& operator>>(std::istream& istrm, Complex& rhs)
{
return rhs.readFrom(istrm);
}
std::ostream& Complex::writeTo(std::ostream& ostrm) const
{
ostrm << leftBrace << re << separator << space << im << rightBrace;
return ostrm;
}
std::istream& Complex::readFrom(std::istream& istrm)
{
char leftBrace(0);
double real(0.0);
char comma(0);
double imaginary(0.0);
char rightBrace(0);
istrm >> leftBrace >> real >> comma >> imaginary >> rightBrace;
if (istrm.good()) {
if ((Complex::leftBrace == leftBrace) && (Complex::separator == comma)
&& (Complex::rightBrace == rightBrace)) {
re = real;
im = imaginary;
} else {
istrm.setstate(std::ios_base::failbit);
}
}
return istrm;
}
|
513a6d60ae20f3cb758ab7853c9bb1a89874c532 | 75a711b3c75a8584d0ada9c4b732b57d7dad10eb | /include/vise/vise_request_handler.h | 7ff3392a77be01264c22e54929497720b10fa19a | [
"BSD-2-Clause"
] | permissive | alexanderwilkinson/vise2 | 3f0ede1f64cf4acdc3060ea03de8d124d0433a69 | a29b898800e7babf3ac7012a056e954eb1af2be4 | refs/heads/master | 2021-06-24T08:27:00.035623 | 2021-01-21T12:09:40 | 2021-01-21T12:09:40 | 200,913,504 | 0 | 5 | BSD-2-Clause | 2021-01-14T13:03:33 | 2019-08-06T19:39:10 | C++ | UTF-8 | C++ | false | false | 1,652 | h | vise_request_handler.h | /** @file vise_request_handler.h
* @brief A singleton class which handles http requests related to vise
*
*
* @author Abhishek Dutta (adutta@robots.ox.ac.uk)
* @date 18 June 2018
*/
#ifndef _VISE_REQUEST_HANDLER_H_
#define _VISE_REQUEST_HANDLER_H_
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/filesystem.hpp>
#define BOOST_LOG_DYN_LINK 1
#include <boost/log/trivial.hpp>
// to generate uuid
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <Magick++.h> // to transform images
#include <eigen3/Eigen/Dense>
#include "http_server/http_request.h"
#include "http_server/http_response.h"
#include "vise/util.h"
#include "vise/search_engine_manager.h"
using namespace std;
using namespace Eigen;
namespace vise {
// uses C++ singleton design pattern
class vise_request_handler {
boost::filesystem::path data_dir_; // storage for vise internal data, search engine repo.
boost::filesystem::path asset_dir_; // location of ui, logo, etc.
vise_request_handler() { };
vise_request_handler(const vise_request_handler& sh) { };
vise_request_handler* operator=(const vise_request_handler &) {
return 0;
}
static vise_request_handler* vise_request_handler_;
public:
static vise_request_handler* instance();
void init(const boost::filesystem::path vise_asset_dir);
void respond_with_static_file(http_response& response, boost::filesystem::path fn);
// request handler endpoints: see docs/vise_server_api.org
void handle_http_request(const http_request& request, http_response& response);
};
}
#endif
|
008b4ec3d19de7654ba791e162c7f7b9a8d5a9f4 | f9b554496eaac8e1c413ebfc2d410e142de7567d | /uva/10008.cpp | ad036afdc595d6e1c0972ebc0a828ceb90d0f6a8 | [] | no_license | shabab477/Competitive-Programming | 9a911b264730aa00482710295bd3f2f0ee253dc7 | 9fa070991c8caf427f9e9c14db0262ec342eaefe | refs/heads/master | 2016-09-12T20:55:47.056789 | 2016-04-30T06:06:41 | 2016-04-30T06:06:41 | 57,429,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,320 | cpp | 10008.cpp | #include <iostream>
using namespace std;
#include <string.h>
#include <algorithm>
#include <stdio.h>
struct Alpha
{
char alpha;
int count;
}
bool isCharacter(char ch)
{
int d = (int)ch;
if((d >= 65 && d <= 90) || (d >= 97 && d <= 122))
{
return true;
}
return false;
}
bool isLower(char ch)
{
int d = (int)ch;
if(d >= 97 && d <= 122)
{
return true;
}
return false;
}
int main() {
int n = 0;
Alpha array[26];
scanf("%d", &n);
for(int c = 0; c < 26; c++)
{
array[c].alpha = (char)(65 + c);
array[c].count = 0;
}
string s = "";
getline(cin, s);
for(int c = 0; c < n; c++)
{
s = "";
getline(cin, s);
//printf("%s", s.c_str());
for(int i = 0; i < s.length(); i++)
{
int d = 0;
if(isCharacter(s.at(i)))
{
if(isLower(s.at(i)))
{
d = ((int)s.at(i)) - 65 - 32;
}
else
{
d = (int)s.at(i) - 65;
}
array[d].count = array[d].count + 1;
}
}
}
sort(array, array + 26, [](Alpha x, Alpha y){
if(x.count == y.count)
{
int d1 = (int)x.alpha;
int d2 = (int)y.alpha;
return d1 < d2;
}
else
{
return x.count > y.count;
}
});
for(int c = 0; c < 26; c++)
{
if(array[c].count == 0)
{
break;
}
printf("%c %d\n", array[c].alpha, array[c].count);
}
return 0;
} |
ef19bbb72e214187b9613d53e259972a74080c15 | f2a3b969582c42748ebfe29806caa423e7f0de2a | /cartographer/mapping/proto/internal/legacy_submap.pb.cc | ac7dd7c22f6726c54a5413ac70ecad70bb5b8e92 | [] | no_license | xuguangyun/map_update_client | 816e6dd698774fcf37bc919c967ccc1161a0f9f0 | 4ddbe618880097ec03e60c36bf8635706f58c1cd | refs/heads/master | 2020-07-29T23:41:18.744694 | 2020-05-07T08:32:52 | 2020-05-07T08:32:52 | 210,002,732 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | true | 68,519 | cc | legacy_submap.pb.cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cartographer/mapping/proto/internal/legacy_submap.proto
#include "cartographer/mapping/proto/internal/legacy_submap.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_cartographer_2fmapping_2fproto_2f3d_2fhybrid_5fgrid_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HybridGrid_cartographer_2fmapping_2fproto_2f3d_2fhybrid_5fgrid_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fprobability_5fgrid_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_LegacyProbabilityGrid_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fprobability_5fgrid_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_LegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_LegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SubmapId_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_cartographer_2ftransform_2fproto_2ftransform_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_Rigid3d_cartographer_2ftransform_2fproto_2ftransform_2eproto;
namespace cartographer {
namespace mapping {
namespace proto {
class LegacySubmap2DDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<LegacySubmap2D> _instance;
} _LegacySubmap2D_default_instance_;
class LegacySubmap3DDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<LegacySubmap3D> _instance;
} _LegacySubmap3D_default_instance_;
class LegacySubmapDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<LegacySubmap> _instance;
} _LegacySubmap_default_instance_;
} // namespace proto
} // namespace mapping
} // namespace cartographer
static void InitDefaultsLegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cartographer::mapping::proto::_LegacySubmap2D_default_instance_;
new (ptr) ::cartographer::mapping::proto::LegacySubmap2D();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::cartographer::mapping::proto::LegacySubmap2D::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_LegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsLegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto}, {
&scc_info_Rigid3d_cartographer_2ftransform_2fproto_2ftransform_2eproto.base,
&scc_info_LegacyProbabilityGrid_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fprobability_5fgrid_2eproto.base,}};
static void InitDefaultsLegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cartographer::mapping::proto::_LegacySubmap3D_default_instance_;
new (ptr) ::cartographer::mapping::proto::LegacySubmap3D();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::cartographer::mapping::proto::LegacySubmap3D::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_LegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsLegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto}, {
&scc_info_Rigid3d_cartographer_2ftransform_2fproto_2ftransform_2eproto.base,
&scc_info_HybridGrid_cartographer_2fmapping_2fproto_2f3d_2fhybrid_5fgrid_2eproto.base,}};
static void InitDefaultsLegacySubmap_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cartographer::mapping::proto::_LegacySubmap_default_instance_;
new (ptr) ::cartographer::mapping::proto::LegacySubmap();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::cartographer::mapping::proto::LegacySubmap::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<3> scc_info_LegacySubmap_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsLegacySubmap_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto}, {
&scc_info_SubmapId_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto.base,
&scc_info_LegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base,
&scc_info_LegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base,}};
void InitDefaults_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto() {
::google::protobuf::internal::InitSCC(&scc_info_LegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_LegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_LegacySubmap_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
}
::google::protobuf::Metadata file_level_metadata_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto[3];
constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto = nullptr;
constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto = nullptr;
const ::google::protobuf::uint32 TableStruct_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap2D, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap2D, local_pose_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap2D, num_range_data_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap2D, finished_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap2D, probability_grid_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap3D, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap3D, local_pose_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap3D, num_range_data_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap3D, finished_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap3D, high_resolution_hybrid_grid_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap3D, low_resolution_hybrid_grid_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap, submap_id_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap, submap_2d_),
PROTOBUF_FIELD_OFFSET(::cartographer::mapping::proto::LegacySubmap, submap_3d_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::cartographer::mapping::proto::LegacySubmap2D)},
{ 9, -1, sizeof(::cartographer::mapping::proto::LegacySubmap3D)},
{ 19, -1, sizeof(::cartographer::mapping::proto::LegacySubmap)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::cartographer::mapping::proto::_LegacySubmap2D_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::cartographer::mapping::proto::_LegacySubmap3D_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::cartographer::mapping::proto::_LegacySubmap_default_instance_),
};
::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto = {
{}, AddDescriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto, "cartographer/mapping/proto/internal/legacy_submap.proto", schemas,
file_default_instances, TableStruct_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto::offsets,
file_level_metadata_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto, 3, file_level_enum_descriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto, file_level_service_descriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto,
};
const char descriptor_table_protodef_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto[] =
"\n7cartographer/mapping/proto/internal/le"
"gacy_submap.proto\022\032cartographer.mapping."
"proto\032+cartographer/mapping/proto/pose_g"
"raph.proto\032Acartographer/mapping/proto/i"
"nternal/legacy_probability_grid.proto\032/c"
"artographer/mapping/proto/3d/hybrid_grid"
".proto\032,cartographer/transform/proto/tra"
"nsform.proto\"\302\001\n\016LegacySubmap2D\0229\n\nlocal"
"_pose\030\001 \001(\0132%.cartographer.transform.pro"
"to.Rigid3d\022\026\n\016num_range_data\030\002 \001(\005\022\020\n\010fi"
"nished\030\003 \001(\010\022K\n\020probability_grid\030\004 \001(\01321"
".cartographer.mapping.proto.LegacyProbab"
"ilityGrid\"\216\002\n\016LegacySubmap3D\0229\n\nlocal_po"
"se\030\001 \001(\0132%.cartographer.transform.proto."
"Rigid3d\022\026\n\016num_range_data\030\002 \001(\005\022\020\n\010finis"
"hed\030\003 \001(\010\022K\n\033high_resolution_hybrid_grid"
"\030\004 \001(\0132&.cartographer.mapping.proto.Hybr"
"idGrid\022J\n\032low_resolution_hybrid_grid\030\005 \001"
"(\0132&.cartographer.mapping.proto.HybridGr"
"id\"\305\001\n\014LegacySubmap\0227\n\tsubmap_id\030\001 \001(\0132$"
".cartographer.mapping.proto.SubmapId\022=\n\t"
"submap_2d\030\002 \001(\0132*.cartographer.mapping.p"
"roto.LegacySubmap2D\022=\n\tsubmap_3d\030\003 \001(\0132*"
".cartographer.mapping.proto.LegacySubmap"
"3Db\006proto3"
;
::google::protobuf::internal::DescriptorTable descriptor_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto = {
false, InitDefaults_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto,
descriptor_table_protodef_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto,
"cartographer/mapping/proto/internal/legacy_submap.proto", &assign_descriptors_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto, 970,
};
void AddDescriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto() {
static constexpr ::google::protobuf::internal::InitFunc deps[4] =
{
::AddDescriptors_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto,
::AddDescriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fprobability_5fgrid_2eproto,
::AddDescriptors_cartographer_2fmapping_2fproto_2f3d_2fhybrid_5fgrid_2eproto,
::AddDescriptors_cartographer_2ftransform_2fproto_2ftransform_2eproto,
};
::google::protobuf::internal::AddDescriptors(&descriptor_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto, deps, 4);
}
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto = []() { AddDescriptors_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto(); return true; }();
namespace cartographer {
namespace mapping {
namespace proto {
// ===================================================================
void LegacySubmap2D::InitAsDefaultInstance() {
::cartographer::mapping::proto::_LegacySubmap2D_default_instance_._instance.get_mutable()->local_pose_ = const_cast< ::cartographer::transform::proto::Rigid3d*>(
::cartographer::transform::proto::Rigid3d::internal_default_instance());
::cartographer::mapping::proto::_LegacySubmap2D_default_instance_._instance.get_mutable()->probability_grid_ = const_cast< ::cartographer::mapping::proto::LegacyProbabilityGrid*>(
::cartographer::mapping::proto::LegacyProbabilityGrid::internal_default_instance());
}
class LegacySubmap2D::HasBitSetters {
public:
static const ::cartographer::transform::proto::Rigid3d& local_pose(const LegacySubmap2D* msg);
static const ::cartographer::mapping::proto::LegacyProbabilityGrid& probability_grid(const LegacySubmap2D* msg);
};
const ::cartographer::transform::proto::Rigid3d&
LegacySubmap2D::HasBitSetters::local_pose(const LegacySubmap2D* msg) {
return *msg->local_pose_;
}
const ::cartographer::mapping::proto::LegacyProbabilityGrid&
LegacySubmap2D::HasBitSetters::probability_grid(const LegacySubmap2D* msg) {
return *msg->probability_grid_;
}
void LegacySubmap2D::clear_local_pose() {
if (GetArenaNoVirtual() == nullptr && local_pose_ != nullptr) {
delete local_pose_;
}
local_pose_ = nullptr;
}
void LegacySubmap2D::clear_probability_grid() {
if (GetArenaNoVirtual() == nullptr && probability_grid_ != nullptr) {
delete probability_grid_;
}
probability_grid_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LegacySubmap2D::kLocalPoseFieldNumber;
const int LegacySubmap2D::kNumRangeDataFieldNumber;
const int LegacySubmap2D::kFinishedFieldNumber;
const int LegacySubmap2D::kProbabilityGridFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LegacySubmap2D::LegacySubmap2D()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.LegacySubmap2D)
}
LegacySubmap2D::LegacySubmap2D(const LegacySubmap2D& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_local_pose()) {
local_pose_ = new ::cartographer::transform::proto::Rigid3d(*from.local_pose_);
} else {
local_pose_ = nullptr;
}
if (from.has_probability_grid()) {
probability_grid_ = new ::cartographer::mapping::proto::LegacyProbabilityGrid(*from.probability_grid_);
} else {
probability_grid_ = nullptr;
}
::memcpy(&num_range_data_, &from.num_range_data_,
static_cast<size_t>(reinterpret_cast<char*>(&finished_) -
reinterpret_cast<char*>(&num_range_data_)) + sizeof(finished_));
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.LegacySubmap2D)
}
void LegacySubmap2D::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_LegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
::memset(&local_pose_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&finished_) -
reinterpret_cast<char*>(&local_pose_)) + sizeof(finished_));
}
LegacySubmap2D::~LegacySubmap2D() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.LegacySubmap2D)
SharedDtor();
}
void LegacySubmap2D::SharedDtor() {
if (this != internal_default_instance()) delete local_pose_;
if (this != internal_default_instance()) delete probability_grid_;
}
void LegacySubmap2D::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const LegacySubmap2D& LegacySubmap2D::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_LegacySubmap2D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
return *internal_default_instance();
}
void LegacySubmap2D::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.LegacySubmap2D)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && local_pose_ != nullptr) {
delete local_pose_;
}
local_pose_ = nullptr;
if (GetArenaNoVirtual() == nullptr && probability_grid_ != nullptr) {
delete probability_grid_;
}
probability_grid_ = nullptr;
::memset(&num_range_data_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&finished_) -
reinterpret_cast<char*>(&num_range_data_)) + sizeof(finished_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* LegacySubmap2D::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<LegacySubmap2D*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .cartographer.transform.proto.Rigid3d local_pose = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::transform::proto::Rigid3d::_InternalParse;
object = msg->mutable_local_pose();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// int32 num_range_data = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
msg->set_num_range_data(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bool finished = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
msg->set_finished(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// .cartographer.mapping.proto.LegacyProbabilityGrid probability_grid = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::mapping::proto::LegacyProbabilityGrid::_InternalParse;
object = msg->mutable_probability_grid();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool LegacySubmap2D::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.LegacySubmap2D)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .cartographer.transform.proto.Rigid3d local_pose = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_local_pose()));
} else {
goto handle_unusual;
}
break;
}
// int32 num_range_data = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &num_range_data_)));
} else {
goto handle_unusual;
}
break;
}
// bool finished = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &finished_)));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.LegacyProbabilityGrid probability_grid = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_probability_grid()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.LegacySubmap2D)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.LegacySubmap2D)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void LegacySubmap2D::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.LegacySubmap2D)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.transform.proto.Rigid3d local_pose = 1;
if (this->has_local_pose()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::local_pose(this), output);
}
// int32 num_range_data = 2;
if (this->num_range_data() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->num_range_data(), output);
}
// bool finished = 3;
if (this->finished() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->finished(), output);
}
// .cartographer.mapping.proto.LegacyProbabilityGrid probability_grid = 4;
if (this->has_probability_grid()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::probability_grid(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.LegacySubmap2D)
}
::google::protobuf::uint8* LegacySubmap2D::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.LegacySubmap2D)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.transform.proto.Rigid3d local_pose = 1;
if (this->has_local_pose()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::local_pose(this), target);
}
// int32 num_range_data = 2;
if (this->num_range_data() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->num_range_data(), target);
}
// bool finished = 3;
if (this->finished() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->finished(), target);
}
// .cartographer.mapping.proto.LegacyProbabilityGrid probability_grid = 4;
if (this->has_probability_grid()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::probability_grid(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.LegacySubmap2D)
return target;
}
size_t LegacySubmap2D::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.LegacySubmap2D)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .cartographer.transform.proto.Rigid3d local_pose = 1;
if (this->has_local_pose()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*local_pose_);
}
// .cartographer.mapping.proto.LegacyProbabilityGrid probability_grid = 4;
if (this->has_probability_grid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*probability_grid_);
}
// int32 num_range_data = 2;
if (this->num_range_data() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->num_range_data());
}
// bool finished = 3;
if (this->finished() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void LegacySubmap2D::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.LegacySubmap2D)
GOOGLE_DCHECK_NE(&from, this);
const LegacySubmap2D* source =
::google::protobuf::DynamicCastToGenerated<LegacySubmap2D>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.LegacySubmap2D)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.LegacySubmap2D)
MergeFrom(*source);
}
}
void LegacySubmap2D::MergeFrom(const LegacySubmap2D& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.LegacySubmap2D)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_local_pose()) {
mutable_local_pose()->::cartographer::transform::proto::Rigid3d::MergeFrom(from.local_pose());
}
if (from.has_probability_grid()) {
mutable_probability_grid()->::cartographer::mapping::proto::LegacyProbabilityGrid::MergeFrom(from.probability_grid());
}
if (from.num_range_data() != 0) {
set_num_range_data(from.num_range_data());
}
if (from.finished() != 0) {
set_finished(from.finished());
}
}
void LegacySubmap2D::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.LegacySubmap2D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LegacySubmap2D::CopyFrom(const LegacySubmap2D& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.LegacySubmap2D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LegacySubmap2D::IsInitialized() const {
return true;
}
void LegacySubmap2D::Swap(LegacySubmap2D* other) {
if (other == this) return;
InternalSwap(other);
}
void LegacySubmap2D::InternalSwap(LegacySubmap2D* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(local_pose_, other->local_pose_);
swap(probability_grid_, other->probability_grid_);
swap(num_range_data_, other->num_range_data_);
swap(finished_, other->finished_);
}
::google::protobuf::Metadata LegacySubmap2D::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto);
return ::file_level_metadata_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto[kIndexInFileMessages];
}
// ===================================================================
void LegacySubmap3D::InitAsDefaultInstance() {
::cartographer::mapping::proto::_LegacySubmap3D_default_instance_._instance.get_mutable()->local_pose_ = const_cast< ::cartographer::transform::proto::Rigid3d*>(
::cartographer::transform::proto::Rigid3d::internal_default_instance());
::cartographer::mapping::proto::_LegacySubmap3D_default_instance_._instance.get_mutable()->high_resolution_hybrid_grid_ = const_cast< ::cartographer::mapping::proto::HybridGrid*>(
::cartographer::mapping::proto::HybridGrid::internal_default_instance());
::cartographer::mapping::proto::_LegacySubmap3D_default_instance_._instance.get_mutable()->low_resolution_hybrid_grid_ = const_cast< ::cartographer::mapping::proto::HybridGrid*>(
::cartographer::mapping::proto::HybridGrid::internal_default_instance());
}
class LegacySubmap3D::HasBitSetters {
public:
static const ::cartographer::transform::proto::Rigid3d& local_pose(const LegacySubmap3D* msg);
static const ::cartographer::mapping::proto::HybridGrid& high_resolution_hybrid_grid(const LegacySubmap3D* msg);
static const ::cartographer::mapping::proto::HybridGrid& low_resolution_hybrid_grid(const LegacySubmap3D* msg);
};
const ::cartographer::transform::proto::Rigid3d&
LegacySubmap3D::HasBitSetters::local_pose(const LegacySubmap3D* msg) {
return *msg->local_pose_;
}
const ::cartographer::mapping::proto::HybridGrid&
LegacySubmap3D::HasBitSetters::high_resolution_hybrid_grid(const LegacySubmap3D* msg) {
return *msg->high_resolution_hybrid_grid_;
}
const ::cartographer::mapping::proto::HybridGrid&
LegacySubmap3D::HasBitSetters::low_resolution_hybrid_grid(const LegacySubmap3D* msg) {
return *msg->low_resolution_hybrid_grid_;
}
void LegacySubmap3D::clear_local_pose() {
if (GetArenaNoVirtual() == nullptr && local_pose_ != nullptr) {
delete local_pose_;
}
local_pose_ = nullptr;
}
void LegacySubmap3D::clear_high_resolution_hybrid_grid() {
if (GetArenaNoVirtual() == nullptr && high_resolution_hybrid_grid_ != nullptr) {
delete high_resolution_hybrid_grid_;
}
high_resolution_hybrid_grid_ = nullptr;
}
void LegacySubmap3D::clear_low_resolution_hybrid_grid() {
if (GetArenaNoVirtual() == nullptr && low_resolution_hybrid_grid_ != nullptr) {
delete low_resolution_hybrid_grid_;
}
low_resolution_hybrid_grid_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LegacySubmap3D::kLocalPoseFieldNumber;
const int LegacySubmap3D::kNumRangeDataFieldNumber;
const int LegacySubmap3D::kFinishedFieldNumber;
const int LegacySubmap3D::kHighResolutionHybridGridFieldNumber;
const int LegacySubmap3D::kLowResolutionHybridGridFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LegacySubmap3D::LegacySubmap3D()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.LegacySubmap3D)
}
LegacySubmap3D::LegacySubmap3D(const LegacySubmap3D& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_local_pose()) {
local_pose_ = new ::cartographer::transform::proto::Rigid3d(*from.local_pose_);
} else {
local_pose_ = nullptr;
}
if (from.has_high_resolution_hybrid_grid()) {
high_resolution_hybrid_grid_ = new ::cartographer::mapping::proto::HybridGrid(*from.high_resolution_hybrid_grid_);
} else {
high_resolution_hybrid_grid_ = nullptr;
}
if (from.has_low_resolution_hybrid_grid()) {
low_resolution_hybrid_grid_ = new ::cartographer::mapping::proto::HybridGrid(*from.low_resolution_hybrid_grid_);
} else {
low_resolution_hybrid_grid_ = nullptr;
}
::memcpy(&num_range_data_, &from.num_range_data_,
static_cast<size_t>(reinterpret_cast<char*>(&finished_) -
reinterpret_cast<char*>(&num_range_data_)) + sizeof(finished_));
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.LegacySubmap3D)
}
void LegacySubmap3D::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_LegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
::memset(&local_pose_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&finished_) -
reinterpret_cast<char*>(&local_pose_)) + sizeof(finished_));
}
LegacySubmap3D::~LegacySubmap3D() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.LegacySubmap3D)
SharedDtor();
}
void LegacySubmap3D::SharedDtor() {
if (this != internal_default_instance()) delete local_pose_;
if (this != internal_default_instance()) delete high_resolution_hybrid_grid_;
if (this != internal_default_instance()) delete low_resolution_hybrid_grid_;
}
void LegacySubmap3D::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const LegacySubmap3D& LegacySubmap3D::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_LegacySubmap3D_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
return *internal_default_instance();
}
void LegacySubmap3D::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.LegacySubmap3D)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && local_pose_ != nullptr) {
delete local_pose_;
}
local_pose_ = nullptr;
if (GetArenaNoVirtual() == nullptr && high_resolution_hybrid_grid_ != nullptr) {
delete high_resolution_hybrid_grid_;
}
high_resolution_hybrid_grid_ = nullptr;
if (GetArenaNoVirtual() == nullptr && low_resolution_hybrid_grid_ != nullptr) {
delete low_resolution_hybrid_grid_;
}
low_resolution_hybrid_grid_ = nullptr;
::memset(&num_range_data_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&finished_) -
reinterpret_cast<char*>(&num_range_data_)) + sizeof(finished_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* LegacySubmap3D::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<LegacySubmap3D*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .cartographer.transform.proto.Rigid3d local_pose = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::transform::proto::Rigid3d::_InternalParse;
object = msg->mutable_local_pose();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// int32 num_range_data = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
msg->set_num_range_data(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bool finished = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
msg->set_finished(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// .cartographer.mapping.proto.HybridGrid high_resolution_hybrid_grid = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::mapping::proto::HybridGrid::_InternalParse;
object = msg->mutable_high_resolution_hybrid_grid();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .cartographer.mapping.proto.HybridGrid low_resolution_hybrid_grid = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::mapping::proto::HybridGrid::_InternalParse;
object = msg->mutable_low_resolution_hybrid_grid();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool LegacySubmap3D::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.LegacySubmap3D)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .cartographer.transform.proto.Rigid3d local_pose = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_local_pose()));
} else {
goto handle_unusual;
}
break;
}
// int32 num_range_data = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &num_range_data_)));
} else {
goto handle_unusual;
}
break;
}
// bool finished = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &finished_)));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.HybridGrid high_resolution_hybrid_grid = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_high_resolution_hybrid_grid()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.HybridGrid low_resolution_hybrid_grid = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_low_resolution_hybrid_grid()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.LegacySubmap3D)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.LegacySubmap3D)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void LegacySubmap3D::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.LegacySubmap3D)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.transform.proto.Rigid3d local_pose = 1;
if (this->has_local_pose()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::local_pose(this), output);
}
// int32 num_range_data = 2;
if (this->num_range_data() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->num_range_data(), output);
}
// bool finished = 3;
if (this->finished() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->finished(), output);
}
// .cartographer.mapping.proto.HybridGrid high_resolution_hybrid_grid = 4;
if (this->has_high_resolution_hybrid_grid()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::high_resolution_hybrid_grid(this), output);
}
// .cartographer.mapping.proto.HybridGrid low_resolution_hybrid_grid = 5;
if (this->has_low_resolution_hybrid_grid()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::low_resolution_hybrid_grid(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.LegacySubmap3D)
}
::google::protobuf::uint8* LegacySubmap3D::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.LegacySubmap3D)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.transform.proto.Rigid3d local_pose = 1;
if (this->has_local_pose()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::local_pose(this), target);
}
// int32 num_range_data = 2;
if (this->num_range_data() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->num_range_data(), target);
}
// bool finished = 3;
if (this->finished() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->finished(), target);
}
// .cartographer.mapping.proto.HybridGrid high_resolution_hybrid_grid = 4;
if (this->has_high_resolution_hybrid_grid()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::high_resolution_hybrid_grid(this), target);
}
// .cartographer.mapping.proto.HybridGrid low_resolution_hybrid_grid = 5;
if (this->has_low_resolution_hybrid_grid()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::low_resolution_hybrid_grid(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.LegacySubmap3D)
return target;
}
size_t LegacySubmap3D::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.LegacySubmap3D)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .cartographer.transform.proto.Rigid3d local_pose = 1;
if (this->has_local_pose()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*local_pose_);
}
// .cartographer.mapping.proto.HybridGrid high_resolution_hybrid_grid = 4;
if (this->has_high_resolution_hybrid_grid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*high_resolution_hybrid_grid_);
}
// .cartographer.mapping.proto.HybridGrid low_resolution_hybrid_grid = 5;
if (this->has_low_resolution_hybrid_grid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*low_resolution_hybrid_grid_);
}
// int32 num_range_data = 2;
if (this->num_range_data() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->num_range_data());
}
// bool finished = 3;
if (this->finished() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void LegacySubmap3D::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.LegacySubmap3D)
GOOGLE_DCHECK_NE(&from, this);
const LegacySubmap3D* source =
::google::protobuf::DynamicCastToGenerated<LegacySubmap3D>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.LegacySubmap3D)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.LegacySubmap3D)
MergeFrom(*source);
}
}
void LegacySubmap3D::MergeFrom(const LegacySubmap3D& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.LegacySubmap3D)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_local_pose()) {
mutable_local_pose()->::cartographer::transform::proto::Rigid3d::MergeFrom(from.local_pose());
}
if (from.has_high_resolution_hybrid_grid()) {
mutable_high_resolution_hybrid_grid()->::cartographer::mapping::proto::HybridGrid::MergeFrom(from.high_resolution_hybrid_grid());
}
if (from.has_low_resolution_hybrid_grid()) {
mutable_low_resolution_hybrid_grid()->::cartographer::mapping::proto::HybridGrid::MergeFrom(from.low_resolution_hybrid_grid());
}
if (from.num_range_data() != 0) {
set_num_range_data(from.num_range_data());
}
if (from.finished() != 0) {
set_finished(from.finished());
}
}
void LegacySubmap3D::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.LegacySubmap3D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LegacySubmap3D::CopyFrom(const LegacySubmap3D& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.LegacySubmap3D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LegacySubmap3D::IsInitialized() const {
return true;
}
void LegacySubmap3D::Swap(LegacySubmap3D* other) {
if (other == this) return;
InternalSwap(other);
}
void LegacySubmap3D::InternalSwap(LegacySubmap3D* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(local_pose_, other->local_pose_);
swap(high_resolution_hybrid_grid_, other->high_resolution_hybrid_grid_);
swap(low_resolution_hybrid_grid_, other->low_resolution_hybrid_grid_);
swap(num_range_data_, other->num_range_data_);
swap(finished_, other->finished_);
}
::google::protobuf::Metadata LegacySubmap3D::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto);
return ::file_level_metadata_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto[kIndexInFileMessages];
}
// ===================================================================
void LegacySubmap::InitAsDefaultInstance() {
::cartographer::mapping::proto::_LegacySubmap_default_instance_._instance.get_mutable()->submap_id_ = const_cast< ::cartographer::mapping::proto::SubmapId*>(
::cartographer::mapping::proto::SubmapId::internal_default_instance());
::cartographer::mapping::proto::_LegacySubmap_default_instance_._instance.get_mutable()->submap_2d_ = const_cast< ::cartographer::mapping::proto::LegacySubmap2D*>(
::cartographer::mapping::proto::LegacySubmap2D::internal_default_instance());
::cartographer::mapping::proto::_LegacySubmap_default_instance_._instance.get_mutable()->submap_3d_ = const_cast< ::cartographer::mapping::proto::LegacySubmap3D*>(
::cartographer::mapping::proto::LegacySubmap3D::internal_default_instance());
}
class LegacySubmap::HasBitSetters {
public:
static const ::cartographer::mapping::proto::SubmapId& submap_id(const LegacySubmap* msg);
static const ::cartographer::mapping::proto::LegacySubmap2D& submap_2d(const LegacySubmap* msg);
static const ::cartographer::mapping::proto::LegacySubmap3D& submap_3d(const LegacySubmap* msg);
};
const ::cartographer::mapping::proto::SubmapId&
LegacySubmap::HasBitSetters::submap_id(const LegacySubmap* msg) {
return *msg->submap_id_;
}
const ::cartographer::mapping::proto::LegacySubmap2D&
LegacySubmap::HasBitSetters::submap_2d(const LegacySubmap* msg) {
return *msg->submap_2d_;
}
const ::cartographer::mapping::proto::LegacySubmap3D&
LegacySubmap::HasBitSetters::submap_3d(const LegacySubmap* msg) {
return *msg->submap_3d_;
}
void LegacySubmap::clear_submap_id() {
if (GetArenaNoVirtual() == nullptr && submap_id_ != nullptr) {
delete submap_id_;
}
submap_id_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LegacySubmap::kSubmapIdFieldNumber;
const int LegacySubmap::kSubmap2DFieldNumber;
const int LegacySubmap::kSubmap3DFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LegacySubmap::LegacySubmap()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.LegacySubmap)
}
LegacySubmap::LegacySubmap(const LegacySubmap& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_submap_id()) {
submap_id_ = new ::cartographer::mapping::proto::SubmapId(*from.submap_id_);
} else {
submap_id_ = nullptr;
}
if (from.has_submap_2d()) {
submap_2d_ = new ::cartographer::mapping::proto::LegacySubmap2D(*from.submap_2d_);
} else {
submap_2d_ = nullptr;
}
if (from.has_submap_3d()) {
submap_3d_ = new ::cartographer::mapping::proto::LegacySubmap3D(*from.submap_3d_);
} else {
submap_3d_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.LegacySubmap)
}
void LegacySubmap::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_LegacySubmap_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
::memset(&submap_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&submap_3d_) -
reinterpret_cast<char*>(&submap_id_)) + sizeof(submap_3d_));
}
LegacySubmap::~LegacySubmap() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.LegacySubmap)
SharedDtor();
}
void LegacySubmap::SharedDtor() {
if (this != internal_default_instance()) delete submap_id_;
if (this != internal_default_instance()) delete submap_2d_;
if (this != internal_default_instance()) delete submap_3d_;
}
void LegacySubmap::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const LegacySubmap& LegacySubmap::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_LegacySubmap_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto.base);
return *internal_default_instance();
}
void LegacySubmap::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.LegacySubmap)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && submap_id_ != nullptr) {
delete submap_id_;
}
submap_id_ = nullptr;
if (GetArenaNoVirtual() == nullptr && submap_2d_ != nullptr) {
delete submap_2d_;
}
submap_2d_ = nullptr;
if (GetArenaNoVirtual() == nullptr && submap_3d_ != nullptr) {
delete submap_3d_;
}
submap_3d_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* LegacySubmap::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<LegacySubmap*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .cartographer.mapping.proto.SubmapId submap_id = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::mapping::proto::SubmapId::_InternalParse;
object = msg->mutable_submap_id();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .cartographer.mapping.proto.LegacySubmap2D submap_2d = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::mapping::proto::LegacySubmap2D::_InternalParse;
object = msg->mutable_submap_2d();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .cartographer.mapping.proto.LegacySubmap3D submap_3d = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::cartographer::mapping::proto::LegacySubmap3D::_InternalParse;
object = msg->mutable_submap_3d();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool LegacySubmap::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.LegacySubmap)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .cartographer.mapping.proto.SubmapId submap_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_submap_id()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.LegacySubmap2D submap_2d = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_submap_2d()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.LegacySubmap3D submap_3d = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_submap_3d()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.LegacySubmap)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.LegacySubmap)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void LegacySubmap::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.LegacySubmap)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.mapping.proto.SubmapId submap_id = 1;
if (this->has_submap_id()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::submap_id(this), output);
}
// .cartographer.mapping.proto.LegacySubmap2D submap_2d = 2;
if (this->has_submap_2d()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::submap_2d(this), output);
}
// .cartographer.mapping.proto.LegacySubmap3D submap_3d = 3;
if (this->has_submap_3d()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, HasBitSetters::submap_3d(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.LegacySubmap)
}
::google::protobuf::uint8* LegacySubmap::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.LegacySubmap)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.mapping.proto.SubmapId submap_id = 1;
if (this->has_submap_id()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::submap_id(this), target);
}
// .cartographer.mapping.proto.LegacySubmap2D submap_2d = 2;
if (this->has_submap_2d()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::submap_2d(this), target);
}
// .cartographer.mapping.proto.LegacySubmap3D submap_3d = 3;
if (this->has_submap_3d()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, HasBitSetters::submap_3d(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.LegacySubmap)
return target;
}
size_t LegacySubmap::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.LegacySubmap)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .cartographer.mapping.proto.SubmapId submap_id = 1;
if (this->has_submap_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*submap_id_);
}
// .cartographer.mapping.proto.LegacySubmap2D submap_2d = 2;
if (this->has_submap_2d()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*submap_2d_);
}
// .cartographer.mapping.proto.LegacySubmap3D submap_3d = 3;
if (this->has_submap_3d()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*submap_3d_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void LegacySubmap::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.LegacySubmap)
GOOGLE_DCHECK_NE(&from, this);
const LegacySubmap* source =
::google::protobuf::DynamicCastToGenerated<LegacySubmap>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.LegacySubmap)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.LegacySubmap)
MergeFrom(*source);
}
}
void LegacySubmap::MergeFrom(const LegacySubmap& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.LegacySubmap)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_submap_id()) {
mutable_submap_id()->::cartographer::mapping::proto::SubmapId::MergeFrom(from.submap_id());
}
if (from.has_submap_2d()) {
mutable_submap_2d()->::cartographer::mapping::proto::LegacySubmap2D::MergeFrom(from.submap_2d());
}
if (from.has_submap_3d()) {
mutable_submap_3d()->::cartographer::mapping::proto::LegacySubmap3D::MergeFrom(from.submap_3d());
}
}
void LegacySubmap::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.LegacySubmap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LegacySubmap::CopyFrom(const LegacySubmap& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.LegacySubmap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LegacySubmap::IsInitialized() const {
return true;
}
void LegacySubmap::Swap(LegacySubmap* other) {
if (other == this) return;
InternalSwap(other);
}
void LegacySubmap::InternalSwap(LegacySubmap* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(submap_id_, other->submap_id_);
swap(submap_2d_, other->submap_2d_);
swap(submap_3d_, other->submap_3d_);
}
::google::protobuf::Metadata LegacySubmap::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto);
return ::file_level_metadata_cartographer_2fmapping_2fproto_2finternal_2flegacy_5fsubmap_2eproto[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace proto
} // namespace mapping
} // namespace cartographer
namespace google {
namespace protobuf {
template<> PROTOBUF_NOINLINE ::cartographer::mapping::proto::LegacySubmap2D* Arena::CreateMaybeMessage< ::cartographer::mapping::proto::LegacySubmap2D >(Arena* arena) {
return Arena::CreateInternal< ::cartographer::mapping::proto::LegacySubmap2D >(arena);
}
template<> PROTOBUF_NOINLINE ::cartographer::mapping::proto::LegacySubmap3D* Arena::CreateMaybeMessage< ::cartographer::mapping::proto::LegacySubmap3D >(Arena* arena) {
return Arena::CreateInternal< ::cartographer::mapping::proto::LegacySubmap3D >(arena);
}
template<> PROTOBUF_NOINLINE ::cartographer::mapping::proto::LegacySubmap* Arena::CreateMaybeMessage< ::cartographer::mapping::proto::LegacySubmap >(Arena* arena) {
return Arena::CreateInternal< ::cartographer::mapping::proto::LegacySubmap >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
|
1c4a29a622c412d8612da32eb4a90f2afa9b30d1 | 03df7376721a13fa14fa2cb73d19612454a923b4 | /AirForce/Engine.h | be0d726d7784a316d416a85fc3484ace60d9d136 | [] | no_license | KarolPietryka/AirForce | 54509d7f55f080320769291a25e7c23d24c282ef | c27428d15b8a9cf7768b988faacaa45ba9fbbd28 | refs/heads/master | 2020-09-29T03:31:47.405121 | 2019-12-09T18:29:44 | 2019-12-09T18:29:44 | 226,939,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,480 | h | Engine.h | #pragma once
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include "Libretto.h"
#include "Collision.h"
#include "VisualEffect.h"
#include <vector>
using namespace std;
using namespace sf;
class Engine
{
public:
Engine(float _windowSizeX, float _windowSizeY);
~Engine();
Player & getPlayer();
void setTextureRecforPlayer(const IntRect & rectangle);
void updatePlayer(sf::Clock & _clock);
void playerFire(sf::Clock & _clock);
void createFormation(sf::Clock &_clockFormationTime);
bool isGameOver();
bool isGameCompleted();
void updateBestScore();
int readBestScore();
vector<PlayerMissiles *> getPlayerMissilesVector();
void updateMissiles();
void updateMissiles_OutOfWindow(sf::Vector2f _missilePosition, int &i);
void updateMissiles_Collision(int &i);
void updateFormation();
void updadeFormation_Move(sf::Vector2f _enemyPosition, vector<EnemyPlane *> &_enemyPlanesVector, int &i, int &j);
void updateFormation_OutOfWindow(vector<EnemyPlane *> &_enemyPlanesVector, int &i, int &j);
void updateFormation_Collision(sf::Vector2f _enemyPosition, vector<EnemyPlane *> &_enemyPlanesVector, int &i, int &j);
void updateCollision();
//void updateBattleField();
void updateBackGround(sf::Clock _clock);
void updateVisualEffect();
void drawBackGround(sf::RenderWindow &_window);
void drawMissiles(sf::RenderWindow &_window);
void drawPlayer(sf::RenderWindow &_window);
void drawEnemyFormation(sf::RenderWindow & _window);
void drawExplosion(sf::RenderWindow & _window);
void drawGameOver(sf::RenderWindow & _window);
void drawScore(sf::RenderWindow & _window);
void drawBestScore(sf::RenderWindow & _window);
private:
float windowSizeX, windowSizeY;
Collision collisionEngine;
bool gameOver;
Player player;
Libretto libretto;
int lastGeneratedFormation; //number of last generated Formation. Need to decide if game is over
unsigned formationGeneratorSpeed;// time sinc generation of one formation to other. Used in drawFormation() method
vector <Explosion *> explosionVector;
vector<Formation *> formationAgenda;//flow of formations
vector<Formation *> existingFormations;
vector<PlayerMissiles *> playerMissilesVector;
int delatedFormations; //number of delated formations. Need to decide if game is over
int bestScore;
Texture *backGroundTexture = new sf::Texture;
BackGroundAnimations *backGroundAnimations;
RectangleShape backGroundShape;
Texture *gameOverTexture = new sf::Texture;
RectangleShape gameOverShape;
};
|
6d06e5d94a4414ad771f65398ed6d8f17db81308 | 9e62d7b3861178f6b91e6cb50edbc9f31ae30852 | /Code/LCD.cpp | d90a06d1e1c17a801d29e1652ba59477093adb7e | [] | no_license | YassinRostom/Inf-Display-Module | 0c940e191d215978296003d2e6823b1165f24241 | 8b57dabf246c19b76581b4187516ecdc6d022c47 | refs/heads/main | 2023-09-05T16:27:47.956376 | 2021-11-14T19:22:52 | 2021-11-14T19:22:52 | 428,018,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,079 | cpp | LCD.cpp | //************************************************************************/
// Integrated Autonomous Tester - PROJ325 - LCD.cpp
//
// Responsible for displaying the test results to the user
//
//************************************************************************/
#include "LCD.h"
//LCD Initialization
SPI_TFT_ILI9341 TFT(PB_15, PB_14, PB_13, PB_12, PB_1, PB_2,"TFT"); // mosi, miso, sclk, cs, reset, dc
//Serial USB Connection
Serial pc(USBTX, USBRX);
//Functions
void LCD_Display();
void LCD_init();
//Inputs
AnalogIn input(A0);
//Variables
float samples[10];
float Sum=0;
float average;
float Average_Voltage;
float BatteryLevel=0.0;
//Flags Initialization
bool LCD_Ready= false;
bool LCD_Clear= false;
bool Display_StopTest= true;
bool Print_StopTest = true;
//Timer
Timer RunTest;
//Thread
Thread LCD_thread;
//************************************************************************
// LCD_init()
// Responsible for Initializing the TFT LCD
// Display the Boot up Message
// Parameters - void
// Return - void
//************************************************************************
void LCD_init()
{
int i;
TFT.claim(stdout); // send stdout to the TFT display
//TFT.claim(stderr); // send stderr to the TFT display
// Determine battery level
for(int i=0; i<10; i++)
{
samples[i] = input.read();
Sum=Sum+samples[i];
wait(0.001f);
}
average= Sum/10;
Average_Voltage= average*3.3;
BatteryLevel=(Average_Voltage/3)*100;
//Boot up Message
TFT.set_orientation(3);
TFT.background(White);
TFT.foreground(Red);
TFT.cls();
TFT.set_font((unsigned char*) Neu42x35);
TFT.locate(50,5);
printf("Integrated ");
TFT.locate(20,40);
printf("Auto Tester");
TFT.line(0,80,320,80,Black); //x1,y1,x2,y2
TFT.locate(42,100);
printf("Y Rostom");
TFT.locate(35,140);
printf("10563669");
//Display Battery Level
TFT.locate(75,220);
TFT.set_font((unsigned char*) Arial12x12);
printf("Battery Level=%2.0f%%",BatteryLevel);
//Set Flag
LCD_Clear= true;
}//end LCD init
//************************************************************************
// LCD_Display()
// Display the test results to the user
// Parameters - void
// Return - void
//************************************************************************
void LCD_Display()
{
while (1)
{
//Checks if the (Master) Bluetooth Module have been Turned OFF
if (RunTest.read_ms() > 15000.0 && Print_StopTest && State!=5)
{
//Clear LCD
TFT.cls();
TFT.fillrect(0,0,320,90,Yellow); //x1,y1,x2,y2
TFT.fillrect(0,150,320,240,Yellow); //x1,y1,x2,y2
TFT.background(White);
TFT.foreground(Black);
TFT.set_font((unsigned char*) Neu42x35);
TFT.locate(10,105);
printf("Test Stopped");
//Set Flag
LCD_Clear=true;
//Reset Timer
RunTest.stop();
RunTest.reset();
//Clear Flag
Print_StopTest=false;
}//end if
//Executed by the Bluetooth_Rx_Data Function
while(UPDATE_LCD)
{
if(TP_Counter==1)
{
//Start Timer
RunTest.stop();
RunTest.reset();
}//end if
if(Display_StopTest==false && (State==1 ||State==2 || State==3 || State==4) )
{
//Clear LCD
TFT.cls();
//Set Flags
Display_StopTest= true;
Print_StopTest= true;
}//end if
if(Print_StopTest==false && (State==1 ||State==2 || State==3 || State==4) )
{
//Clear LCD
TFT.cls();
//Set Flag
Print_StopTest= true;
}//end if
//Clear LCD
if (LCD_Clear)
{
//Clear LCD
TFT.cls();
//Reset Flag
LCD_Clear= false;
}//end if
//LCD Display Settings
TFT.foreground(Blue);
TFT.background(White);
TFT.set_font((unsigned char*) Arial28x28);
TFT.locate(0,10);
//Print the Test Running
if (State==1) printf("Low Range Test ");
else if (State==2) printf("High Range Test ");
else if (State==3) printf("Continuity Test ");
else if (State==4) printf("B-Continuity Test");
if(State==1 ||State==2 || State==3 || State==4) TFT.line(0,40,320,40,Black);
//Acquire Lock
DataLock.lock();
TFT.foreground(Black);
//Print Test Point
if(TP_Counter == 1 && State != 5 && Check_RxData ==13)
{
TFT.locate(0,50);
printf("TP 1:");
TFT.locate(85,50);
}
else if (TP_Counter == 2 && State != 5 && Check_RxData ==13)
{
TFT.locate(0,100);
printf("TP 2:");
TFT.locate(85,100);
}
else if (TP_Counter == 3 && State != 5 && Check_RxData ==13)
{
TFT.locate(0,150);
printf("TP 3:");
TFT.locate(85,150);
}
else if (TP_Counter == 4 && State != 5 && Check_RxData ==13)
{
TFT.locate(0,200);
printf("TP 4:");
TFT.locate(85,200);
}
//Release Lock
DataLock.unlock();
//Print Test Results
if (State==1 && Check_RxData ==13)
{
//Low Range Test
//Acquire Lock
DataLock.lock();
if (voltage_lowrange > 0.150f && voltage_lowrange < 0.280f)
{
TFT.foreground(Yellow);
printf("Out of Range ");
}
else if (voltage_lowrange >= 0.280f)
{
TFT.foreground(Red);
printf("Open Circuit ");
}
else if (voltage_lowrange < ShortC_Condition)
{
TFT.foreground(Red);
printf("Short Circuit ");
}
else
{
TFT.foreground(Green);
printf("%2.2f Ohm ", resistance_lowrange);
}
//Release Lock
DataLock.unlock();
}//end Low Range Test
else if (State==2 && Check_RxData ==13)
{
//High Range Test
//Acquire Lock
DataLock.lock();
if (voltage_highrange > 2.3f && voltage_highrange < 3.0f)
{
TFT.foreground(Yellow);
printf("Out of Range ");
}
else if (voltage_highrange >= OpenC_Condition)
{
TFT.foreground(Red);
printf("Open Circuit ");
}
else if (voltage_lowrange < ShortC_Condition)
{
TFT.foreground(Red);
printf("Short Circuit ");
}
else
{
TFT.foreground(Green);
printf("%2.2f Ohm ", resistance_highrange);
}
//Release Lock
DataLock.unlock();
}//end High Range Test
else if (State==3 && Check_RxData ==13)
{
//Continuity Test
//Acquire Lock
DataLock.lock();
//Harness Test
if (voltage_highrange >= OpenC_Condition)
{
TFT.foreground(Red);
printf("Open Circuit ");
}
else if (voltage_lowrange < ShortC_Condition)
{
TFT.foreground(Green);
printf("Pass ");
}
else
{
TFT.foreground(Yellow);
if (voltage_lowrange < 0.150f) printf("Fail %2.2f Ohm", resistance_lowrange);
else if (voltage_highrange < 2.3f) printf("Fail %2.2f Ohm", resistance_highrange);
else printf("Fail ");
}
//Release Lock
DataLock.unlock();
}//end Continuity Test
else if (State==4 && Check_RxData ==13)
{
//Bespoke Continuity Test
//Acquire Lock
DataLock.lock();
if (Bespoke_State==6)
{
TFT.foreground(Black);
printf("Measure ");
}
else if (Bespoke_State==7)
{
TFT.foreground(Green);
printf("Pass ");
}
else if (Bespoke_State==8)
{
TFT.foreground(Yellow);
printf("Fail ");
}
else if (Bespoke_State==9)
{
TFT.foreground(Red);
printf("Open Circuit ");
}
//Release Lock
DataLock.unlock();
}//end Bespoke Continuity Test
else if (State==5 && Display_StopTest)
{
//Test Stopeed
//Clear screen
TFT.cls();
TFT.fillrect(0,0,320,90,Yellow); //x1,y1,x2,y2
TFT.fillrect(0,150,320,240,Yellow); //x1,y1,x2,y2
TFT.background(White);
TFT.foreground(Black);
TFT.set_font((unsigned char*) Neu42x35);
TFT.locate(10,105);
printf("Test Stopped");
//Clear flags
Print_StopTest=false;
Display_StopTest=false;
}//end Stop
//Reset flag
UPDATE_LCD = false;
}//end while
}//end while(1)
}//end void serial_T
|
0a76c7fee75d8de1689c96f2d1d3d016f667df4a | 69074c766f83085cd0d4dec8f3c002f9c4c9b32a | /target_tracking/src/KalmanFilter.cpp | e4df43477daedaf4a4ecaa4f3b71999041bf8657 | [] | no_license | umdrobotics/Rendezvous | f1c94c166172ec1687aa3738fbaf16eaafe53bd6 | b1d168a171983a04756c7526f4f2136988dbf7e3 | refs/heads/master | 2020-04-12T03:08:33.620224 | 2019-04-29T18:21:50 | 2019-04-29T18:21:50 | 65,505,156 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 11,186 | cpp | KalmanFilter.cpp |
#include "target_tracking/KalmanFilter.h"
// Module "core"
#include <sstream> // stringstream, ...
#include <iostream> // std::cout, std::end, ...
#include <iomanip> // std::setprecision
// #include <signal.h>
//#include <opencv2/core/core.hpp>
// Module "highgui"
//#include <opencv2/highgui/highgui.hpp>
// Module "imgproc"
//#include <opencv2/imgproc/imgproc.hpp>
// Module "video"
//#include <opencv2/video/video.hpp>
// Output
//#include <cstdlib>
// Vector
//#include <vector>
using namespace std;
#define ROSCONSOLE_MIN_SEVERITY ROSCONSOLE_SEVERITY_DEBUG
KalmanFilter::KalmanFilter()
: m_nStateSize(4)
, m_nMeasurementSize(2)
, m_nInputSize(0)
, m_nCVType(CV_64F)
, m_bHasFirstMeasurementProcessed(false)
, m_kf(cv::KalmanFilter(4, 2, 0, CV_64F))
, m_matCurrentState(cv::Mat(4, 1, CV_64F))
, m_matMeasurement(cv::Mat(4, 1, CV_64F))
{
ConstructorHelper();
}
KalmanFilter::KalmanFilter(int nStateSize,
int nMeasurementSize,
int nInputSize,
unsigned int nCVType)
: m_nStateSize(nStateSize)
, m_nMeasurementSize(nMeasurementSize)
, m_nInputSize(nInputSize)
, m_nCVType(nCVType)
, m_bHasFirstMeasurementProcessed(false)
, m_kf(cv::KalmanFilter(nStateSize, nMeasurementSize, nInputSize, nCVType))
, m_matCurrentState(cv::Mat(m_nStateSize, 1, m_nCVType))
, m_matMeasurement(cv::Mat(m_nStateSize, 1, m_nCVType))
{
ConstructorHelper();
}
KalmanFilter::~KalmanFilter()
{
ROS_INFO("Destructing KalmanFilter.");
}
ostream& KalmanFilter::GetString(ostream& os)
{
return os << "State Size:" << m_nStateSize
<< ", Measurement Size:" << m_nMeasurementSize
<< ", Input Size:" << m_nInputSize
<< ", CV Type:" << m_nCVType
<< ", Initialized?:" << m_bHasFirstMeasurementProcessed;
}
ostream& KalmanFilter::GetCurrentState(ostream& os)
{
return os << m_matCurrentState;
}
cv::Mat KalmanFilter::ProcessMeasurement(double dT, double targetX, double targetY)
{
// Transition State Matrix A
// Note: set dT at each processing step!
// [ 1 0 dT 0 ]
// [ 0 1 0 dT ]
// [ 0 0 1 0 ]
// [ 0 0 0 1 ]
m_kf.transitionMatrix.at<double>(2) = dT;
m_kf.transitionMatrix.at<double>(7) = dT;
// Kalman Update
cv::Mat measurement(m_nMeasurementSize, 1, CV_64F); //(measSize, 1, type);
measurement.at<double>(0) = targetX;
measurement.at<double>(1) = targetY;
ROS_INFO_STREAM("StatePre 1: " << m_kf.statePre);
ROS_INFO_STREAM("StatePost 1: " << m_kf.statePost);
if(!m_bHasFirstMeasurementProcessed){
m_kf.statePre.at<double>(0) = targetX;
m_kf.statePre.at<double>(1) = targetY;
m_kf.statePre.at<double>(2) = 0.0;
m_kf.statePre.at<double>(3) = 0.0;
cv::setIdentity(m_kf.errorCovPre);
cv::setIdentity(m_kf.errorCovPost, cv::Scalar::all(.1));
m_bHasFirstMeasurementProcessed = true;
}
else
{
m_kf.predict();
}
cv::Mat state = m_kf.correct(measurement);
ROS_INFO_STREAM("StatePre 2: " << m_kf.statePre);
ROS_INFO_STREAM("StatePost 2: " << m_kf.statePost);
return state;
// cv::Mat state(m_nStateSize, 1, m_nCVType);
// cv::Mat state = m_kf.predict();
// if(!m_bHasFirstMeasurementProcessed)
// {
// state.at<double>(0) = targetX;
// state.at<double>(1) = targetY;
// state.at<double>(2) = 0;
// state.at<double>(3) = 0;
// }
//cout << "State post:" << endl << state << endl;
// return state ;
}
cv::Mat loopStepWebWithoutMeasurement(cv::KalmanFilter kf, double dT , cv::Mat latestState)
{
//for some reason, if we just assign kf.statePost = latestState directly, it crashes
kf.statePost.at<double>(0) = latestState.at<double>(0);
kf.statePost.at<double>(1) = latestState.at<double>(1);
kf.statePost.at<double>(2) = latestState.at<double>(2);
kf.statePost.at<double>(3) = latestState.at<double>(3);
// [1 0 dt 0]
// [0 1 0 dt]
// [0 0 1 0]
// [0 0 0 1]
//now update dt
kf.transitionMatrix.at<double>(2) = dT;
kf.transitionMatrix.at<double>(7) = dT;
cv::Mat state(4,1,CV_64F); //(statesize,1,type);
state = kf.predict();
//cout << "State post no measurement:" << endl << state << endl;
return state ;
} ///end function
// private methods
void KalmanFilter::ConstructorHelper()
{
// Transition State Matrix F
// Note: set dT at each processing step!
// [ 1 0 dT 0 ]
// [ 0 1 0 dT ]
// [ 0 0 1 0 ]
// [ 0 0 0 1 ]
cv::setIdentity(m_kf.transitionMatrix);
// Measure Matrix H
// [ 1 0 0 0 ]
// [ 0 1 0 0 ]
m_kf.measurementMatrix = cv::Mat::zeros(m_nMeasurementSize, m_nStateSize, m_nCVType);
m_kf.measurementMatrix.at<double>(0) = 1.0f;
m_kf.measurementMatrix.at<double>(5) = 1.0f;
// Process Noise Covariance Matrix Q
// [ Ex 0 0 0 ]
// [ 0 Ey 0 0 ]
// [ 0 0 Ev_x 0 ]
// [ 0 0 0 Ev_y ]
cv::setIdentity(m_kf.processNoiseCov, cv::Scalar(2.5e-1));
// Measures Noise Covariance Matrix R
// [ Ex 0 ]
// [ 0 Ey ]
//cv::setIdentity(m_kf.measurementNoiseCov, cv::Scalar(1e-1));
cv::setIdentity(m_kf.measurementNoiseCov, cv::Scalar(4.0));
}
//nonmember methods
ostream& operator<<(ostream& os, KalmanFilter& kf)
{
return kf.GetString(os);
}
//this has good insight into how to do found not found control, test it later
/*
double loopStep(cv::KalmanFilter kf, double dT, )
{
if (found)
{ // [1 0 dt 0]
// [0 1 0 dt]
// [0 0 1 0]
// [0 0 0 1]
//now update dt
// >>>> Matrix A
kf.transitionMatrix.at<double>(2) = dT;
kf.transitionMatrix.at<double>(7) = dT;
// <<<< Matrix A
cout << "dT:" << endl << dT << endl;
state = kf.predict();
cout << "State post:" << endl << state << endl;
// >>>>> Kalman Update
if (balls.size() == 0)
{
notFoundCount++;
cout << "notFoundCount:" << notFoundCount << endl; if( notFoundCount >= 10 )
{
found = false;
}
else
kf.statePost = state;
}
else
{
notFoundCount = 0;
meas.at(0) = ballsBox[0].x + ballsBox[0].width / 2;
meas.at(1) = ballsBox[0].y + ballsBox[0].height / 2;
//meas.at(2) = (float)ballsBox[0].width;
//meas.at(3) = (float)ballsBox[0].height;
if (!found) // First detection!
{
// >>>> Initialization
kf.errorCovPre.at(0) = 1; // px
kf.errorCovPre.at(7) = 1; // px
kf.errorCovPre.at(14) = 1;
kf.errorCovPre.at(21) = 1;
kf.errorCovPre.at(28) = 1; // px
kf.errorCovPre.at(35) = 1; // px
state.at(0) = meas.at(0);
state.at(1) = meas.at(1);
state.at(2) = 0;
state.at(3) = 0;
state.at(4) = meas.at(2);
state.at(5) = meas.at(3);
// <<<< Initialization
found = true;
}
else
{kf.correct(meas);} // Kalman Correction
} */
/*
void crudeTestWeb()
{
double actualX[]={2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06};
double actualY[]={803811,803811,803811,803811,803811,803811,803811,803811,803811,803811};
double ts[] = {0.5, 0.6, 0.7, 0.4, 0.5, 0.8, 1.4, 1.2, 0.6, 0.87};
cv::KalmanFilter mykf = initializeKalmanFilterWeb();
cv::Mat targetLocPrediction = loopStepWeb(mykf, ts[0], actualX[0], actualY[0], true);
cout <<"initial " <<targetLocPrediction<<"\n";
for (int i = 1; i< 10; i++)
{
targetLocPrediction = loopStepWeb(mykf, ts[i], actualX[i], actualY[i], false);
cout <<"prediction number "<<i <<" : " <<targetLocPrediction<<"\n";
}
cout <<"now redo with x and y flipped \n";
double notY[]={2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06,2.49527e+06};
double notX[]={803811,803811,803811,803811,803811,803811,803811,803811,803811,803811};
mykf = initializeKalmanFilterWeb();
targetLocPrediction = loopStepWeb(mykf, ts[0], notX[0], notY[0], true);
cout <<"initial " <<targetLocPrediction<<"\n";
for (int i = 1; i< 10; i++)
{
targetLocPrediction = loopStepWeb(mykf, ts[i], notX[i], notY[i], false);
cout <<"prediction number "<<i <<" : " <<targetLocPrediction<<"\n";
}
//return void;
}
double expTestWeb()
{
double quads[]={1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000};
double sqrts[]={1, 1.4142, 1.7321, 2, 2.2361 ,2.4495 ,2.6458, 2.8284, 3, 3.1623};
double ts[] = {0.5, 0.6, 0.7, 0.4, 0.5, 0.8, 1.4, 1.2, 0.6, 0.87};
cv::KalmanFilter mykf = initializeKalmanFilterWeb();
cv::Mat targetLocPrediction = loopStepWeb(mykf, ts[0], quads[0], sqrts[0],true);
cout <<"initial " <<targetLocPrediction<<" ";
cout <<"actual x y " <<quads[0] <<" "<<sqrts[0]<<" \n";
for (int i = 1; i< 10; i++)
{
targetLocPrediction = loopStepWeb(mykf, ts[i], quads[i], sqrts[i], false);
cout <<"prediction number "<<i <<" : " <<targetLocPrediction<<" actual x y " << quads[i] << " " << sqrts[i] << " \n";
}
}
double trigTestWeb()
{
//test trig functions for 0, pi/10, 2*pi/10, ...
double sin[]={0, .309, .5878, .8090, .9511, 1, .9511, .8090, .5878, .309};
double cos[]={1, .9511, .8090, .5787, .309 ,0 ,-.309, -.5787, -.8090, -.9511, -1};
double ts[] = {0.5, 0.6, 0.7, 0.4, 0.5, 0.8, 1.4, 1.2, 0.6, 0.87};
cv::KalmanFilter mykf = initializeKalmanFilterWeb();
cv::Mat targetLocPrediction = loopStepWeb(mykf, ts[0], sin[0], cos[0],true);
cout <<"initial " <<targetLocPrediction<<" ";
cout <<"actual x y " <<sin[0] <<" "<<cos[0]<<" \n";
for (int i = 1; i< 10; i++)
{
targetLocPrediction = loopStepWeb(mykf, ts[i], sin[i], cos[i], false);
cout <<"prediction number "<<i <<" : " <<targetLocPrediction<<" actual x y " << sin[i] << " " << cos[i] << " \n";
}
}
*/
/*
void WriteToCSV(vector<Point> loc, vector<Point> vel, Vector<Point> predLoc)
{
ofstream myFile;
printf("about to open file for Kalman");
myFile.open("/home/ubuntu/kalmanLog.csv");
if (myFile.is_open()) {printf("success\n");} else {printf("failure\n");}
myFile << "locX, locY, velX, velY, predLocX, predLocY, predVelX, predVelY";
for (int i =0; i= predLoc.size(); i++)
{
myFile << loc[i].x << ","
<< loc[i].y << ","
<< vel[i].x << ","
<< vel[i].y << ","
<< predLoc[i].x << ","
<< predLoc[i].y << ","
<< std:endl;
}
myFile.close();
}
*/
|
0cab716df9aa1900ef4e93c8dd18976bd22b2fce | 9987fded6026ace187753eaa3e520d0bb72047a0 | /isis/src/base/objs/RadarSkyMap/RadarSkyMap.cpp | 3864654f21f1bc5591054738736144a87107e00e | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | kberryUSGS/ISIS3 | 1345e6727746e2ebc348058ff3ec47c252928604 | b6aba8c38db54d84b1eb5807a08d12190bf8634e | refs/heads/dev | 2021-07-17T16:53:37.490510 | 2021-03-13T00:09:53 | 2021-03-13T00:09:53 | 118,936,778 | 0 | 1 | Unlicense | 2020-03-31T19:44:30 | 2018-01-25T16:17:20 | C++ | UTF-8 | C++ | false | false | 1,327 | cpp | RadarSkyMap.cpp | /** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include "RadarSkyMap.h"
namespace Isis {
/** Constructor a map between focal plane x/y and right acension/declination
*
* @param parent parent camera which will use this map
*
*/
RadarSkyMap::RadarSkyMap(Camera *parent) : CameraSkyMap(parent) {
}
/** Compute ra/dec from slant range
*
* Radar can't paint a star will always return false
*
* @param ux distorted focal plane x in millimeters
* @param uy distorted focal plane y in millimeters
* @param uz distorted focal plane z in millimeters
*
* @return conversion was successful
*/
bool RadarSkyMap::SetFocalPlane(const double ux, const double uy,
double uz) {
return false;
}
/**
* Compute slant range from ra/dec.
*
* Radar can't paint a star will always return false
*
* @param ra The right ascension angle
* @param dec The declination
*
*/
bool RadarSkyMap::SetSky(const double ra, const double dec) {
return false;
}
}
|
5889d71c8eb0062c60b803a48331548e287b0b97 | da54fc282e407ea430a1b3dd99c602a7857e88ac | /system/main/VideoRetrievalSystem.cpp | dc15a0372df6453b22190f5414e5f9a1d6d622c2 | [] | no_license | slh0302/Idm | 7d41901337158d2d2ec91a1e6d5f2c011c515dc0 | a5fa7bb1be8f7147bad3e75343ad2a13f50db910 | refs/heads/master | 2018-10-15T13:43:41.328727 | 2018-07-12T03:53:45 | 2018-07-12T03:53:45 | 114,886,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,128 | cpp | VideoRetrievalSystem.cpp | //
// Created by slh on 17-11-11.
//
#include <iostream>
#include "boost/timer.hpp"
#include "boost/thread.hpp"
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include "boost/algorithm/string.hpp"
#include <feature.h>
#include <sstream>
#include <vector>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <fstream>
#include <msg.h>
#include "binary.h"
#include "msg.h"
/// psocket
int socket_as_client ;
bool connected_to_fileserver = false;
char* DEBUG_SEARCH_SERVER_IP="162.105.95.94";
char* DEBUG_FILE_SERVER_IP="222.29.111.46";
#define FILE_SERVER_PORT 3333
bool connectToFileServer(FeatureMsgInfo* fmi);
/// info string
#define DATA_COUNT 43455
#define DATA_COUNT_PERSON 8046
#define DATA_BINARY 371
std::string File_prefix = "./";
string IndexFileName = File_prefix + "Video.index";
string IndexFileNameInfo = File_prefix+ "Video.info";
string IndexReLoad = File_prefix + ".IndexReLoad";
const int FEATURE_LENGTH = 128;
boost::mutex INDEX_MUTEX_LOCK;
int DATA_LENGTH = 0;
int INFO_LENGTH = 0;
bool STOP_SINGAL = false;
struct Info_String
{
char info[100];
};
typedef struct
{
int xlu; /// left up
int ylu;
int xrd; /// right down
int yrd;
int info_id;
unsigned char data[FEATURE_LENGTH];
}FeatureWithBox;
typedef struct
{
int xlu; /// left up
int ylu;
int xrd; /// right down
int yrd;
int info_id;
}FeatureWithBoxInfo;
/// global var
FeatureWithBoxInfo* boxInfo = NULL;
FeatureBinary::DataSet* dataSet = NULL;
FeatureMsgInfo* dataInfoSet = NULL;
std::string ROOT_DIR = "../data/";
std::string ROOT_FONT = "./";
// Binary Model File
std::string binary_proto_file = ROOT_DIR + "bcar.prototxt";
std::string binary_proto_weight = ROOT_DIR + "bcar.caffemodel";
// task list
// time func
double elapsed ()
{
struct timeval tv;
gettimeofday (&tv, NULL);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
// map vehicle
void LoadVehicleSpace();
// map person
void LoadPersonSpace();
// send request
bool sendSearchResult(FeatureMsgInfo* fmi);
bool sendSearchResult(FeatureMsgInfo* fmi,int topLeftX,int topLeftY,int bottomRightX,int bottomRightY);
// load thread
void LoadDataFromFile();
// change data
int ChangeDataNum(int num, FILE* _f);
void TransferData(FeatureWithBox* box, FeatureMsgInfo* info, int data_len, int info_len);
// client thread
void ClientBinaryThread(int client_sockfd, char* remote_addr, feature_index::FeatureIndex feature_index,
caffe::Net<float>* bnet);
int main(int argc, char *argv[])
{
google::InitGoogleLogging(argv[0]);
/// Init Feature Gpu
feature_index::FeatureIndex fea_index;
if(argc < 3) {
std::cout << "argc num not enough." << std::endl;
std::cout << "arg1: 'Video.info' location" << std::endl;
std::cout << "arg2: this server's ip" << std::endl;
std::cout << "arg3: Temp data file path" << std::endl;
return 1;
}
File_prefix = argv[1];
DEBUG_SEARCH_SERVER_IP = argv[2];
ROOT_FONT = argv[3];
IndexFileName = File_prefix + "/Video.index";
IndexFileNameInfo = File_prefix + "/Video.info";
IndexReLoad = File_prefix + ".IndexReLoad";
/// Init Binary Index
/// Load Binary Table
std::string table_filename= ROOT_DIR + "table.index";
if(!std::fstream(table_filename.c_str())) {
std::cout << "Table File Wrong" << std::endl;
return 1;
}
FeatureBinary::CreateTable(table_filename.c_str(), 16);
/// Load Binary Index
/// std::cout<<"data Set "<<((FeatureBinary::feature*)p)->getDataSet()[1].data[1]<<std::endl;
/// Load Binary Caffe Model
caffe::Net<float>* bnet = fea_index.InitNet(binary_proto_file, binary_proto_weight);
std::cout<<"Binary Caffe Net Init Done"<<std::endl;
// server status
int server_sockfd;//服务器端套接�?
int client_sockfd;//客户端套接字
int len;
struct sockaddr_in my_addr; //服务器网络地址结构�?
struct sockaddr_in remote_addr; //客户端网络地址结构�?
socklen_t sin_size;
char buf[BUFSIZ]; //数据传送的缓冲�?
memset(&my_addr,0,sizeof(my_addr)); //数据初始�?-清零
my_addr.sin_family = AF_INET; //设置为IP通信
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port=htons(18000); //服务器端口号
if((server_sockfd = socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
int on=1;
if((setsockopt(server_sockfd, SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)))<0) {
perror("####ServerMsg###:setsockopt failed");
return false;
}
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
listen(server_sockfd,10);
sin_size=sizeof(struct sockaddr_in);
std::cout<<"Server Begin"<<std::endl;
boost::thread th(boost::bind(&LoadDataFromFile));
while(1){
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept");
break;
}
printf("accept client %s\n",inet_ntoa(remote_addr.sin_addr));
// double info
int typeNum = -1;
if(len = recv(client_sockfd,buf,BUFSIZ,0)>0){
buf[len]='\0';
typeNum = atoi(buf);
send(client_sockfd,"Welcome\n",7,0);
}
switch (typeNum){
case 0:
{
boost::thread thread_1(boost::bind(&ClientBinaryThread, client_sockfd,
inet_ntoa(remote_addr.sin_addr), fea_index, bnet));
break;
}
case -1:
cout<<"Wrong num"<<endl;
}
}
close(server_sockfd);
return 0;
}
void ClientBinaryThread(int client_sockfd, char* remote_addr, feature_index::FeatureIndex feature_index,
caffe::Net<float>* bnet)
{
int len = 0;
char buf[BUFSIZ];
int numPicInOnePlaceVehicle[100] = {0};
std::string locationStrVehicle[20];
std::vector<std::string> run_param;
if((len=recv(client_sockfd,buf,BUFSIZ,0))>0)
{
buf[len]='\0';
printf("%s\n",buf);
// handle buf
std::string temp = buf;
boost::split(run_param, temp, boost::is_any_of(" ,!"), boost::token_compress_on);
// run time param
std::string file_name = run_param[0];
int count = atoi(run_param[1].c_str());
int Limit = atoi(run_param[2].c_str());
// read data
std::vector<cv::Mat> pic_list;
std::vector<int> label;
std::cout<<"File: "<< ROOT_FONT + "/searchFile/" + file_name << std::endl;
cv::Mat cv_origin = cv::imread(ROOT_FONT + "/searchFile/" + file_name,1);
cv::Mat cv_img ;
cv::resize(cv_origin,cv_img, cv::Size(224,224));
pic_list.push_back(cv_img);
label.push_back(0);
double t1 = 0;
// Extract feature
unsigned char *data = new unsigned char[ 1024 ];
double t0 = elapsed();
feature_index.MemoryBinaryPictureFeatureExtraction(count, data, bnet, "fc_hash/relu", pic_list, label);
std::cout<<"done data"<<std::endl;
// Retrival k-NN
int k = 20;
int nq = 1;
FeatureBinary::SortTable* sorttable;
FeatureBinary::DataSet* get_t = NULL;
std::vector<std::string> file_name_list;
{
boost::mutex::scoped_lock lock(INDEX_MUTEX_LOCK);
get_t = dataSet;
sorttable = new FeatureBinary::SortTable[DATA_LENGTH];
int *dt = FeatureBinary::DoHandle(data);
// bianary search
int index_num = FeatureBinary::retrival(dt, get_t, DATA_LENGTH, 16, Limit, sorttable);
t1 = elapsed();
// handle result
std::string result_path = "";
// output the result
/// tmp doing TODO:: Change
std::string ori_path = "rm -rf " + ROOT_FONT + "/run/originResult/*";
system(ori_path.c_str());
int return_num = 20 < index_num ? 20 : index_num;
for (int j = 0; j < return_num; j++) {
FeatureWithBoxInfo tempInfo = boxInfo[sorttable[j].info];
FeatureMsgInfo _sendInfo = dataInfoSet[tempInfo.info_id];
if(!sendSearchResult(&_sendInfo, tempInfo.xlu, tempInfo.ylu, tempInfo.xrd, tempInfo.yrd)){
cout<<"fail "<< _sendInfo.ServerIP<< endl;
}
cout<<"info FileName "<< _sendInfo.FileName << ",FrameNum " << _sendInfo.FrameNum<< endl;
char filename [100];
sprintf(filename, "%s_%d_%d_%d_%d_%d.jpg\0",_sendInfo.FileName,_sendInfo.FrameNum,
tempInfo.xlu, tempInfo.ylu, tempInfo.xrd, tempInfo.yrd);
cout<<tempInfo.xlu<<" "<<tempInfo.ylu<<" "<<tempInfo.xrd<<" "<<tempInfo.yrd<<endl;
file_name_list.push_back(std::string(filename));
}
}
std::ofstream reout(ROOT_FONT + "/run/runResult/map.txt",std::ios::out);
std::map<int, int*>::iterator it;
reout<<(t1 - t0)<<std::endl;
std::string ROOT_DIR = "";
for(int i = 0;i < file_name_list.size(); i++){
reout<<ROOT_DIR + file_name_list[i]<<std::endl;
}
reout.close();
char send_buf[BUFSIZ];
sprintf(send_buf, "OK\0");
std::string te(send_buf);
int send_len = te.length();
if(send(client_sockfd,send_buf,send_len,0)<0)
{
printf("Server Ip: %s error\n",remote_addr);
}
}
close(client_sockfd);
printf("Server Ip: %s done\n",remote_addr);
}
int ChangeDataNum(int num, FILE* _f) {
if (_f == NULL) {
return -1;
}
fseek(_f, 0, SEEK_SET);
int has = 0;
fread(&has, sizeof(int), 1, _f);
fseek(_f, 0, SEEK_SET);
int tmp = has + num;
fwrite(&tmp, sizeof(int), 1, _f);
fseek(_f, 0, SEEK_END);
return has;
}
void LoadDataFromFile(){
/// BEGIN SETTING
FILE* _init = fopen(IndexFileNameInfo.c_str(), "rb");
cout<< "BEGIN LOAD " << IndexFileNameInfo.c_str() <<endl;
if (_init == NULL) {
cout<< "No File" <<endl;
_init = fopen(IndexFileNameInfo.c_str(), "wb");
int tmp = 0;
fwrite(&tmp, sizeof(int), 1, _init);
fclose(_init);
_init = fopen(IndexFileName.c_str(), "wb");
fwrite(&tmp, sizeof(int), 1, _init);
fclose(_init);
}
else {
cout<< "has file" <<endl;
fread(&INFO_LENGTH, sizeof(int), 1, _init);
FeatureMsgInfo* s = new FeatureMsgInfo[INFO_LENGTH];
fseek(_init, sizeof(int), SEEK_SET);
fread(s, sizeof(FeatureMsgInfo), INFO_LENGTH, _init);
fclose(_init);
_init = fopen(IndexFileName.c_str(), "rb");
fread(&DATA_LENGTH, sizeof(int), 1, _init);
fseek(_init, sizeof(int), SEEK_SET);
cout<< "INFO_LENGTH: "<<INFO_LENGTH << " DATA_LENGTH:"<< DATA_LENGTH <<endl;
FeatureWithBox* tmp = new FeatureWithBox[DATA_LENGTH];
fread(tmp, sizeof(FeatureWithBox), DATA_LENGTH, _init);
fclose(_init);
cout<< s[0].FileName <<endl;
/// do have data
TransferData(tmp, s, DATA_LENGTH, INFO_LENGTH);
cout<< INFO_LENGTH << " "<< DATA_LENGTH <<endl;
}
// TODO: Reload data
while(1){
if(STOP_SINGAL){
break;
}
if (!std::fstream(IndexReLoad,std::ios::in)){
cout<<"No update, skip"<<endl;
boost::this_thread::sleep(boost::posix_time::seconds(60));
continue;
}
int total = 0;
cout<< "Begin reload" <<endl;
FILE* _f = fopen(IndexFileName.c_str(), "rb");
fread(&total, sizeof(int), 1, _f);
fclose(_f);
if(total == DATA_LENGTH){
boost::this_thread::sleep(boost::posix_time::seconds(30));
}else{
_f = fopen(IndexFileNameInfo.c_str(), "rb");
fread(&INFO_LENGTH, sizeof(int), 1, _f);
cout<< "Detected reload" <<endl;
FeatureMsgInfo* s = new FeatureMsgInfo[INFO_LENGTH];
fseek(_f, sizeof(int), SEEK_SET);
fread(s, sizeof(FeatureMsgInfo), INFO_LENGTH, _f);
fclose(_f);
_f = fopen(IndexFileName.c_str(), "rb");
fread(&DATA_LENGTH, sizeof(int), 1, _f);
fseek(_f, sizeof(int), SEEK_SET);
FeatureWithBox* tmp = new FeatureWithBox[DATA_LENGTH];
fread(tmp, sizeof(FeatureWithBox), DATA_LENGTH, _f);
fclose(_f);
/// do have data
TransferData(tmp, s, DATA_LENGTH, INFO_LENGTH);
}
if(remove(IndexReLoad.c_str())==0){
cout<<"load success"<<endl;
}else{
cout<<"load fail"<<endl;
}
}
}
void TransferData(FeatureWithBox* box, FeatureMsgInfo* info, int data_len, int info_len){
{
boost::mutex::scoped_lock lock(INDEX_MUTEX_LOCK);
cout<< "debuf" <<endl;
if(boxInfo != NULL)
delete[] boxInfo ;
if(dataInfoSet != NULL)
delete[] dataInfoSet ;
if(dataSet != NULL)
delete[] dataSet ;
cout<< "debuf" <<endl;
boxInfo = new FeatureWithBoxInfo[data_len];
dataInfoSet = info;
dataSet = new FeatureBinary::DataSet[data_len];
cout<< data_len<<" "<<info_len << endl;
for(int i=0; i< data_len; i++){
boxInfo[i].info_id = box[i].info_id;
// cout<<dataInfoSet[box[i].info_id].FileName <<endl;
boxInfo[i].xlu = box[i].xlu;
boxInfo[i].xrd = box[i].xrd;
boxInfo[i].ylu = box[i].ylu;
boxInfo[i].yrd = box[i].yrd;
memcpy((dataSet + i)->data, FeatureBinary::DoHandle(box[i].data), sizeof(int) * 64 );
// cout<< i <<" "<<box[i].ylu << endl;
}
delete[] box;
cout<< data_len<<" "<<info_len << endl;
cout<< "Done Load" <<endl;
}
}
bool connectToFileServer(FeatureMsgInfo* fmi){
socket_as_client = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in kk;
kk.sin_family=AF_INET;
kk.sin_port=htons(FILE_SERVER_PORT);
//kk.sin_addr.s_addr = inet_addr(fmi->ServerIP);
kk.sin_addr.s_addr = inet_addr(DEBUG_FILE_SERVER_IP);
if(connect(socket_as_client,(struct sockaddr*)&kk,sizeof(kk)) <0) {
perror("####ServerMsg###:connect error");
return false;
}
return true;
}
bool sendSearchResult(FeatureMsgInfo* fmi){
if(!connected_to_fileserver){
if(connectToFileServer(fmi)){
cout<<"error, exit!"<<endl;
connected_to_fileserver = true;
}
else{
return false;
}
}
MSGPackage sendbuf;
memset(&sendbuf,'\0',sizeof(sendbuf));
//send data
memset(fmi->ServerIP,'\0',sizeof(fmi->ServerIP));
int len = strlen(DEBUG_SEARCH_SERVER_IP) < MAX_IP_SIZE - 1 ? strlen(DEBUG_SEARCH_SERVER_IP) : MAX_IP_SIZE - 1 ;
memcpy(fmi->ServerIP,DEBUG_SEARCH_SERVER_IP,len);
//int MSGLength = MSG_Package_Retrival(fmi,sendbuf.data);
int MSGLength = 0;
sendbuf.datalen = MSGLength;
if(send(socket_as_client, &sendbuf, sizeof(sendbuf.datalen) + MSGLength, 0) < 0){
perror("####ServerMsg###:send error");
return false;
}
//#if 1
// cout<<"send one search result"<<endl;
// static int send_pkg_count = 0;
// char filename[256] = {'\0'};
// sprintf(filename,"mmr6_sendSearchResult_pkg_%d.log",send_pkg_count++);
// FILE* dump = fopen(filename,"wb");
// fwrite(&sendbuf,sizeof(sendbuf.datalen) + MSGLength,1,dump);
// fflush(dump);
// fclose(dump);
//#endif
return true;
}
bool sendSearchResult(FeatureMsgInfo* fmi,int topLeftX,int topLeftY,int bottomRightX,int bottomRightY){
if(!connected_to_fileserver){
if(connectToFileServer(fmi)){
cout<<"error, exit!"<<endl;
connected_to_fileserver = true;
}
else{
return false;
}
}
fmi->BoundingBoxNum = 1;
MSGPackage sendbuf;
memset(&sendbuf,'\0',sizeof(sendbuf));
//send data
memset(fmi->ServerIP,'\0',sizeof(fmi->ServerIP));
int len = strlen(DEBUG_SEARCH_SERVER_IP) < MAX_IP_SIZE - 1 ? strlen(DEBUG_SEARCH_SERVER_IP) : MAX_IP_SIZE - 1 ;
memcpy(fmi->ServerIP,DEBUG_SEARCH_SERVER_IP,len);
int MSGLength = MSG_Package_Retrival(fmi,topLeftX, topLeftY, bottomRightX, bottomRightY, sendbuf.data);
sendbuf.datalen = MSGLength;
if(send(socket_as_client, &sendbuf, sizeof(sendbuf.datalen) + MSGLength, 0) < 0){
perror("####ServerMsg###:send error");
return false;
}
#if 0
cout<<"send one search result"<<endl;
static int send_pkg_count = 0;
char filename[256] = {'\0'};
sprintf(filename,"mmr6_sendSearchResult_pkg_%d.log",send_pkg_count++);
FILE* dump = fopen(filename,"wb");
fwrite(&sendbuf,sizeof(sendbuf.datalen) + MSGLength,1,dump);
fflush(dump);
fclose(dump);
#endif
return true;
}
|
a1aaa6d04559f3fb9e32b51681eae6aca50ad8cd | eacb259838517910db3703ddd63dfbef07191071 | /include/matrix.hpp | c3e20537478b6e3c99d7a8a37495f79a0170906c | [] | no_license | amitsingh19975/Boost_Simple_Matrix | e2b52136ec29e0125825fe6fa832ab82786010d6 | baf16bee097166b10d38c2232d620f5663224705 | refs/heads/master | 2020-04-22T00:19:32.162174 | 2019-03-24T18:42:34 | 2019-03-24T18:42:34 | 169,975,636 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,885 | hpp | matrix.hpp | #ifndef MATRIX_HPP
#define MATRIX_HPP
#include <vector>
#include <iostream>
#include <type_traits>
/**
* Simple Matrix
*/
namespace simple{
/**
* Base class for casting
*/
template<typename Expression>
struct BaseExpression{
/**
* @return Expression
*/
constexpr auto self() const-> Expression const&{
return static_cast<Expression const&>(*this);
}
virtual ~BaseExpression(){}
};
/**
* Binary Expression
*/
template<typename Operation, typename Op1, typename Op2>
struct BinaryExpression : public BaseExpression<BinaryExpression<Operation,Op1,Op2>>{
Op1 const& m_lhs;
Op2 const& m_rhs;
Operation m_oper;
/**
* Constructor
* @param Op1 operand
* @param Op2 operand
*/
BinaryExpression(Op1 const& lhs, Op2 const& rhs):m_lhs(lhs),m_rhs(rhs){}
/**
* Saving Common type for later use
*/
using Type = std::common_type_t<typename Op1::Type,typename Op2::Type>;
/**
* evaluating expression
* @param i of type size_t
* @param j of type size_t
*/
constexpr auto operator()(size_t i, size_t j) const -> Type{
return m_oper(m_lhs.self(),m_rhs.self(),i,j);
}
/**
* @return rows
*/
constexpr auto row() const noexcept -> size_t{return m_lhs.row();}
/**
* @return cols
*/
constexpr auto col() const noexcept -> size_t{return m_rhs.col();}
/**
* @return size of vector
*/
constexpr auto size() const noexcept -> size_t{return row() * col();}
virtual ~BinaryExpression(){}
};
/**
* Addition struct which tells how to add
* two binary expression
*/
struct Addtion{
/**
* operator () overloading
* @param Op1 operand
* @param Op2 operand
* @param i of type size_t
* @param j of type size_t
* @return std::common_type_t<typename Op1::Type,typename Op2::Type>
*/
template<typename Op1, typename Op2>
constexpr auto operator()(Op1 const& lhs, Op2 const& rhs, size_t i, size_t j) const->
std::common_type_t<typename Op1::Type,typename Op2::Type>{
return lhs(i,j) + rhs(i,j);
}
};
/**
* Subtraction struct which tells how to add
* two binary expression
*/
struct Subtraction{
/**
* operator () overloading
* @param Op1 operand
* @param Op2 operand
* @param i of type size_t
* @param j of type size_t
* @return std::common_type_t<typename Op1::Type,typename Op2::Type>
*/
template<typename Op1, typename Op2>
constexpr auto operator()(Op1 const& lhs, Op2 const& rhs, size_t i, size_t j) const->
std::common_type_t<typename Op1::Type,typename Op2::Type>{
return lhs(i,j) - rhs(i,j);
}
};
/**
* Multipication struct which tells how to add
* two binary expression
*/
struct Multipication{
/**
* operator () overloading
* @param Op1 operand
* @param Op2 operand
* @param i of type size_t
* @param j of type size_t
* @return std::common_type_t<typename Op1::Type,typename Op2::Type>
*/
template<typename Op1, typename Op2>
constexpr auto operator()(Op1 const& lhs, Op2 const& rhs, size_t i, size_t j) const->
std::common_type_t<typename Op1::Type,typename Op2::Type>{
std::common_type_t<typename Op1::Type,typename Op2::Type> sum = 0;
for(size_t k = 0; k < lhs.col(); k++){
sum += lhs(i,k) * rhs(k,j);
}
return sum;
}
};
/**
* operator + overloading
* @param lhs type of BaseExpression
* @param rhs type of BaseExpression
* @return BinaryExpression<Addtion,Op1,Op2>
*/
template<typename Op1, typename Op2>
auto operator+(BaseExpression<Op1> const& lhs, BaseExpression<Op2> const& rhs) -> BinaryExpression<Addtion,Op1,Op2>{
assert(lhs.self().row() == rhs.self().row());
assert(lhs.self().col() == rhs.self().col());
return {lhs.self(),rhs.self()};
}
/**
* operator - overloading
* @param lhs type of BaseExpression
* @param rhs type of BaseExpression
* @return BinaryExpression<Subtraction,Op1,Op2>
*/
template<typename Op1, typename Op2>
auto operator-(BaseExpression<Op1> const& lhs, BaseExpression<Op2> const& rhs) -> BinaryExpression<Subtraction,Op1,Op2>{
assert(lhs.self().row() == rhs.self().row());
assert(lhs.self().col() == rhs.self().col());
return {lhs.self(),rhs.self()};
}
/**
* operator * overloading
* @param lhs type of BaseExpression
* @param rhs type of BaseExpression
* @return BinaryExpression<Multipication,Op1,Op2>
*/
template<typename Op1, typename Op2>
auto operator*(BaseExpression<Op1> const& lhs, BaseExpression<Op2> const& rhs) -> BinaryExpression<Multipication,Op1,Op2>{
assert(lhs.self().row() == rhs.self().col());
return {lhs.self(),rhs.self()};
}
template<typename T>
class Matrix : public BaseExpression<Matrix<T>>{
private:
/**
* private member for storing data
*/
std::vector<T> m_data;
/**
* prevate member for storing rows
*/
size_t m_row;
/**
* prevate member for storing cols
*/
size_t m_col;
public:
using Type = T;
/**
* default constructor
*/
Matrix():m_row(0),m_col(0){}
/**
* Constructor
* @param row type of size_t
* @param col type of size_t
*/
Matrix(size_t row, size_t col):m_row(row),m_col(col),m_data(col * row, 0){}
/**
* Constructor
* @param row type of size_t
* @param col type of size_t
* @param initial type of any type for storing default value
*/
Matrix(size_t row, size_t col, T initial):m_row(row),m_col(col),m_data(col * row, initial){}
/**
* Constructor
* @param row type of size_t
* @param col type of size_t
* @param data type of std::vector of any type
*/
Matrix(size_t row, size_t col, std::vector<T>& data):m_row(row),m_col(col),m_data(data){}
/**
* Constructor
* @param row type of size_t
* @param col type of size_t
* @param data type of std::vector of any type move semantics
*/
Matrix(size_t row, size_t col, std::vector<T>&& data):m_row(row),m_col(col),m_data(std::move(data)){}
/**
* Copy Constructor
* @param m type of Matrix
*/
Matrix(Matrix<T> const& m):m_row(m.m_row),m_col(m.m_col),m_data(m.m_data){}
/**
* Copy Constructor
* @param m type of Matrix
*/
template<typename Expression>
Matrix(BaseExpression<Expression> const& m);
/**
* Operator() Overloading
* @param i type of size_t
* @param j type of size_t
* @return T
*/
T& operator()(size_t i, size_t j);
/**
* Operator() Overloading
* @param i type of size_t
* @param j type of size_t
* @return const T
*/
const T operator()(size_t i, size_t j) const;
/**
* Operator[] Overloading
* for accessing linearly
* @param i type of size_t
* @return T&
*/
T& operator[](size_t i);
/**
* @returns the number of rows
*/
size_t row() const noexcept;
/**
* @returns the number of cols
*/
size_t col() const noexcept;
/**
* @returns the number of size of vector
*/
size_t size() const noexcept;
/**
* Operator<< Overloading
* for showing matrix
*/
friend std::ostream &operator<<(std::ostream &os, Matrix const &m){
os<<'['<<' '<<'\n';
for(size_t i = 0; i < m.row(); i++){
os<<' '<<'('<<' ';
for (size_t j = 0; j < m.col(); j++){
os << m.m_data[(j * m.row()) + i]<<',';
if(j != m.col() - 1){
os<<' ';
}
}
os<<')'<<','<<'\n';
}
os<<']'<<'\n';
return os;
}
/**
* Operator== Overloading
* @return Matrix
*/
template<typename Expression>
Matrix& operator=(BaseExpression<Expression> const &rhs);
/**
* Operator== Overloading
* @return Matrix
*/
template<typename Expression>
Matrix& operator=(BaseExpression<Expression> &&rhs);
/**
* Operator+= Overloading
* for addtion of two matrices
* and assigns them
* @return Matrix
*/
template<typename Expression>
Matrix& operator+=(BaseExpression<Expression> const &rhs);
/**
* Operator-= Overloading
* for subtraction of two matrices
* and assigns them
* @return Matrix
*/
template<typename Expression>
Matrix& operator-=(BaseExpression<Expression> const &rhs);
/**
* Operator*= Overloading
* for multipication of two matrices
* and assigns them
* @return Matrix
*/
template<typename Expression>
Matrix operator*=(BaseExpression<Expression> const &rhs);
/**
* Operator== Overloading
* for comparision of two matrices
* @return bool true if they are equal
* otherwise false
*/
template<typename Expression>
bool operator==(BaseExpression<Expression> const &rhs);
/**
* Operator!= Overloading
* for comparision of two matrices
* @return bool true if they are not equal
* otherwise false
*/
template<typename Expression>
bool operator!=(BaseExpression<Expression> const &rhs);
/**
* Destructor
*/
~Matrix(){}
};
template<typename T>
template<typename Expression>
Matrix<T>::Matrix(BaseExpression<Expression> const& m){
Expression const& temp = m.self();
m_data.resize(temp.row() * temp.col());
m_row = temp.row();
m_col = temp.col();
for(auto i = 0 ; i < m_row ; i++){
for(auto j = 0 ; j < m_col ; j++){
this->operator()(i,j) = temp(i,j);
}
}
}
template<typename T>
size_t Matrix<T>::row() const noexcept{
return m_row;
}
template<typename T>
size_t Matrix<T>::col() const noexcept{
return m_col;
}
template<typename T>
size_t Matrix<T>::size() const noexcept{
return m_data.size();
}
template<typename T>
T& Matrix<T>::operator()(size_t i, size_t j){
if(i >= m_row || j >= m_col){
throw std::out_of_range("Out of Range!");
}
return m_data[(j * m_row) + i];
}
template<typename T>
const T Matrix<T>::operator()(size_t i, size_t j) const{
if(i >= m_row || j >= m_col){
throw std::out_of_range("Out of Range!");
}
return m_data[(j * m_row) + i];
}
template<typename T>
T& Matrix<T>::operator[](size_t i){
if(i >= m_data.size()){
throw std::out_of_range("Out of Range!");
}
return m_data[i];
}
template<typename T>
template<typename Expression>
Matrix<T>& Matrix<T>::operator+=(BaseExpression<Expression> const &rhs){
*this = (*this + rhs);
return *this;
}
template<typename T>
template<typename Expression>
Matrix<T>& Matrix<T>::operator-=(BaseExpression<Expression> const &rhs){
*this = (*this - rhs);
return *this;
}
template<typename T>
template<typename Expression>
Matrix<T> Matrix<T>::operator*=(BaseExpression<Expression> const &rhs){
Matrix<T> temp = *this * rhs;
*this = temp;
return *this;
}
template<typename T>
template<typename Expression>
Matrix<T>& Matrix<T>::operator=(BaseExpression<Expression> const &rhs){
Expression const& n_rhs = rhs.self();
this->m_col = n_rhs.col();
this->m_row = n_rhs.row();
m_data.resize(m_col*m_row);
for(auto i = 0; i < row(); i++){
for(auto j = 0; j < col(); j++){
this->operator()(i,j) = n_rhs(i,j);
}
}
return *this;
}
template<typename T>
template<typename Expression>
Matrix<T>& Matrix<T>::operator=(BaseExpression<Expression> &&rhs){
Expression const& n_rhs = rhs.self();
this->m_col = std::move(n_rhs.col());
this->m_row = std::move(n_rhs.row());
m_data.resize(m_col*m_row);
for(auto i = 0; i < n_rhs.row(); i++){
for(auto j = 0; j < n_rhs.col(); j++){
this->operator()(i,j) = std::move(n_rhs(i,j));
}
}
return *this;
}
template<typename T>
template<typename Expression>
bool Matrix<T>::operator==(BaseExpression<Expression> const& rhs){
Expression const& n_rhs = rhs.self();
if(this->m_col != n_rhs.col() && this->m_row != n_rhs.row()) return false;
for(auto i = 0; i < n_rhs.row(); i++){
for(auto j = 0; j < n_rhs.col(); j++){
if( this->operator()(i,j) != n_rhs(i,j) ) return false;
}
}
return true;
}
template<typename T>
template<typename Expression>
bool Matrix<T>::operator!=(BaseExpression<Expression> const& rhs){
return !((*this) == rhs);
}
}
#endif |
48f414f02e92cae8f526781a06e355af4185c0a7 | 0a7c429c78853d865ff19f2a75f26690b8e61b9c | /Usul/Interfaces/IProjectCoordinates.h | 27bc591c627224ecaa6426065303cb67f9190672 | [] | no_license | perryiv/cadkit | 2a896c569b1b66ea995000773f3e392c0936c5c0 | 723db8ac4802dd8d83ca23f058b3e8ba9e603f1a | refs/heads/master | 2020-04-06T07:43:30.169164 | 2018-11-13T03:58:57 | 2018-11-13T03:58:57 | 157,283,008 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | h | IProjectCoordinates.h |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Arizona State University
// All rights reserved.
// BSD License: http://www.opensource.org/licenses/bsd-license.html
// Created by: Adam Kubach
//
///////////////////////////////////////////////////////////////////////////////
#ifndef __USUL_PROJECT_COORDINATES_H__
#define __USUL_PROJECT_COORDINATES_H__
#include "Usul/Interfaces/IUnknown.h"
#include "Usul/Math/Vector3.h"
#include <vector>
#include <map>
#include <string>
namespace Usul {
namespace Interfaces {
struct IProjectCoordinates : public Usul::Interfaces::IUnknown
{
/// Smart-pointer definitions.
USUL_DECLARE_QUERY_POINTERS ( IProjectCoordinates );
/// Id for this interface.
enum { IID = 1081536333u };
struct ProjectionInfo
{
ProjectionInfo ( const std::string& name_, int code_ ) : name ( name_ ), code ( code_ )
{
}
std::string name;
int code;
};
typedef std::vector<ProjectionInfo> ProjectionInfos;
typedef std::map<std::string, ProjectionInfos> Projections;
/// Get a list of projection names.
virtual Projections projectionList() const = 0;
/// Project to lat/lon with elevation using given spatial reference id.
virtual void projectToSpherical ( const Usul::Math::Vec3d& orginal, unsigned int srid, Usul::Math::Vec3d& latLonPoint ) const = 0;
}; // struct IProjectCoordinates
} // end namespace Interfaces
} // end namespace Usul
#endif /* __USUL_PROJECT_COORDINATES_H__ */
|
c00e93d4197a19d838b3d4d54a6b120f3b7dc7e6 | aa7eca0eeccc7c71678a90fc04c02dce9f47ec46 | /Codes_13TeV/PostAnalyzer_Run2015Data_2p5fbinv/PostAnalyzer_Qstar13TeV/LimitCode/BAT-0.9.2/src/BCH2DDict.cxx | e8a0b44580dd183741e5fbba39195d5c6c9cf2fa | [
"DOC"
] | permissive | rockybala/Analyses_codes | 86c055ebe45b8ec96ed7bcddc5dd9c559d643523 | cc727a3414bef37d2e2110b66a4cbab8ba2bacf2 | refs/heads/master | 2021-09-15T10:25:33.040778 | 2018-05-30T11:50:42 | 2018-05-30T11:50:42 | 133,632,693 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 29,095 | cxx | BCH2DDict.cxx | //
// File generated by /cvmfs/cms.cern.ch/slc6_amd64_gcc481/lcg/root/5.34.10-cms7//bin/rootcint at Sun Feb 14 14:56:16 2016
// Do NOT change. Changes will be lost next time file is generated
//
#define R__DICTIONARY_FILENAME BCH2DDict
#include "RConfig.h" //rootcint 4834
#if !defined(R__ACCESS_IN_SYMBOL)
//Break the privacy of classes -- Disabled for the moment
#define private public
#define protected public
#endif
// Since CINT ignores the std namespace, we need to do so in this file.
namespace std {} using namespace std;
#include "BCH2DDict.h"
#include "TClass.h"
#include "TBuffer.h"
#include "TMemberInspector.h"
#include "TError.h"
#ifndef G__ROOT
#define G__ROOT
#endif
#include "RtypesImp.h"
#include "TIsAProxy.h"
#include "TFileMergeInfo.h"
// START OF SHADOWS
namespace ROOT {
namespace Shadow {
} // of namespace Shadow
} // of namespace ROOT
// END OF SHADOWS
namespace ROOT {
void BCH2D_ShowMembers(void *obj, TMemberInspector &R__insp);
static void BCH2D_Dictionary();
static void *new_BCH2D(void *p = 0);
static void *newArray_BCH2D(Long_t size, void *p);
static void delete_BCH2D(void *p);
static void deleteArray_BCH2D(void *p);
static void destruct_BCH2D(void *p);
// Function generating the singleton type initializer
static TGenericClassInfo *GenerateInitInstanceLocal(const ::BCH2D*)
{
::BCH2D *ptr = 0;
static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(::BCH2D),0);
static ::ROOT::TGenericClassInfo
instance("BCH2D", "./../BAT/BCH2D.h", 34,
typeid(::BCH2D), DefineBehavior(ptr, ptr),
0, &BCH2D_Dictionary, isa_proxy, 0,
sizeof(::BCH2D) );
instance.SetNew(&new_BCH2D);
instance.SetNewArray(&newArray_BCH2D);
instance.SetDelete(&delete_BCH2D);
instance.SetDeleteArray(&deleteArray_BCH2D);
instance.SetDestructor(&destruct_BCH2D);
return &instance;
}
TGenericClassInfo *GenerateInitInstance(const ::BCH2D*)
{
return GenerateInitInstanceLocal((::BCH2D*)0);
}
// Static variable to force the class initialization
static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::BCH2D*)0x0); R__UseDummy(_R__UNIQUE_(Init));
// Dictionary for non-ClassDef classes
static void BCH2D_Dictionary() {
::ROOT::GenerateInitInstanceLocal((const ::BCH2D*)0x0)->GetClass();
}
} // end of namespace ROOT
namespace ROOT {
// Wrappers around operator new
static void *new_BCH2D(void *p) {
return p ? ::new((::ROOT::TOperatorNewHelper*)p) ::BCH2D : new ::BCH2D;
}
static void *newArray_BCH2D(Long_t nElements, void *p) {
return p ? ::new((::ROOT::TOperatorNewHelper*)p) ::BCH2D[nElements] : new ::BCH2D[nElements];
}
// Wrapper around operator delete
static void delete_BCH2D(void *p) {
delete ((::BCH2D*)p);
}
static void deleteArray_BCH2D(void *p) {
delete [] ((::BCH2D*)p);
}
static void destruct_BCH2D(void *p) {
typedef ::BCH2D current_t;
((current_t*)p)->~current_t();
}
} // end of namespace ROOT for class ::BCH2D
/********************************************************
* BCH2DDict.cxx
* CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED
* FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX().
* CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE.
********************************************************/
#ifdef G__MEMTEST
#undef malloc
#undef free
#endif
#if defined(__GNUC__) && __GNUC__ >= 4 && ((__GNUC_MINOR__ == 2 && __GNUC_PATCHLEVEL__ >= 1) || (__GNUC_MINOR__ >= 3))
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
extern "C" void G__cpp_reset_tagtableBCH2DDict();
extern "C" void G__set_cpp_environmentBCH2DDict() {
G__add_compiledheader("TObject.h");
G__add_compiledheader("TMemberInspector.h");
G__add_compiledheader("../BAT/BCH2D.h");
G__cpp_reset_tagtableBCH2DDict();
}
#include <new>
extern "C" int G__cpp_dllrevBCH2DDict() { return(30051515); }
/*********************************************************
* Member function Interface Method
*********************************************************/
/* BCH2D */
static int G__BCH2DDict_171_0_1(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
BCH2D* p = NULL;
char* gvp = (char*) G__getgvp();
int n = G__getaryconstruct();
if (n) {
if ((gvp == (char*)G__PVOID) || (gvp == 0)) {
p = new BCH2D[n];
} else {
p = new((void*) gvp) BCH2D[n];
}
} else {
if ((gvp == (char*)G__PVOID) || (gvp == 0)) {
p = new BCH2D;
} else {
p = new((void*) gvp) BCH2D;
}
}
result7->obj.i = (long) p;
result7->ref = (long) p;
G__set_tagnum(result7,G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_2(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
BCH2D* p = NULL;
char* gvp = (char*) G__getgvp();
//m: 1
if ((gvp == (char*)G__PVOID) || (gvp == 0)) {
p = new BCH2D((TH2D*) G__int(libp->para[0]));
} else {
p = new((void*) gvp) BCH2D((TH2D*) G__int(libp->para[0]));
}
result7->obj.i = (long) p;
result7->ref = (long) p;
G__set_tagnum(result7,G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_3(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 85, (long) ((BCH2D*) G__getstructoffset())->GetHistogram());
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_4(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
((BCH2D*) G__getstructoffset())->SetHistogram((TH2D*) G__int(libp->para[0]));
G__setnull(result7);
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_5(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
((BCH2D*) G__getstructoffset())->SetGlobalMode((double*) G__int(libp->para[0]));
G__setnull(result7);
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_6(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
switch (libp->paran) {
case 4:
((BCH2D*) G__getstructoffset())->Print((const char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (int) G__int(libp->para[2]), (int) G__int(libp->para[3]));
G__setnull(result7);
break;
case 3:
((BCH2D*) G__getstructoffset())->Print((const char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (int) G__int(libp->para[2]));
G__setnull(result7);
break;
case 2:
((BCH2D*) G__getstructoffset())->Print((const char*) G__int(libp->para[0]), (int) G__int(libp->para[1]));
G__setnull(result7);
break;
case 1:
((BCH2D*) G__getstructoffset())->Print((const char*) G__int(libp->para[0]));
G__setnull(result7);
break;
}
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_7(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
switch (libp->paran) {
case 2:
((BCH2D*) G__getstructoffset())->Draw((int) G__int(libp->para[0]), (bool) G__int(libp->para[1]));
G__setnull(result7);
break;
case 1:
((BCH2D*) G__getstructoffset())->Draw((int) G__int(libp->para[0]));
G__setnull(result7);
break;
case 0:
((BCH2D*) G__getstructoffset())->Draw();
G__setnull(result7);
break;
}
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_8(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
((BCH2D*) G__getstructoffset())->CalculateIntegratedHistogram();
G__setnull(result7);
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_9(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letdouble(result7, 100, (double) ((BCH2D*) G__getstructoffset())->GetLevel((double) G__double(libp->para[0])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_10(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
{
vector<int>* pobj;
vector<int> xobj = ((BCH2D*) G__getstructoffset())->GetNIntervalsY((TH2D*) G__int(libp->para[0]), *(int*) G__Intref(&libp->para[1]));
pobj = new vector<int>(xobj);
result7->obj.i = (long) ((void*) pobj);
result7->ref = result7->obj.i;
G__store_tempobject(*result7);
}
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_11(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 85, (long) ((BCH2D*) G__getstructoffset())->GetLowestBandGraph((TH2D*) G__int(libp->para[0]), *((vector<int>*) G__int(libp->para[1]))));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_12(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 85, (long) ((BCH2D*) G__getstructoffset())->GetLowestBandGraph((TH2D*) G__int(libp->para[0])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_13(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
{
vector<double>* pobj;
vector<double> xobj = ((BCH2D*) G__getstructoffset())->GetLevelBoundary((double) G__double(libp->para[0]));
pobj = new vector<double>(xobj);
result7->obj.i = (long) ((void*) pobj);
result7->ref = result7->obj.i;
G__store_tempobject(*result7);
}
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_14(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
{
vector<double>* pobj;
vector<double> xobj = ((BCH2D*) G__getstructoffset())->GetLevelBoundary((TH2D*) G__int(libp->para[0]), (double) G__double(libp->para[1]));
pobj = new vector<double>(xobj);
result7->obj.i = (long) ((void*) pobj);
result7->ref = result7->obj.i;
G__store_tempobject(*result7);
}
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_15(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 85, (long) ((BCH2D*) G__getstructoffset())->GetBandGraph((double) G__double(libp->para[0]), (double) G__double(libp->para[1])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_16(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 85, (long) ((BCH2D*) G__getstructoffset())->GetBandGraph((TH2D*) G__int(libp->para[0]), (double) G__double(libp->para[1])
, (double) G__double(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__BCH2DDict_171_0_17(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 85, (long) ((BCH2D*) G__getstructoffset())->GetBandGraphs((TH2D*) G__int(libp->para[0]), *(int*) G__Intref(&libp->para[1])));
return(1 || funcname || hash || result7 || libp) ;
}
// automatic copy constructor
static int G__BCH2DDict_171_0_18(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
BCH2D* p;
void* tmp = (void*) G__int(libp->para[0]);
p = new BCH2D(*(BCH2D*) tmp);
result7->obj.i = (long) p;
result7->ref = (long) p;
G__set_tagnum(result7,G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D));
return(1 || funcname || hash || result7 || libp) ;
}
// automatic destructor
typedef BCH2D G__TBCH2D;
static int G__BCH2DDict_171_0_19(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
char* gvp = (char*) G__getgvp();
long soff = G__getstructoffset();
int n = G__getaryconstruct();
//
//has_a_delete: 0
//has_own_delete1arg: 0
//has_own_delete2arg: 0
//
if (!soff) {
return(1);
}
if (n) {
if (gvp == (char*)G__PVOID) {
delete[] (BCH2D*) soff;
} else {
G__setgvp((long) G__PVOID);
for (int i = n - 1; i >= 0; --i) {
((BCH2D*) (soff+(sizeof(BCH2D)*i)))->~G__TBCH2D();
}
G__setgvp((long)gvp);
}
} else {
if (gvp == (char*)G__PVOID) {
delete (BCH2D*) soff;
} else {
G__setgvp((long) G__PVOID);
((BCH2D*) (soff))->~G__TBCH2D();
G__setgvp((long)gvp);
}
}
G__setnull(result7);
return(1 || funcname || hash || result7 || libp) ;
}
// automatic assignment operator
static int G__BCH2DDict_171_0_20(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
BCH2D* dest = (BCH2D*) G__getstructoffset();
*dest = *(BCH2D*) libp->para[0].ref;
const BCH2D& obj = *dest;
result7->ref = (long) (&obj);
result7->obj.i = (long) (&obj);
return(1 || funcname || hash || result7 || libp) ;
}
/* Setting up global function */
/*********************************************************
* Member function Stub
*********************************************************/
/* BCH2D */
/*********************************************************
* Global function Stub
*********************************************************/
/*********************************************************
* Get size of pointer to member function
*********************************************************/
class G__Sizep2memfuncBCH2DDict {
public:
G__Sizep2memfuncBCH2DDict(): p(&G__Sizep2memfuncBCH2DDict::sizep2memfunc) {}
size_t sizep2memfunc() { return(sizeof(p)); }
private:
size_t (G__Sizep2memfuncBCH2DDict::*p)();
};
size_t G__get_sizep2memfuncBCH2DDict()
{
G__Sizep2memfuncBCH2DDict a;
G__setsizep2memfunc((int)a.sizep2memfunc());
return((size_t)a.sizep2memfunc());
}
/*********************************************************
* virtual base class offset calculation interface
*********************************************************/
/* Setting up class inheritance */
/*********************************************************
* Inheritance information setup/
*********************************************************/
extern "C" void G__cpp_setup_inheritanceBCH2DDict() {
/* Setting up class inheritance */
}
/*********************************************************
* typedef information setup/
*********************************************************/
extern "C" void G__cpp_setup_typetableBCH2DDict() {
/* Setting up typedef entry */
G__search_typename2("vector<ROOT::TSchemaHelper>",117,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR),0,-1);
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__BCH2DDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__BCH2DDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("vector<TVirtualArray*>",117,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR),0,-1);
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__BCH2DDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__BCH2DDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("vector<int>",117,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR),0,-1);
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__BCH2DDictLN_reverse_iteratorlEvectorlEintcOallocatorlEintgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__BCH2DDictLN_reverse_iteratorlEvectorlEintcOallocatorlEintgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR));
G__setnewtype(-1,NULL,0);
}
/*********************************************************
* Data Member information setup/
*********************************************************/
/* Setting up class,struct,union tag member variable */
/* BCH2D */
static void G__setup_memvarBCH2D(void) {
G__tag_memvar_setup(G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D));
{ BCH2D *p; p=(BCH2D*)0x1000; if (p) { }
G__memvar_setup((void*)0,85,0,0,G__get_linked_tagnum(&G__BCH2DDictLN_TH2D),-1,-1,4,"fHistogram=",0,(char*)NULL);
G__memvar_setup((void*)0,85,0,0,G__get_linked_tagnum(&G__BCH2DDictLN_TH1D),-1,-1,4,"fIntegratedHistogram=",0,(char*)NULL);
G__memvar_setup((void*)0,100,0,0,-1,-1,-1,4,"fMode[2]=",0,(char*)NULL);
G__memvar_setup((void*)0,105,0,0,-1,-1,-1,4,"fModeFlag=",0,(char*)NULL);
}
G__tag_memvar_reset();
}
extern "C" void G__cpp_setup_memvarBCH2DDict() {
}
/***********************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
***********************************************************/
/*********************************************************
* Member function information setup for each class
*********************************************************/
static void G__setup_memfuncBCH2D(void) {
/* BCH2D */
G__tag_memfunc_setup(G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D));
G__memfunc_setup("BCH2D",323,G__BCH2DDict_171_0_1, 105, G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("BCH2D",323,G__BCH2DDict_171_0_2, 105, G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D), -1, 0, 1, 1, 1, 0, "U 'TH2D' - 0 - h", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetHistogram",1230,G__BCH2DDict_171_0_3, 85, G__get_linked_tagnum(&G__BCH2DDictLN_TH2D), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("SetHistogram",1242,G__BCH2DDict_171_0_4, 121, -1, -1, 0, 1, 1, 1, 0, "U 'TH2D' - 0 - hist", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("SetGlobalMode",1282,G__BCH2DDict_171_0_5, 121, -1, -1, 0, 1, 1, 1, 0, "D - - 0 - mode", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("Print",525,G__BCH2DDict_171_0_6, 121, -1, -1, 0, 4, 1, 1, 0,
"C - - 10 - filename i - - 0 '0' options "
"i - - 0 '0' ww i - - 0 '0' wh", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("Draw",398,G__BCH2DDict_171_0_7, 121, -1, -1, 0, 2, 1, 1, 0,
"i - - 0 '0' options g - - 0 'true' drawmode", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("CalculateIntegratedHistogram",2883,G__BCH2DDict_171_0_8, 121, -1, -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetLevel",792,G__BCH2DDict_171_0_9, 100, -1, -1, 0, 1, 1, 1, 0, "d - - 0 - p", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetNIntervalsY",1407,G__BCH2DDict_171_0_10, 117, G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR), G__defined_typename("vector<int>"), 0, 2, 1, 1, 0,
"U 'TH2D' - 0 - h i - - 1 - nfoundmax", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetLowestBandGraph",1797,G__BCH2DDict_171_0_11, 85, G__get_linked_tagnum(&G__BCH2DDictLN_TGraph), -1, 0, 2, 1, 1, 0,
"U 'TH2D' - 0 - h u 'vector<int,allocator<int> >' 'vector<int>' 0 - nint", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetLowestBandGraph",1797,G__BCH2DDict_171_0_12, 85, G__get_linked_tagnum(&G__BCH2DDictLN_TGraph), -1, 0, 1, 1, 1, 0, "U 'TH2D' - 0 - h", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetLevelBoundary",1628,G__BCH2DDict_171_0_13, 117, G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), G__defined_typename("vector<double>"), 0, 1, 1, 1, 0, "d - - 0 - level", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetLevelBoundary",1628,G__BCH2DDict_171_0_14, 117, G__get_linked_tagnum(&G__BCH2DDictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), G__defined_typename("vector<double>"), 0, 2, 1, 1, 0,
"U 'TH2D' - 0 - h d - - 0 - level", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetBandGraph",1159,G__BCH2DDict_171_0_15, 85, G__get_linked_tagnum(&G__BCH2DDictLN_TGraph), -1, 0, 2, 1, 1, 0,
"d - - 0 - level1 d - - 0 - level2", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetBandGraph",1159,G__BCH2DDict_171_0_16, 85, G__get_linked_tagnum(&G__BCH2DDictLN_TGraph), -1, 0, 3, 1, 1, 0,
"U 'TH2D' - 0 - h d - - 0 - level1 "
"d - - 0 - level2", (char*)NULL, (void*) NULL, 0);
G__memfunc_setup("GetBandGraphs",1274,G__BCH2DDict_171_0_17, 85, G__get_linked_tagnum(&G__BCH2DDictLN_TGraph), -1, 2, 2, 1, 1, 0,
"U 'TH2D' - 0 - h i - - 1 - n", (char*)NULL, (void*) NULL, 0);
// automatic copy constructor
G__memfunc_setup("BCH2D", 323, G__BCH2DDict_171_0_18, (int) ('i'), G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D), -1, 0, 1, 1, 1, 0, "u 'BCH2D' - 11 - -", (char*) NULL, (void*) NULL, 0);
// automatic destructor
G__memfunc_setup("~BCH2D", 449, G__BCH2DDict_171_0_19, (int) ('y'), -1, -1, 0, 0, 1, 1, 0, "", (char*) NULL, (void*) NULL, 0);
// automatic assignment operator
G__memfunc_setup("operator=", 937, G__BCH2DDict_171_0_20, (int) ('u'), G__get_linked_tagnum(&G__BCH2DDictLN_BCH2D), -1, 1, 1, 1, 1, 0, "u 'BCH2D' - 11 - -", (char*) NULL, (void*) NULL, 0);
G__tag_memfunc_reset();
}
/*********************************************************
* Member function information setup
*********************************************************/
extern "C" void G__cpp_setup_memfuncBCH2DDict() {
}
/*********************************************************
* Global variable information setup for each class
*********************************************************/
static void G__cpp_setup_global0() {
/* Setting up global variables */
G__resetplocal();
}
static void G__cpp_setup_global1() {
G__resetglobalenv();
}
extern "C" void G__cpp_setup_globalBCH2DDict() {
G__cpp_setup_global0();
G__cpp_setup_global1();
}
/*********************************************************
* Global function information setup for each class
*********************************************************/
static void G__cpp_setup_func0() {
G__lastifuncposition();
}
static void G__cpp_setup_func1() {
}
static void G__cpp_setup_func2() {
}
static void G__cpp_setup_func3() {
}
static void G__cpp_setup_func4() {
}
static void G__cpp_setup_func5() {
}
static void G__cpp_setup_func6() {
}
static void G__cpp_setup_func7() {
}
static void G__cpp_setup_func8() {
}
static void G__cpp_setup_func9() {
}
static void G__cpp_setup_func10() {
}
static void G__cpp_setup_func11() {
}
static void G__cpp_setup_func12() {
}
static void G__cpp_setup_func13() {
G__resetifuncposition();
}
extern "C" void G__cpp_setup_funcBCH2DDict() {
G__cpp_setup_func0();
G__cpp_setup_func1();
G__cpp_setup_func2();
G__cpp_setup_func3();
G__cpp_setup_func4();
G__cpp_setup_func5();
G__cpp_setup_func6();
G__cpp_setup_func7();
G__cpp_setup_func8();
G__cpp_setup_func9();
G__cpp_setup_func10();
G__cpp_setup_func11();
G__cpp_setup_func12();
G__cpp_setup_func13();
}
/*********************************************************
* Class,struct,union,enum tag information setup
*********************************************************/
/* Setup class/struct taginfo */
G__linked_taginfo G__BCH2DDictLN_vectorlEdoublecOallocatorlEdoublegRsPgR = { "vector<double,allocator<double> >" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR = { "vector<ROOT::TSchemaHelper,allocator<ROOT::TSchemaHelper> >" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR = { "reverse_iterator<vector<ROOT::TSchemaHelper,allocator<ROOT::TSchemaHelper> >::iterator>" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR = { "vector<TVirtualArray*,allocator<TVirtualArray*> >" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR = { "reverse_iterator<vector<TVirtualArray*,allocator<TVirtualArray*> >::iterator>" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_TH1D = { "TH1D" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_TH2D = { "TH2D" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_TGraph = { "TGraph" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_BCH2D = { "BCH2D" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR = { "vector<int,allocator<int> >" , 99 , -1 };
G__linked_taginfo G__BCH2DDictLN_reverse_iteratorlEvectorlEintcOallocatorlEintgRsPgRcLcLiteratorgR = { "reverse_iterator<vector<int,allocator<int> >::iterator>" , 99 , -1 };
/* Reset class/struct taginfo */
extern "C" void G__cpp_reset_tagtableBCH2DDict() {
G__BCH2DDictLN_vectorlEdoublecOallocatorlEdoublegRsPgR.tagnum = -1 ;
G__BCH2DDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR.tagnum = -1 ;
G__BCH2DDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR.tagnum = -1 ;
G__BCH2DDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR.tagnum = -1 ;
G__BCH2DDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR.tagnum = -1 ;
G__BCH2DDictLN_TH1D.tagnum = -1 ;
G__BCH2DDictLN_TH2D.tagnum = -1 ;
G__BCH2DDictLN_TGraph.tagnum = -1 ;
G__BCH2DDictLN_BCH2D.tagnum = -1 ;
G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR.tagnum = -1 ;
G__BCH2DDictLN_reverse_iteratorlEvectorlEintcOallocatorlEintgRsPgRcLcLiteratorgR.tagnum = -1 ;
}
extern "C" void G__cpp_setup_tagtableBCH2DDict() {
/* Setting up class,struct,union tag entry */
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_vectorlEdoublecOallocatorlEdoublegRsPgR);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_TH1D);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_TH2D);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_TGraph);
G__tagtable_setup(G__get_linked_tagnum_fwd(&G__BCH2DDictLN_BCH2D),sizeof(BCH2D),-1,34048,(char*)NULL,G__setup_memvarBCH2D,G__setup_memfuncBCH2D);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_vectorlEintcOallocatorlEintgRsPgR);
G__get_linked_tagnum_fwd(&G__BCH2DDictLN_reverse_iteratorlEvectorlEintcOallocatorlEintgRsPgRcLcLiteratorgR);
}
extern "C" void G__cpp_setupBCH2DDict(void) {
G__check_setup_version(30051515,"G__cpp_setupBCH2DDict()");
G__set_cpp_environmentBCH2DDict();
G__cpp_setup_tagtableBCH2DDict();
G__cpp_setup_inheritanceBCH2DDict();
G__cpp_setup_typetableBCH2DDict();
G__cpp_setup_memvarBCH2DDict();
G__cpp_setup_memfuncBCH2DDict();
G__cpp_setup_globalBCH2DDict();
G__cpp_setup_funcBCH2DDict();
if(0==G__getsizep2memfunc()) G__get_sizep2memfuncBCH2DDict();
return;
}
class G__cpp_setup_initBCH2DDict {
public:
G__cpp_setup_initBCH2DDict() { G__add_setup_func("BCH2DDict",(G__incsetup)(&G__cpp_setupBCH2DDict)); G__call_setup_funcs(); }
~G__cpp_setup_initBCH2DDict() { G__remove_setup_func("BCH2DDict"); }
};
G__cpp_setup_initBCH2DDict G__cpp_setup_initializerBCH2DDict;
|
3430a7665349d409a87c5615fe69157a6838630a | 7253d45d66b12b309f320c2f7cd25ae94bf8c0d8 | /systems/collision.cpp | 7bb55d93e242cf041019554536728f7c54bfa9b2 | [] | no_license | bysnack/ray_caster | 781648a82656cf5610f05e5ba389330c2d686ece | 1fa7c6034f81da220faa5e3d5379744b41225328 | refs/heads/master | 2021-07-03T14:08:42.042129 | 2021-01-24T20:15:29 | 2021-01-24T20:15:29 | 218,593,513 | 0 | 0 | null | 2020-02-08T20:48:58 | 2019-10-30T18:16:29 | C++ | UTF-8 | C++ | false | false | 2,455 | cpp | collision.cpp | #include "collision.h"
#include "../components/components.h"
#include "../utils/vector.h"
/*
* Anonymous namespace
*
* @brief Contains a set of helper functions used to detect collisions
*/
namespace {
/*
* Heading to pos modifier
*
* @brief Calculates a position modifier depending on the current
* heading
* @param heading The heading entity of the movable component
* @returns The calculated position modifier
*/
utils::coordinates::world heading_to_pos_modifier(components::heading heading) {
utils::coordinates::world modifier{0.f, 0.f};
switch (heading) {
case components::heading::east:
modifier = {-1.f, 0.f};
break;
case components::heading::west:
modifier = {1.f, 0.f};
break;
case components::heading::south:
modifier = {0.f, -1.f};
break;
case components::heading::north:
modifier = {0.f, 1.f};
break;
}
return modifier;
}
/*
* Cells colision detecter
*
* @brief Detects collisions between a movable and a group of
* cells
* @param cells The group of cells
* @param component The component to detect collisions with
* @returns Whether a collision was detected or not
*/
template <class entity_t>
bool detect_collision(const std::vector<entities::cell> &cells,
const entity_t &entity) {
auto &[e_position, e_dimensions] = std::get<components::spatial>(entity);
auto [ecx, ecy] = e_position - (e_dimensions / 2);
for (auto &&cell : cells) {
auto &[c_position, c_dimensions] = std::get<components::spatial>(cell);
const auto &[cx, cy] = c_position;
if (ecx < cx + c_dimensions.x && ecx + e_dimensions.x > cx &&
ecy < cy + c_dimensions.y && ecy + e_dimensions.y > cy) {
return true;
}
}
return false;
}
} // namespace
namespace systems {
void collision(entities::entities &container) noexcept {
// only movables can collisionate
container.apply_for<components::spatial, components::speed,
components::heading>([&](auto &&entity) {
// detect collisions with map cells
if (detect_collision(container.get<entities::cell>(), entity)) {
// step back if a collision was detected
std::get<components::spatial>(entity).position +=
heading_to_pos_modifier(std::get<components::heading>(entity)) *
std::get<components::speed>(entity);
}
});
}
} // namespace systems
|
1e9c126aa7cc8701b05a9fef7d9e4044ac6c7744 | 5d0a98b4a6e80e0d663c2503a7b9462812e96141 | /full-screen-window/4DPlugin.cpp | ae9c494c9f077211cfd9e963926b11dbe1a277b7 | [] | no_license | miyako/4d-plugin-full-screen-window | e8339499b66f913ad3c0cb37b5447e2e8b6429a3 | 17cc86e0e3201459404340cdea0abab8abb52d42 | refs/heads/master | 2020-05-23T08:00:38.539098 | 2018-05-29T00:53:38 | 2018-05-29T00:53:38 | 80,484,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,670 | cpp | 4DPlugin.cpp | /* --------------------------------------------------------------------------------
#
# 4DPlugin.cpp
# source generated by 4D Plugin Wizard
# Project : full-screen-window
# author : miyako
# 2017/01/31
#
# --------------------------------------------------------------------------------*/
#include "4DPluginAPI.h"
#include "4DPlugin.h"
#if VERSIONMAC
#import <objc/runtime.h>
#endif
#if VERSIONMAC
#ifndef __LP64__
//or check CGFLOAT_IS_DOUBLE
#define VERSION_MAC_64 0
#define VERSION_MAC_32 1
#else
#define VERSION_MAC_64 1
#define VERSION_MAC_32 0
#endif
#endif
//experimenting with notofication
@interface Listener : NSObject
{
}
- (id)init;
- (void)dealloc;
- (void)didExitFullScreen:(NSNotification *)notification;
@end
@implementation Listener
- (id)init
{
if(!(self = [super init])) return self;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center
addObserver:self
selector: @selector(didExitFullScreen:)
name:NSWindowDidExitFullScreenNotification
object:nil];
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self];
[super dealloc];
}
- (void)didExitFullScreen:(NSNotification *)notification
{
// NSWindow *window = [notification object];
}
@end
void PluginMain(PA_long32 selector, PA_PluginParameters params)
{
try
{
PA_long32 pProcNum = selector;
sLONG_PTR *pResult = (sLONG_PTR *)params->fResult;
PackagePtr pParams = (PackagePtr)params->fParameters;
CommandDispatcher(pProcNum, pResult, pParams);
}
catch(...)
{
}
}
void CommandDispatcher (PA_long32 pProcNum, sLONG_PTR *pResult, PackagePtr pParams)
{
switch(pProcNum)
{
// --- full-screen-window
//#if VERSION_MAC_64
case 1 :
Get_window_full_screen(pResult, pParams);
break;
case 2 :
SET_WINDOW_FULL_SCREEN(pResult, pParams);
break;
//#endif
}
}
// ------------------------------ full-screen-window ------------------------------
NSWindow *PA_GetWindowRef64(int winId)
{
//EX_GET_HWND has been fixed in 15R3 to return a NSWindow* on mac 64bit.
//http://forums.4d.fr/Post/EN/15872830/1/17032044
PA_ulong32 version = (PA_Get4DVersion() & 0x0000FFFF);
// int minor = version & 0x000F;
int r = (version & 0x00F0) >> 4;
int major = (version & 0xFF00) >> 8;
if (((major >=0x15) && (r >= 3)) || (major >=0x16))
{
return (NSWindow *)PA_GetWindowPtr(reinterpret_cast<NSWindow *>(winId));
}
return 0;
}
BOOL Is_window_full_screen(C_LONGINT Param1)
{
BOOL isWindowFullScreen = NO;
NSWindow *window = PA_GetWindowRef64(Param1.getIntValue());
isWindowFullScreen = (([window styleMask] & NSFullScreenWindowMask) == NSFullScreenWindowMask);
return isWindowFullScreen;
}
void Get_window_full_screen(sLONG_PTR *pResult, PackagePtr pParams)
{
C_LONGINT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
returnValue.setIntValue(Is_window_full_screen(Param1));
returnValue.setReturn(pResult);
}
#define CMD_GET_WINDOW_RECT (443)
void SET_WINDOW_FULL_SCREEN(sLONG_PTR *pResult, PackagePtr pParams)
{
C_LONGINT Param1;
C_LONGINT Param2;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
// direct call of NSWindow toggleFullScreen or NSButton performClick cause problems in 4D
if ((!Is_window_full_screen(Param1)) && Param2.getIntValue())
{
//goto full screen
PA_Variable params[5];
params[0] = PA_CreateVariable(eVK_Longint);
params[1] = PA_CreateVariable(eVK_Longint);
params[2] = PA_CreateVariable(eVK_Longint);
params[3] = PA_CreateVariable(eVK_Longint);
params[4] = PA_CreateVariable(eVK_Longint);
PA_SetLongintVariable(¶ms[4], Param1.getIntValue());
PA_ExecuteCommandByID(CMD_GET_WINDOW_RECT, params, 5);
int x = PA_GetLongintVariable(params[0]);
int y = PA_GetLongintVariable(params[1]);
PA_ClearVariable(¶ms[0]);
PA_ClearVariable(¶ms[1]);
PA_ClearVariable(¶ms[2]);
PA_ClearVariable(¶ms[3]);
PA_ClearVariable(¶ms[4]);
//get the local position of the zoom button
NSWindow *window = PA_GetWindowRef64(Param1.getIntValue());
NSButton *zoomButton = [window standardWindowButton:NSWindowZoomButton];
NSRect frame = [zoomButton frame];
//CGPoint is upside-down
CGPoint p;
p.x = x + frame.origin.x + (frame.size.width / 2);
p.y = y - frame.origin.y - (frame.size.height / 2);
//simulate a click event
CGEventSourceRef eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef e;
//remember the current mouse position
CGEventRef oe = CGEventCreate(nil);
CGPoint op = CGEventGetLocation(oe);
CFRelease(oe);
//post click!
e = CGEventCreateMouseEvent (eventSource, kCGEventMouseMoved ,p , 0);
CGEventPost(kCGHIDEventTap, e);
CGEventSetType(e, kCGEventLeftMouseDown);
CGEventPost(kCGHIDEventTap, e);
CGEventSetType(e, kCGEventLeftMouseUp);
CGEventPost(kCGHIDEventTap, e);
CGEventSetType(e, kCGEventMouseMoved);
CGEventSetLocation(e, op);
CGEventPost(kCGHIDEventTap, e);
CFRelease(e);
}else if ((Is_window_full_screen(Param1)) && !Param2.getIntValue())
{
//return from full screen
//the only known way to make sure 4D redraws the window is to deactivate it
[NSApp deactivate];
NSWindow *window = PA_GetWindowRef64(Param1.getIntValue());
[window toggleFullScreen:nil];
//none of these can force a redraw;
[window setViewsNeedDisplay:YES];
[window flushWindow];
[window display];
[window update];
}
}
|
df590b2ff744fa78cad91846999c14b527912bbb | fbc9b87e8b425715286addf14a19205bcbf21923 | /Primer Parcial/cicloforanidado/main.cpp | 372ee035703078ce234009af50b31bda5239368c | [] | no_license | decoello/Programacion2 | 20a1ed0ea5b9ffdde6ff65f65df6e88d3bf1d8ae | 5c056bf99d808242bb6906e3e7adf96936c26373 | refs/heads/master | 2020-06-04T02:01:26.926760 | 2014-09-23T04:24:26 | 2014-09-23T04:24:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | main.cpp | #include <iostream>
using namespace std;
int main()
{
int i,k;
for(i=1;i<5;i++){
for(k=1;k<=i;k++){
cout<<k;
}
cout<<"\n";
}
for(i=5;i>=1;i--){
for(k=1;k<=i;k++){
cout<<k;
}
cout<<"\n";
}
}
|
6e93a52b28c27e25ffcbd32dedbd8ed1bbf81d51 | 11372f47584ed7154697ac3b139bf298cdc10675 | /刷题比赛/HDU/1283.cpp | b3c56aacc7132c8b15bf995d17175245db4e073f | [] | no_license | strategist614/ACM-Code | b5d893103e4d2ea0134fbaeb0cbd18c0fec06d12 | d1e0f36dab47f649e2fade5e7ff23cfd0e8c8e56 | refs/heads/master | 2020-12-20T04:21:50.750182 | 2020-01-24T07:43:50 | 2020-01-24T07:45:08 | 235,958,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | cpp | 1283.cpp | /*
独立思考
一个题不会做,收获5%,写了代码10%,提交对了30%,总结吃透了这个题才是100%.
*/
#include<bits/stdc++.h>
using namespace std;
template <typename T>
void read(T &x)
{
x = 0;
char c = getchar();
int sgn = 1;
while(c<'0'||c>'9'){if(c=='-')sgn=-1;c=getchar();}
while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
x*=sgn;
}
template <typename T>
void out(T x)
{
if(x<0){putchar('-');x=-x;}
if(x>=10)out(x/10);
putchar(x%10+'0');
}
typedef long long ll;
typedef unsigned long long ull;
int m1,m2,r1,r2,r3;
void A()
{
r1 = m1;
}
void B()
{
r2 = m2;
}
void C()
{
m1 = r3;
}
void D()
{
m2 = r3;
}
void E()
{
r3 = r1+r2;
}
void F()
{
r3 = r1-r2;
}
int main ()
{
int n,m;
while(scanf("%d %d",&n,&m)!=EOF)
{
string s;
cin>>s;
m1 = n,m2 = m,r1 = 0,r2 = 0,r3 = 0;
for(int i = 0;i<s.size();i++)
{
if(s[i] == 'A') A();
else if(s[i] == 'B') B();
else if(s[i] == 'C') C();
else if(s[i] == 'D') D();
else if(s[i] == 'E') E();
else F();
}
cout<<m1<<","<<m2<<endl;
}
return 0 ;
} |
3ead160e96f1d1a25e39dff6a7666580365dbe4e | bcddc28628daa3dd1904077bb3307759e7bc732a | /Design Hit Counter.cpp | 85a0f5d2c3c3254966ef9b9a0ad3bdc34d97db3a | [] | no_license | Funsom/Leetcode | 985304fda728cd13a9e16d8d73563f1cacb9a5b0 | c613acb1fed2021f03faa74a73bb8df0d1874e60 | refs/heads/master | 2020-03-19T02:44:32.641984 | 2017-03-24T19:45:15 | 2017-03-24T19:45:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | cpp | Design Hit Counter.cpp | class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() {
res=0;
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
if(!roc.empty()&&roc.back().first==timestamp){
roc.back().second++;
}
else{
roc.push_back({timestamp,1});
}
res++;
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
while(!roc.empty()&&(timestamp-roc.front().first)>=300){
res-=roc.front().second;
roc.pop_front();
}
return res;
}
private:
int res=0;
list<pair<int,int>>roc;
};
|
8587b59230f0b20dfc722b28c272a39ae72b600a | 243b10891fb389f408a48c8f17215464ff7def49 | /KEditor/Inc/Actor/image_actor.cpp | d9d98d6c9feb9440c9a0b6595e5557ccdf38f879 | [] | no_license | kwangminy27/K-Diablo-II-Expansion | 4b3eb4146331995410f77494337e8e61f76f73cb | 9a2adcf915a59871df50848da7db531dcba38979 | refs/heads/master | 2020-04-11T05:50:12.683927 | 2019-01-02T12:44:27 | 2019-01-02T12:44:27 | 161,561,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,819 | cpp | image_actor.cpp | #include "stdafx.h"
#include "image_actor.h"
#include "Component/default_component.h"
void K::ImageActor::Initialize()
{
try
{
auto const& object_manager = ObjectManager::singleton();
auto transform = object_manager->CreateComponent<Transform>(TAG{ TRANSFORM, 0 });
CPTR_CAST<Transform>(transform)->set_local_scaling(Vector3{ 160.f, 80.f, 1.f });
CPTR_CAST<Transform>(transform)->set_local_translation(Vector3::Zero);
AddComponent(transform);
auto material = object_manager->CreateComponent<Material>(TAG{ MATERIAL, 0 });
CPTR_CAST<Material>(material)->SetTexture("catacomb floor", 0, 0, 0);
CPTR_CAST<Material>(material)->SetSampler(LINEAR_SAMPLER, 0, 0, 0);
MaterialConstantBuffer Material_CB{};
Material_CB.diffuse = DirectX::Colors::White.v;
CPTR_CAST<Material>(material)->SetMaterialConstantBuffer(Material_CB, 0, 0);
AddComponent(material);
auto const& rendering_manager = RenderingManager::singleton();
auto renderer = object_manager->CreateComponent<Renderer>(TAG{ RENDERER, 0 });
CPTR_CAST<Renderer>(renderer)->set_mesh(ResourceManager::singleton()->FindMesh(TEX_RECT));
CPTR_CAST<Renderer>(renderer)->set_shader(rendering_manager->FindShader(BASIC_ANIMATION_2D_SHADER));
CPTR_CAST<Renderer>(renderer)->set_render_state(rendering_manager->FindRenderState(DEPTH_DISABLE));
CPTR_CAST<Renderer>(renderer)->set_render_state(rendering_manager->FindRenderState(ALPHA_BLEND));
AddComponent(renderer);
auto collider = object_manager->CreateComponent<ColliderAABB>(TAG{ COLLIDER, 0 });
CPTR_CAST<ColliderAABB>(collider)->set_group_tag(UI);
CPTR_CAST<ColliderAABB>(collider)->set_relative_info(AABB{ Vector2::Zero, Vector2{ 80.f, 40.f } });
AddComponent(collider);
}
catch (std::exception const& _e)
{
std::cout << _e.what() << std::endl;
}
catch (...)
{
std::cout << "ImageActor::Initialize" << std::endl;
}
}
K::APTR K::ImageActor::Clone() const
{
return APTR{ new ImageActor{ *this }, [](ImageActor* _p) {
_p->_Finalize();
delete _p;
} };
}
void K::ImageActor::Serialize(InputMemoryStream& _imstream)
{
}
void K::ImageActor::Serialize(OutputMemoryStream& _omstream)
{
}
void K::ImageActor::set_LT(Vector2 const& _LT)
{
LT_ = _LT;
}
void K::ImageActor::set_RB(Vector2 const& _RB)
{
RB_ = _RB;
}
K::ImageActor::ImageActor(ImageActor const& _other) : ActorClient(_other)
{
LT_ = _other.LT_;
RB_ = _other.RB_;
}
K::ImageActor::ImageActor(ImageActor&& _other) noexcept : ActorClient(std::move(_other))
{
LT_ = std::move(_other.LT_);
RB_ = std::move(_other.RB_);
}
void K::ImageActor::_Finalize()
{
}
void K::ImageActor::_Render(float _time)
{
Animation2DConstantBuffer animation_2d_CB{};
animation_2d_CB.LT = LT_;
animation_2d_CB.RB = RB_;
RenderingManager::singleton()->UpdateConstantBuffer(ANIMATION_2D, &animation_2d_CB);
}
|
c0389dc8aba865df68cb23da3d0de398d13a0431 | b465f47fbcc1037905a2e54dc6bc3b83b80d268f | /CP Codes/Dictionary Search.cpp | 3518fa19c377b6ff3783166531d7ce4e41856b8d | [] | no_license | mrafayfarooq/CPP-Codes | 7db47576a8b8120b0c0d40838b4d322e059b7c31 | 037dd4733c88c4fd0e55c7f4146c2abda5b7ac51 | refs/heads/master | 2016-09-12T11:17:03.249549 | 2016-04-27T18:03:20 | 2016-04-27T18:03:20 | 57,234,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | Dictionary Search.cpp | /*Author:k112257-M.Rafay Farooq
Program Mechanism: Take a character from user and find that character
in the dictionary and tell that how many time that word occurs*/
#include<iostream>
#include<conio.h>
#include<fstream>
#include<assert.h>
using namespace std;
int main()
{
char search;
char find;
string str;
int i=0;
ifstream infile;
infile.open("Dictionary.txt");
cout<<"Please Input a word you wanted to search"<<endl;
cin>>find;
while(!infile.eof())
{
infile>>search;
if(search==find)
{
i++;
}
}
cout<<endl;
//Exception Hanling
try
{
if(i!=0)
{
cout<<i-1;
}
else
{
throw 0;
}
}
catch(int i)
{
cout<<i;
}
getch();
}
|
10013c403a4119b43f5e12cf2489b0febe285858 | f42c5827c1cdccbdf4289789a5ba06d5a1aada6b | /SerialStream.h | baa189060857b0205e89823988605b7b50c7baa6 | [] | no_license | jasperswallen/dhrystone-mbed | e337a1b864855e344ddbde58a09180a77fb10ef4 | 1ab64da99654c55450e9e6a276bec9754201c376 | refs/heads/master | 2023-02-22T16:59:29.605016 | 2021-01-26T09:16:09 | 2021-01-26T09:16:09 | 333,025,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,882 | h | SerialStream.h | #ifndef SERIALSTREAM_H
#define SERIALSTREAM_H
#include <mbed.h>
#include <platform/Stream.h>
/**
* SerialStream
* Bringing MBed serial ports back like it's 1999... or at least 2019.
*
* This class adapts an MBed 6.0 serial port class into a Stream instance.
* This lets you do two useful things with it:
* - Call printf() and scanf() on it
* - Pass it to code that expects a Stream to print things on.
*
*/
template <class SerialClass> class SerialStream : public Stream
{
SerialClass &serialClass;
public:
/**
* Create a SerialStream from a serial port.
* @param _serialClass BufferedSerial or UnbufferedSerial instance
* @param name The name of the stream associated with this serial port
* (optional)
*/
SerialStream(SerialClass &_serialClass, const char *name = nullptr)
: Stream(name), serialClass(_serialClass)
{
}
// override Stream::read() and write() to call serial class directly.
// This avoids the overhead of feeding in individual characters.
virtual ssize_t write(const void *buffer, size_t length)
{
return serialClass.write(buffer, length);
}
virtual ssize_t read(void *buffer, size_t length)
{
return serialClass.read(buffer, length);
}
void sigio(Callback<void()> func)
{
serialClass.sigio(func);
}
void attach(Callback<void()> func, SerialBase::IrqType type = RxIrq)
{
serialClass.attach(func, type);
}
private:
// Dummy implementations -- these will never be called because we override
// write() and read() instead. but we have to override them since they're
// pure virtual.
virtual int _putc(int c)
{
return 0;
}
virtual int _getc()
{
return 0;
}
};
#endif // SERIALSTREAM_H
|
5f92afe092e3de913073b6b577377419bbed9083 | 46558a72c0babae2e12ae51c06f0e3ed609bec45 | /test3/src/test3.cpp | e5b07d0e3efbcc8f1f76636d09d7cbad0d339c2a | [] | no_license | 13651077712/algorithmPractice | f861e6480b07f4137a3d64f7443b42df5489a5fb | 5bd67d75c3d48aae46c21b6428d2db345fbbc531 | refs/heads/master | 2020-08-27T00:24:40.990483 | 2019-11-04T03:28:37 | 2019-11-04T03:28:37 | 217,193,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | cpp | test3.cpp | //============================================================================
// Name : test3.cpp
// Author : bxk
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include "Solution.h"
using namespace std;
int main() {
int num;
string J,S;
Solution* sol = new Solution();
getline(cin,J);
getline(cin,S);
num = sol->numJewelsInStones(J,S);
cout << "拥有的宝石数为:" << num << endl;
return 0;
}
|
8b9848ec5733a7f3b52424dcd7c525ea5117c230 | 36baa210a9d8f31cf11ac805da92545aeac516ba | /DataStructures/main.cpp | b7827b68426bb87375307af7934720ece81cc9ad | [] | no_license | kenshin0302/DataStructures | 09643c74f7cdef867f9513ec4e5b6255aed55bf2 | bb94d7ee1d231b44eb7a02c3b598ea6407cf91d1 | refs/heads/master | 2021-05-18T02:41:56.324535 | 2020-04-02T08:28:15 | 2020-04-02T08:28:15 | 251,069,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | main.cpp | #include "MyStack.h"
#include<iostream>
#include <string>
int main() {
MyStack<int> stack(4);
for (size_t i = 0; i < 1000; i++) {
std::cout << i << std::endl;
stack.Push(i);
}
//LOG("aaa");
std::cout << std::to_string(*stack.Pop()) << std::endl;
std::cout << std::to_string(*stack.Peek()) << std::endl;
char exit;
std::cin>>exit;
} |
b3a83bb79fe9b2723d8ae9a8159f63b35c01ce8f | 0749005eeb6d702d7a1205bb6ac87109a0750128 | /C++/Zad5/Zad5/Lista.h | 3c54a55193a5650f1cadef3f2ebdf158366aff10 | [] | no_license | KamilFCB/Studies | 140305e4b1285f5d9c1d6f009b2de98f1dfb54c8 | 32dbb3b77f421a1f4cdc74828acb5db5e6988a67 | refs/heads/master | 2022-07-23T23:28:25.167352 | 2020-02-11T17:55:53 | 2020-02-11T17:55:53 | 133,565,429 | 0 | 2 | null | 2022-07-08T19:22:26 | 2018-05-15T19:46:03 | C | UTF-8 | C++ | false | false | 338 | h | Lista.h | #pragma once
#include <iostream>
using namespace std;
class Lista
{
public:
Lista();
Lista(int v);
~Lista();
void wypisz();
public:
class Wezel
{
public:
Wezel();
Wezel(double v);
~Wezel();
Wezel *prev;
Wezel *next;
double val;
void dodaj(double v, int poz);
};
public:
Wezel *pierwszy;
Wezel *ostatni;
}; |
efdacf09ec4ef7814d63f0489b2fbe513ef0d9a3 | 03b5b83024bf236ae0aaddfcecc7bec7b93c8516 | /test/test.cpp | 0902eb851c6169d5359ef6e7184e811b10f66737 | [] | no_license | kouxichao/crnn | 049d25876dbce9ba9541a455aefad623426f1415 | 476d1fa46fcfdee28aa05c7fb18cc7b3f628833f | refs/heads/master | 2020-04-06T12:52:02.960052 | 2019-09-21T02:54:47 | 2019-09-21T02:54:47 | 157,473,964 | 27 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 4,381 | cpp | test.cpp | #include<dirent.h>
#include<string.h>
#include<stdio.h>
#include<iostream>
#include<vector>
#include "text_recognization.h"
#include "dlib/dlib/image_io.h"
#include "dlib/dlib/image_processing.h"
#include "dlib/dlib/image_processing/generic_image.h"
int toLowercase(std::string& name_string)
{
for (size_t i = 0; i < name_string.size(); i++)
{
if (name_string[i] >= 'A' && name_string[i] <= 'Z')
{
name_string[i] = name_string[i] + 32;
}
}
return 0;
}
int getAllImages(const char* image_dir, std::vector<std::string>& vImgPaths)
{
DIR* pDir = NULL;
struct dirent* ent = NULL;
pDir = opendir(image_dir);
if (pDir == 0)
{
printf("open folder(%s) FAIL\n", image_dir);
return 0;
}
std::string strFolder = image_dir;
if (strFolder[strFolder.size() - 1] != '/')
strFolder += "/";
while (ent = readdir(pDir))
{
if (ent->d_type & DT_DIR && strcmp(ent -> d_name,".") != 0 && strcmp(ent -> d_name,"..") != 0 )
{
char path[255];
strcpy(path, strFolder.c_str());
strcat(path, ent->d_name);
strcat(path, "/");
getAllImages(path, vImgPaths);
}
int len = (int)strlen(ent->d_name);
if (len >= 5 && strcmp(ent->d_name + len - 4, ".jpg") == 0)
{
char filepath[256];
sprintf(filepath, "%s%s", strFolder.c_str(), ent->d_name);
vImgPaths.push_back(filepath);
printf("%s\n", filepath);
}
}
closedir(pDir);
return 0;
}
int main(int argc, char const *argv[])
{
// const char* imagePath = argv[1];
// std::vector<std::string> vec_imagePath;
// getAllImages(imagePath, vec_imagePath);
FILE *fp = fopen("annotation_test.txt", "r+");
if(NULL == fp)
{
fprintf(stderr, "fopen annotation_test.txt error\n");
}
char pname[255];
long idx;
float count = 0, pre = 0;
while(1)
{
if((fscanf(fp, "%s %ld", pname, &idx)) == EOF)
{
// fprintf(stderr, "fscanf end(error)\n");
break;
}
dlib::array2d<dlib::rgb_pixel> m;
load_image(m, pname);
/* if (m.empty())
{
fprintf(stderr, "cv::imread %s failed\n", imagepath);
return -1;
}
*/
FILE *stream = NULL;
stream = fopen("crnn.data", "wb");
if(NULL == stream)
{
fprintf(stderr, "imgdata read error!");
exit(1);
}
#ifndef RGB_META
unsigned char* rgb_panel = new unsigned char[m.nc()*m.nr()*3];
unsigned char* rgb_panel_r = rgb_panel;
unsigned char* rgb_panel_g = rgb_panel + m.nc()*m.nr();
unsigned char* rgb_panel_b = rgb_panel + m.nc()*m.nr()*2;
for(int r = 0; r < m.nr(); r++)
{
for(int c = 0; c < m.nc(); c++)
{
rgb_panel_r[r*m.nc()+c] = m[r][c].red;
rgb_panel_g[r*m.nc()+c] = m[r][c].green;
rgb_panel_b[r*m.nc()+c] = m[r][c].blue;
}
}
// unsigned char* rgbData = new unsigned char[m.cols*m.rows*3];
fwrite(rgb_panel, 1, m.nc()*m.nr()*3, stream);
delete [] rgb_panel;
#else
fwrite(&m[0][0], 1, m.nc()*m.nr()*3, stream);
#endif
fclose(stream);
DKSBoxTextRecognizationParam param;
param.lexicon = false;//使用词典
char *result,*finres;
typedef struct{
int xmin;
int ymin;
int xmax;
int ymax;
}Bbox;
Bbox bb={0, 0, m.nc(), m.nr()};//124 72 201 89
DKSBox box = {bb.xmin, bb.ymin, bb.xmax, bb.ymin, bb.xmax, bb.ymax, bb.xmin, bb.ymax};
DKBoxTextRecognizationInit();
result = DKBoxTextRecognizationProcess("crnn.data", m.nc(), m.nr(), box, param);
std::size_t name_sta = std::string(pname).find_first_of("_");
std::size_t name_end = std::string(pname).find_last_of("_");
fprintf(stderr, "path:%s\n", pname);
std::string name_string = std::string(pname).substr(name_sta+1, name_end - name_sta - 1);
count++;
printf("%f_recognization results(%s): %s\n",count, name_string.c_str(), result);
toLowercase(name_string);
if(strcmp(result, name_string.c_str()) == 0)
pre++;
printf("%f_recognization results(%s): %s\n",pre, name_string.c_str(), result);
DKBoxTextRecognizationEnd();
}
printf("acc:%f\n", pre/count);
return 0;
}
|
2e73243009135fc0c1aceaaf0d323a0d985593b6 | ace20ae898aadf18c4ef8a2355b528422fc27bb5 | /codeforces/1042D.cpp | 6ba1b25790176c3d9ed776e2c165b1dcd2ad4ef4 | [] | no_license | pidddgy/competitive-programming | 19fd79e7888789c68bf93afa3e63812587cbb0fe | ec86287a0a70f7f43a13cbe26f5aa9c5b02f66cc | refs/heads/master | 2022-01-28T07:01:07.376581 | 2022-01-17T21:37:06 | 2022-01-17T21:37:06 | 139,354,420 | 0 | 3 | null | 2021-04-06T16:56:29 | 2018-07-01T19:03:53 | C++ | UTF-8 | C++ | false | false | 2,104 | cpp | 1042D.cpp | #include <bits/stdc++.h>
using namespace std;
#define cerr if(false) cerr
#define watch(x) cerr << (#x) << " is " << (x) << endl;
#define endl '\n'
#define ld long double
#define int long long
#define pii pair<int, int>
#define fi first
#define se second
#define sz(a) (int)a.size()
#define all(x) (x).begin(), (x).end()
void solve() {
}
const int maxn = 200500;
int a[maxn];
int cur = 0;
int seg[3*maxn];
void upd(int pos, int val) {
pos += cur;
seg[pos] = val;
for(int i = pos/2; i >= 1; i /= 2) {
seg[i] = seg[i*2] + seg[i*2+1];
}
}
int query(int l, int r) {
l += cur;
r += cur;
int res = 0;
while(l <= r) {
if(l%2 == 1) res += seg[l++];
if(r%2 == 0) res += seg[r--];
l /= 2;
r /= 2;
}
return res;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, t;
cin >> n >> t;
for(int i = 1; i <= n; i++) cin >> a[i];
vector<int> cmp;
int sum = 0;
for(int i = 0; i <= n; i++) {
sum += a[i];
// S.emplace(sum);
cmp.emplace_back(sum);
}
// cerr << endl;
sort(all(cmp));
cmp.erase(unique(all(cmp)), cmp.end());
cur = sz(cmp);
int ans = 0;
sum = 0;
upd((lower_bound(all(cmp), 0) - cmp.begin())+1, 1);
for(int i = 1; i <= n; i++) {
sum += a[i];
int rem = -(t-sum-1);
int ind;
auto ree = lower_bound(all(cmp), rem);
if(ree != cmp.end()) {
ind = ree-cmp.begin()+1;
cerr << "querying " << ind << " " << cur << endl;
ans += query(ind, cur);
}
ind = (lower_bound(all(cmp), sum) - cmp.begin())+1;
int old = query(ind, ind);
upd(ind, old+1);
}
cout << ans << endl;
}
/*
rem = minimum element you can subtract
find all with less than or equal to
*/
// Did you read the bounds?
// Did you make typos?
// Are there edge cases (N=1?)
// Are array sizes proper?
// Integer overflow?
// DS reset properly between test cases?
// Is using long longs causing TLE?
// Are you using floating points?
|
2e4368ae62c53c40dba8ddb38645b42f94f9d180 | f9105601fdfb86ec6872b35725cabc61e7585e66 | /OperOverAssign/OperOverAssign.cpp | 40ed088d082e53b0fe5376b67f3ffb1da4565507 | [] | no_license | qudwns2052/cpp | 48d2d9d416c428f80d45de59e1fa707ad5111f1b | 512b7e205dd374327e665c1c7b15c3adc13582f0 | refs/heads/master | 2021-10-19T23:11:47.292646 | 2019-02-24T16:19:54 | 2019-02-24T16:19:54 | 170,008,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 687 | cpp | OperOverAssign.cpp | #include "stdafx.h"
#include <iostream>
using namespace std;
class CMyData
{
private:
int *m_pnData = nullptr;
public:
explicit CMyData(int nParam)
{
m_pnData = new int(nParam);
}
~CMyData() { delete m_pnData; }
operator int() { return *m_pnData; }
CMyData& operator=(const CMyData &rhs)
{
if (this == &rhs)
return *this;
delete m_pnData;
m_pnData = new int(*rhs.m_pnData);
}
CMyData& operator+=(const CMyData &rhs)
{
int *pnNewData = new int(*m_pnData);
*pnNewData += *rhs.m_pnData;
delete m_pnData;
m_pnData = pnNewData;
return *this;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CMyData a(0), b(5);
a = b;
cout << a << endl;
return 0;
}
|
df89c0b8e4d64cd69a88436acb3ef53951d1f391 | fa7474550cac23f55205666e13a99e59c749db97 | /crash-reporter/crash_serializer.cc | 7090ae87365330d698ed5299d3b28b6b329822fa | [
"BSD-3-Clause"
] | permissive | kalyankondapally/chromiumos-platform2 | 4fe8bac63a95a07ac8afa45088152c2b623b963d | 5e5337009a65b1c9aa9e0ea565f567438217e91f | refs/heads/master | 2023-01-05T15:25:41.667733 | 2020-11-08T06:12:01 | 2020-11-08T07:16:44 | 295,388,294 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,144 | cc | crash_serializer.cc | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "crash-reporter/crash_serializer.h"
#include <stdio.h>
#include <string>
#include <utility>
#include <base/big_endian.h>
#include <base/compiler_specific.h> // FALLTHROUGH
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/optional.h>
#include <base/strings/string_util.h>
#include <base/threading/platform_thread.h>
#include <base/time/default_clock.h>
#include <base/time/time.h>
#include "crash-reporter/crash_sender_base.h"
#include "crash-reporter/crash_sender_util.h"
#include "crash-reporter/paths.h"
#include "crash-reporter/util.h"
namespace crash_serializer {
namespace {
void AddMetaField(crash::CrashInfo* info,
const std::string& key,
const std::string& value) {
if (!base::IsStringUTF8(key)) {
LOG(ERROR) << "key was not UTF8: " << key;
return;
}
if (!base::IsStringUTF8(value)) {
LOG(ERROR) << "value for key '" << key << "' was not UTF8";
return;
}
crash::CrashMetadata* meta = info->add_fields();
meta->set_key(key);
meta->set_text(value);
}
base::Optional<crash::CrashBlob> MakeBlob(const std::string& name,
const base::FilePath& file) {
if (!base::IsStringUTF8(name)) {
LOG(ERROR) << "key was not UTF8: " << name;
return base::nullopt;
}
std::string contents;
if (!base::ReadFileToString(file, &contents)) {
return base::nullopt;
}
crash::CrashBlob b;
b.set_key(name);
b.set_blob(contents);
b.set_filename(file.BaseName().value());
return b;
}
} // namespace
Serializer::Serializer(std::unique_ptr<base::Clock> clock,
const Options& options)
: util::SenderBase(std::move(clock), options),
out_("/dev/stdout"),
fetch_cores_(options.fetch_coredumps),
max_message_size_bytes_(options.max_proto_bytes) {}
// The serializer doesn't remove crashes, so do nothing.
void Serializer::RecordCrashRemoveReason(CrashRemoveReason reason) {}
void Serializer::PickCrashFiles(const base::FilePath& crash_dir,
std::vector<util::MetaFile>* to_send) {
std::vector<base::FilePath> meta_files = util::GetMetaFiles(crash_dir);
for (const auto& meta_file : meta_files) {
LOG(INFO) << "Checking metadata: " << meta_file.value();
std::string reason;
util::CrashInfo info;
switch (EvaluateMetaFileMinimal(meta_file, /*allow_old_os_timestamps=*/true,
&reason, &info,
/*processing_file=*/nullptr)) {
case kRemove:
FALLTHROUGH; // Don't remove; rather, ignore the report.
case kIgnore:
LOG(INFO) << "Ignoring: " << reason;
break;
case kSend:
to_send->push_back(std::make_pair(meta_file, std::move(info)));
break;
default:
NOTREACHED();
}
}
}
void Serializer::SerializeCrashes(
const std::vector<util::MetaFile>& crash_meta_files) {
if (crash_meta_files.empty()) {
return;
}
std::string client_id = util::GetClientId();
base::File lock(AcquireLockFileOrDie());
int64_t crash_id = -1;
for (const auto& pair : crash_meta_files) {
crash_id++;
const base::FilePath& meta_file = pair.first;
const util::CrashInfo& info = pair.second;
LOG(INFO) << "Evaluating crash report: " << meta_file.value();
base::TimeDelta sleep_time;
if (!util::GetSleepTime(meta_file, /*max_spread_time=*/base::TimeDelta(),
hold_off_time_, &sleep_time)) {
LOG(WARNING) << "Failed to compute sleep time for " << meta_file.value();
continue;
}
LOG(INFO) << "Scheduled to send in " << sleep_time.InSeconds() << "s";
lock.Close(); // Don't hold lock during sleep.
if (!util::IsMock()) {
base::PlatformThread::Sleep(sleep_time);
} else if (!sleep_function_.is_null()) {
sleep_function_.Run(sleep_time);
}
lock = AcquireLockFileOrDie();
// Mark the crash as being processed so that if we crash, we don't try to
// send the crash again.
util::ScopedProcessingFile processing(meta_file);
// User-specific crash reports become inaccessible if the user signs out
// while sleeping, thus we need to check if the metadata is still
// accessible.
if (!base::PathExists(meta_file)) {
LOG(INFO) << "Metadata is no longer accessible: " << meta_file.value();
continue;
}
const util::CrashDetails details = {
.meta_file = meta_file,
.payload_file = info.payload_file,
.payload_kind = info.payload_kind,
.client_id = client_id,
.metadata = info.metadata,
};
crash::FetchCrashesResponse resp;
resp.set_crash_id(crash_id);
std::vector<crash::CrashBlob> blobs;
base::FilePath core_path;
if (!SerializeCrash(details, resp.mutable_crash(), &blobs, &core_path)) {
// If we cannot serialize the crash, give up -- there won't be anything to
// write.
LOG(ERROR) << "Failed to serialize " << meta_file.value();
continue;
}
// Write the CrashInfo to output.
if (!WriteFetchCrashesResponse(resp)) {
// If we cannot write the CrashInfo, give up on the crash -- callers won't
// be able to reconstruct anything useful from the report.
LOG(ERROR) << "Failed to write CrashInfo proto for: " << meta_file.value()
<< ". Giving up on this crash";
continue;
}
if (!WriteBlobs(crash_id, blobs)) {
// If this fails, keep trying to process the crash -- the coredump could
// still be useful.
LOG(ERROR) << "Failed to write blobs for " << meta_file.value();
}
if (!core_path.empty() && !WriteCoredump(crash_id, core_path)) {
LOG(ERROR) << "Failed to write core for " << meta_file.value();
}
}
}
bool Serializer::SerializeCrash(const util::CrashDetails& details,
crash::CrashInfo* info,
std::vector<crash::CrashBlob>* blobs,
base::FilePath* core_path) {
util::FullCrash crash = ReadMetaFile(details);
// Add fields that are present directly in the FullCrash struct
info->set_exec_name(crash.exec_name);
AddMetaField(info, "board", crash.board);
AddMetaField(info, "hwclass", crash.hwclass);
info->set_prod(crash.prod);
info->set_ver(crash.ver);
info->set_sig(crash.sig);
AddMetaField(info, "sig2", crash.sig);
AddMetaField(info, "image_type", crash.image_type);
AddMetaField(info, "boot_mode", crash.boot_mode);
AddMetaField(info, "error_type", crash.error_type);
AddMetaField(info, "guid", crash.guid);
// Add fields from key_vals
for (const auto& kv : crash.key_vals) {
const std::string& key = kv.first;
const std::string& val = kv.second;
if (key == "in_progress_integration_test") {
info->set_in_progress_integration_test(val);
} else if (key == "collector") {
info->set_collector(val);
} else {
AddMetaField(info, key, val);
}
}
// Add payload file
base::Optional<crash::CrashBlob> payload =
MakeBlob(crash.payload.first, crash.payload.second);
if (!payload) {
return false;
}
blobs->push_back(*payload);
// Add files
for (const auto& kv : crash.files) {
base::Optional<crash::CrashBlob> blob = MakeBlob(kv.first, kv.second);
if (blob) {
blobs->push_back(*blob);
}
}
if (fetch_cores_) {
base::FilePath maybe_core = details.meta_file.ReplaceExtension(".core");
if (base::PathExists(maybe_core)) {
*core_path = maybe_core;
}
}
return true;
}
bool Serializer::WriteFetchCrashesResponse(
const crash::FetchCrashesResponse& crash_data) {
// Initialize string with the size and then append the proto to that so that
// we get the data in a single buffer with no extra copies.
size_t size = crash_data.ByteSizeLong();
// Convert to a fixed size to ensure a consistent serialization format.
static_assert(sizeof(size_t) <= sizeof(uint64_t),
"size_t is too big to fit in 8 bytes");
uint64_t size_uint64 = size;
char size_bytes[sizeof(size_uint64)];
base::WriteBigEndian(size_bytes, size_uint64);
std::string buf(size_bytes, size_bytes + sizeof(size_uint64));
if (!crash_data.AppendToString(&buf)) {
LOG(ERROR) << "Failed to serialize proto to string";
return false;
}
if (!base::AppendToFile(out_, buf.data(), buf.size())) {
PLOG(ERROR) << "Failed to append";
return false;
}
CHECK_EQ(buf.size(), size + sizeof(size_uint64));
return true;
}
bool Serializer::WriteBlobs(int64_t crash_id,
const std::vector<crash::CrashBlob>& blobs) {
crash::FetchCrashesResponse resp;
resp.set_crash_id(crash_id);
bool success = true;
for (const auto& blob : blobs) {
size_t actual_size = blob.blob().size();
// Divide and round up to calculate the number of protos to split this
// blob into.
int proto_count =
(actual_size + max_message_size_bytes_ - 1) / max_message_size_bytes_;
crash::CrashBlob* send_blob = resp.mutable_blob();
send_blob->set_key(blob.key());
send_blob->set_filename(blob.filename());
size_t offset = 0;
for (int i = 0; i < proto_count; i++) {
// Re-retrieve the pointer here because WriteFetchCrashesResponse might
// invalidate it; see
// https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#fields
send_blob = resp.mutable_blob();
CHECK_LE(offset, blob.blob().size());
send_blob->set_blob(blob.blob().substr(offset, max_message_size_bytes_));
if (!WriteFetchCrashesResponse(resp)) {
LOG(ERROR) << "Failed to write blob: " << blob.key()
<< " starting at offset: " << offset;
// Don't continue with this blob -- even if we succeed at sending a
// later chunk, callers won't be able to correctly reassemble the
// data.
success = false;
break;
}
offset += max_message_size_bytes_;
}
}
return success;
}
bool Serializer::WriteCoredump(int64_t crash_id, base::FilePath core_path) {
crash::FetchCrashesResponse resp;
resp.set_crash_id(crash_id);
base::File core_file(core_path,
base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!core_file.IsValid()) {
LOG(ERROR) << "Failed to open " << core_path.value() << " for reading: "
<< base::File::ErrorToString(core_file.error_details());
return false;
}
int64_t size = core_file.GetLength();
if (size < 0) {
LOG(ERROR) << "Failed to get size for core file: " << core_path.value()
<< ": " << base::File::ErrorToString(core_file.error_details());
return false;
} else if (size == 0) {
LOG(WARNING) << "Coredump " << core_path.value()
<< " is empty. Proceeding anyway.";
}
int64_t total_read = 0;
while (total_read < size) {
std::vector<char> buf(max_message_size_bytes_);
// Don't read the entire core into memory at once, as it could be multiple
// GBs.
int read = core_file.Read(total_read, buf.data(), max_message_size_bytes_);
if (read < 0) {
LOG(ERROR) << "Failed to read: " << core_path.value()
<< "at offset: " << total_read << ": "
<< base::File::ErrorToString(core_file.error_details());
// Don't continue reading the core -- even if later calls succeed, the
// caller won't be able to correctly reassemble the coredump.
return false;
}
resp.set_core(buf.data(), read);
if (!WriteFetchCrashesResponse(resp)) {
LOG(ERROR) << "Failed to write core dump at offset " << total_read;
// Don't continue reading the core -- even if later calls succeed, the
// caller won't be able to correctly reassemble the coredump.
return false;
}
total_read += read;
}
return true;
}
} // namespace crash_serializer
|
75bb9f23fa2b752b0dc2689f6e10db3c58e6c079 | a8247916c4e226bb77822db627dc72681669cefa | /main/src/game.cpp | 1a47fd66af8f2267d15b7467e714455f665c2814 | [] | no_license | RioneSSL/RI-AI | 817c0f8683abf02e27d273f79f9b23aa2b01b016 | f0709628279c6c19aa992c00bbf7712a9bb707c5 | refs/heads/master | 2022-12-17T01:24:15.483434 | 2020-09-21T09:48:28 | 2020-09-21T09:48:28 | 278,121,351 | 1 | 4 | null | 2020-08-13T09:46:24 | 2020-07-08T15:06:53 | Makefile | UTF-8 | C++ | false | false | 5,001 | cpp | game.cpp | #include <iostream>
#include <cmath>
#include <rclcpp/rclcpp.hpp>
#include "game.hpp"
using namespace std;
using namespace std::chrono_literals;
Game::Game() : Node("Masuo"){ //setting
publisher = this->create_publisher<message_info::msg::RobotCommands>("robot_commands",10); //grsimへのpublisher
auto callback =
[this](const message_info::msg::VisionDetections::SharedPtr vision_message) -> void //visionからのsubscriber
{
for(int i=0; i<4; i++){
if(vision_message->frames[i].balls.size()>0 &&vision_message->frames[i].balls.size()<10)
{
ball = vision_message->frames[i].balls[0]; //ボール座標
}
/*message_info::msg::DetectionRobot temp;
for(int i = 0; i<8; i++){
frame.blue_robots[i] = temp;
}*/
if(vision_message->frames[i].robots_blue.size() && vision_message->frames[i].robots_blue.size()<=16){ //robot information
for (auto robot : vision_message->frames[i].robots_blue) {
frame.blue_robots[robot.robot_id]=robot;
}
}
}
};
auto callback_geometry =
[this](const message_info::msg::VisionGeometry::SharedPtr geometry_message) -> void //visionからのsubscriber
{
float field_length = geometry_message->field_length;
float field_width = geometry_message->field_width;
goal.their.x=field_length/2; // right goal position
goal.their.y=0;
goal.our.x=field_length/(-2); //left goal position
goal.our.y=0;
goal.field_width = field_width;
goal.field_length = field_length;
goal.goal_width = geometry_message->goal_width;
goal.goal_depth = geometry_message->goal_depth;
};
auto callback_referee =
[this](const message_info::msg::Referee::SharedPtr referee_message) -> void //visionからのsubscriber
{
referee.command = referee_message->command;
};
subscriber = this->create_subscription<message_info::msg::VisionDetections>("vision_detections",10,callback); // ball, robot information
subscriber_geometry = this->create_subscription<message_info::msg::VisionGeometry>("vision_geometry",10,callback_geometry); //field information
subscriber_referee = this->create_subscription<message_info::msg::Referee>("referee_info",10,callback_referee);
timer_ = create_wall_timer(16ms, std::bind(&Game::timer_callback, this)); //16ms周期でtimer_callbackが実行される
}
void Game::test(){
message_info::msg::RobotCommands send;
message_info::msg::Role devide;
geometry_msgs::msg::Pose2D target_position;
target_position.x = 2;
target_position.y = 2;
Referee::translate(referee, ball);
Role::decision(ball,frame,goal,devide); //role decide
//cout<<"AT="<<devide.attacker<<" GL="<<devide.goalie<<" OF="<<devide.offense[0]<<" DF="<<devide.defense[0]<<endl;
referee.info="FREE";
if(referee.info == "HALT"){
}else if(referee.play == true or referee.info == "NORMAL_START"){
send.commands.push_back(Attack::pass(ball,frame.blue_robots[devide.attacker],goal,target_position,kick_flag)); //アタッカーメインプログラム
send.commands.push_back(Offense::main(ball,frame.blue_robots[devide.offense[0]],frame.blue_robots[devide.attacker] ,goal,kick_flag));
send.commands.push_back(Goalie::main(ball,frame.blue_robots[devide.goalie],goal));
send.commands.push_back(Defense::main(ball,frame.blue_robots[devide.defense[0]],goal));
}else if(referee.info == "STOP"){
send.commands.push_back(Attack::stop_position(ball,frame.blue_robots[devide.attacker],goal,0.5));
for(int offense_id = 0; offense_id < 10; offense_id++){
send.commands.push_back(Offense::stop(ball,frame.blue_robots[devide.offense[offense_id]],goal));
}
for(int defense_id = 0; defense_id < 10; defense_id++){
send.commands.push_back(Defense::stop(ball,frame.blue_robots[devide.defense[defense_id]],goal));
}
send.commands.push_back(Goalie::stop(ball,frame.blue_robots[devide.goalie],goal));
}else if(referee.info == "FORCE_START"){
}else if(referee.info == "OUR_KICKOFF_START"){
send.commands.push_back(Attack::stop_position(ball,frame.blue_robots[devide.attacker],goal,0.5));
Home::main(ball,frame,goal,devide,send);
}else if(referee.info == "OUR_PANALTY_PRE"){
}else if(referee.info == "THEIR_PENALTY_PRE"){
}else if(referee.info == "OUR_DIRECT"){
}else if(referee.info == "THEIR_DIRECT"){
}else if(referee.info == "OUR_INDRIRECT"){
}else if(referee.info == "THEIR_INDIRECT"){
}else if(referee.info == "FREE"){
}
send.commands.push_back(Goalie::main(ball,frame.blue_robots[0],goal));
send.commands.push_back(Attacker::main(ball,frame.blue_robots[1],goal));
this->publisher->publish(send); //grsimへパブリッシュ
}
void Game::timer_callback(){
Game::test();
} |
d02fe26c9c66b4ea0ef68ef2ffe238880086c2a8 | 7d2a5178df248ecaad56be4dffb891cfa109896d | /PETOOL_DLL/InlineHook.cpp | d1be4b19a61d3650a32ab8c2ef35949bdb12c94e | [] | no_license | arckiCriss/PETools | ce5845e75c3c38b2c025afdf139ef17585bcb286 | 12e64174e378759f4d5da5b2d9cc29ea5964bae8 | refs/heads/master | 2020-06-23T15:45:27.243797 | 2019-06-10T14:36:02 | 2019-06-10T14:36:02 | 198,667,979 | 1 | 0 | null | 2019-07-24T16:01:59 | 2019-07-24T16:01:58 | null | GB18030 | C++ | false | false | 4,040 | cpp | InlineHook.cpp | #include "stdafx.h"
//8个32位通用寄存器
struct REGISTER_X86
{
DWORD eax;
DWORD ebx;
DWORD ecx;
DWORD edx;
DWORD esp;
DWORD ebp;
DWORD esi;
DWORD edi;
};
DWORD srcFuncAddr = 0; //原函数的入口地址
DWORD retFuncAddr = 0; //返回至原函数的地址
REGISTER_X86 register_x86 = { 0 }; //保存寄存器状态
PBYTE pSrcCodeBuffer = 0; //保存被HOOK的代码句
/**
* MyMessageBoxA_X86
*/
DWORD param1_MyMessageBoxA = 0;
DWORD param2_MyMessageBoxA = 0;
DWORD param3_MyMessageBoxA = 0;
DWORD param4_MyMessageBoxA = 0;
#if MY_X86
_declspec(naked)
#endif
void InlineHook_MyMessageBoxA_X86() //裸函数:自己处理堆栈平衡
{
#if MY_X86
_asm
{
//寄存器入栈保存
pushfd //将32位标志寄存器EFLAGS压栈
pushad //将所有的32位通用寄存器压栈
}
//>>>>>>>> begin :执行自己的代码>>>>>>>>
//打印寄存器
_asm
{
mov register_x86.eax, eax
mov register_x86.ebx, ebx
mov register_x86.ecx, ecx
mov register_x86.edx, edx
mov register_x86.esp, esp
mov register_x86.ebp, ebp
mov register_x86.esi, esi
mov register_x86.edi, edi
}
printf("8个通用寄存器:eax=%08X,ebx=%08X,ecx=%08X,edx=%08X,esp=%08X,ebp=%08X,esi=%08X,edi=%08X \n", register_x86.eax, register_x86.ebx, register_x86.ecx, register_x86.edx, register_x86.esp, register_x86.ebp, register_x86.esi, register_x86.edi);
//打印参数
_asm
{
//MessageBox函数共有4个参数入栈,且还有8个通用寄存器和1个EL寄存器入栈
//堆栈中esp+(8+1)*0x4+0x10 是第1个入栈的参数
mov eax, DWORD PTR SS : [esp + 0x34]
mov param1_MyMessageBoxA, eax
//堆栈中esp+(8+1)*0x4+0xC 是第2个入栈的参数
mov eax, DWORD PTR SS : [esp + 0x30]
mov param2_MyMessageBoxA, eax
//堆栈中esp+(8+1)*0x4+0x8 是第3个入栈的参数
mov eax, DWORD PTR SS : [esp + 0x2C]
mov param3_MyMessageBoxA, eax
//堆栈中esp+(8+1)*0x4+0x4 是第4个入栈的参数
mov eax, DWORD PTR SS : [esp + 0x28]
mov param4_MyMessageBoxA, eax
}
printf("MessageBoxA的参数: 参数1=%d , 参数2=%s, 参数3=%s, 参数4=%d \n", param1_MyMessageBoxA, param2_MyMessageBoxA, param3_MyMessageBoxA, param4_MyMessageBoxA);
//>>>>>>>> end :执行自己的代码>>>>>>>>
_asm
{
//寄存器出栈恢复现场
popad
popfd
//执行被覆盖的原代码
// MessageBoxA的前五字节:
// 75F57E60 8B FF mov edi, edi
// 75F57E62 55 push ebp
// 75F57E63 8B EC mov ebp, esp
mov edi, edi
push ebp
mov ebp, esp
//跳转回原函数
jmp retFuncAddr
}
#endif
}
/**
* InlineHook
* 参数 destDllName
* 参数 destFuncName
* 参数 hookFuncAddr
* 参数 byteLen 指定用原函数前(byteLen)字节的代码替换成jmp指令,最少为5字节(被Hook函数的前byteLen字节必须是完整的代码句)
*/
void InlineHook_X86(CHAR* destDllName, CHAR* destFuncName, DWORD hookFuncAddr, int byteLen)
{
//获取目标函数的入口地址
HMODULE destDll = GetModuleHandle(destDllName);
if (destDll == 0)
{
printf("错误:不存在目标模块%s \n", destDllName);
return;
}
srcFuncAddr = (DWORD)GetProcAddress(destDll, destFuncName);
if (srcFuncAddr == 0)
{
printf("错误:目标模块中不存在目标函数%s \n", destFuncName);
return;
}
//计算Hook结束时返回的地址
retFuncAddr = srcFuncAddr + byteLen;
//保存前(byteLen)字节的代码
pSrcCodeBuffer = (PBYTE)malloc(byteLen);
memset(pSrcCodeBuffer, 0x0, byteLen);
memcpy(pSrcCodeBuffer, (void*)srcFuncAddr, byteLen);
//修改前(byteLen)字节的代码为 JMP XXX
DWORD oldProtect = 0; DWORD newProtect = 0;
VirtualProtect((LPVOID)srcFuncAddr, byteLen, PAGE_EXECUTE_READWRITE, &oldProtect);
*(PBYTE)(srcFuncAddr) = 0xE9; //jmp
*(DWORD*)(srcFuncAddr + 1) = hookFuncAddr - srcFuncAddr - 5; //jmp X
VirtualProtect((LPVOID)srcFuncAddr, byteLen, oldProtect, &newProtect);
//测试调用
MessageBox(0, TEXT("testText"), TEXT("testCaption"), 0);
}
|
2bd6b35a4c5879838d318e1b6f14e4a5aae25bf1 | abe541ae6e92d6683de6a0432ad0cf662a0fc5f9 | /Algorithms/Implementation/between-two-sets.cpp | c53436947098e67326d41da6dd6f24a36913a32f | [] | no_license | ozzi7/Hackerrank-Solutions | ab64805124f81256269d3a5ee766200cb495d8c1 | d094f83ffcbcf9bd264ddbac7c27091eedd21ad3 | refs/heads/master | 2021-01-01T19:44:33.257815 | 2018-08-10T20:39:39 | 2018-08-10T20:39:39 | 98,666,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,567 | cpp | between-two-sets.cpp | #include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <cstdlib>
#include <ctime>
#include <deque>
#include <bitset>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <numeric>
using namespace std;
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define pii pair <int, int>
#define pll pair <long long, long long>
#define vi vector <int>
#define FOR(i, a, b) for (int i=a; i<b; i++)
#define F0R(i, a) for (int i=0; i<a; i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define mp make_pair
#define pb push_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
const int MOD = 1000000007;
long long gcd(long long a, long long b) { if (b == 0) return a; a %= b; return gcd(b, a); }
long long lcm(long long a, long long b) { return (a * b / gcd(a, b)); }
int main()
{
ios::sync_with_stdio(false);
int n, m, val;
int lcm1 = 1;
int gcd1;
cin >> n >> m;
F0R(i, n) {
cin >> val;
lcm1 = lcm(val, lcm1);
}
cin >> gcd1;
F0R(i, m - 1) {
cin >> val;
gcd1 = gcd(gcd1, val);
}
int count = 0;
int curr = lcm1;
while (curr <= gcd1) {
if (gcd1 % curr == 0) count++;
curr += lcm1;
}
cout << count << endl;
return 0;
} |
fb7463f3d9115d3b52a24ddf49012250b1981097 | 064a279a3ce7e18802b728f57b266a9cd7f8d181 | /objects.cpp | 648c0f0baeab4386957485b6c4257e64d41052dd | [
"MIT"
] | permissive | simop07/boids-2D-simulation | 014cae402830e5505f1644845e304be05a47738c | eaaea4c65d2d0243b0c4e78271231160364c0a74 | refs/heads/main | 2023-04-14T20:14:58.430948 | 2023-01-04T13:22:54 | 2023-01-04T13:22:54 | 490,634,037 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | cpp | objects.cpp | #include "objects.hpp"
double Vector_2d::xcomp() const { return m_x; }
double Vector_2d::ycomp() const { return m_y; }
double Vector_2d::norm() const { return sqrt(m_x * m_x + m_y * m_y); }
Vector_2d& Vector_2d::operator+=(Vector_2d const& v) {
m_x += v.m_x;
m_y += v.m_y;
return *this;
}
Vector_2d& Vector_2d::operator*=(double k) {
m_x *= k;
m_y *= k;
return *this;
}
void Vector_2d::setx(double x) { m_x = x; }
void Vector_2d::sety(double y) { m_y = y; }
Vector_2d operator-(Vector_2d const& v) { return {-v.xcomp(), -v.ycomp()}; }
Vector_2d operator+(Vector_2d const& l, Vector_2d const& r) {
auto result{l};
return result += r;
}
Vector_2d operator-(Vector_2d const& l, Vector_2d const& r) { return l + (-r); }
Vector_2d operator*(Vector_2d const& l, double k) {
auto result{l};
return result *= k;
}
bool operator==(Vector_2d const& l, Vector_2d const& r) {
return l.xcomp() == r.xcomp() && l.ycomp() == r.ycomp();
}
bool operator!=(Vector_2d const& l, Vector_2d const& r) { return !(l == r); }
|
4fc5cccf65a693fb4296e0b1d8275171d84c33be | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-quicksight/source/model/TopBottomFilter.cpp | 6971e510e0bd3091387516fdfed2520d350cb1ed | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 3,765 | cpp | TopBottomFilter.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/quicksight/model/TopBottomFilter.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace QuickSight
{
namespace Model
{
TopBottomFilter::TopBottomFilter() :
m_filterIdHasBeenSet(false),
m_columnHasBeenSet(false),
m_limit(0),
m_limitHasBeenSet(false),
m_aggregationSortConfigurationsHasBeenSet(false),
m_timeGranularity(TimeGranularity::NOT_SET),
m_timeGranularityHasBeenSet(false),
m_parameterNameHasBeenSet(false)
{
}
TopBottomFilter::TopBottomFilter(JsonView jsonValue) :
m_filterIdHasBeenSet(false),
m_columnHasBeenSet(false),
m_limit(0),
m_limitHasBeenSet(false),
m_aggregationSortConfigurationsHasBeenSet(false),
m_timeGranularity(TimeGranularity::NOT_SET),
m_timeGranularityHasBeenSet(false),
m_parameterNameHasBeenSet(false)
{
*this = jsonValue;
}
TopBottomFilter& TopBottomFilter::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("FilterId"))
{
m_filterId = jsonValue.GetString("FilterId");
m_filterIdHasBeenSet = true;
}
if(jsonValue.ValueExists("Column"))
{
m_column = jsonValue.GetObject("Column");
m_columnHasBeenSet = true;
}
if(jsonValue.ValueExists("Limit"))
{
m_limit = jsonValue.GetInteger("Limit");
m_limitHasBeenSet = true;
}
if(jsonValue.ValueExists("AggregationSortConfigurations"))
{
Aws::Utils::Array<JsonView> aggregationSortConfigurationsJsonList = jsonValue.GetArray("AggregationSortConfigurations");
for(unsigned aggregationSortConfigurationsIndex = 0; aggregationSortConfigurationsIndex < aggregationSortConfigurationsJsonList.GetLength(); ++aggregationSortConfigurationsIndex)
{
m_aggregationSortConfigurations.push_back(aggregationSortConfigurationsJsonList[aggregationSortConfigurationsIndex].AsObject());
}
m_aggregationSortConfigurationsHasBeenSet = true;
}
if(jsonValue.ValueExists("TimeGranularity"))
{
m_timeGranularity = TimeGranularityMapper::GetTimeGranularityForName(jsonValue.GetString("TimeGranularity"));
m_timeGranularityHasBeenSet = true;
}
if(jsonValue.ValueExists("ParameterName"))
{
m_parameterName = jsonValue.GetString("ParameterName");
m_parameterNameHasBeenSet = true;
}
return *this;
}
JsonValue TopBottomFilter::Jsonize() const
{
JsonValue payload;
if(m_filterIdHasBeenSet)
{
payload.WithString("FilterId", m_filterId);
}
if(m_columnHasBeenSet)
{
payload.WithObject("Column", m_column.Jsonize());
}
if(m_limitHasBeenSet)
{
payload.WithInteger("Limit", m_limit);
}
if(m_aggregationSortConfigurationsHasBeenSet)
{
Aws::Utils::Array<JsonValue> aggregationSortConfigurationsJsonList(m_aggregationSortConfigurations.size());
for(unsigned aggregationSortConfigurationsIndex = 0; aggregationSortConfigurationsIndex < aggregationSortConfigurationsJsonList.GetLength(); ++aggregationSortConfigurationsIndex)
{
aggregationSortConfigurationsJsonList[aggregationSortConfigurationsIndex].AsObject(m_aggregationSortConfigurations[aggregationSortConfigurationsIndex].Jsonize());
}
payload.WithArray("AggregationSortConfigurations", std::move(aggregationSortConfigurationsJsonList));
}
if(m_timeGranularityHasBeenSet)
{
payload.WithString("TimeGranularity", TimeGranularityMapper::GetNameForTimeGranularity(m_timeGranularity));
}
if(m_parameterNameHasBeenSet)
{
payload.WithString("ParameterName", m_parameterName);
}
return payload;
}
} // namespace Model
} // namespace QuickSight
} // namespace Aws
|
b6ff88d40f0be1abffe3f5179ab4c990687a2b71 | c847fc66148a59b3462d1c299bcc7f8afc88322c | /SceneTitleMenu/LayerTitleFront.h | d67e075f51ca55d4d98c68c7788b20bbe300a804 | [] | no_license | sasanon/action | 40d7392ffc9b47bc417be8d50665cf62beb38ee9 | f4fa8d0b52665cf165908354ca035d6b3722572d | refs/heads/master | 2020-05-17T01:53:17.249552 | 2015-03-10T02:28:41 | 2015-03-10T02:28:41 | 31,696,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | h | LayerTitleFront.h | #ifndef __LayerTitleFront_h__
#define __LayerTitleFront_h__
#include "cocos2d.h"
class LayerTitleFront : public cocos2d::Layer
{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
virtual void update (float delta);
// implement the "static create()" method manually
CREATE_FUNC(LayerTitleFront);
};
extern LayerTitleFront* layertitlefront;
#endif
|
8526fe71dc86d13814bec8337537d15cba0360d0 | 1e5d25a8e0e31b78c4e979af55ee2ad64687c258 | /77 Combinations/combination-optimization.cpp | de5928c221a8b11bbaa1a95d2dc0dadedfa031af | [] | no_license | charlenellll/LeetCodeSolution | ed02ee9b4059d6c1c6972af8cc56ea7bc85d401f | 3b846bf4cc1817aaae9e4e392547ad9ccde04e76 | refs/heads/master | 2021-01-01T16:18:58.440351 | 2019-11-19T15:48:04 | 2019-11-19T15:48:04 | 97,808,314 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | cpp | combination-optimization.cpp | class Solution {
private:
vector<vector<int>> res;
vector<bool> used;
void generateCombination(int n, int k, int start, vector<int> &c){
if( c.size() == k ){
res.push_back(c);
return;
}
// There's k-c.size() vacancies left, so the slot [i..n] has to have at least k-c.size() elements
for(int i = start; i <= n-(k-c.size())+1; i++){
c.push_back(i);
generateCombination(n, k, i+1 ,c);
c.pop_back();
}
return;
}
public:
vector<vector<int>> combine(int n, int k) {
if( n <= 0 || k <=0 || k > n)
return res;
vector<int> c;
generateCombination(n,k,1,c);
return res;
}
};
// This code's runtime beats 98.63% cpp submissions |
5398f807174a8ea8551acfd41e599f912ae56614 | 9b4b8bc4fff192264db7e4996f5a53f0163e2784 | /并查集/1069.cpp | 9df3579e06cf8a9d7fc3d1affb659804ed25861d | [] | no_license | momoliu88/wikioi | a72f37b25e2bfc93677825cc7814965f64c7be57 | 5d5e3242241efdf37e798038e4bb95db42430024 | refs/heads/master | 2020-05-29T19:44:32.383356 | 2014-01-06T09:07:03 | 2014-01-06T09:07:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | cpp | 1069.cpp | #include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
#define MAXN 20001
#define MAXM 100001
int pa[MAXN*2];
typedef struct Node{
int a,b,c;
}Node;
int find(int x){
if(x==pa[x]) return x;
pa[x] = find(pa[x]);
return pa[x];
}
bool join(int x,int y){
int fx = find(x);
int fy = find(y);
if(fx==fy)
return true;
pa[fx] = fy;
return false;
}
bool cmp(Node a,Node b){
return a.c > b.c;
}
int main(){
int N,M;
scanf("%d%d",&N,&M);
Node crime[M];
for(int i = 1;i<=2*N;i++)
pa[i] = i;
for(int i = 0 ; i< M;i++)
{
scanf("%d%d%d",&crime[i].a,&crime[i].b,&crime[i].c);
}
sort(crime,crime+M,cmp);
int ans=-1;
for(int i = 0 ; i < M;i++){
int fx = find(crime[i].a);
int fy = find(crime[i].b);
if(fx == fy)
{
ans = i;
break;
}
else{
pa[fx] = find(crime[i].b+N);
pa[fy] = find(crime[i].a+N);
}
}
if(ans==-1)
printf("0\n");
else
printf("%d\n",crime[ans].c);
} |
c440ba11a675ae0787dc783543d68c018e20972c | 51ec27cf1f9d14c6a36435ef893f05a0cdec3810 | /tcpServer/main.cpp | 45701599fd07da27c1aa93d5b9a53fe13db5952d | [] | no_license | Lev-vz/NBprj | 892296ce8ed1daaf7ff11bf7d3730269e877dfc2 | b455653fffb555ec831ed4572d59223b0eccfbb2 | refs/heads/master | 2023-02-27T15:08:05.761209 | 2021-02-05T13:33:35 | 2021-02-05T13:33:35 | 325,499,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,082 | cpp | main.cpp | #include <iostream>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "defines.h"
#include "tools.h"
#include <sys/select.h>
//#define BUFFER_SIZE 1024
using namespace std;
int getSoketForServer(int port, int n){
int socketId = socket(AF_INET, SOCK_STREAM, 0); //Создаёт конечную точку соединения и возвращает файловый дескриптор
struct sockaddr_in serverAddr; //структура данных для открытия исходящего сокета
bzero((char*)&serverAddr, sizeof(serverAddr)); //обнуление всех полей структуры
serverAddr.sin_family = AF_INET; //семейство протоколов - интернет
serverAddr.sin_port = htons(port); //назначаем порт 3081
serverAddr.sin_addr.s_addr = INADDR_ANY; //INADDR_ANY - все адреса локального хоста (0.0.0.0); INADDR_LOOPBACK - (127.0.0.1);
bind(socketId, (struct sockaddr *) &serverAddr, sizeof(serverAddr));//Связывает сокет с конкретным адресом
listen(socketId, n); //Подготавливает привязываемый сокет к принятию входящих соединений
cout<<"Server open port "<<port<<"\n";
return socketId;
}
int getAccept(int socketId){
struct sockaddr_storage serverStorage;
socklen_t addr_size = sizeof(serverStorage);
int newSocket = accept(socketId, (struct sockaddr*)&serverStorage, &addr_size); //приём запроса на установление соединения от удаленного хоста
cout<<"newSocket"<<"-"<<newSocket<<endl;//----------------------------------Check Out -----------------------------------------
return newSocket;
}
void * fileLoadThread(void *attr){//int ctrlSocket){
int socketId = getSoketForServer(3081, 1);//socket(AF_INET, SOCK_STREAM, 0); //Создаёт конечную точку соединения и возвращает файловый дескриптор
int newSocket = getAccept(socketId);//accept(socketId, (struct sockaddr*)&serverStorage, &addr_size); //приём запроса на установление соединения от удаленного хоста
//cout<<newSocket<<"-";//----------------------------------Check Out -----------------------------------------
string resp;
char buffer[BUFFER_SIZE];
FILE *f = (FILE*)attr;
while(1){
bzero(buffer,BUFFER_SIZE);
int len = rcv(newSocket, buffer, 81);//read(newSocket, buffer, BUFFER_SIZE - 1);
if(!strcmp(buffer,"exitFload")){
break;
}else{
fputs(buffer,f);
}
resp = to_string(len).c_str();//+" ";
cout<<buffer<<"\n";
send(newSocket, resp.c_str(), resp.length(),0);
}
resp = "fileLoadComplit";
send(newSocket, resp.c_str(), resp.length(),0);
cout<<resp<<"\n";
fclose(f);
close(newSocket);
close(socketId);
}
pthread_t fileLoad(int newSocket){
char buffer[BUFFER_SIZE];
int len = rcv(newSocket, buffer, 80);
string resp = to_string(len).c_str();//+" ";
send(newSocket, resp.c_str(), resp.length(),0);
string fileName=buffer;
FILE *f = fopen(fileName.c_str(),"wb");
if(f<=0) return -1;
pthread_t tid;
void* attr = (void*)f;
pthread_create(&tid, NULL, fileLoadThread, attr);
return tid;
}
int main(int argc, char** argv) {
pthread_t tid; /* идентификатор потока */
void* attr=NULL; /* aтрибуты потока */
int socketId = getSoketForServer(3080, 5);//socket(AF_INET, SOCK_STREAM, 0); //Создаёт конечную точку соединения и возвращает файловый дескриптор
while(1)
{
int newSocket = getAccept(socketId);//accept(socketId, (struct sockaddr*)&serverStorage, &addr_size); //приём запроса на установление соединения от удаленного хоста
//cout<<newSocket<<"-";//----------------------------------Check Out -----------------------------------------
string resp;
char buffer[BUFFER_SIZE];
while(1){
bzero(buffer,BUFFER_SIZE);
int get = read(newSocket, buffer, BUFFER_SIZE - 1);
buffer[get] = '\0';
resp = to_string(get).c_str();//+" ";
cout<<"80:"<<buffer<<"\n";
send(newSocket, resp.c_str(), resp.length(),0);
if(!strcmp(buffer,"fload")){
fileLoad(newSocket);//pthread_create(&tid, NULL, fileLoad, attr);
}else if(!strcmp(buffer,"exit") || !strcmp(buffer,"exitServer") || !strcmp(buffer,"")) break;
}
close(newSocket);
if(!strcmp(buffer,"exitServer")) break;
}
close(socketId);
cout<<"Normal server exit\n";
return 0;
} |
3c89747840862c8e543702309010cce39933c008 | 7868fe0216e80926efc69709262772253851508d | /Aladdin/AppleItem.cpp | 8db7c8d3c353ddbda758c40e36067ad327e4f537 | [] | no_license | khangjig/Aladdin_ForTheLastTime | 173679bf0442650267c2483a15d0a5567796946a | a2af08b0bba3de3776ce23f5a477d53142311d0d | refs/heads/master | 2022-01-04T19:14:33.566074 | 2019-12-28T02:31:08 | 2019-12-28T02:31:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | AppleItem.cpp | #include "AppleItem.h"
#include "Guard1State.h"
vector<Animation *> AppleItem::animations = vector<Animation *>();
AppleItem::AppleItem(int x, int y, int CellID, int id)
{
this->x = x;
this->y = y;
this->CellID = CellID;
this->id = id;
collider.x = x;
collider.y = y;
collider.vx = 0;
collider.vy = 0;
collider.width = APPLE_ITEM_WIDTH;
collider.height = APPLE_ITEM_HEIGHT;
}
void AppleItem::LoadResources(RECT* listSprite, Sprite * items)
{
Animation * anim = new Animation(100);
Sprite *apple = new Sprite(items->GetTexture(), listSprite[0], TEXTURE_TRANS_COLOR_5);
anim->AddFrame(apple);
animations.push_back(anim);
}
void AppleItem::Update(DWORD dt)
{
}
void AppleItem::Render()
{
SpriteData spriteData;
spriteData.width = APPLE_ITEM_WIDTH;
spriteData.height = APPLE_ITEM_HEIGHT;
spriteData.x = this->x;
spriteData.y = this->y;
spriteData.scale = 1;
spriteData.angle = 0;
spriteData.isLeft = true;
spriteData.isFlipped = true;
this->animations[0]->Render(spriteData);
}
AppleItem::~AppleItem()
{
} |
5d09d8a3047fb5e44e51eccfb3eb018234aeb28d | 9fc07f1b2aa196d66ee6edd3b7386b55495f1554 | /Plants/Ogayonne_JonLuke_Plants.cpp | 4b2d0ad95df14feec55ea56c744952f5e75b4d42 | [] | no_license | JonLukeOgayonne/Final_Project_Plants | 7b8cef9d3460c760950d605a26867c0bb99842ae | 41960256e74d5c9ede1f0b8f8e26dc3591dd3b4c | refs/heads/master | 2023-05-02T20:18:09.928492 | 2021-05-10T03:40:17 | 2021-05-10T03:40:17 | 365,397,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,097 | cpp | Ogayonne_JonLuke_Plants.cpp | /*
JonLuke R. Ogayonne
CIS 1202 501
May 04, 2021
*/
#include <iostream>
#include<string>
#include "Plant.h"
#include "Tree.h"
#include "Flower.h"
using namespace std;
int main() {
// data types.
string plantID, plantColor;
int plantSize;
double plantLifespan;
int plantFruit;
// Prompt user to enter plant data.
cout << " Enter the name of the tree: ";
getline(cin, plantID);
cout << " Enter the foot size of the tree: ";
cin >> plantSize;
cout << " Enter the lifespan, of the tree, in years: ";
cin >> plantLifespan;
cout << " Does this tree give fruit?\n If yes enter the number 1, but if no enter 0: ";
cin >> plantFruit;
cin.ignore();
// Loop when user enters a number besides 1 and 0.
while (plantFruit > 1 || plantFruit < 0) {
cout << " Invalid entry.\n Please enter a valid yes or no: ";
cin >> plantFruit;
}
// Create tree class.
Tree tree(plantID, plantSize, plantLifespan, plantFruit);
// Display the contents of the tree.
cout << "\n Plant description:\n\n Tree\n ID: " << tree.displayID() << "\n Size: ";
cout << tree.displaySize() << " feet\n Lifespan: up to " << tree.displayLife() << " years\n";
cout << " Does it bare fruit?: ";
// If statement to determine that tree gives fruit.
if (tree.getFruit() == 1) {
cout << " Yes\n" << endl;
}
else {
cout << " No\n" << endl;
}
//
// Prompt user to enter flower data.
cout << " Enter the name of the flower: ";
getline(cin, plantID);
cout << " Enter the size of the flower, in inches: ";
cin >> plantSize;
cout << " Enter the lifespan of the flower, in months: ";
cin >> plantLifespan;
cin.ignore();
cout << " Enter the color of the flower peddles: ";
getline(cin, plantColor);
// Create flower class.
Flower flower(plantID, plantSize, plantLifespan, plantColor);
// Display the contents of the tree.
cout << "\n Plant description:\n\n Flower\n ID: " << flower.displayID() << "\n Size: ";
cout << flower.displaySize() << " inches\n Lifespan: up to " << flower.displayLife() << " months\n";
cout << " Color: " << flower.getPeddleColor() << endl;
// Terminate program.
return 0;
} |
9130e8084032b612f4261e369f97691e5d867497 | 6660b02a2c7a69dad7f0b56dd22f5f5cc0a89bb6 | /structs_to_json.hpp | 511e07a4c222e2c4b5b15f352c31da061b289115 | [] | no_license | chenmusun/EasyServer | 2e4d111cc7ad3ff10d2897a97de19ebb26af5cb1 | bd3f166b46ad1f237b164919e7026d95c30c9bb7 | refs/heads/master | 2021-01-11T03:25:31.130549 | 2017-04-07T04:09:06 | 2017-04-07T04:09:06 | 71,035,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,622 | hpp | structs_to_json.hpp | #ifndef STRUCTS_TO_JSON_HPP_
#define STRUCTS_TO_JSON_HPP_
#include<string>
#include <jsoncpp/json/json.h>
#include"visit_struct.hpp"
struct SelfDefinedClass{
};
struct ConvertObjectToJson{
ConvertObjectToJson(Json::Value * root){
root_=root;
}
template<typename T>
void convert_impl(const char * name,const T& value,std::true_type)
{
Json::Value item;
visit_struct::apply_visitor(ConvertObjectToJson(&item),value);
(*root_)[name]=item;
}
template<typename T>
void convert_impl(const char * name,const T& value,std::false_type)
{
(*root_)[name]=value;
}
template<typename T>
void convert_impl(const char *name,const std::vector<T>& value,std::false_type)
{
Json::Value arr;
for(auto pos=value.begin();pos!=value.end();++pos){
Json::Value item;
visit_struct::apply_visitor(ConvertObjectToJson(&item),*pos);
arr.append(item);
}
(*root_)[name]=arr;
}
template <typename T>
void operator()(const char * name, const T& value)
{
convert_impl(name,value,std::is_base_of<SelfDefinedClass,T>());
// (*root_)[name]=value;
}
Json::Value * root_;
};
#endif
|
8e4da3cd1fe81f5d35d2495126c7fc67ad0c38e1 | 3d1d97c4ccf318c961b53d4580ebbc3104fe93ec | /TestTSPriorityQueue/unittest1.cpp | 1ae46e55beb6df75c8f7a88c21c3368deaa37b76 | [] | no_license | Sir0ga90/ThreadSafePriorityQueue | 161a27929793cdfd2dc31928ab7ac3e0914b8214 | 2b93393e7f056c40efe83b55c62a43d231c74d48 | refs/heads/master | 2020-03-28T13:18:27.506186 | 2018-09-11T21:48:36 | 2018-09-11T21:48:36 | 148,381,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | unittest1.cpp | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../TSPriority_Queue/TSPriorQueue.h"
#include "../TSPriority_Queue/PriorityQueueDerived.h"
#include <algorithm>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestTSPriorityQueue {
TEST_CLASS(UnitTest1) {
public:
PriorityQueueDerived<int> _pq;
TEST_METHOD(TestMethodPush) {
int myInt = 8;
_pq.push(myInt);
Assert::AreEqual(_pq.top(), myInt);
}
TEST_METHOD(TestPriority) {
std::vector<int> iVec{ 9, 20, 2 };
for (auto i : iVec) {
_pq.push(i);
}
Assert::AreEqual(_pq.top(), 20);
}
};
} |
342261963fd138d91ef0ede24fbea6f07531f2cf | ea89955e343ced5e705b4a338039e658a4ba67cb | /Source/Shell/ShellMenuItem.cpp | a882094c316a9b65b2687a3351c4095b73b39618 | [] | no_license | kennethdmiller3/videoventure | 775ce24ee4aebe3dfc65876a3fc9abb93f29b51d | 7182b78fde61421c48abc679ef6f2992e740d678 | refs/heads/master | 2021-06-03T19:26:26.704306 | 2020-07-25T05:37:02 | 2020-07-25T05:37:02 | 32,195,803 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,231 | cpp | ShellMenuItem.cpp | #include "StdAfx.h"
#include "ShellMenuItem.h"
#include "VarItem.h"
#include "Font.h"
// color palette
const Color4 optionbackcolor[NUM_BUTTON_STATES] =
{
Color4( 0.2f, 0.2f, 0.2f, 0.5f ),
Color4( 0.1f, 0.3f, 1.0f, 0.5f ),
Color4( 0.4f, 0.4f, 0.4f, 0.5f ),
Color4( 0.1f, 0.7f, 1.0f, 0.5f ),
};
const Color4 optionbordercolor[NUM_BUTTON_STATES] =
{
Color4( 0.0f, 0.0f, 0.0f, 1.0f ),
Color4( 0.0f, 0.0f, 0.0f, 1.0f ),
Color4( 0.0f, 0.0f, 0.0f, 1.0f ),
Color4( 0.0f, 0.0f, 0.0f, 1.0f ),
};
const Color4_2 optionlabelcolor[NUM_BUTTON_STATES] =
{
{ Color4( 0.1f, 0.6f, 1.0f, 1.0f ), Color4( 0.1f, 0.6f, 1.0f, 1.0f ) },
{ Color4( 1.0f, 0.9f, 0.1f, 1.0f ), Color4( 1.0f, 0.9f, 0.1f, 1.0f ) },
{ Color4( 0.7f, 0.7f, 0.7f, 1.0f ), Color4( 1.0f, 1.0f, 1.0f, 1.0f ) },
{ Color4( 1.0f, 0.9f, 0.1f, 1.0f ), Color4( 1.0f, 1.0f, 1.0f, 1.0f ) },
};
const Color4 inertbordercolor[] =
{
Color4( 0.1f, 0.1f, 0.1f, 1.0f ),
};
const Color4_2 inertlabelcolor[] =
{
{ Color4( 0.7f, 0.7f, 0.7f, 1.0f ), Color4( 0.7f, 0.7f, 0.7f, 1.0f ) }
};
// render the button
void ShellMenuItem::Render(unsigned int aId, float aTime, const Transform2 &aTransform)
{
unsigned int state = mState;
if (VarItem *item = Database::varitem.Get(mVariable))
if (item->GetInteger() == mValue)
state |= BUTTON_SELECTED;
if (mButtonColor)
{
// render button
glBegin(GL_QUADS);
glColor4fv(mButtonColor[state]);
glVertex2f(mButtonPos.x, mButtonPos.y);
glVertex2f(mButtonPos.x + mButtonSize.x, mButtonPos.y);
glVertex2f(mButtonPos.x + mButtonSize.x, mButtonPos.y + mButtonSize.y);
glVertex2f(mButtonPos.x, mButtonPos.y + mButtonSize.y);
glEnd();
}
if (mLabel)
{
FontDrawBegin(sDefaultFontHandle);
// get text corner position
size_t labellen = strlen(mLabel);
Vector2 labelcorner(
mButtonPos.x + mLabelPos.x - mLabelJustify.x * mCharSize.x * labellen,
mButtonPos.y + mLabelPos.y + (1.0f - mLabelJustify.y) * mCharSize.y);
if (mBorderColor)
{
// render border
FontDrawColor(mBorderColor[state]);
FontDrawString(mLabel, labelcorner.x - 2, labelcorner.y - 2, mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x , labelcorner.y - 2, mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x + 2, labelcorner.y - 2, mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x - 2, labelcorner.y , mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x + 2, labelcorner.y , mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x - 2, labelcorner.y + 2, mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x , labelcorner.y + 2, mCharSize.x, -mCharSize.y, 0);
FontDrawString(mLabel, labelcorner.x + 2, labelcorner.y + 2, mCharSize.x, -mCharSize.y, 0);
}
// render label
Color4 color;
float interp = ((sim_turn & 16) ? 16 - (sim_turn & 15) : (sim_turn & 15)) / 16.0f;
for (int c = 0; c < 4; c++)
color[c] = Lerp(mLabelColor[state][0][c], mLabelColor[state][1][c], interp);
FontDrawColor(color);
FontDrawString(mLabel, labelcorner.x, labelcorner.y, mCharSize.x, -mCharSize.y, 0);
FontDrawEnd();
}
}
|
2ee0a243340a07e9c8b46db4cc51686d8d0f30b7 | 6d3dc5ec1a562724888ac7b56178c2b4aa32754c | /src/interfaces/python/opengm/inference/pyReducedInference.cxx | 3403c4d27f6294c4a850a88115c6c3d47b71b9cf | [
"MIT"
] | permissive | lijx10/opengm | 82ef2cfd7dc19e1e8c69826e088e11adddf02509 | 3ee326e544a54d92e2981f1dd65ca9949b93c220 | refs/heads/master | 2020-04-15T20:57:44.696418 | 2019-01-10T08:03:10 | 2019-01-10T08:03:10 | 165,015,640 | 8 | 0 | MIT | 2019-01-10T07:53:22 | 2019-01-10T07:53:22 | null | UTF-8 | C++ | false | false | 4,219 | cxx | pyReducedInference.cxx | #ifdef WITH_QPBO
// redefined symbol since pyTrws.cxx:(.text+0x0): multiple definition of `DefaultErrorFn(char*)'
#define DefaultErrorFn DefaultErrorFn_ReducedInference
#include <boost/python.hpp>
#include <string>
#include "inf_def_visitor.hxx"
#include <opengm/inference/reducedinference.hxx>
#include <param/reduced_inference_param.hxx>
// SUBSOLVERS
//#ifdef WITH_MULTICUT
//#include <opengm/inference/multicut.hxx>
//#endif
#ifdef WITH_CPLEX
#include <opengm/inference/lpcplex.hxx>
#include <param/lpcplex_param.hxx>
#endif
//#ifdef WITH_FASTPD
//#include <opengm/inference/external/fastPD.hxx>
//#endif
#ifdef WITH_TRWS
#include <opengm/inference/external/trws.hxx>
#include <param/trws_external_param.hxx>
#endif
//#ifdef WITH_GCOLIB
//#include <opengm/inference/external/gco.hxx>
//#endif
using namespace boost::python;
#if PY_MAJOR_VERSION == 2
static void wrap_import_array() {
import_array();
}
#else
static void * wrap_import_array() {
import_array();
}
#endif
template<class GM,class ACC>
void export_reduced_inference(){
#ifdef WITH_CPLEX
const bool withCplex=true;
#else
const bool withCplex=false;
#endif
#ifdef WITH_TRWS
const bool withTrws=true;
#else
const bool withTrws=false;
#endif
using namespace boost::python;
wrap_import_array();
typedef opengm::ReducedInferenceHelper<GM> RedInfHelper;
typedef typename RedInfHelper::InfGmType SubGmType;
append_subnamespace("solver");
// documentation
std::string srName = semiRingName <typename GM::OperatorType,ACC >() ;
InfSetup setup;
setup.cite = "";
setup.algType = "qpbo-reduced inference";
setup.hyperParameterKeyWords = StringVector(1,std::string("subInference"));
setup.hyperParametersDoc = StringVector(1,std::string("inference algorithms for the sub-problems"));
setup.dependencies = "This algorithm needs the Qpbo library from ??? , "
"compile OpenGM with CMake-Flag ``WITH_QPBO`` set to ``ON`` ";
// parameter of inference will change if hyper parameter changes
setup.hasInterchangeableParameter = false;
{
#ifdef WITH_CPLEX
// export parameter
typedef opengm::LPCplex<SubGmType, ACC> SubInfType;
typedef opengm::ReducedInference<GM,ACC,SubInfType> PyReducedInf;
// set up hyper parameter name for this template
setup.isDefault = withCplex;
setup.hyperParameters= StringVector(1,std::string("cplex"));
// export sub-inf param and param
exportInfParam<SubInfType>("_SubParameter_ReducedInference_Cplex");
exportInfParam<PyReducedInf>("_ReducedInference_Cplex");
// export inference itself
class_< PyReducedInf>("_ReducedInference_Cplex",init<const GM & >())
.def(InfSuite<PyReducedInf,false>(std::string("ReducedInference"),setup))
;
#endif
}
{
#ifdef WITH_TRWS
typedef opengm::external::TRWS<SubGmType> SubInfType;
typedef opengm::ReducedInference<GM,ACC,SubInfType> PyReducedInf;
// set up hyper parameter name for this template
setup.isDefault = !withCplex;
setup.hyperParameters= StringVector(1,std::string("trws"));
// THE ENUMS OF SUBSOLVERS NEED TO BE EXPORTED AGAIN.... THIS COULD BE SOLVED BETTER....
const std::string enumName=std::string("_SubInference_ReducedInference_Trws_EnergyType")+srName;
enum_<typename SubInfType::Parameter::EnergyType> (enumName.c_str())
.value("view", SubInfType::Parameter::VIEW)
.value("tables", SubInfType::Parameter::TABLES)
.value("tl1", SubInfType::Parameter::TL1)
.value("tl2", SubInfType::Parameter::TL2)
;
// export sub-inf param and param
exportInfParam<SubInfType>("_SubParameter_ReducedInference_Trws");
exportInfParam<PyReducedInf>("_ReducedInference_Trws");
// export inference itself
class_< PyReducedInf>("_ReducedInference_Trws",init<const GM & >())
.def(InfSuite<PyReducedInf,false>(std::string("ReducedInference"),setup))
;
#endif
}
}
template void export_reduced_inference<opengm::python::GmAdder,opengm::Minimizer>();
#endif
|
8cdfbb9609be98215237aaad6691cccb93d56211 | 52d97c724054fe880e8bb22e9ab5185227ed14f6 | /mortgageCalculator2.cpp | 4dce039036b588e39ea7e0b03dcdc2df35286e84 | [] | no_license | mkwok94/School | 9c66d5c6cc93d4257b4a9891eb970f43d40f04b3 | bb1448629de4156243584a3e2e4ff05f208aafa1 | refs/heads/master | 2020-04-12T05:43:20.326900 | 2017-02-10T06:11:57 | 2017-02-10T06:11:57 | 62,365,085 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,223 | cpp | mortgageCalculator2.cpp | #include <iostream>
#include <string>
#include <cmath>
using namespace std;
int getPassword()
{
int i;
i = 0;
while (i != 3)
{
string password;
cout << "Enter the password: ";
getline(cin, password);
if(password.compare("12345") == 0)
{
return 0;
}
else
{
cout << "INVALID. \n\n";
}
i = i + 1;
} // while
return 1;
} // getPassword
int main()
{
int isPasswordRight;
isPasswordRight = getPassword();
if (isPasswordRight == 1)
{
return -1;
}
if (isPasswordRight == 0)
{
int borrowed;
double rate;
cout << endl;
cout << endl;
cout << "What's the amount borrowed: ";
cin >> borrowed;
cout << "What's the annual interest rate: ";
cin >> rate;
cout << endl;
cout << endl;
double mortgage;
double r = (rate/100) / 12;
int payback = 30;
int n = payback * 12;
mortgage = (borrowed * pow(1+r, n) * r)/( pow(1+r, n) - 1);
cout << "Amount borrowed: " << borrowed << endl;
cout << "Annual interest rate: " << rate << endl;
cout << "Payback period: " << payback << " years" << endl;
cout << "Monthly payback: $" << mortgage << endl;
}
} |
00926a2b5b88335ecd1a643599967a8aa2ccea4c | eca9d5f5410dd00224e08bcf8a7d23b4b05ea1f6 | /src/magnet.cpp | ed004314050e52aeccb97a43e8d93107c8c199df | [] | no_license | shivam14300/Jetpack-Joyride-Clone | 40d04cbcf3f01ac59b9a9ad87b652da4a3a8e9cf | 874e12002957488e1a65074e40f6bbaae4ae4775 | refs/heads/master | 2020-04-30T21:41:22.236226 | 2019-03-22T08:18:06 | 2019-03-22T08:18:06 | 177,099,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,356 | cpp | magnet.cpp | #include "magnet.h"
#include "main.h"
#include<math.h>
Magnet::Magnet(float x, float y, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = 0;
this->timer = 0.0f;
// Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
// A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
GLfloat vertex_buffer_data[100];
// for(int i=0,x=0;i<360;i++)
// {
// if(i%40 < 20){
// vertex_buffer_data[x++] = 0.5f*cos((M_PI*(float)i)/(float)180);
// vertex_buffer_data[x++] = 0.5f*sin((M_PI*(float)i)/(float)180);
// vertex_buffer_data[x++] = 0.0f;
// vertex_buffer_data[x++] = 1.0f*cos((M_PI*(float)i)/(float)180);
// vertex_buffer_data[x++] = 1.0*sin((M_PI*(float)i)/(float)180);
// vertex_buffer_data[x++] = 0.0f;
// vertex_buffer_data[x++] = 1.0f*cos((M_PI*(float)(i+1))/(float)180);
// vertex_buffer_data[x++] = 1.0f*sin((M_PI*(float)(i+1))/(float)180);
// vertex_buffer_data[x++] = 0.0f;
// vertex_buffer_data[x++] = 0.5f*cos((M_PI*(float)i)/(float)180);
// vertex_buffer_data[x++] = 0.5f*sin((M_PI*(float)i)/(float)180);
// vertex_buffer_data[x++] = 0.0f;
// vertex_buffer_data[x++] = 0.5f*cos((M_PI*(float)(i+1))/(float)180);
// vertex_buffer_data[x++] = 0.5f*sin((M_PI*(float)(i+1))/(float)180);
// vertex_buffer_data[x++] = 0.0f;
// vertex_buffer_data[x++] = 1.0f*cos((M_PI*(float)(i+1))/(float)180);
// vertex_buffer_data[x++] = 1.0f*sin((M_PI*(float)(i+1))/(float)180);
// vertex_buffer_data[x++] = 0.0f;
// }
// }
vertex_buffer_data[0] = 0.5f;vertex_buffer_data[1] = 0.5f;vertex_buffer_data[2] = 0.0f;
vertex_buffer_data[3] = 0.5f;vertex_buffer_data[4] = -0.25f;vertex_buffer_data[5] = 0.0f;
vertex_buffer_data[6] = 0.25f;vertex_buffer_data[7] = -0.25f;vertex_buffer_data[8] = 0.0f;
vertex_buffer_data[9] = 0.5f;vertex_buffer_data[10] = 0.5f;vertex_buffer_data[11] = 0.0f;
vertex_buffer_data[12] = 0.25f;vertex_buffer_data[13] = -0.25f;vertex_buffer_data[14] = 0.0f;
vertex_buffer_data[15] = 0.25f;vertex_buffer_data[16] = 0.25f;vertex_buffer_data[17] = 0.0f;
vertex_buffer_data[18] = 0.5f;vertex_buffer_data[19] = 0.5f;vertex_buffer_data[20] = 0.0f;
vertex_buffer_data[21] = 0.25f;vertex_buffer_data[22] = 0.25f;vertex_buffer_data[23] = 0.0f;
vertex_buffer_data[24] = -0.5f;vertex_buffer_data[25] = 0.5f;vertex_buffer_data[26] = 0.0f;
vertex_buffer_data[27] = -0.5f;vertex_buffer_data[28] = 0.5f;vertex_buffer_data[29] = 0.0f;
vertex_buffer_data[30] = -0.25f;vertex_buffer_data[31] = 0.25f;vertex_buffer_data[32] = 0.0f;
vertex_buffer_data[33] = 0.25f;vertex_buffer_data[34] = 0.25f;vertex_buffer_data[35] = 0.0f;
vertex_buffer_data[36] = -0.5f;vertex_buffer_data[37] = 0.5f;vertex_buffer_data[38] = 0.0f;
vertex_buffer_data[39] = -0.25f;vertex_buffer_data[40] = -0.25f;vertex_buffer_data[41] = 0.0f;
vertex_buffer_data[42] = -0.5f;vertex_buffer_data[43] = -0.25f;vertex_buffer_data[44] = 0.0f;
vertex_buffer_data[45] = -0.5f;vertex_buffer_data[46] = 0.5f;vertex_buffer_data[47] = 0.0f;
vertex_buffer_data[48] = -0.25f;vertex_buffer_data[49] = 0.25f;vertex_buffer_data[50] = 0.0f;
vertex_buffer_data[51] = -0.25f;vertex_buffer_data[52] = -0.25f;vertex_buffer_data[53] = 0.0f;
this->object = create3DObject(GL_TRIANGLES, 6*3, vertex_buffer_data, color, GL_FILL);
}
void Magnet::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
// No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate
// rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object);
}
void Magnet::set_position(float x, float y)
{
this->position = glm::vec3(x, y, 0);
}
void Magnet::tick()
{
}
|
717d8ce2cd46865bbce91f66a9d19be224893f0e | 68329a5d26876479f59f6d3e281f67c994bce867 | /B00_P2_BERNABE_PAU_CERRRILLO_MARC/Exercici2Practica2/main.cpp | 7a69b5313860fd5ff59c63ee351e6fd640bbb4ba | [] | no_license | paubernabe/EstructuraDeDades | a355ac725ff3883deb05dccdbbeccd4cf0a3e7c8 | e4628218833c4d1e40ef89935182f3b54e4af7f8 | refs/heads/master | 2021-10-23T22:46:39.527243 | 2019-03-20T17:15:05 | 2019-03-20T17:15:05 | 122,514,188 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,270 | cpp | main.cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: paubc
*
* Created on 22 / de març / 2018, 13:07
*/
#include <cstdlib>
#include "LinkedDeque.hpp"
#include <vector>
#include <iostream>
#include <stdexcept>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
LinkedDeque<int> linked;
int option, seeMenu(),ele;
do{
seeMenu();
cin >> option;
switch(option){
case 1:
cin >> ele;
linked.insertFront(ele);
cout << "Element " << ele << " introduit" << endl;
break;
case 2:
cin >> ele;
linked.insertRear(ele);
cout << "Element " << ele<< " introduit" << endl;
break;
case 3:
try{
linked.deleteFront();
}catch(invalid_argument&exception){
cout<<exception.what()<<endl;
}
cout << "Element " << linked.getFront() << " eliminat" << endl;
break;
case 4:
try{
linked.deleteRear();
}catch(invalid_argument&exception){
cout<<exception.what()<<endl;
}
cout << "Element " << linked.getRear() << " eliminat" << endl;
break;
case 5:
linked.print();
break;
case 6:
linked.deleteFront();
linked.deleteRear();
linked.insertFront(20);
linked.insertFront(30);
linked.insertRear(80);
linked.insertRear(45);
linked.deleteFront();
linked.print();
break;
case 7:
linked.deleteFront();
linked.deleteRear();
linked.insertFront(2);
linked.insertFront(3);
linked.insertRear(8);
linked.insertRear(4);
linked.deleteFront();
linked.print();
break;
case 8:
cout << "Fins la proxima" << endl;
linked.~LinkedDeque();
break;
}
} while (option!=8);
return 0;
}
int seeMenu(){
int option,i;
string opt []={ "Inserir element pel davant", "Inserir element pel final","Eliminar element pel davant","Eliminar element pel final","Imprimir contingut de LINKED DEQUE","Imprimir Cas Prova 1","Imprimir Cas Prova 2", "Sortir" };
vector <string> arr_options (opt, opt+8);
//Si marca error, fallo tipic Netbeans.
for (i=0;i<arr_options.size();++i){
cout << i+1 << "." << arr_options[i] << endl;
}
return 0;
}
//**PREGUNTES*****************************************
/*
1. Has implementat la LinkedDeque amb templates? Sigui quina sigui la teva resposta,
justifica el motiu pel qual has pres aquesta decisió
*
* Si, l'he implementat amb template, d'aquesta manera podem afegir tot tipus d'elements
* a la nostra LinkedDeque i a més podrem reutilitzar codi en gran varietat de casos.
*
2. Tenint en compte la teva implementació del TAD LinkedDeque, indica per a cadascuna
de les operacions del TAD LinkedDeque quin és el seu cost computacional teòric.
Justifica la resposta
*
* Els inserts i deletes podem trobar un cost de O(1), això es deu a que
* al estar enllaçats els nodes amb punters, el cost es redueix dràsticament
* a diferència que ho fessim amb llista, ja que amb llista, quan estem tractant elements són
* molt més pesades en sentit computacionals, ja que quan inserim o borrem, acostuma a afectar a tota
* la llista sencera i cada procés suma, amb els nombres que utilitzem ara, no ho notem, però
* amb una gran quantitat, l'array queda obsoleta.
*
* Llavors podriem considerar que el print, al fer un recorregut, te un cost més elevat als altres
* ja que passa per tota la llista.
*
*
3. Creieu que la classe Node hauria estat millor implementar-la amb encadenaments
simples? Justifica la teva resposta
*
* Jo crec que si, podriem haver utilitzar un sol encadenament.
* Aquestes dues(single i double linked) tenen la mateixa complexitat en les operacions que hem vist a la
* practica 2, O(1) a la gran majoria.
* Però en alguns casos, com per exemple borrar, ens aniria millor la double linked, ja que
* amb un sol enllaç, perdriem totalment el contacte amb l'altre node i hauràs de buscar aquell node
* cosa que augmenta la complexitat.
* Un punt en contra del double linked és que utilitza molta més memòria.
*
*
*/
|
ede3dd5e89693f94125818f18b5d09ef5ff2a8b5 | ec156e39a7c3b372d8f1ded40a49aa9acef8f6e5 | /test/return_forget_frame_subroutine.cpp | 37ac69ddde45fbe55372a0b720beeaf435af2fe6 | [
"CC-BY-4.0"
] | permissive | Farwaykorse/coroutine | 255a4db274a056c5e0731597652783763b4d6737 | cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7 | refs/heads/master | 2020-12-10T10:31:10.642384 | 2019-12-27T05:26:12 | 2019-12-27T05:26:12 | 233,567,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | cpp | return_forget_frame_subroutine.cpp | //
// Author : github.com/luncliff (luncliff@gmail.com)
// License : CC BY 4.0
//
#include <coroutine/return.h>
#include "test.h"
using namespace std;
using namespace coro;
// the type is default constructible
auto invoke_and_no_await() -> forget_frame {
return {};
};
auto coro_forget_frame_without_await_test() -> int {
try {
invoke_and_no_await();
return EXIT_SUCCESS;
} catch (const exception& ex) {
_println_(ex.what());
return __LINE__;
}
}
#if defined(CMAKE_TEST)
int main(int, char* []) {
return coro_forget_frame_without_await_test();
}
#elif __has_include(<CppUnitTest.h>)
#include <CppUnitTest.h>
template <typename T>
using TestClass = ::Microsoft::VisualStudio::CppUnitTestFramework::TestClass<T>;
class coro_forget_frame_without_await
: public TestClass<coro_forget_frame_without_await> {
TEST_METHOD(test_coro_forget_frame_without_await) {
coro_forget_frame_without_await_test();
}
};
#endif
|
0dbf2874032e350a060e686de0b763a6348d6734 | fa7ec826c6e1645b780a2a16617a5f08f16dfff9 | /include/geoshape/Point2D.h | d2169ebf75b3495ad22a313187178413d987d2ad | [
"MIT"
] | permissive | xzrunner/geoshape | 3692a8b9fe567426d5ce1dada42543d84589378c | a79d5ef70e9949afeef472878ca25ed81d7ee1e6 | refs/heads/master | 2023-03-02T03:41:01.187203 | 2023-02-25T00:42:28 | 2023-02-25T00:42:28 | 152,873,339 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | h | Point2D.h | #pragma once
#include "geoshape/Shape2D.h"
namespace gs
{
class Point2D : public Shape2D
{
public:
Point2D() {}
Point2D(const sm::vec2& pos);
virtual ShapeType2D GetType() const override { return ShapeType2D::Point; }
virtual std::unique_ptr<Shape2D> Clone() const override;
virtual bool IsContain(const sm::vec2& pos) const override;
virtual bool IsIntersect(const sm::rect& rect) const override;
virtual void Translate(float dx, float dy) override;
auto& GetPos() const { return m_pos; }
void SetPos(const sm::vec2& pos);
private:
void UpdateBounding();
private:
sm::vec2 m_pos;
#ifndef NO_RTTR
RTTR_ENABLE(Shape2D)
#endif // NO_RTTR
}; // Point2D
} |
c4c75600bb59bf6d924b57d0c40740f5a35b2973 | fd2b32674d9c2dc9b14fb3a803b6dc9aafc641dc | /day17/old/old_part1.cpp | 2e389723ebc0b9762ac825f4bbee5c0971562bee | [] | no_license | felrock/Advent-of-Code-2020 | 5287203ffa77fc8100183be8501ef4bcc1f0125d | 8db0f738331680a7bc74e7df74f224d0d947c40a | refs/heads/master | 2023-02-05T13:36:35.892658 | 2020-12-24T15:19:33 | 2020-12-24T15:19:33 | 317,660,011 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,589 | cpp | old_part1.cpp | #include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <array>
#include <map>
#include <regex>
#include <unordered_map>
using XYZ = std::tuple<int, int, int>;
std::string xyzToString(const XYZ& xyz)
{
return std::to_string(std::get<0>(xyz)) + "," + std::to_string(std::get<1>(xyz)) + "," + std::to_string(std::get<2>(xyz));
}
XYZ stringToXyz(const std::string& str)
{
std::string s;
std::vector<int> nums;
for(const auto& chr : str)
{
if(chr == ',')
{
nums.push_back(std::stoi(s));
s = "";
}
else
{
s += chr;
}
}
return XYZ(nums[0], nums[1], nums[2]);
}
int countNeighbors(const XYZ& xyz, const std::unordered_map<std::string, XYZ>& world, const std::vector<XYZ>& neighbors)
{
int count_neighbors = 0;
int x1 = std::get<0>(xyz);
int y1 = std::get<1>(xyz);
int z1 = std::get<2>(xyz);
for(const auto& n : neighbors)
{
XYZ txyz = std::make_tuple(x1+std::get<0>(n), y1+std::get<1>(n), z1+std::get<2>(n));
if(world.find(xyzToString(txyz)) != world.end())
{
count_neighbors++;
}
}
return count_neighbors;
}
int main(int argc, char** argv)
{
std::fstream file(argv[1]);
std::string s;
// read
std::unordered_map<std::string, XYZ> world;
int x=0, y=0, z=0;
while(std::getline(file, s))
{
for(const auto& chr : s)
{
if(chr == '#')
{
XYZ xyz = std::make_tuple(x, y, z);
world[xyzToString(xyz)] = xyz;
}
x++;
}
x = 0;
y++;
}
// create neighbor positions
const std::vector<int> val = {1, 0, -1};
std::vector<XYZ> neighbors;
for(const auto& v1 : val)
{
for(const auto& v2 : val)
{
for(const auto& v3 : val)
{
if(v1 != 0 || v2 != 0 || v3 != 0)
{
neighbors.push_back(std::make_tuple(v1,v2,v3));
}
}
}
}
// iterate world
unsigned int iteration = 0;
const unsigned int max_iterations = 6;
while(iteration < max_iterations)
{
std::unordered_map<std::string, XYZ> new_world;
for(const auto& xyz : world)
{
int count_neighbors = countNeighbors(xyz.second, world, neighbors);
if(count_neighbors == 2 || count_neighbors == 3)
{
new_world[xyz.first] = xyz.second;
}
// see if anything should be added around current pos
int x1 = std::get<0>(xyz.second);
int y1 = std::get<1>(xyz.second);
int z1 = std::get<2>(xyz.second);
for(const auto& v : neighbors)
{
XYZ neighbor_pos = std::make_tuple(x1+std::get<0>(v), y1+std::get<1>(v), z1+std::get<2>(v));
// found empty neighbor
std::string neighbor_pos_str = xyzToString(neighbor_pos);
if(world.find(neighbor_pos_str) == world.end())
{
int count_neighbor_neighbors = countNeighbors(neighbor_pos, world, neighbors);
if(count_neighbor_neighbors == 3)
{
new_world[neighbor_pos_str] = neighbor_pos;
}
}
}
}
world = new_world;
iteration++;
}
std::cout << world.size() << std::endl;
return 0;
} |
fb4b45f0f6265c742525cbc6a8e8f5fdb2ed7151 | 1ebcfbba6da89d31a0c99a04d0ba931b989d61be | /Tool/EtcTool.cpp | 86e6223793f43fc67b099c4c650d3d48734f838e | [
"Unlicense"
] | permissive | sangshub/55231 | a36ed4b765a6fb61a9b719c2247966d84c1e2496 | 1f31ab8610999856e932bac9327255475f56e4d4 | refs/heads/master | 2021-01-25T04:09:39.054813 | 2017-06-12T06:44:35 | 2017-06-12T06:44:35 | 93,401,540 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,441 | cpp | EtcTool.cpp | // EtcTool.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "Tool.h"
#include "Monster.h"
#include "EtcTool.h"
#include "Tile.h"
#include "FileInfo.h"
#include "TextureMgr.h"
#include "BufferMgr.h"
#include "ObjMgr.h"
#include "ObjFactory.h"
#include "TileMap.h"
// CEtcTool 대화 상자입니다.
IMPLEMENT_DYNAMIC(CEtcTool, CDialog)
CEtcTool::CEtcTool(CWnd* pParent /*=NULL*/)
: CDialog(CEtcTool::IDD, pParent)
, m_pVtxTex(NULL)
, m_pTextureMgr(CTextureMgr::GetInstance())
, m_pBufferMgr(CBufferMgr::GetInstance())
, m_pObjMgr(CObjMgr::GetInstance())
, m_pTileMap(CTileMap::GetInstance())
{
}
CEtcTool::~CEtcTool()
{
Release();
}
void CEtcTool::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_ListBox);
DDX_Control(pDX, IDC_PICTURE, m_Picture);
}
BEGIN_MESSAGE_MAP(CEtcTool, CDialog)
ON_LBN_SELCHANGE(IDC_LIST1, &CEtcTool::OnLbnSelchangeList1)
ON_BN_CLICKED(IDC_BUTTON1, &CEtcTool::OnBnClickedReturn)
ON_WM_CLOSE()
ON_WM_SHOWWINDOW()
END_MESSAGE_MAP()
// CEtcTool 메시지 처리기입니다.
void CEtcTool::Release()
{
for_each(m_ImgPathList.begin(), m_ImgPathList.end(), ::CDeleteObj());
m_ImgPathList.clear();
for_each(m_ObjDataList.begin(), m_ObjDataList.end(), ::CDeleteObj());
m_ObjDataList.clear();
for(map<CString, CImage*>::iterator iter = m_mapImage.begin();
iter != m_mapImage.end(); ++iter)
{
iter->second->Destroy();
::Safe_Delete(iter->second);
}
m_mapImage.clear();
::Safe_Delete_Array(m_pVtxTex);
}
BOOL CEtcTool::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: 여기에 추가 초기화 작업을 추가합니다.
CFileInfo::DirtoryInfoExtraction_Ex(TEXT("../Texture/Obj"), m_ImgPathList);
wstring wstrCombine = TEXT("");
TCHAR szCount[MIN_STR] = TEXT("");
for(list<IMGPATH*>::iterator iter = m_ImgPathList.begin();
iter != m_ImgPathList.end(); iter++)
{
_itow_s((*iter)->iCount, szCount, 10);
if(FAILED(m_pTextureMgr->InsertTexture((*iter)->wstrPath,(*iter)->wstrObjKey,
TEXTYPE_MULTI,(*iter)->wstrStateKey,TEXT(""),(*iter)->iCount )))
return FALSE;
if((*iter)->wstrStateKey == TEXT("Normal"))
{
wstring wstrFilePath = (*iter)->wstrPath;
TCHAR szRelativePath[MIN_STR] = TEXT("");
wsprintf(szRelativePath, wstrFilePath.c_str(), 0);
map<CString, CImage*>::iterator iter2 = m_mapImage.find((*iter)->wstrObjKey.c_str());
if(iter2 == m_mapImage.end())
{
CImage* pImage = new CImage;
pImage->Load(szRelativePath);
m_mapImage.insert(map<CString, CImage*>::value_type((*iter)->wstrObjKey.c_str(), pImage));
}
m_ListBox.AddString((*iter)->wstrObjKey.c_str());
}
}
m_pVtxTex = new VTXTEX[4];
m_pBufferMgr->GetVtxInfo(TEXT("UnitTex"), m_pVtxTex);
return TRUE; // return TRUE unless you set the focus to a control
// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
void CEtcTool::OnShowWindow(BOOL bShow, UINT nStatus)
{
CDialog::OnShowWindow(bShow, nStatus);
// TODO: 여기에 메시지 처리기 코드를 추가합니다.
m_pTileMap->SetEtcMode(true);
}
void CEtcTool::OnClose()
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
m_pTileMap->SetEtcMode(false);
CDialog::OnClose();
}
void CEtcTool::OnLbnSelchangeList1()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
CString strSelectName = TEXT("");
int iSelectIdx = m_ListBox.GetCurSel();
if(iSelectIdx == -1)
return;
m_ListBox.GetText(iSelectIdx, strSelectName);
map<CString, CImage*>::iterator iter = m_mapImage.find(strSelectName);
m_wstrCurSelName = strSelectName;
if(iter == m_mapImage.end())
return;
m_Picture.SetBitmap(*iter->second);
}
void CEtcTool::OnBnClickedReturn()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
if(!m_ObjDataList.empty())
{
vector<CObj*> vecTile = m_pTileMap->GetFullTile();
int iSize = vecTile.size();
for(int i = 0; i < iSize; ++i)
{
if(m_ObjDataList.back()->vPos.x == vecTile[i]->GetInfo()->vPos.x
&& m_ObjDataList.back()->vPos.z == vecTile[i]->GetInfo()->vPos.z)
((CTile*)vecTile[i])->SetObjCnt(0);
}
::Safe_Delete(m_ObjDataList.back());
m_ObjDataList.pop_back();
m_pObjMgr->MonsterLastDelete();
}
}
void CEtcTool::CreateObj(D3DXVECTOR3 vPos)
{
int iSelect = m_ListBox.GetCurSel();
if(iSelect == -1)
return;
//m_pBufferMgr->SetVtxInfo(TEXT("UnitTex"), m_pVtxTex);
vPos.y = 1.f;
CObj* pObj = (CMonster*)CObjFactory<CMonster>::CreateObj(); // 수정해야함
pObj->SetPos(vPos);
pObj->SetObjKey(m_wstrCurSelName);
CObjMgr::GetInstance()->AddObj(OBJ_MONSTER, pObj);
SLIME* tData = new SLIME;
tData->vPos = vPos;
wcscpy_s(tData->szObjkey,m_wstrCurSelName.c_str());
m_ObjDataList.push_back(tData);
vector<CObj*> vecTile = m_pTileMap->GetFullTile();
int iSize = vecTile.size();
for(int i = 0; i < iSize; ++i)
{
if(vecTile[i]->GetInfo()->vPos.x == m_ObjDataList.back()->vPos.x
&& vecTile[i]->GetInfo()->vPos.z == m_ObjDataList.back()->vPos.z)
{
((CTile*)vecTile[i])->SetTileObj(pObj);
return;
}
}
}
void CEtcTool::SaveToMyForm(const CString& strPath)
{
CString strObjPath = strPath;
CString strObjName = PathFindFileName(strObjPath);
strObjName.Replace(TEXT(".dat"), TEXT(""));
strObjName = strObjName + TEXT("_Etc.txt");
CString strOriginName = PathFindFileName(strObjPath);
strObjPath.Replace(strOriginName, strObjName);
HANDLE hFile = CreateFile(strObjPath, GENERIC_WRITE
, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwByte;
for(list<SLIME*>::iterator iter = m_ObjDataList.begin();
iter != m_ObjDataList.end(); iter++)
{
WriteFile(hFile, (*iter), sizeof(SLIME), &dwByte, NULL);
}
CloseHandle(hFile);
}
void CEtcTool::LoadToMyForm(const CString& strPath)
{
//m_pObjMgr->MonsterDataReset();
for_each(m_ObjDataList.begin(), m_ObjDataList.end(), CDeleteObj());
m_ObjDataList.clear();
CString strObjPath = strPath;
CString strObjName = PathFindFileName(strObjPath);
strObjName.Replace(TEXT(".dat"), TEXT(""));
strObjName = strObjName + TEXT("_Etc.txt");
CString strOriginName = PathFindFileName(strObjPath);
strObjPath.Replace(strOriginName, strObjName);
HANDLE hFile = CreateFile(strObjPath, GENERIC_READ
, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwByte;
vector<CObj*> vecTile = m_pTileMap->GetFullTile();
int iSize = vecTile.size();
while(1)
{
SLIME* pData = new SLIME;
ReadFile(hFile, pData, sizeof(SLIME), &dwByte, NULL);
if(dwByte == 0)
{
Safe_Delete(pData);
break;
}
m_pBufferMgr->SetVtxInfo(TEXT("UnitTex"), m_pVtxTex);
pData->vPos.y = 1.f;
CObj* pObj = (CMonster*)CObjFactory<CMonster>::CreateObj();
pObj->SetPos(pData->vPos);
pObj->SetObjKey(pData->szObjkey);
m_pObjMgr->AddObj(OBJ_MONSTER, pObj);
m_ObjDataList.push_back(pData);
for(int i = 0; i < iSize; ++i)
{
if(vecTile[i]->GetInfo()->vPos.x == m_ObjDataList.back()->vPos.x
&& vecTile[i]->GetInfo()->vPos.z == m_ObjDataList.back()->vPos.z)
((CTile*)vecTile[i])->SetTileObj(pObj);
}
}
CloseHandle(hFile);
}
void CEtcTool::DeleteEtcData(D3DXVECTOR3 vPos)
{
for(list<SLIME*>::iterator iter = m_ObjDataList.begin();
iter != m_ObjDataList.end();)
{
if((*iter)->vPos.x == vPos.x
&& (*iter)->vPos.z == vPos.z)
{
::Safe_Delete(*iter);
iter = m_ObjDataList.erase(iter);
return;
}
else
++iter;
}
} |
02f14d0fc6d0bdf46d8591479c414a765adcda35 | ab7a432885b11cd96eee137e296da7ae6ca96d52 | /atcoder/B172/c.cpp | c38e2c86a925f1c6656bc54f588f4293fe2ee87f | [] | no_license | n3k0fi5t/competitive_programming | 4bd0b845a2d43231c34894817973782b338a8ef6 | 363b40cad754c44ee106f0299f60f4de3c125555 | refs/heads/master | 2023-02-20T10:40:07.798767 | 2021-01-17T03:59:03 | 2021-01-17T03:59:03 | 284,964,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | c.cpp | #include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define imei(...) "[ "<< #__VA_ARGS__ <<" = "<< __VA_ARGS__ <<" ] "
using namespace std;
void solve(int t) {
int n;
cin >> n;
}
vector<ll> a,b;
int n, m, k;
int main(int argc, char *argv[])
{
int ans = 0;
cin >> n >> m >> k;
a.resize(n+1, 0);
b.resize(m+1, 0);
for (int i = 1; i <= n; i++) {
cin >> a[i];
a[i] += a[i-1];
}
for (int i = 1; i <= m; i++) {
cin >> b[i];
b[i] += b[i-1];
}
for (int i = 0, j = m; i <= n; i++) {
if (a[i] > k) break;
while(a[i] + b[j] > k)
j--;
ans = max(ans, i+j);
}
cout << ans;
return 0;
}
|
a66e410ebc7262bcd5acdf841e5220adf1bd1b69 | 1eeba9a9c3eaf3249a78a07ff8e03e69523a4f78 | /include/radix/util/Hash.hpp | 11d0d71d9d7ac5bf0f7d732a8d3bcaf645abd7de | [
"Zlib"
] | permissive | alyssais/RadixEngine | 3d40a31ec783438af2fb5c2756d71e98bf0d5fac | c9647067fbd1c65fe02db9e6012cc6f37420b854 | refs/heads/master | 2022-12-01T21:28:26.486541 | 2020-07-19T00:34:50 | 2020-07-19T13:59:08 | 287,838,730 | 0 | 0 | Zlib | 2020-08-15T23:09:15 | 2020-08-15T23:09:14 | null | UTF-8 | C++ | false | false | 1,884 | hpp | Hash.hpp | #ifndef RADIX_UTIL_HASH_HPP
#define RADIX_UTIL_HASH_HPP
#include <cstdint>
namespace radix {
namespace impl {
// MurmurHash2, by Austin Appleby, https://sites.google.com/site/murmurhash/
#if 0
constexpr unsigned int MurmurHash2(const void *key, int len, unsigned int seed) {
static_assert(sizeof(int) == 4, "int type isn't 4 bytes long");
const unsigned int m = 0x5bd1e995;
const int r = 24;
unsigned int h = seed ^ len;
const unsigned char *data = (const unsigned char*)key;
while (len >= 4) {
unsigned int k = *(unsigned int *)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch (len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
#endif
constexpr unsigned int MurmurHashNeutral2(const char *key, int len, unsigned int seed) {
static_assert(sizeof(int) == 4, "int type isn't 4 bytes long");
const unsigned int m = 0x5bd1e995;
const int r = 24;
unsigned int h = seed ^ len;
const char *data = key;
while (len >= 4) {
unsigned int k = data[0];
k |= data[1] << 8;
k |= data[2] << 16;
k |= data[3] << 24;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch (len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
}
/*constexpr uint32_t Hash32(const void *key, int len) {
return impl::MurmurHashNeutral2(key, len, 0);
}*/
constexpr int conststrlen(const char *str) {
return *str ? 1 + conststrlen(str + 1) : 0;
}
constexpr uint32_t Hash32(const char *str) {
return impl::MurmurHashNeutral2(str, conststrlen(str), 0);
}
} /* namespace radix */
#endif /* RADIX_UTIL_HASH_HPP */
|
1684c2399e231d91ea36128c9a6038f77952c120 | 6e40dca200bc41836fc479e59cf361617771812d | /tests/synchronized_tests.cpp | 8df7667e73674d3ea059a71a98161967efe8934b | [
"Unlicense"
] | permissive | aautushka/haisu | e7568663770d57c6a489ed4720c821dd7a60b5b6 | 3d961ffa090ade54aa3d6e8fc82cacb71c40cbb2 | refs/heads/master | 2021-12-15T07:07:13.217299 | 2021-12-04T07:29:48 | 2021-12-04T07:29:48 | 79,335,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,181 | cpp | synchronized_tests.cpp | /*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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 <gtest/gtest.h>
#include <vector>
#include <thread>
#include "haisu/concurrency.h"
struct synchronized_test : ::testing::Test
{
};
TEST_F(synchronized_test, synchronizes_access_to_an_object)
{
haisu::synchronized<std::vector<int>> v;
v->push_back(123);
EXPECT_EQ(123, v->back());
}
TEST_F(synchronized_test, locks_mutex_multiple_times_within_the_same_expression)
{
haisu::synchronized<std::vector<int>> v;
v->push_back(1);
v->push_back(2);
EXPECT_EQ(3, v->front() + v->back());
}
TEST_F(synchronized_test, stress_test)
{
haisu::synchronized<std::vector<int>> v;
std::thread t1([&](){for (int i = 0; i < 1000000; ++i) v->push_back(i);});
std::thread t2([&](){for (int i = 0; i < 1000000; ++i) v->push_back(i);});
std::thread t3([&](){for (int i = 0; i < 1000000; ++i) v->push_back(i);});
std::thread t4([&](){for (int i = 0; i < 1000000; ++i) v->push_back(i);});
t1.join();
t2.join();
t3.join();
t4.join();
EXPECT_EQ(4000000, v->size());
}
|
d3fdaca51d470cc4ace4c06e14efeba43bb7133a | 1f58668ff008cbdc9c8a266f98e0eacad5c389ec | /others/QtC++Course/build-Qt436-Desktop_Qt_5_12_3_MinGW_32_bit-Debug/ui_suredialog.h | 728c312db6f05b4e5c5595905a13ae6d2ac7f95a | [] | no_license | rockdonald2/studying | c17201299cd565fad79d34955cbc49cf6e850619 | 069750a060be00c5e2a36fd1ae91f95b13f12537 | refs/heads/master | 2021-06-15T14:33:53.486395 | 2021-02-10T08:48:17 | 2021-02-10T08:48:17 | 134,238,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,787 | h | ui_suredialog.h | /********************************************************************************
** Form generated from reading UI file 'suredialog.ui'
**
** Created by: Qt User Interface Compiler version 5.12.3
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_SUREDIALOG_H
#define UI_SUREDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_SureDialog
{
public:
QVBoxLayout *verticalLayout;
QLabel *label;
QHBoxLayout *horizontalLayout;
QSpacerItem *horizontalSpacer;
QPushButton *okButton;
QPushButton *cancelButton;
void setupUi(QDialog *SureDialog)
{
if (SureDialog->objectName().isEmpty())
SureDialog->setObjectName(QString::fromUtf8("SureDialog"));
SureDialog->resize(400, 183);
verticalLayout = new QVBoxLayout(SureDialog);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
label = new QLabel(SureDialog);
label->setObjectName(QString::fromUtf8("label"));
QFont font;
font.setPointSize(26);
label->setFont(font);
verticalLayout->addWidget(label);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalSpacer = new QSpacerItem(379, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
okButton = new QPushButton(SureDialog);
okButton->setObjectName(QString::fromUtf8("okButton"));
horizontalLayout->addWidget(okButton);
cancelButton = new QPushButton(SureDialog);
cancelButton->setObjectName(QString::fromUtf8("cancelButton"));
horizontalLayout->addWidget(cancelButton);
verticalLayout->addLayout(horizontalLayout);
retranslateUi(SureDialog);
QMetaObject::connectSlotsByName(SureDialog);
} // setupUi
void retranslateUi(QDialog *SureDialog)
{
SureDialog->setWindowTitle(QApplication::translate("SureDialog", "Dialog", nullptr));
label->setText(QApplication::translate("SureDialog", "Are you sure?", nullptr));
okButton->setText(QApplication::translate("SureDialog", "OK", nullptr));
cancelButton->setText(QApplication::translate("SureDialog", "Cancel", nullptr));
} // retranslateUi
};
namespace Ui {
class SureDialog: public Ui_SureDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_SUREDIALOG_H
|
d7408624d42d8251f324486fc5ab8aabae48dcdb | 697b96cea985d4b19d506ddece109a5706c7518a | /content/graph/matching/min-bi-cover.cpp | e5ac66531fdf6a09b381c635756a935d0ea52284 | [
"MIT"
] | permissive | ToxicPie/codebook | ed08db73a80ba0bda811f5a9b24bf050819995a0 | fc084c4b61026f33a03f2901430b6fe36d2c1e6f | refs/heads/master | 2023-07-19T02:08:17.566513 | 2021-08-31T17:53:39 | 2021-08-31T17:53:39 | 275,392,346 | 10 | 1 | MIT | 2021-08-31T17:53:40 | 2020-06-27T14:46:14 | C++ | UTF-8 | C++ | false | false | 1,274 | cpp | min-bi-cover.cpp | // maximum independent set = all vertices not covered
// include Dinic, x : [0, n), y : [0, m]
struct Bipartite_vertex_cover {
Dinic D;
int n, m, s, t, x[maxn], y[maxn];
void make_edge(int x, int y) {D.make_edge(x, y + n, 1);}
int matching() {
int re = D.max_flow(s, t);
for(int i = 0; i < n; i++)
for(Dinic::edge &e : D.v[i])
if(e.to != s && e.flow == 1) {
x[i] = e.to - n, y[e.to - n] = i;
break;
}
return re;
}
// init() and matching() before use
void solve(vector<int> &vx, vector<int> &vy) {
bitset<maxn * 2 + 10> vis;
queue<int> q;
for(int i = 0; i < n; i ++)
if(x[i] == -1)
q.push(i), vis[i] = 1;
while(!q.empty()) {
int now = q.front();
q.pop();
if(now < n) {
for(Dinic::edge &e : D.v[now])
if(e.to != s && e.to - n != x[now] && !vis[e.to])
vis[e.to] = 1, q.push(e.to);
} else {
if(!vis[y[now - n]])
vis[y[now - n]] = 1, q.push(y[now - n]);
}
}
for(int i = 0; i < n; i++)
if(!vis[i])
vx.pb(i);
for(int i = 0; i < m; i++)
if(vis[i + n])
vy.pb(i);
}
void init(int _n, int _m) {
n = _n, m = _m, s = n + m, t = s + 1;
for(int i = 0; i < n; i++)
x[i] = -1, D.make_edge(s, i, 1);
for(int i = 0; i < m; i++)
y[i] = -1, D.make_edge(i + n, t, 1);
}
};
|
da16026b6e3ad66df9cdca96afe312eba3ca1390 | b73f2ac1df7539f6d12afcb03e4a5625926e803b | /src/Capture/FileOutputStream.cpp | 5622bedc4c2f95ce20781128560dad19eb1122a2 | [] | no_license | nikkadim/SLS | 80c09ee4b2bb930335f73be753d48fcb9f24cbda | 5b34987bd5f4fd8ed9ac0614f39ddcf28e6f1d72 | refs/heads/master | 2020-03-21T08:25:57.863594 | 2013-08-09T19:35:50 | 2013-08-09T19:35:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | FileOutputStream.cpp | #include "Capture/FileOutputStream.h"
FileOutputStream::FileOutputStream(string& filename, int width, int height)
{
m_filename = filename;
m_width = width;
m_height = height;
}
void FileOutputStream::Open(void)
{
m_io.openSaveStream(m_filename, m_width, m_height, 30);
}
void FileOutputStream::WriteStream(shared_ptr<MeshInterchange> mesh)
{
m_io.saveStream(*mesh.get());
}
void FileOutputStream::Close(void)
{
m_io.closeSaveStream();
} |
65b0d4b40ad7b81d66dbfc708c0d0a2e77b8bbfd | 20b59e8a6419ed7ddb5adf35d05f0eb63e040076 | /test_file/test_hands/cards.cpp | c594f2361f72c16877b35786af85cc9cc1d9160f | [] | no_license | josekijosephi/poker | 00fd25b5accfd6104935fcb5212300dc8f0a84a4 | acc8a77ef7566abfc232e1f1d40600f2fee469bc | refs/heads/master | 2022-08-03T01:29:02.335811 | 2020-05-26T06:25:31 | 2020-05-26T06:25:31 | 266,235,000 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,375 | cpp | cards.cpp | /*
* Here we are concerned with creating a new deck
* of cards and printing a current deck
*
*/
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <chrono> // we are going to try get milliseconds and pump fresh cards out faster
//#include <ctime>
#include <cstdlib>
#include "cards.h"
// These two make assignment easier
std::vector<std::string> suits = { "\u2667", "\u2662", "\u2664", "\u2661" };
std::string values = "23456789TJQKA";
Card::Card(Suit s, Value v)
{
suit = s;
value = v;
symbol = suits[s];
number = values[v];
}
void Card::print_card(int method)
{
if ( method == 1 )
{
std::cout << "\u2219\u2219\u2219\u2219\u2219" << std::endl;
std::cout << "\u2219" << std::setw(2) << number << std::setw(4) << "\u2219" << std::endl;
std::cout << "\u2219" << std::setw(4) << symbol << std::setw(4) << "\u2219" << std::endl;
std::cout << "\u2219\u2219\u2219\u2219\u2219" << std::endl;
std::cout << "\n";
} else
{
std::cout << "Suit," << symbol << ",Value," << number << std::endl;
std::cout << "\n";
}
}
Deck::Deck()
{
// Create a way to check if a card has been used
int all_cards[NUM_SUITS][NUM_VALUES];
for (int i = 0; i < NUM_SUITS; i++)
for (int j = 0; j <NUM_VALUES; j++)
all_cards[i][j] = 0;
int count = 0;
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
);
std::srand(ms.count());
while (++count <= NUM_CARDS)
{
int i, j;
i = std::rand() % NUM_SUITS;
j = std::rand() % NUM_VALUES;
int row_cycles = 0, col_cycles = 0;
while (all_cards[i][j])
{
// we need to find the next free card
j++;
j = j % NUM_VALUES;
col_cycles++;
i = i + (col_cycles % NUM_VALUES == 0);
i = i % NUM_SUITS;
}
all_cards[i][j] = 1;
cards.push_back(Card((Suit)i,(Value)j));
}
}
void Deck::print_deck(int method)
{
// Going to cycle trhough all cards and print them
// using dogmatic c++
for (std::vector<Card>::iterator it = cards.begin();
it != cards.end(); ++it)
it->print_card(method);
}
Card Deck::pop_card()
{
// Need to utilise the pop function
// but return the last card too
Card last_card = cards.back();
cards.pop_back();
return last_card;
}
void pretty_card_print(std::vector<Card> cards)
{
for (int i = 0; i < cards.size(); i++)
std::cout << "\u2219\u2219\u2219\u2219\u2219 ";
std::cout << std::endl;
for (int i = 0; i < cards.size(); i++)
std::cout << "\u2219" << std::setw(2) << cards[i].get_number() << std::setw(6) << "\u2219 ";
std::cout << std::endl;
for (int i = 0; i < cards.size(); i++)
printf("%s %s %s ", "\u2219", cards[i].get_symbol().c_str(),"\u2219");
std::cout << std::endl;
for (int i = 0; i < cards.size(); i++)
std::cout << "\u2219\u2219\u2219\u2219\u2219 ";
std::cout << std::endl;
}
void simple_card_print(std::vector<Card> pocket, std::vector<Card> cards)
{
for (auto it : pocket)
it.print_card(0);
//for (auto it : cards)
// it.print_card(0);
}
|
2fe9dd58f223922d025b653a6cc345b1e02963d3 | 5388d29600f9eef6e3a401e41fbb1ec5f01c9c4e | /02_Lists/11_merge.cpp | aac81f930b1efa27648c695ea17ef92ba7fe7f78 | [] | no_license | a-lagopus/CPP-Playground | 380ecac02e9d4a87d6aed0dd2823d5b82b58f689 | 600bbfa1b0fd9f23534d4475e12ba90c77a7cef1 | refs/heads/master | 2020-04-02T04:12:41.290521 | 2018-11-06T21:57:41 | 2018-11-06T21:57:41 | 154,005,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,150 | cpp | 11_merge.cpp | #include <stdio.h>
#include <iostream>
#include <list>
using namespace std;
bool merge(list<int> * a,list<int> * b,list<int> * c){
while (!a->empty() && !b->empty())
{
if(a->front() <= b->front()){
c->push_back(a->front());
a->pop_front();
}else{
c->push_back(b->front());
b->pop_front();
}
}
while (!a->empty()){
c->push_back(a->front());
a->pop_front();
}
while (!b->empty()){
c->push_back(b->front());
b->pop_front();
}
return 0;
}
//Write a function that merges two sorted lists into a new sorted list.
//[1,4,6],[2,3,5] → [1,2,3,4,5,6].
//You can do this quicker than concatenating them followed by a sort.
int main()
{
list<int> list1({1,3,5,7,9,10,11,22});
list<int> list2({2,4,6,8,12});
list<int> list3({});
for(list<int>::iterator it=list1.begin();it != list1.end(); ++it) cout<< *it << " ";
cout << endl;
for(list<int>::iterator it=list2.begin();it != list2.end(); ++it) cout<< *it << " ";
cout << endl;
merge(&list1,&list2,&list3);
for(list<int>::iterator it=list3.begin();it != list3.end(); ++it) cout<< *it << " ";
cout << endl;
return 0;
}
|
d5bfee1c865fe56cc4612e2fa566d1480eeb154f | 27fbce7c075cd9f4cee7e1250e82cd56a7699c02 | /tao/x11/PolicyC.h | 626a47a09eb714895538c191a8213399d7823fca | [
"MIT"
] | permissive | jwillemsen/taox11 | fe11af6a7185c25d0f236b80c608becbdbf3c8c3 | f16805cfdd5124d93d2426094191f15e10f53123 | refs/heads/master | 2023-09-04T18:23:46.570811 | 2023-08-14T19:50:01 | 2023-08-14T19:50:01 | 221,247,177 | 0 | 0 | MIT | 2023-09-04T14:53:28 | 2019-11-12T15:14:26 | C++ | UTF-8 | C++ | false | false | 18,208 | h | PolicyC.h | /**
* @file PolicyC.h
* @author Martin Corino
*
* @brief CORBA C++11 Policy client stub class.
* Handcrafted after initial generation by RIDL.
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
/*
* **** Code generated by the RIDL Compiler ****
* RIDL has been developed by:
* Remedy IT Expertise BV
* The Netherlands
* https://www.remedy.nl
*/
#ifndef __RIDL_POLICYC_H_INCLUDED__
#define __RIDL_POLICYC_H_INCLUDED__
#include /**/ "ace/pre.h"
#include "tao/x11/stddef.h"
#include "tao/x11/basic_traits.h"
#include "tao/x11/corba.h"
#include "tao/x11/system_exception.h"
#include "tao/x11/object.h"
#include "tao/x11/user_exception.h"
#include "tao/x11/anytypecode/any.h"
#include "tao/x11/anytypecode/typecode_ref.h"
#include "tao/x11/taox11_export.h"
using namespace TAOX11_NAMESPACE;
// generated from c++/cli_hdr/include.erb
#include "tao/x11/UShortSeqC.h"
// generated from c++/cli_hdr/include.erb
#include "tao/x11/CurrentC.h"
// generated from c++/cli_hdr/include.erb
#include "tao/x11/Policy_ForwardC.h"
// generated from StubHeaderWriter#enter_module
namespace TAOX11_NAMESPACE {
namespace CORBA {
// generated from c++/cli_hdr/typedef.erb
using PolicyErrorCode = int16_t;
// generated from c++/anyop_hdr/typedef.erb
extern TAOX11_AnyTypeCode_Export TAOX11_CORBA::typecode_reference const _tc_PolicyErrorCode;
// generated from StubHeaderWriter#visit_const
constexpr PolicyErrorCode BAD_POLICY = 0;
// generated from StubHeaderWriter#visit_const
constexpr PolicyErrorCode UNSUPPORTED_POLICY = 1;
// generated from StubHeaderWriter#visit_const
constexpr PolicyErrorCode BAD_POLICY_TYPE = 2;
// generated from StubHeaderWriter#visit_const
constexpr PolicyErrorCode BAD_POLICY_VALUE = 3;
// generated from StubHeaderWriter#visit_const
constexpr PolicyErrorCode UNSUPPORTED_POLICY_VALUE = 4;
// generated from c++/cli_hdr/except_pre.erb
class TAOX11_Export PolicyError final
: public TAOX11_CORBA::UserException
{
public:
const char* what() const noexcept override;
void _raise () const override;
void _tao_encode (TAO_OutputCDR &cdr) const override;
void _tao_decode (TAO_InputCDR &cdr) override;
/// Deep copy
TAOX11_CORBA::Exception *_tao_duplicate () const override;
// generated from c++/cli_hdr/except_post.erb
PolicyError ();
~PolicyError () noexcept override = default;
PolicyError (const PolicyError&) = default;
PolicyError (PolicyError&&) = default;
explicit PolicyError (TAOX11_CORBA::PolicyErrorCode reason);
PolicyError& operator= (const PolicyError& x);
PolicyError& operator= (PolicyError&& x);
void reason (const TAOX11_CORBA::PolicyErrorCode& _reason);
void reason (TAOX11_CORBA::PolicyErrorCode&& _reason);
const TAOX11_CORBA::PolicyErrorCode& reason () const;
TAOX11_CORBA::PolicyErrorCode& reason ();
protected:
void _info (std::ostream& strm) const override;
private:
TAOX11_CORBA::PolicyErrorCode reason_;
}; // PolicyError
// generated from c++/anyop_hdr/typedef.erb
extern TAOX11_AnyTypeCode_Export TAOX11_CORBA::typecode_reference const _tc_PolicyError;
// generated from c++/cli_hdr/except_pre.erb
class TAOX11_Export InvalidPolicies final
: public TAOX11_CORBA::UserException
{
public:
const char* what() const noexcept override;
void _raise () const override;
void _tao_encode (TAO_OutputCDR &cdr) const override;
void _tao_decode (TAO_InputCDR &cdr) override;
/// Deep copy
TAOX11_CORBA::Exception *_tao_duplicate () const override;
// generated from c++/cli_hdr/except_post.erb
InvalidPolicies ();
~InvalidPolicies () noexcept override = default;
InvalidPolicies (const InvalidPolicies&) = default;
InvalidPolicies (InvalidPolicies&&) = default;
explicit InvalidPolicies (TAOX11_CORBA::UShortSeq indices);
InvalidPolicies& operator= (const InvalidPolicies& x);
InvalidPolicies& operator= (InvalidPolicies&& x);
void indices (const TAOX11_CORBA::UShortSeq& _indices);
void indices (TAOX11_CORBA::UShortSeq&& _indices);
const TAOX11_CORBA::UShortSeq& indices () const;
TAOX11_CORBA::UShortSeq& indices ();
protected:
void _info (std::ostream& strm) const override;
private:
TAOX11_CORBA::UShortSeq indices_;
}; // InvalidPolicies
// generated from c++/anyop_hdr/typedef.erb
extern TAOX11_AnyTypeCode_Export TAOX11_CORBA::typecode_reference const _tc_InvalidPolicies;
// generated from StubHeaderWriter#enter_interface
// generated from c++/cli_hdr/interface_fwd.erb
#if !defined (_INTF_TAOX11_NAMESPACE__CORBA__POLICY_FWD_)
#define _INTF_TAOX11_NAMESPACE__CORBA__POLICY_FWD_
class TAOX11_Export Policy;
class TAOX11_Export Policy_proxy;
using Policy_proxy_ptr = Policy_proxy*;
namespace POA
{
class TAOX11_Export Policy;
}
#endif // !_INTF_TAOX11_NAMESPACE__CORBA__POLICY_FWD_
// generated from CxxWriterBase#at_global_scope
} // namespace TAOX11_NAMESPACE
} // namespace CORBA
// entering CxxWriterBase#at_global_scope
// generated from c++/cli_hdr/interface_object_traits.erb
#if !defined (_INTF_TAOX11_NAMESPACE__CORBA__POLICY_TRAITS_DECL_)
#define _INTF_TAOX11_NAMESPACE__CORBA__POLICY_TRAITS_DECL_
namespace TAOX11_NAMESPACE
{
namespace CORBA
{
template<>
TAOX11_Export object_traits< TAOX11_CORBA::Policy>::shared_ptr_type
object_traits< TAOX11_CORBA::Policy>::lock_shared (
TAOX11_CORBA::Policy*);
template<>
TAOX11_Export object_traits< TAOX11_CORBA::Policy>::ref_type object_traits< TAOX11_CORBA::Policy>::narrow (
object_traits< TAOX11_CORBA::Object>::ref_type);
} // namespace CORBA
namespace IDL
{
template<>
struct traits < TAOX11_CORBA::Policy> :
public IDL::common_byval_traits <IDL::traits<TAOX11_CORBA::Policy>::ref_type>,
public CORBA::object_traits < TAOX11_CORBA::Policy>
{
static constexpr bool local = false;
static constexpr bool abstract = false;
template <typename OStrm_, typename Formatter = formatter<TAOX11_CORBA::Policy, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val} ; }
};
} // namespace IDL
} // namespace TAOX11_NAMESPACE
#endif // !_INTF_TAOX11_NAMESPACE__CORBA__POLICY_TRAITS_DECL_
// leaving CxxWriterBase#at_global_scope
namespace TAOX11_NAMESPACE
{
namespace CORBA
{
// generated from c++/cli_hdr/interface_pre.erb
class TAOX11_Export Policy
: public virtual TAOX11_CORBA::Object
{
public:
friend struct TAOX11_CORBA::object_traits<Policy>;
using _traits_type = IDL::traits<Policy>;
using _ref_type = _traits_type::ref_type;
std::string _interface_repository_id () const override;
// generated from c++/cli_hdr/attribute.erb
virtual TAOX11_CORBA::PolicyType policy_type();
// generated from c++/cli_hdr/operation.erb
virtual object_traits<Policy>::ref_type copy ();
// generated from c++/cli_hdr/operation.erb
virtual void destroy ();
static TAOX11_CORBA::object_traits<Policy>::ref_type _narrow (
TAOX11_CORBA::object_traits< TAOX11_CORBA::Object>::ref_type);
protected:
template <typename _Tp1, typename, typename ...Args>
friend object_reference<_Tp1> make_reference(Args&& ...args);
Policy ();
explicit Policy (TAOX11_NAMESPACE::Object_proxy_ptr op);
~Policy () = default;
virtual object_traits<Policy>::ref_type copy_i ();
private:
Policy(const Policy&) = delete;
Policy& operator=(const Policy&) = delete;
}; // Policy
// generated from c++/anyop_hdr/typedef.erb
extern TAOX11_AnyTypeCode_Export TAOX11_CORBA::typecode_reference const _tc_Policy;
} // namespace CORBA
} // namespace TAOX11_NAMESPACE
// generated from StubHeaderTraitsWriter#pre_visit
namespace TAOX11_NAMESPACE {
namespace IDL {
#if !defined (_INTF_FMT_TAOX11_NAMESPACE__CORBA__POLICY_TRAITS_DECL_)
#define _INTF_FMT_TAOX11_NAMESPACE__CORBA__POLICY_TRAITS_DECL_
template <typename OStrm_>
struct formatter< CORBA::Policy, OStrm_>
{
OStrm_& operator ()(
OStrm_&,
IDL::traits<CORBA::Policy>::in_type);
};
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_&,
IDL::traits<CORBA::Policy>::__Writer<Fmt>);
#endif // !_INTF_FMT_TAOX11_NAMESPACE__CORBA__POLICY_TRAITS_DECL_
// generated from c++/cli_hdr/struct_idl_traits.erb
#if !defined (_STRUCT_TAOX11_NAMESPACE__CORBA__POLICYERROR_TRAITS_)
#define _STRUCT_TAOX11_NAMESPACE__CORBA__POLICYERROR_TRAITS_
template<>
struct traits < TAOX11_CORBA::PolicyError>
: IDL::common_traits< TAOX11_CORBA::PolicyError>
{
template <typename OStrm_, typename Formatter = formatter<value_type, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val} ; }
};
template <typename OStrm_>
struct formatter< TAOX11_CORBA::PolicyError, OStrm_>
{
inline OStrm_& operator ()(
OStrm_& os_,
IDL::traits<TAOX11_CORBA::PolicyError>::in_type)
{
return os_ << "CORBA::PolicyError";
}
};
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits<TAOX11_CORBA::PolicyError>::__Writer<Fmt> w)
{
using writer_t = IDL::traits<TAOX11_CORBA::PolicyError>::__Writer<Fmt>;
using formatter_t = typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter<TAOX11_CORBA::PolicyError, OStrm_>,
typename writer_t::formatter_t>::type;
return IDL::traits<TAOX11_CORBA::PolicyError>::write_on (
os, w.val_,
formatter_t ());
}
#endif // _STRUCT_TAOX11_NAMESPACE__CORBA__POLICYERROR_TRAITS_
// generated from c++/cli_hdr/struct_idl_traits.erb
#if !defined (_STRUCT_TAOX11_NAMESPACE__CORBA__INVALIDPOLICIES_TRAITS_)
#define _STRUCT_TAOX11_NAMESPACE__CORBA__INVALIDPOLICIES_TRAITS_
template<>
struct traits < TAOX11_CORBA::InvalidPolicies>
: IDL::common_traits< TAOX11_CORBA::InvalidPolicies>
{
template <typename OStrm_, typename Formatter = formatter<value_type, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val} ; }
};
template <typename OStrm_>
struct formatter< TAOX11_CORBA::InvalidPolicies, OStrm_>
{
inline OStrm_& operator ()(
OStrm_& os_,
IDL::traits<TAOX11_CORBA::InvalidPolicies>::in_type)
{
return os_ << "CORBA::InvalidPolicies";
}
};
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits<TAOX11_CORBA::InvalidPolicies>::__Writer<Fmt> w)
{
using writer_t = IDL::traits<TAOX11_CORBA::InvalidPolicies>::__Writer<Fmt>;
using formatter_t = typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter<TAOX11_CORBA::InvalidPolicies, OStrm_>,
typename writer_t::formatter_t>::type;
return IDL::traits<TAOX11_CORBA::InvalidPolicies>::write_on (
os, w.val_,
formatter_t ());
}
#endif // _STRUCT_TAOX11_NAMESPACE__CORBA__INVALIDPOLICIES_TRAITS_
} // namespace IDL
} // namespace TAOX11_NAMESPACE
// generated from StubHeaderIDLTraitsDefWriter#pre_visit
namespace TAOX11_NAMESPACE {
namespace IDL {
template <typename OStrm_>
inline OStrm_&
formatter< CORBA::Policy, OStrm_>::operator ()(
OStrm_& os_,
IDL::traits<CORBA::Policy>::in_type o_)
{
return os_ << IDL::traits<TAOX11_NAMESPACE::CORBA::Object>::_dump (o_, "CORBA::Policy");
}
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits<CORBA::Policy>::__Writer<Fmt> w)
{
using writer_t = IDL::traits<CORBA::Policy>::__Writer<Fmt>;
using formatter_t = typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter<CORBA::Policy, OStrm_>,
typename writer_t::formatter_t>::type;
return IDL::traits<CORBA::Policy>::write_on (
os, w.val_,
formatter_t ());
}
} // namespace IDL
} // namespace TAOX11_NAMESPACE
namespace TAOX11_NAMESPACE
{
namespace CORBA
{
// generated from c++/cli_hdr/anyop.erb
#if !defined (__TAOX11_ANYOP_TAOX11_NAMESPACE__CORBA__POLICYERROR_DECL__)
#define __TAOX11_ANYOP_TAOX11_NAMESPACE__CORBA__POLICYERROR_DECL__
TAOX11_AnyTypeCode_Export void operator<<= (TAOX11_CORBA::Any &, const TAOX11_CORBA::PolicyError&);
TAOX11_AnyTypeCode_Export void operator<<= (TAOX11_CORBA::Any &, TAOX11_CORBA::PolicyError&&);
TAOX11_AnyTypeCode_Export bool operator>>= (const TAOX11_CORBA::Any &, TAOX11_CORBA::PolicyError&);
#endif
#if !defined (__TAOX11_ANYOP_TAOX11_NAMESPACE__CORBA__INVALIDPOLICIES_DECL__)
#define __TAOX11_ANYOP_TAOX11_NAMESPACE__CORBA__INVALIDPOLICIES_DECL__
TAOX11_AnyTypeCode_Export void operator<<= (TAOX11_CORBA::Any &, const TAOX11_CORBA::InvalidPolicies&);
TAOX11_AnyTypeCode_Export void operator<<= (TAOX11_CORBA::Any &, TAOX11_CORBA::InvalidPolicies&&);
TAOX11_AnyTypeCode_Export bool operator>>= (const TAOX11_CORBA::Any &, TAOX11_CORBA::InvalidPolicies&);
#endif
// generated from c++/cli_hdr/anyop.erb
#if !defined (__TAOX11_ANYOP_TAOX11_NAMESPACE__CORBA__POLICY_DECL__)
#define __TAOX11_ANYOP_TAOX11_NAMESPACE__CORBA__POLICY_DECL__
TAOX11_AnyTypeCode_Export void operator<<= (TAOX11_CORBA::Any &, IDL::traits<TAOX11_CORBA::Policy>::ref_type);
TAOX11_AnyTypeCode_Export bool operator>>= (const TAOX11_CORBA::Any &, IDL::traits<TAOX11_CORBA::Policy>::_ref_type&);
#endif
} // namespac CORBA
} // namespace TAOX11_NAMESPACE
// generated from StubHeaderStdWriter#pre_visit
namespace std {
} // namespace std
// generated from c++/cli_inl/except_inl.erb
inline TAOX11_CORBA::PolicyError::PolicyError ()
: TAOX11_CORBA::UserException ("IDL:CORBA/PolicyError:1.0", "TAOX11_CORBA::PolicyError")
, reason_ (0)
{
}
inline TAOX11_CORBA::PolicyError::PolicyError (PolicyErrorCode reason)
: TAOX11_CORBA::UserException ("IDL:CORBA/PolicyError:1.0", "TAOX11_CORBA::PolicyError")
, reason_ (std::move (reason))
{
}
inline void TAOX11_CORBA::PolicyError::reason (const PolicyErrorCode& _reason) { this->reason_ = _reason; }
inline void TAOX11_CORBA::PolicyError::reason (PolicyErrorCode&& _reason) { this->reason_ = std::move (_reason); }
inline const TAOX11_CORBA::PolicyErrorCode& TAOX11_CORBA::PolicyError::reason () const { return this->reason_; }
inline TAOX11_CORBA::PolicyErrorCode& TAOX11_CORBA::PolicyError::reason () { return this->reason_; }
inline TAOX11_CORBA::PolicyError& TAOX11_CORBA::PolicyError::operator= (const PolicyError& x)
{
if (this != &x)
{
this->UserException::operator = (x);
this->reason_ = x.reason_;
}
return *this;
}
inline TAOX11_CORBA::PolicyError& TAOX11_CORBA::PolicyError::operator= (TAOX11_CORBA::PolicyError&& x)
{
if (this != &x)
{
this->UserException::operator = (x);
this->reason_ = std::move (x.reason_);
}
return *this;
}
// generated from c++/cli_inl/except_inl.erb
inline TAOX11_CORBA::InvalidPolicies::InvalidPolicies ()
: TAOX11_CORBA::UserException ("IDL:CORBA/InvalidPolicies:1.0", "TAOX11_CORBA::InvalidPolicies")
, indices_ ()
{
}
inline TAOX11_CORBA::InvalidPolicies::InvalidPolicies (TAOX11_CORBA::UShortSeq indices)
: TAOX11_CORBA::UserException ("IDL:CORBA/InvalidPolicies:1.0", "TAOX11_CORBA::InvalidPolicies")
, indices_ (std::move (indices))
{
}
inline void TAOX11_CORBA::InvalidPolicies::indices (const TAOX11_CORBA::UShortSeq& _indices) { this->indices_ = _indices; }
inline void TAOX11_CORBA::InvalidPolicies::indices (TAOX11_CORBA::UShortSeq&& _indices) { this->indices_ = std::move (_indices); }
inline const TAOX11_CORBA::UShortSeq& TAOX11_CORBA::InvalidPolicies::indices () const { return this->indices_; }
inline TAOX11_CORBA::UShortSeq& TAOX11_CORBA::InvalidPolicies::indices () { return this->indices_; }
inline TAOX11_CORBA::InvalidPolicies& TAOX11_CORBA::InvalidPolicies::operator= (const TAOX11_CORBA::InvalidPolicies& x)
{
if (this != &x)
{
this->UserException::operator = (x);
this->indices_ = x.indices_;
}
return *this;
}
inline TAOX11_CORBA::InvalidPolicies& TAOX11_CORBA::InvalidPolicies::operator= (TAOX11_CORBA::InvalidPolicies&& x)
{
if (this != &x)
{
this->UserException::operator = (x);
this->indices_ = std::move (x.indices_);
}
return *this;
}
// generated from c++/cli_hdr/interface_os.erb
TAOX11_Export std::ostream& operator<< (
std::ostream& strm,
IDL::traits<TAOX11_CORBA::Policy>::ref_type);
#if defined (__TAOX11_INCLUDE_STUB_PROXY__)
#include "PolicyP.h"
#endif
#include /**/ "ace/post.h"
#endif // __RIDL_POLICYC_H_INCLUDED__
// -*- END -*-
|
00cefdec682d90b9d45d59a242a66b6b579bca50 | ed313bf0460c93ad03ad34e86175250b3c0e6ab4 | /dhuoj/dhu_a.cpp | 40874383c0eb0575accad6c4691f1e53dc955225 | [] | no_license | ThereWillBeOneDaypyf/Summer_SolveSet | fd41059c5ddcbd33e2420277119613e991fb6da9 | 9895a9c035538c95a31f66ad4f85b6268b655331 | refs/heads/master | 2022-10-20T02:31:07.625252 | 2020-04-24T11:51:32 | 2020-04-24T11:51:32 | 94,217,614 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | dhu_a.cpp | #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<vector>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<map>
#include<set>
using namespace std;
//thanks to pyf ...
#define INF 0x3f3f3f3f
#define CLR(x,y) memset(x,y,sizeof(x))
#define mp(x,y) make_pair(x,y)
typedef pair<int, int> PII;
typedef long long ll;
const int N = 1e6 + 5;
int main()
{
string s;
while (cin >> s)
{
stack<char>st;
int flag = 0;
int Max_deep = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(')
st.push(s[i]);
if (st.size() > Max_deep)
Max_deep = st.size();
if (st.size() == 0 && s[i] == ')')
{
flag = 1;
}
if (st.size() && s[i] == ')')
st.pop();
}
if (flag || st.size() != 0)
cout << "NO" << endl;
else
cout << "YES" << " " << Max_deep << endl;
}
} |
e08973d4a4e4ec061a44521e9ec5b0f599f39d5b | 47abbe9932aa4509e0a73480e8541bcac20d8f78 | /pretest.cpp | 4fb1ced64559779a8a87fe0e2b0bfac2c091f44c | [] | no_license | daffalfa/stukdat-02 | f7f9c94794e7da99c4073b5809bb6f201d678651 | 69086f7ec9a5c620b15c6b37faca301f3ebe00c1 | refs/heads/master | 2020-04-26T21:47:05.748917 | 2019-03-05T02:55:02 | 2019-03-05T02:55:02 | 173,851,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | pretest.cpp | #include<iostream>
using namespace std;
void moveZeroToEnd (int arr[], int n)
{
int count = 0;
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
while (count < n)
arr[count++] = 0;
}
void input (int (&arr)[100],int& n)
{
cin>>n;
}
void output (int arr[],int n)
{
cout<<n;
}
int main()
{
int arr[100];
int n;
input(arr,n);
moveZeroToEnd(arr,n);
output(arr,n);
}
|
58793e22b18555f09f140195864def81d35023c7 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/content/browser/devtools/protocol/storage.cc | 9b8db8fe69491ff7704748d4c98da52dd780aff8 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,480 | cc | storage.cc | // This file is generated by TypeBuilder_cpp.template.
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/devtools/protocol/storage.h"
#include "content/browser/devtools/protocol/protocol.h"
#include "third_party/inspector_protocol/crdtp/cbor.h"
#include "third_party/inspector_protocol/crdtp/serializer_traits.h"
namespace content {
namespace protocol {
namespace Storage {
// ------------- Enum values from types.
const char Metainfo::domainName[] = "Storage";
const char Metainfo::commandPrefix[] = "Storage.";
const char Metainfo::version[] = "1.3";
namespace StorageTypeEnum {
const char Appcache[] = "appcache";
const char Cookies[] = "cookies";
const char File_systems[] = "file_systems";
const char Indexeddb[] = "indexeddb";
const char Local_storage[] = "local_storage";
const char Shader_cache[] = "shader_cache";
const char Websql[] = "websql";
const char Service_workers[] = "service_workers";
const char Cache_storage[] = "cache_storage";
const char All[] = "all";
const char Other[] = "other";
} // namespace StorageTypeEnum
std::unique_ptr<UsageForType> UsageForType::fromValue(protocol::Value* value, ErrorSupport* errors)
{
if (!value || value->type() != protocol::Value::TypeObject) {
errors->addError("object expected");
return nullptr;
}
std::unique_ptr<UsageForType> result(new UsageForType());
protocol::DictionaryValue* object = DictionaryValue::cast(value);
errors->push();
protocol::Value* storageTypeValue = object->get("storageType");
errors->setName("storageType");
result->m_storageType = ValueConversions<String>::fromValue(storageTypeValue, errors);
protocol::Value* usageValue = object->get("usage");
errors->setName("usage");
result->m_usage = ValueConversions<double>::fromValue(usageValue, errors);
errors->pop();
if (errors->hasErrors())
return nullptr;
return result;
}
std::unique_ptr<protocol::DictionaryValue> UsageForType::toValue() const
{
std::unique_ptr<protocol::DictionaryValue> result = DictionaryValue::create();
result->setValue("storageType", ValueConversions<String>::toValue(m_storageType));
result->setValue("usage", ValueConversions<double>::toValue(m_usage));
return result;
}
void UsageForType::AppendSerialized(std::vector<uint8_t>* out) const {
crdtp::cbor::EnvelopeEncoder envelope_encoder;
envelope_encoder.EncodeStart(out);
out->push_back(crdtp::cbor::EncodeIndefiniteLengthMapStart());
crdtp::SerializeField(crdtp::SpanFrom("storageType"), m_storageType, out);
crdtp::SerializeField(crdtp::SpanFrom("usage"), m_usage, out);
out->push_back(crdtp::cbor::EncodeStop());
envelope_encoder.EncodeStop(out);
}
std::unique_ptr<UsageForType> UsageForType::clone() const
{
ErrorSupport errors;
return fromValue(toValue().get(), &errors);
}
std::unique_ptr<CacheStorageContentUpdatedNotification> CacheStorageContentUpdatedNotification::fromValue(protocol::Value* value, ErrorSupport* errors)
{
if (!value || value->type() != protocol::Value::TypeObject) {
errors->addError("object expected");
return nullptr;
}
std::unique_ptr<CacheStorageContentUpdatedNotification> result(new CacheStorageContentUpdatedNotification());
protocol::DictionaryValue* object = DictionaryValue::cast(value);
errors->push();
protocol::Value* originValue = object->get("origin");
errors->setName("origin");
result->m_origin = ValueConversions<String>::fromValue(originValue, errors);
protocol::Value* cacheNameValue = object->get("cacheName");
errors->setName("cacheName");
result->m_cacheName = ValueConversions<String>::fromValue(cacheNameValue, errors);
errors->pop();
if (errors->hasErrors())
return nullptr;
return result;
}
std::unique_ptr<protocol::DictionaryValue> CacheStorageContentUpdatedNotification::toValue() const
{
std::unique_ptr<protocol::DictionaryValue> result = DictionaryValue::create();
result->setValue("origin", ValueConversions<String>::toValue(m_origin));
result->setValue("cacheName", ValueConversions<String>::toValue(m_cacheName));
return result;
}
void CacheStorageContentUpdatedNotification::AppendSerialized(std::vector<uint8_t>* out) const {
crdtp::cbor::EnvelopeEncoder envelope_encoder;
envelope_encoder.EncodeStart(out);
out->push_back(crdtp::cbor::EncodeIndefiniteLengthMapStart());
crdtp::SerializeField(crdtp::SpanFrom("origin"), m_origin, out);
crdtp::SerializeField(crdtp::SpanFrom("cacheName"), m_cacheName, out);
out->push_back(crdtp::cbor::EncodeStop());
envelope_encoder.EncodeStop(out);
}
std::unique_ptr<CacheStorageContentUpdatedNotification> CacheStorageContentUpdatedNotification::clone() const
{
ErrorSupport errors;
return fromValue(toValue().get(), &errors);
}
std::unique_ptr<CacheStorageListUpdatedNotification> CacheStorageListUpdatedNotification::fromValue(protocol::Value* value, ErrorSupport* errors)
{
if (!value || value->type() != protocol::Value::TypeObject) {
errors->addError("object expected");
return nullptr;
}
std::unique_ptr<CacheStorageListUpdatedNotification> result(new CacheStorageListUpdatedNotification());
protocol::DictionaryValue* object = DictionaryValue::cast(value);
errors->push();
protocol::Value* originValue = object->get("origin");
errors->setName("origin");
result->m_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors())
return nullptr;
return result;
}
std::unique_ptr<protocol::DictionaryValue> CacheStorageListUpdatedNotification::toValue() const
{
std::unique_ptr<protocol::DictionaryValue> result = DictionaryValue::create();
result->setValue("origin", ValueConversions<String>::toValue(m_origin));
return result;
}
void CacheStorageListUpdatedNotification::AppendSerialized(std::vector<uint8_t>* out) const {
crdtp::cbor::EnvelopeEncoder envelope_encoder;
envelope_encoder.EncodeStart(out);
out->push_back(crdtp::cbor::EncodeIndefiniteLengthMapStart());
crdtp::SerializeField(crdtp::SpanFrom("origin"), m_origin, out);
out->push_back(crdtp::cbor::EncodeStop());
envelope_encoder.EncodeStop(out);
}
std::unique_ptr<CacheStorageListUpdatedNotification> CacheStorageListUpdatedNotification::clone() const
{
ErrorSupport errors;
return fromValue(toValue().get(), &errors);
}
std::unique_ptr<IndexedDBContentUpdatedNotification> IndexedDBContentUpdatedNotification::fromValue(protocol::Value* value, ErrorSupport* errors)
{
if (!value || value->type() != protocol::Value::TypeObject) {
errors->addError("object expected");
return nullptr;
}
std::unique_ptr<IndexedDBContentUpdatedNotification> result(new IndexedDBContentUpdatedNotification());
protocol::DictionaryValue* object = DictionaryValue::cast(value);
errors->push();
protocol::Value* originValue = object->get("origin");
errors->setName("origin");
result->m_origin = ValueConversions<String>::fromValue(originValue, errors);
protocol::Value* databaseNameValue = object->get("databaseName");
errors->setName("databaseName");
result->m_databaseName = ValueConversions<String>::fromValue(databaseNameValue, errors);
protocol::Value* objectStoreNameValue = object->get("objectStoreName");
errors->setName("objectStoreName");
result->m_objectStoreName = ValueConversions<String>::fromValue(objectStoreNameValue, errors);
errors->pop();
if (errors->hasErrors())
return nullptr;
return result;
}
std::unique_ptr<protocol::DictionaryValue> IndexedDBContentUpdatedNotification::toValue() const
{
std::unique_ptr<protocol::DictionaryValue> result = DictionaryValue::create();
result->setValue("origin", ValueConversions<String>::toValue(m_origin));
result->setValue("databaseName", ValueConversions<String>::toValue(m_databaseName));
result->setValue("objectStoreName", ValueConversions<String>::toValue(m_objectStoreName));
return result;
}
void IndexedDBContentUpdatedNotification::AppendSerialized(std::vector<uint8_t>* out) const {
crdtp::cbor::EnvelopeEncoder envelope_encoder;
envelope_encoder.EncodeStart(out);
out->push_back(crdtp::cbor::EncodeIndefiniteLengthMapStart());
crdtp::SerializeField(crdtp::SpanFrom("origin"), m_origin, out);
crdtp::SerializeField(crdtp::SpanFrom("databaseName"), m_databaseName, out);
crdtp::SerializeField(crdtp::SpanFrom("objectStoreName"), m_objectStoreName, out);
out->push_back(crdtp::cbor::EncodeStop());
envelope_encoder.EncodeStop(out);
}
std::unique_ptr<IndexedDBContentUpdatedNotification> IndexedDBContentUpdatedNotification::clone() const
{
ErrorSupport errors;
return fromValue(toValue().get(), &errors);
}
std::unique_ptr<IndexedDBListUpdatedNotification> IndexedDBListUpdatedNotification::fromValue(protocol::Value* value, ErrorSupport* errors)
{
if (!value || value->type() != protocol::Value::TypeObject) {
errors->addError("object expected");
return nullptr;
}
std::unique_ptr<IndexedDBListUpdatedNotification> result(new IndexedDBListUpdatedNotification());
protocol::DictionaryValue* object = DictionaryValue::cast(value);
errors->push();
protocol::Value* originValue = object->get("origin");
errors->setName("origin");
result->m_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors())
return nullptr;
return result;
}
std::unique_ptr<protocol::DictionaryValue> IndexedDBListUpdatedNotification::toValue() const
{
std::unique_ptr<protocol::DictionaryValue> result = DictionaryValue::create();
result->setValue("origin", ValueConversions<String>::toValue(m_origin));
return result;
}
void IndexedDBListUpdatedNotification::AppendSerialized(std::vector<uint8_t>* out) const {
crdtp::cbor::EnvelopeEncoder envelope_encoder;
envelope_encoder.EncodeStart(out);
out->push_back(crdtp::cbor::EncodeIndefiniteLengthMapStart());
crdtp::SerializeField(crdtp::SpanFrom("origin"), m_origin, out);
out->push_back(crdtp::cbor::EncodeStop());
envelope_encoder.EncodeStop(out);
}
std::unique_ptr<IndexedDBListUpdatedNotification> IndexedDBListUpdatedNotification::clone() const
{
ErrorSupport errors;
return fromValue(toValue().get(), &errors);
}
// ------------- Enum values from params.
// ------------- Frontend notifications.
void Frontend::CacheStorageContentUpdated(const String& origin, const String& cacheName)
{
if (!m_frontendChannel)
return;
std::unique_ptr<CacheStorageContentUpdatedNotification> messageData = CacheStorageContentUpdatedNotification::Create()
.SetOrigin(origin)
.SetCacheName(cacheName)
.Build();
m_frontendChannel->sendProtocolNotification(InternalResponse::createNotification("Storage.cacheStorageContentUpdated", std::move(messageData)));
}
void Frontend::CacheStorageListUpdated(const String& origin)
{
if (!m_frontendChannel)
return;
std::unique_ptr<CacheStorageListUpdatedNotification> messageData = CacheStorageListUpdatedNotification::Create()
.SetOrigin(origin)
.Build();
m_frontendChannel->sendProtocolNotification(InternalResponse::createNotification("Storage.cacheStorageListUpdated", std::move(messageData)));
}
void Frontend::IndexedDBContentUpdated(const String& origin, const String& databaseName, const String& objectStoreName)
{
if (!m_frontendChannel)
return;
std::unique_ptr<IndexedDBContentUpdatedNotification> messageData = IndexedDBContentUpdatedNotification::Create()
.SetOrigin(origin)
.SetDatabaseName(databaseName)
.SetObjectStoreName(objectStoreName)
.Build();
m_frontendChannel->sendProtocolNotification(InternalResponse::createNotification("Storage.indexedDBContentUpdated", std::move(messageData)));
}
void Frontend::IndexedDBListUpdated(const String& origin)
{
if (!m_frontendChannel)
return;
std::unique_ptr<IndexedDBListUpdatedNotification> messageData = IndexedDBListUpdatedNotification::Create()
.SetOrigin(origin)
.Build();
m_frontendChannel->sendProtocolNotification(InternalResponse::createNotification("Storage.indexedDBListUpdated", std::move(messageData)));
}
void Frontend::flush()
{
m_frontendChannel->flushProtocolNotifications();
}
void Frontend::sendRawCBORNotification(std::vector<uint8_t> notification)
{
m_frontendChannel->sendProtocolNotification(InternalRawNotification::fromBinary(std::move(notification)));
}
// --------------------- Dispatcher.
class DispatcherImpl : public protocol::DispatcherBase {
public:
DispatcherImpl(FrontendChannel* frontendChannel, Backend* backend)
: DispatcherBase(frontendChannel)
, m_backend(backend) {
m_dispatchMap["Storage.clearDataForOrigin"] = &DispatcherImpl::clearDataForOrigin;
m_dispatchMap["Storage.getCookies"] = &DispatcherImpl::getCookies;
m_dispatchMap["Storage.setCookies"] = &DispatcherImpl::setCookies;
m_dispatchMap["Storage.clearCookies"] = &DispatcherImpl::clearCookies;
m_dispatchMap["Storage.getUsageAndQuota"] = &DispatcherImpl::getUsageAndQuota;
m_dispatchMap["Storage.trackCacheStorageForOrigin"] = &DispatcherImpl::trackCacheStorageForOrigin;
m_dispatchMap["Storage.trackIndexedDBForOrigin"] = &DispatcherImpl::trackIndexedDBForOrigin;
m_dispatchMap["Storage.untrackCacheStorageForOrigin"] = &DispatcherImpl::untrackCacheStorageForOrigin;
m_dispatchMap["Storage.untrackIndexedDBForOrigin"] = &DispatcherImpl::untrackIndexedDBForOrigin;
}
~DispatcherImpl() override { }
bool canDispatch(const String& method) override;
void dispatch(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<protocol::DictionaryValue> messageObject) override;
std::unordered_map<String, String>& redirects() { return m_redirects; }
protected:
using CallHandler = void (DispatcherImpl::*)(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> messageObject, ErrorSupport* errors);
using DispatchMap = std::unordered_map<String, CallHandler>;
DispatchMap m_dispatchMap;
std::unordered_map<String, String> m_redirects;
void clearDataForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void getCookies(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void setCookies(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void clearCookies(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void getUsageAndQuota(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void trackCacheStorageForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void trackIndexedDBForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void untrackCacheStorageForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
void untrackIndexedDBForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*);
Backend* m_backend;
};
bool DispatcherImpl::canDispatch(const String& method) {
return m_dispatchMap.find(method) != m_dispatchMap.end();
}
void DispatcherImpl::dispatch(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<protocol::DictionaryValue> messageObject)
{
std::unordered_map<String, CallHandler>::iterator it = m_dispatchMap.find(method);
DCHECK(it != m_dispatchMap.end());
protocol::ErrorSupport errors;
(this->*(it->second))(callId, method, message, std::move(messageObject), &errors);
}
class ClearDataForOriginCallbackImpl : public Backend::ClearDataForOriginCallback, public DispatcherBase::Callback {
public:
ClearDataForOriginCallbackImpl(std::unique_ptr<DispatcherBase::WeakPtr> backendImpl, int callId, const String& method, crdtp::span<uint8_t> message)
: DispatcherBase::Callback(std::move(backendImpl), callId, method, message) { }
void sendSuccess() override
{
std::unique_ptr<protocol::DictionaryValue> resultObject = DictionaryValue::create();
sendIfActive(std::move(resultObject), DispatchResponse::OK());
}
void fallThrough() override
{
fallThroughIfActive();
}
void sendFailure(const DispatchResponse& response) override
{
DCHECK(response.status() == DispatchResponse::kError);
sendIfActive(nullptr, response);
}
};
void DispatcherImpl::clearDataForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* originValue = object ? object->get("origin") : nullptr;
errors->setName("origin");
String in_origin = ValueConversions<String>::fromValue(originValue, errors);
protocol::Value* storageTypesValue = object ? object->get("storageTypes") : nullptr;
errors->setName("storageTypes");
String in_storageTypes = ValueConversions<String>::fromValue(storageTypesValue, errors);
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<ClearDataForOriginCallbackImpl> callback(new ClearDataForOriginCallbackImpl(weakPtr(), callId, method, message));
m_backend->ClearDataForOrigin(in_origin, in_storageTypes, std::move(callback));
return;
}
class GetCookiesCallbackImpl : public Backend::GetCookiesCallback, public DispatcherBase::Callback {
public:
GetCookiesCallbackImpl(std::unique_ptr<DispatcherBase::WeakPtr> backendImpl, int callId, const String& method, crdtp::span<uint8_t> message)
: DispatcherBase::Callback(std::move(backendImpl), callId, method, message) { }
void sendSuccess(std::unique_ptr<protocol::Array<protocol::Network::Cookie>> cookies) override
{
std::unique_ptr<protocol::DictionaryValue> resultObject = DictionaryValue::create();
resultObject->setValue("cookies", ValueConversions<protocol::Array<protocol::Network::Cookie>>::toValue(cookies.get()));
sendIfActive(std::move(resultObject), DispatchResponse::OK());
}
void fallThrough() override
{
fallThroughIfActive();
}
void sendFailure(const DispatchResponse& response) override
{
DCHECK(response.status() == DispatchResponse::kError);
sendIfActive(nullptr, response);
}
};
void DispatcherImpl::getCookies(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* browserContextIdValue = object ? object->get("browserContextId") : nullptr;
Maybe<String> in_browserContextId;
if (browserContextIdValue) {
errors->setName("browserContextId");
in_browserContextId = ValueConversions<String>::fromValue(browserContextIdValue, errors);
}
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<GetCookiesCallbackImpl> callback(new GetCookiesCallbackImpl(weakPtr(), callId, method, message));
m_backend->GetCookies(std::move(in_browserContextId), std::move(callback));
return;
}
class SetCookiesCallbackImpl : public Backend::SetCookiesCallback, public DispatcherBase::Callback {
public:
SetCookiesCallbackImpl(std::unique_ptr<DispatcherBase::WeakPtr> backendImpl, int callId, const String& method, crdtp::span<uint8_t> message)
: DispatcherBase::Callback(std::move(backendImpl), callId, method, message) { }
void sendSuccess() override
{
std::unique_ptr<protocol::DictionaryValue> resultObject = DictionaryValue::create();
sendIfActive(std::move(resultObject), DispatchResponse::OK());
}
void fallThrough() override
{
fallThroughIfActive();
}
void sendFailure(const DispatchResponse& response) override
{
DCHECK(response.status() == DispatchResponse::kError);
sendIfActive(nullptr, response);
}
};
void DispatcherImpl::setCookies(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* cookiesValue = object ? object->get("cookies") : nullptr;
errors->setName("cookies");
std::unique_ptr<protocol::Array<protocol::Network::CookieParam>> in_cookies = ValueConversions<protocol::Array<protocol::Network::CookieParam>>::fromValue(cookiesValue, errors);
protocol::Value* browserContextIdValue = object ? object->get("browserContextId") : nullptr;
Maybe<String> in_browserContextId;
if (browserContextIdValue) {
errors->setName("browserContextId");
in_browserContextId = ValueConversions<String>::fromValue(browserContextIdValue, errors);
}
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<SetCookiesCallbackImpl> callback(new SetCookiesCallbackImpl(weakPtr(), callId, method, message));
m_backend->SetCookies(std::move(in_cookies), std::move(in_browserContextId), std::move(callback));
return;
}
class ClearCookiesCallbackImpl : public Backend::ClearCookiesCallback, public DispatcherBase::Callback {
public:
ClearCookiesCallbackImpl(std::unique_ptr<DispatcherBase::WeakPtr> backendImpl, int callId, const String& method, crdtp::span<uint8_t> message)
: DispatcherBase::Callback(std::move(backendImpl), callId, method, message) { }
void sendSuccess() override
{
std::unique_ptr<protocol::DictionaryValue> resultObject = DictionaryValue::create();
sendIfActive(std::move(resultObject), DispatchResponse::OK());
}
void fallThrough() override
{
fallThroughIfActive();
}
void sendFailure(const DispatchResponse& response) override
{
DCHECK(response.status() == DispatchResponse::kError);
sendIfActive(nullptr, response);
}
};
void DispatcherImpl::clearCookies(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* browserContextIdValue = object ? object->get("browserContextId") : nullptr;
Maybe<String> in_browserContextId;
if (browserContextIdValue) {
errors->setName("browserContextId");
in_browserContextId = ValueConversions<String>::fromValue(browserContextIdValue, errors);
}
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<ClearCookiesCallbackImpl> callback(new ClearCookiesCallbackImpl(weakPtr(), callId, method, message));
m_backend->ClearCookies(std::move(in_browserContextId), std::move(callback));
return;
}
class GetUsageAndQuotaCallbackImpl : public Backend::GetUsageAndQuotaCallback, public DispatcherBase::Callback {
public:
GetUsageAndQuotaCallbackImpl(std::unique_ptr<DispatcherBase::WeakPtr> backendImpl, int callId, const String& method, crdtp::span<uint8_t> message)
: DispatcherBase::Callback(std::move(backendImpl), callId, method, message) { }
void sendSuccess(double usage, double quota, std::unique_ptr<protocol::Array<protocol::Storage::UsageForType>> usageBreakdown) override
{
std::unique_ptr<protocol::DictionaryValue> resultObject = DictionaryValue::create();
resultObject->setValue("usage", ValueConversions<double>::toValue(usage));
resultObject->setValue("quota", ValueConversions<double>::toValue(quota));
resultObject->setValue("usageBreakdown", ValueConversions<protocol::Array<protocol::Storage::UsageForType>>::toValue(usageBreakdown.get()));
sendIfActive(std::move(resultObject), DispatchResponse::OK());
}
void fallThrough() override
{
fallThroughIfActive();
}
void sendFailure(const DispatchResponse& response) override
{
DCHECK(response.status() == DispatchResponse::kError);
sendIfActive(nullptr, response);
}
};
void DispatcherImpl::getUsageAndQuota(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* originValue = object ? object->get("origin") : nullptr;
errors->setName("origin");
String in_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<GetUsageAndQuotaCallbackImpl> callback(new GetUsageAndQuotaCallbackImpl(weakPtr(), callId, method, message));
m_backend->GetUsageAndQuota(in_origin, std::move(callback));
return;
}
void DispatcherImpl::trackCacheStorageForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* originValue = object ? object->get("origin") : nullptr;
errors->setName("origin");
String in_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr();
DispatchResponse response = m_backend->TrackCacheStorageForOrigin(in_origin);
if (response.status() == DispatchResponse::kFallThrough) {
channel()->fallThrough(callId, method, message);
return;
}
if (weak->get())
weak->get()->sendResponse(callId, response);
return;
}
void DispatcherImpl::trackIndexedDBForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* originValue = object ? object->get("origin") : nullptr;
errors->setName("origin");
String in_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr();
DispatchResponse response = m_backend->TrackIndexedDBForOrigin(in_origin);
if (response.status() == DispatchResponse::kFallThrough) {
channel()->fallThrough(callId, method, message);
return;
}
if (weak->get())
weak->get()->sendResponse(callId, response);
return;
}
void DispatcherImpl::untrackCacheStorageForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* originValue = object ? object->get("origin") : nullptr;
errors->setName("origin");
String in_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr();
DispatchResponse response = m_backend->UntrackCacheStorageForOrigin(in_origin);
if (response.status() == DispatchResponse::kFallThrough) {
channel()->fallThrough(callId, method, message);
return;
}
if (weak->get())
weak->get()->sendResponse(callId, response);
return;
}
void DispatcherImpl::untrackIndexedDBForOrigin(int callId, const String& method, crdtp::span<uint8_t> message, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors)
{
// Prepare input parameters.
protocol::DictionaryValue* object = DictionaryValue::cast(requestMessageObject->get("params"));
errors->push();
protocol::Value* originValue = object ? object->get("origin") : nullptr;
errors->setName("origin");
String in_origin = ValueConversions<String>::fromValue(originValue, errors);
errors->pop();
if (errors->hasErrors()) {
reportProtocolError(callId, DispatchResponse::kInvalidParams, kInvalidParamsString, errors);
return;
}
std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr();
DispatchResponse response = m_backend->UntrackIndexedDBForOrigin(in_origin);
if (response.status() == DispatchResponse::kFallThrough) {
channel()->fallThrough(callId, method, message);
return;
}
if (weak->get())
weak->get()->sendResponse(callId, response);
return;
}
// static
void Dispatcher::wire(UberDispatcher* uber, Backend* backend)
{
std::unique_ptr<DispatcherImpl> dispatcher(new DispatcherImpl(uber->channel(), backend));
uber->setupRedirects(dispatcher->redirects());
uber->registerBackend("Storage", std::move(dispatcher));
}
} // Storage
} // namespace content
} // namespace protocol
|
05c5ab7a4f8f87bd91e82699d46b33e8d12539c7 | 25983054099903dc8615d6ee26e3a11f9d725322 | /SumReverseOrder.cpp | edc791aad42387d04d64f4e962ecfea320e83d23 | [] | no_license | joshbenner851/Cracking-Coding-Interview | 5c6334a1097cdc76e65f9b218d5289a821217ad4 | 0b8f24d38458bd2dde4848231527ac89c0b92a38 | refs/heads/master | 2021-01-20T19:59:31.604407 | 2016-08-26T16:32:42 | 2016-08-26T16:32:42 | 61,261,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | cpp | SumReverseOrder.cpp | //Things to add: Carrying columns: 5 + 7 = 1 -> 2 not 12
//You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the Ts digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
// EXAMPLE
// Input:(7-> 1 -> 6) + (5 -> 9 -> 2).Thatis,617 + 295.
// Output: 2 -> 1 -> 9.That is, 912.
// FOLLOW UP
// Suppose the digits are stored in forward order. Repeat the above problem. EXAMPLE
// Input:(6 -> 1 -> 7) + (2 -> 9 -> 5).That is,617 + 295.
// Output: 9 -> 1 -> 2.That is, 912.
//Method: Create a new linkedlist that is appending new nodes with the sum of the two linked lists
public LinkedList sumReverseOrder(Node firstListNode, Node secondListNode)
{
Node newList;
while(firstListNode->next != null && secondListNode != null)
{
if(firstListNode->next == null){
Node addNode;
addNode.data = 0 + secondListNode.data;
newList->next = addNode;
secondListNode = secondListNode->next;
}
else if(secondListNode->next == null){
Node addNode;
addNode.data = 0 + firstListNode.data;
newList->next = addNode;
firstListNode = secondListNode->next;
}
else
{
Node addNode;
addNode.data = firstListNode.data + secondListNode.data;
newList->next = addNode;
secondListNode = secondListNode->next;
firstListNode = secondListNode->next;
}
}
}
//Questions:
//Do the linkedlist's need to be unchanged?
//If not we could save space by only editing one of the existing linkedLists and leaving the other alone
//Do we have each linkedLists Length, if so use the greatest as the list to change
//There are nodes for empty values right(ie the tens place is empty(0)?)
//Edge Cases:
//If the lists are different sizes, just add zero and continue to push
//Both lists are empty
//Doesn't matter if the data is 0 for either node EX: 001 + 0051 = 0061 = 1600(base 10)
//Ex: 1500 + 100
//FOLLOW UP:
//Doubly
//Assumming the linkedLists are not empty
public LinkedList sumForwardOrder(Node firstListNode, Node secondListNode)
{
Node firstNode;
Node secondNode;
Node newList;
//cycling to get the one's column
while(firstListNode->next != null){
firstNode = firstListNode;
firstListNode = firstListNode->next;
}
while(secondListNode->next != null){
secondNode = secondListNode;
secondListNode = secondListNode->next;
}
newList.data = firstNode.data + secondNode.data;
//just reverse add the lists
while(firstNode->prev != null && secondNode->prev != null){
Node addNode;
if(firstNode->prev == null){
addNode.data = 0 + secondNode.data;
addNode->next = newList;
newList.prev = addNode;
secondNode = secondNode->prev;
}
else if(secondNode->prev == null){
addNode.data = 0 + firstNode.data;
addNode->next = newList;
newList.prev = addNode;
firstNode = secondNode->prev;
}
else
{
addNode.data = firstNode.data + secondNode.data;
addNode->next = newList;
firstNode = secondNode->prev;
secondNode = secondNode->prev;
newList.prev = addNode;
}
newList = addNode;
}
}
//Questions:
//IMPORANT: is this singly or doubly linked?
//If singly we must cycle through both lists to get the length so that we're not adding tens and hundreds
//Do the lists needs to be unchanged?
|
273900b51e8a5cecff98ef45ff28d2af5850f315 | 3f0a8e94be42866e44d95f09f503938f45046ef8 | /LoadBalancer.h | be227a6bccd7b26da51e63c5ffbb292d13e0699e | [] | no_license | VetaMaximova/SignatureGeneration | 3c31df84b1b535c57e94c92055380bc6788bb3d7 | 165d336e1fd4e728ef1d0396104e3276102990ff | refs/heads/main | 2023-01-13T20:51:51.333362 | 2020-11-15T21:36:46 | 2020-11-15T21:36:46 | 313,127,795 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 597 | h | LoadBalancer.h | ///
/// @file
/// @copyright Copyright (C) 2020, Bayerische Motoren Werke Aktiengesellschaft
/// (BMW AG)
///
#ifndef _LOADBALANCER_H_
#define _LOADBALANCER_H_
#include "HashWriter.h"
#include <boost/thread.hpp>
#include <memory>
class LoadBalancer {
public:
LoadBalancer(const std::shared_ptr<FileWriter> file_writer,
const size_t block_size);
void Stop();
void AddData(std::shared_ptr<char> data);
private:
std::vector<std::unique_ptr<HashWriter>> hash_writers;
boost::thread_group thread_group;
const uint32_t min_threads_count = 4;
};
#endif //_LOADBALANCER_H_
|
d38c54ca31b851f1ceee6d3d09bf08eb9fe5f80b | 90e2f09587cac69b1f4a76f3f090d1c02ef78391 | /src/modes/system/systemConfigurationWidget.cpp | 6328ae0a309cfe67e484cd93e6e2d807f1bc7833 | [
"BSD-3-Clause"
] | permissive | KDE/ksystemlog | 70fa55a30bb960c6954e6d01f7c7d286a33f24eb | 6ba2eb3ed81390fda48b091b114610d5c747b8a3 | refs/heads/master | 2023-08-16T18:26:34.352481 | 2023-08-06T01:54:13 | 2023-08-06T01:54:13 | 42,737,002 | 13 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,856 | cpp | systemConfigurationWidget.cpp | /*
SPDX-FileCopyrightText: 2007 Nicolas Ternisien <nicolas.ternisien@gmail.com>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "systemConfigurationWidget.h"
SystemConfigurationWidget::SystemConfigurationWidget()
: LogModeConfigurationWidget(i18n("System Log"), QStringLiteral(SYSTEM_MODE_ICON), i18n("System Log"))
{
auto layout = new QVBoxLayout(this);
const QString description = i18n("<p>These files will be analyzed to show the <b>System logs</b>.</p>");
mFileList = new LogLevelFileList(this, description);
connect(mFileList, &FileList::fileListChanged, this, &LogModeConfigurationWidget::configurationChanged);
layout->addWidget(mFileList);
}
bool SystemConfigurationWidget::isValid() const
{
if (!mFileList->isEmpty()) {
qCDebug(KSYSTEMLOG) << "System configuration valid";
return true;
}
qCDebug(KSYSTEMLOG) << "System configuration not valid";
return false;
}
void SystemConfigurationWidget::saveConfig()
{
qCDebug(KSYSTEMLOG) << "Saving config from System Options...";
auto *systemConfiguration = Globals::instance().findLogMode(QStringLiteral(SYSTEM_LOG_MODE_ID))->logModeConfiguration<SystemConfiguration *>();
systemConfiguration->setLogFilesPaths(mFileList->paths());
systemConfiguration->setLogFilesLevels(mFileList->levels());
}
void SystemConfigurationWidget::readConfig()
{
auto *systemConfiguration = Globals::instance().findLogMode(QStringLiteral(SYSTEM_LOG_MODE_ID))->logModeConfiguration<SystemConfiguration *>();
mFileList->removeAllItems();
mFileList->addPaths(systemConfiguration->logFilesPaths(), systemConfiguration->logFilesLevels());
}
void SystemConfigurationWidget::defaultConfig()
{
// TODO Find a way to read the configuration per default
readConfig();
}
#include "moc_systemConfigurationWidget.cpp"
|
90adaf82cfec3a453cb8de8010cbe0b1188fb884 | 9bdd58cc75b495e67ec6c186802c81121199c064 | /amsr-vector-fs-libvac/lib/include/vac/memory/optional_traits.h | db87bb9dd4d35cd3a3b58d3e66ceb8d783b3546a | [] | no_license | flankersky/vector_ap_bsw | 3bac290b569dd2f72d4d4971fcb8f96b8e188914 | b8f667356126a4f76a79109b02ee14ae1cd16a58 | refs/heads/master | 2022-01-14T03:38:29.499494 | 2019-07-04T04:15:02 | 2019-07-04T04:15:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,082 | h | optional_traits.h | /**********************************************************************************************************************
* COPYRIGHT
* -------------------------------------------------------------------------------------------------------------------
* \verbatim
* Copyright (c) 2018 by Vector Informatik GmbH. All rights reserved.
*
* This software is copyright protected and proprietary to Vector Informatik GmbH.
* Vector Informatik GmbH grants to you only those rights as set out in the license conditions.
* All other rights remain with Vector Informatik GmbH.
* \endverbatim
* -------------------------------------------------------------------------------------------------------------------
* FILE DESCRIPTION
* -----------------------------------------------------------------------------------------------------------------*/
/** \file optional_traits.h
* \brief Type-Traits relating to vac::memory::optional
*
*********************************************************************************************************************/
#ifndef LIB_INCLUDE_VAC_MEMORY_OPTIONAL_TRAITS_H_
#define LIB_INCLUDE_VAC_MEMORY_OPTIONAL_TRAITS_H_
/**********************************************************************************************************************
* INCLUDES
*********************************************************************************************************************/
#include <type_traits>
namespace vac {
namespace memory {
/**
* \brief Forward declaration for the optional class.
*/
template <class T>
class optional;
/**
* \brief Check if type is optional type
* \details implementation if type is not optional
*/
template <typename C>
struct is_optional : std::false_type {};
/**
* \brief Check if type is optional type
* \details implementation if type is optional
*/
template <typename T>
struct is_optional<vac::memory::optional<T>> : std::true_type {};
} // namespace memory
} // namespace vac
#endif // LIB_INCLUDE_VAC_MEMORY_OPTIONAL_TRAITS_H_
|
450b4a61e6884f2ca5af02f998fa9b41b2c0bc65 | 7480d4c05930f0d56e9e4532cf0b7e305fcf4ed1 | /window_with_imgui/main.cpp | 30952f8d082e8c2d21d038389836fcb99a299742 | [] | no_license | mrjbom/OpenGL-examples | ee64693ff8615becc411a22dcad0b86743224c8f | 78e368ac47fd532c6b29dfb98019e1570c8897eb | refs/heads/master | 2022-02-13T04:21:53.050358 | 2019-08-26T11:12:47 | 2019-08-26T11:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,604 | cpp | main.cpp | #include <iostream>
#include <chrono>
#include <GL/glut.h>
#include "imgui.h"
#include "imgui_impl_glut.h"
#include "imgui_impl_opengl2.h"
#ifdef _MSC_VER
#pragma warning (disable: 4505) // unreferenced local function has been removed
#endif
using namespace std;
constexpr auto FPS_RATE = 120;
int windowHeight = 600, windowWidth = 600;
void init();
void displayFunction();
void idleFunction();
double getTime();
double getTime()
{
using Duration = std::chrono::duration<double>;
return std::chrono::duration_cast<Duration>(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count();
}
const double frame_delay = 1.0 / FPS_RATE;
double last_render = 0;
void init()
{
glutDisplayFunc(displayFunction);
glutIdleFunc(idleFunction);
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-windowWidth / 2, windowWidth / 2, -windowHeight / 2, windowHeight / 2);
}
void idleFunction()
{
const double current_time = getTime();
if ((current_time - last_render) > frame_delay)
{
last_render = current_time;
glutPostRedisplay();
}
}
static bool showWindow = true;
void displayFunction()
{
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplGLUT_NewFrame();
if (showWindow)
{
ImGui::Begin("Another Window", &showWindow); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
showWindow = false;
ImGui::End();
}
/**/
glClear(GL_COLOR_BUFFER_BIT);
glColor3ub(238, 130, 238);
glBegin(GL_POLYGON);
glVertex3i(-150, 150, 0);
glVertex3i(150, 150, 0);
glVertex3i(150, -150, 0);
glVertex3i(-150, -150, 0);
glEnd();
ImGui::Render();
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
glEnd();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition((GetSystemMetrics(SM_CXSCREEN) - windowWidth) / 2, (GetSystemMetrics(SM_CYSCREEN) - windowHeight) / 2);
glutCreateWindow("Window");
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
init();
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplGLUT_Init();
ImGui_ImplGLUT_InstallFuncs();
ImGui_ImplOpenGL2_Init();
glutMainLoop();
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplGLUT_Shutdown();
ImGui::DestroyContext();
return 0;
}
|
be227d9a2bef1b8785f78ed42ddd3aaa87a3cf19 | a13950bee0e609a7492412bb8cd0f8c2fe91ca0f | /depthrgbobserver.h | d2ca0c802d0eb92d8d1247cc9b5a246c361980ae | [] | no_license | StPessina/OpenGEVApplication | 8d01e34bfd56d8f87682ea0d14280262be4ff508 | 580b52f7aa34a53638d7b923e29b83555672feb8 | refs/heads/master | 2021-01-15T16:14:29.811112 | 2016-03-05T15:45:05 | 2016-03-05T15:45:05 | 47,760,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | h | depthrgbobserver.h | #ifndef DEPTHRGBOBSERVER_H
#define DEPTHRGBOBSERVER_H
#include <QObject>
#include <log4cpp/Category.hh>
#include "Application/streamdatareceiver.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include <chrono>
#include "simpleviewer.h"
class DepthRgbObserver : public QObject
{
Q_OBJECT
public:
explicit DepthRgbObserver(QObject* parent = 0);
DepthRgbObserver(StreamDataReceiver* channel);
std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point end;
//SimpleViewer simpleViewer;
const pcl::PointCloud<pcl::PointXYZRGBA>::Ptr ptrCloud;
signals:
void newStreamData(const pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &cloud);
public slots:
void refreshStartTime();
void update();
private:
log4cpp::Category &logger = log4cpp::Category::getInstance("ComponentLog");
pcl::PointCloud<pcl::PointXYZRGBA> cloud;
StreamDataReceiver *channel;
long meanTimeMs;
};
#endif // DEPTHRGBOBSERVER_H
|
303e34e1c2203146b20dc3a780d1ccd40b46598c | 245641aa3e21083de399edf1e051a2ba8ac8dbce | /src/segmenterbin/segmentation-create-subsegments.cc | ccc3f7e68400d990fa4292876ac9f3a043449084 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | AccessibleAI/kaldi | 06e4b7d95c6bfaea50a67fb7f0ead664bd99ff31 | 6c6395d36cd06d3fd328a9f4a6e4ebba1383e356 | refs/heads/master | 2021-01-21T05:40:17.370150 | 2016-01-11T08:54:17 | 2016-01-11T08:54:17 | 48,358,346 | 0 | 0 | null | 2015-12-21T07:50:55 | 2015-12-21T07:50:55 | null | UTF-8 | C++ | false | false | 4,989 | cc | segmentation-create-subsegments.cc | // segmenterbin/segmentation-create-subsegments.cc
// Copyright 2015 Vimal Manohar (Johns Hopkins University)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "segmenter/segmenter.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using namespace segmenter;
const char *usage =
"Create subsegmentation of a segmentation based on another segmentation."
"The intersection of the segmentation are assiged a new label specified "
"by subsegment-label\n"
"\n"
"Usage: segmentation-create-subsegments --subsegment-label=1000 --filter-label=10 [options] (segmentation-in-rspecifier|segmentation-in-rxfilename) (filter-segmentation-in-rspecifier|filter-segmentation-out-rxfilename) (segmentation-out-wspecifier|segmentation-out-wxfilename)\n"
" e.g.: segmentation-copy --binary=false foo -\n"
" segmentation-copy ark:1.ali ark,t:-\n";
bool binary = true, ignore_missing = true;
int32 filter_label = -1, subsegment_label = -1;
ParseOptions po(usage);
po.Register("binary", &binary, "Write in binary mode (only relevant if output is a wxfilename)");
po.Register("filter-label", &filter_label, "The label on which the "
"filtering is done");
po.Register("subsegment-label", &subsegment_label, "If non-negative, "
"change the label of "
"the intersection of the two segmentations to this integer.");
po.Register("ignore-missing", &ignore_missing, "Ignore missing "
"segmentations in filter");
po.Read(argc, argv);
if (po.NumArgs() != 3) {
po.PrintUsage();
exit(1);
}
std::string segmentation_in_fn = po.GetArg(1),
secondary_segmentation_in_fn = po.GetArg(2),
segmentation_out_fn = po.GetArg(3);
// all these "fn"'s are either rspecifiers or filenames.
bool in_is_rspecifier =
(ClassifyRspecifier(segmentation_in_fn, NULL, NULL)
!= kNoRspecifier),
filter_is_rspecifier =
(ClassifyRspecifier(secondary_segmentation_in_fn, NULL, NULL)
!= kNoRspecifier),
out_is_wspecifier =
(ClassifyWspecifier(segmentation_out_fn, NULL, NULL, NULL)
!= kNoWspecifier);
if (in_is_rspecifier != out_is_wspecifier || in_is_rspecifier != filter_is_rspecifier)
KALDI_ERR << "Cannot mix regular files and archives";
int64 num_done = 0, num_err = 0;
if (!in_is_rspecifier) {
Segmentation seg;
{
bool binary_in;
Input ki(segmentation_in_fn, &binary_in);
seg.Read(ki.Stream(), binary_in);
}
Segmentation secondary_seg;
{
bool binary_in;
Input ki(secondary_segmentation_in_fn, &binary_in);
secondary_seg.Read(ki.Stream(), binary_in);
}
Segmentation new_seg;
seg.CreateSubSegments(secondary_seg, filter_label, subsegment_label, &new_seg);
Output ko(segmentation_out_fn, binary);
seg.Write(ko.Stream(), binary);
KALDI_LOG << "Copied segmentation to " << segmentation_out_fn;
return 0;
} else {
SegmentationWriter writer(segmentation_out_fn);
SequentialSegmentationReader reader(segmentation_in_fn);
RandomAccessSegmentationReader filter_reader(secondary_segmentation_in_fn);
for (; !reader.Done(); reader.Next(), num_done++) {
const Segmentation &seg = reader.Value();
std::string key = reader.Key();
if (!filter_reader.HasKey(key)) {
KALDI_WARN << "Could not find filter for utterance " << key;
if (!ignore_missing) {
num_err++;
} else
writer.Write(key, seg);
continue;
}
const Segmentation &secondary_segmentation = filter_reader.Value(key);
Segmentation new_seg;
seg.CreateSubSegments(secondary_segmentation, filter_label, subsegment_label, &new_seg);
writer.Write(key, new_seg);
}
KALDI_LOG << "Created subsegments for " << num_done << " segmentations; failed with "
<< num_err << " segmentations";
return (num_done != 0 ? 0 : 1);
}
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
|
bbdee99dbb0efc118e50f38e3633975fd1726668 | 12154201c2c4dc8968b690fa8237ebfe1932f60a | /BOJ/10101.cpp | fda81ca6d55fa108517ac247d2d2ab38cf648a99 | [] | no_license | heon24500/PS | 9cc028de3d9b1a26543b5bd498cfd5134d3d6de4 | df901f6fc71f8c9d659b4c5397d44de9a2031a9d | refs/heads/master | 2023-02-20T17:06:30.065944 | 2021-01-25T12:43:48 | 2021-01-25T12:43:48 | 268,433,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | cpp | 10101.cpp | #include <iostream>
using namespace std;
int main() {
int angle[3];
int sum = 0;
bool isEqual = true;
for (int i = 0; i < 3; i++) {
cin >> angle[i];
sum += angle[i];
if (angle[i] != 60) isEqual = false;
}
if (isEqual) cout << "Equilateral";
else {
if (sum == 180) {
if ((angle[0] == angle[1]) || (angle[0] == angle[2]) || (angle[1] == angle[2])) cout << "Isosceles";
else cout << "Scalene";
}
else cout << "Error";
}
return 0;
} |
fa66b3d89d2ba19a701c55fccf0bf45a988b60f8 | db08a68639f7352b54ddf04d77f203956b9e328b | /Chapter4/main/main.cpp | 8c2d30209387d041a358b4b8b691abcdd173ab58 | [] | no_license | BrandonSchaefer/Formal-Language-Algorithms | 13ab86f6d8a05d568042e5196c8eed284618e5f8 | 9110ebd37d64f050ac3b4a239945434e4cfe4c66 | refs/heads/master | 2019-01-19T17:58:42.725355 | 2011-06-02T20:42:29 | 2011-06-02T20:42:29 | 1,688,917 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,100 | cpp | main.cpp | #include "gramLib.h"
#include "gramIO.h"
#include "chap4.h"
using namespace std;
int main(){
char gramIn[30] = "grammers/grammerA.txt";
char gramOutA[30] = "grammer3.txt";
char gramOutB[30] = "grammer3Out.txt";
int i = 0;
// char* test[10] = {"a", "aa", "aab", "baa", "aabb", "bbaa", "bbbaaa", "aaabbb", "abba", "bababa"};
while(i++ < 1 ){
alg4_8(gramOutA, gramOutB);//, test[i++]);
}
/*
alg4_1(gramOutA, gramOutB);
alg4_2(gramOutB, gramOutA);
alg4_3(gramOutA, gramOutB);
alg4_4_2(gramOutB, gramOutA);
alg4_4_4(gramOutA, gramOutB);*/
// alg4_3(gramOutA, gramOutB);
// alg4_4_2(gramOutA, gramOutB);
// alg4_4_4(gramOutA, gramOutB);
// *(gramOutA+10) += 1;
// *(gramIn+16) += 1;
//}
// alg4_1("testGramer.txt", gramOutA);
// alg4_2(gramOutA, gramOutB);
// alg4_2(gramOutA, gramOutB);
// alg4_2(gramOutA, gramOutB);
/* *(gramOutA + 10) += 1;
alg4_3(gramOutB, gramOutA);
*(gramOutB + 10) += 1;
alg4_4_2(gramOutA, gramOutB);
*(gramOutA + 10) += 1;
alg4_4_4(gramOutB, gramOutA); */
cout << gramOutA << endl;
cout << "WORKED" << endl;
while(1);
}
|
71cf0f1778890b28940c9dd48e43a33b077d0008 | 1212b9f40d5863b4d351aa122f4ed25d952b0c5d | /include/Dictionary.h | b72a4e6fbb7f5cc9eb4184fe321e8e34dc0f2c9e | [] | no_license | suziyousif/Hangman_Game_POO | 055a3bf6b995097d87482878931f0390929cfe7b | 58228000c6a7bd9c0fd72dc1f0a80318048f4555 | refs/heads/master | 2020-05-16T21:40:27.882715 | 2019-06-14T17:38:26 | 2019-06-14T17:38:26 | 183,312,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | Dictionary.h | #ifndef DICTIONARY_H
#define DICTIONARY_H
#include "Word.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
class Dictionary
{
public:
Dictionary();
void addWord(Word *_word);
Word *selectWord();
virtual ~Dictionary();
protected:
private:
vector <Word*> vec_words;
vector <Word*>::iterator it;
};
#endif // DICTIONARY_H
|
db6c92dbe105dc6fe8070ba8b25fb8682c5d5d28 | a3569601d203ad418a5cf68043001be5610da90f | /Array/26.删除有序数组中的重复项.cpp | 57c1caa75cb6609dfcec292bf700751d0c635465 | [] | no_license | l1nkkk/leetcode | a12b0e117dd5e580fe8356f66774f75edb4612ac | 6c4bb462afb68f5cd913d6f3010b39f62dce2d86 | refs/heads/master | 2023-03-16T17:25:18.765935 | 2022-08-06T15:31:42 | 2022-08-06T15:31:42 | 220,748,877 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | 26.删除有序数组中的重复项.cpp | //
// Created by l1nkkk on 2021/7/26.
//
#include <iostream>
#include <vector>
using namespace std;
namespace leetcode26{
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0) return 0;
int slow, fast;
slow = 0;
fast = 0;
while(fast < nums.size()){
if(nums[slow] != nums[fast]) {
++slow;
nums[slow] = nums[fast];
}
++fast;
}
return slow+1;
}
};
} |
7777a6ce75dd78152fa99f34b6bb5ae4d622932d | 67c2a90c7edfac3cfd891cb332c45e71cf4a6ad1 | /src/cdm_rcpp_irt_classify.cpp | c8c5096ba439004f0566b7eaae02aeec583f3ee5 | [] | no_license | alexanderrobitzsch/CDM | 48316397029327f213967dd6370a709dd1bd2e0a | 7fde48c9fe331b020ad9c7d8b0ec776acbff6a52 | refs/heads/master | 2022-09-28T18:09:22.491208 | 2022-08-26T11:36:31 | 2022-08-26T11:36:31 | 95,295,826 | 21 | 11 | null | 2019-06-19T09:40:01 | 2017-06-24T12:19:45 | R | UTF-8 | C++ | false | false | 1,120 | cpp | cdm_rcpp_irt_classify.cpp | //// File Name: cdm_rcpp_irt_classify.cpp
//// File Version: 0.07
// [[Rcpp::depends(RcppArmadillo)]]
//#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
//using namespace arma;
///********************************************************************
///** cdm_rcpp_irt_classify_individuals
// [[Rcpp::export]]
Rcpp::List cdm_rcpp_irt_classify_individuals( Rcpp::NumericMatrix like )
{
int N = like.nrow();
int TP = like.ncol();
Rcpp::IntegerVector class_index(N);
Rcpp::NumericVector class_maxval(N);
double val=0;
int ind=0;
for (int nn=0; nn<N; nn++){
val=0;
ind=0;
for (int tt=0; tt<TP; tt++){
if ( like(nn,tt) > val ){
val = like(nn,tt);
ind = tt;
}
}
class_index[nn] = ind + 1;
class_maxval[nn] = val;
}
//---- OUTPUT:
return Rcpp::List::create(
Rcpp::Named("class_index") = class_index,
Rcpp::Named("class_maxval") = class_maxval
);
}
///********************************************************************
|
70a9c7707faa418eadc5a8cf089add654fd95150 | 0da00c4d8c477be869b0c1d2c3dcdff8f94142be | /SPOJ/STRSEQ.cpp | 854866a2592101441a235dae37335d7a62fc117b | [] | no_license | Kevinwen1999/Other-solutions | 031274517754e9684146261beeaf5369c810a0b0 | 5bfecc4bbf3fc2a7e90914c7558a6b458280556f | refs/heads/master | 2021-06-11T18:30:03.596911 | 2021-05-24T05:11:00 | 2021-05-24T05:11:00 | 100,914,594 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | cpp | STRSEQ.cpp | #include <bits/stdc++.h>
#define MAXN 100010
#define INF 0x3f3f3f3f
using namespace std;
string in;
int N;
int nextidx[MAXN][10];
int dp[MAXN];
int nextone[MAXN];
int DP(int cur) {
if (~dp[cur]) return dp[cur];
dp[cur] = INF;
for (int i = 0; i < 10; i++) {
int nx = nextidx[cur + 1][i];
if (nx == INF) {
nextone[cur] = i;
return dp[cur] = 0;
}
if (dp[cur] > DP(nx) + 1) {
dp[cur] = DP(nx) + 1;
nextone[cur] = i;
}
}
return dp[cur];
}
int main() {
while (cin >> in) {
int N = in.size();
in = " " + in;
for (int j = 0; j < 10; j++)
nextidx[N + 1][j] = INF;
for (int i = N; i >= 0; i--) {
for (int j = 0; j < 10; j++) {
nextidx[i][j] = nextidx[i + 1][j];
}
if (i)
nextidx[i][in[i] - '0'] = i;
}
if (nextidx[0][0] == INF) {
cout << "0\n";
continue;
}
else {
memset(dp, -1, sizeof dp);
int minans = INF, st;
for (int i = 1; i < 10; i++) {
int nx = nextidx[1][i];
if (nx == INF) {
st = i;
break;
} else {
if (DP(nx) < minans) {
minans = DP(nx);
st = i;
}
}
}
int pnt = 0;
while(pnt != INF) {
cout << st;
pnt = nextidx[pnt + 1][st];
if (pnt == INF) break;
st = nextone[pnt];
}
cout << "\n";
}
}
}
|
6ce558473162363d75435e8e3b45a5fa9ee9c8ae | 33a52c90e59d8d2ffffd3e174bb0d01426e48b4e | /uva/11300-/11307.cc | b95be63de06a8b46c2fe39877b9bb656b6cf3031 | [] | no_license | Hachimori/onlinejudge | eae388bc39bc852c8d9b791b198fc4e1f540da6e | 5446bd648d057051d5fdcd1ed9e17e7f217c2a41 | refs/heads/master | 2021-01-10T17:42:37.213612 | 2016-05-09T13:00:21 | 2016-05-09T13:00:21 | 52,657,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,179 | cc | 11307.cc | #include<iostream>
#include<sstream>
#include<vector>
using namespace std;
const int BUF = 10005, COLOR = 20, INF = 1<<20;
int nNode, nIn[BUF];
vector<int> adj[BUF];
bool read(){
for(int i=0;i<BUF;i++){ adj[i].clear(); nIn[i] = 0; }
cin >> nNode;
if(nNode==0) return false;
string dummy; getline(cin,dummy);
for(int i=0;i<nNode;i++){
string s;
getline(cin,s);
stringstream in(s);
int src, dst;
char ch;
in >> src >> ch;
while(in >> dst){
adj[src].push_back(dst);
nIn[dst]++;
}
}
return true;
}
int rec(int cur, int color, int dp[BUF][COLOR]){
int &ret = dp[cur][color];
if(ret!=-1) return ret;
ret = 0;
for(int i=0;i<adj[cur].size();i++){
int minV = INF;
for(int col=1;col<COLOR;col++)
if(color!=col)
minV = min(minV,rec(adj[cur][i],col,dp)+col);
ret += minV;
}
return ret;
}
void work(){
static int dp[BUF][20];
memset(dp,-1,sizeof(dp));
for(int i=0;i<nNode;i++)
if(nIn[i]==0){
int minV = INF;
for(int col=1;col<COLOR;col++)
minV = min(minV,rec(i,col,dp)+col);
cout << minV << endl;
}
}
int main(){
while(read()) work();
return 0;
}
|
fe702d0bbe217b535eec1a2e5c4b2e6aa86969a6 | e9ce970d4690c49acd5141e5608925924c41eca6 | /CPP/HelloCpp2/chapter_27/OperatorOverload2.cpp | d21f45ccb810e7befa096a2b15a4c34fe80e6652 | [
"MIT"
] | permissive | hrntsm/study-language | 8422f2fa5ad45521031dd32334463736107a012f | 922578a5321d70c26b935e6052f400125e15649c | refs/heads/main | 2023-08-30T02:10:26.585375 | 2021-11-18T12:47:58 | 2021-11-18T12:47:58 | 341,214,562 | 1 | 0 | MIT | 2021-02-23T01:41:40 | 2021-02-22T13:45:32 | Python | UTF-8 | C++ | false | false | 302 | cpp | OperatorOverload2.cpp | #include <iostream>
using namespace std;
class String
{
public:
char *str;
String operator=(char *str)
{
this->str = str;
return *this;
}
};
int main()
{
String str1, str2;
str1 = str2 = "Kitty on your lap\n";
cout << str1.str << str2.str;
return 0;
}
|
c8070fbc0dd8a902f20033354e8081d8ca3fc86f | b59bd8b2004c25c7e0780a840c7b163020945f72 | /Solutions/C++/Problem 062.cpp | c53a815167c54bb9677e402fc00b7acab8740257 | [] | no_license | serishan/LeetCode | 5d9b5338279a22059610b936c48bd5279cd73543 | 1d1d492176628e76729ec7ca1e1266b0c99a0a76 | refs/heads/master | 2020-04-25T13:58:58.168403 | 2019-04-26T10:07:42 | 2019-04-26T10:07:42 | 172,825,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | cpp | Problem 062.cpp | /*
Problem 62: Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
*/
/* Time: 4ms */
class Solution {
public:
int uniquePaths(int m, int n)
{
//All the grid has the value 1
vector<vector<int>> grid(n, vector<int>(m, 1));
int upMost = 0, downMost = n-1, rightMost = m-1, leftMost = 0;
for(int col = 1; col <= rightMost; ++col)
for(int row = 1; row <= downMost; ++row)
grid[row][col] = grid[row-1][col] + grid[row][col-1];
return grid[downMost][rightMost];
}
}; |
3dc5fa58bbcf3590c083ac85217e340e663406b8 | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/nt2/exponential/include/constants/log10_elo.hpp | 651c5a79eb54cb5fa017a5e1385415df365b3d18 | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 190 | hpp | log10_elo.hpp | #ifndef NT2_EXPONENTIAL_INCLUDE_CONSTANTS_LOG10_ELO_HPP_INCLUDED
#define NT2_EXPONENTIAL_INCLUDE_CONSTANTS_LOG10_ELO_HPP_INCLUDED
#include <nt2/exponential/constants/log10_elo.hpp>
#endif
|
153edaf503b7de3aff4398be6d9eca1f019b4810 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_6984.cpp | 4d6a7c0388b596664cffe3895ffd2453d2fbfd4c | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | cpp | httpd_new_log_6984.cpp | ap_log_error(APLOG_MARK, APLOG_TRACE2, 0, server,
"%s: reusing backend connection %pI<>%pI",
scheme, local_addr, conn->addr); |
aba548ee71e7463c209aa59199e053342df9d932 | 0c9a1d588d5b1d6c741aac3613862985424c90a5 | /printer_manager/cupsconnection4ppds.cpp | 6a865cafda183381cfa0bf15b056f8fe3cff9c05 | [] | no_license | UbuntuKylin/kylin-printer | 0aa3702c1cb888ec16acc2dd428d6cb0a7bd8d14 | 419168270ee8c00d2a6b660e8f221f8547f1d4b0 | refs/heads/master | 2023-06-28T14:21:15.992747 | 2021-03-08T11:01:05 | 2021-03-08T11:01:05 | 327,815,268 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | cpp | cupsconnection4ppds.cpp | #include <QTimer>
#include <QDateTime>
#include "cupsconnection4ppds.h"
#include "ukuiPrinter.h"
CupsConnection4PPDs::CupsConnection4PPDs()
{
qDebug() << "CUPS开始建立" << QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");
server = cupsServer();
ippPortNum = ippPort();
encryptionType = cupsEncryption();
int cancel = 0;
ppdRequestConnection = httpConnect2(server, ippPortNum, nullptr, AF_UNSPEC, (http_encryption_t)encryptionType, 1, 30000, &cancel);
if (!ppdRequestConnection)
{
throw std::runtime_error("Failed to construct ppdRequestConnection!");
}
else
{
qDebug() << "CUPS服务ppdRequestConnection建立成功!";
}
qDebug() << "CUPS建立完成" << QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");
}
CupsConnection4PPDs *CupsConnection4PPDs::getInstance()
{
static CupsConnection4PPDs *cupsInstance = nullptr;
if (cupsInstance == nullptr)
{
try
{
cupsInstance = new CupsConnection4PPDs;
}
catch (const std::runtime_error &re)
{
qDebug() << "runtime_error:" << re.what();
}
}
return cupsInstance;
}
|
6aac4ac212a55dc128854339fd63869fbf30e082 | b571a0ae02b7275b52499c66a756d10815136326 | /1049.Last.Stone.Weight.II/sol.cpp | 5549a4ec68b3b7b508ed32645fc8b2479b867b43 | [] | no_license | xjs-js/leetcode | 386f9acf89f7e69b5370fdeffa9e5120cf57f868 | ef7601cbac1a64339e519d263604f046c747eda8 | refs/heads/master | 2022-02-02T00:51:23.798702 | 2022-01-19T14:48:13 | 2022-01-19T14:48:13 | 89,140,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | cpp | sol.cpp | class Solution {
public:
int pkg(vector<int>& vol, vector<int>& val, int v) {
int f[v+1];
memset(f, 0, sizeof f);
int n = val.size();
for (int i = 0; i < n; ++i) {
int curVol = vol[i];
int curVal = val[i];
for (int j = v; j >= curVol; --j)
f[j] = max(f[j], f[j - curVol] + curVal);
}
return f[v];
}
int calc(vector<int>& nums, int target) {
return pkg(nums, nums, target);
}
int lastStoneWeightII(vector<int>& stones) {
int sum = 0;
for (int i = 0; i < stones.size(); ++i) sum += stones[i];
int relt = calc(stones, sum/2);
return (sum - relt) - relt;
}
};
|
4be4a221159641dfe9547c78042cbee5d9daae02 | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/xpressive/detail/core/results_cache.hpp | 5ee0def5226b6c5bb8ca184b0ece70a055a4a23b | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 81 | hpp | results_cache.hpp | #include "thirdparty/boost_1_58_0/boost/xpressive/detail/core/results_cache.hpp"
|
6e6fce171a46c6eefee27d1a30a5dd3b5a9eadb2 | dea58388a1ef05d3c934c0b5f16ec8a7569c72d6 | /MiniDebugger/DlgProxy.h | 5eb14ece356fc5669eae7fef361855a998fae20d | [] | no_license | feilang864/MiniDebugger | 3fa7cd8df5345f5d663a26d55fe4f6a3ebcda003 | 2dfdb8fc0707eb97cf0651effde2fe418eb50765 | refs/heads/master | 2021-01-10T11:28:04.121506 | 2015-08-07T13:02:59 | 2015-08-07T13:02:59 | 45,438,335 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 725 | h | DlgProxy.h |
// DlgProxy.h: 头文件
//
#pragma once
class CMiniDebuggerDlg;
// CMiniDebuggerDlgAutoProxy 命令目标
class CMiniDebuggerDlgAutoProxy : public CCmdTarget
{
DECLARE_DYNCREATE(CMiniDebuggerDlgAutoProxy)
CMiniDebuggerDlgAutoProxy(); // 动态创建所使用的受保护的构造函数
// 特性
public:
CMiniDebuggerDlg* m_pDialog;
// 操作
public:
// 重写
public:
virtual void OnFinalRelease();
// 实现
protected:
virtual ~CMiniDebuggerDlgAutoProxy();
// 生成的消息映射函数
DECLARE_MESSAGE_MAP()
DECLARE_OLECREATE(CMiniDebuggerDlgAutoProxy)
// 生成的 OLE 调度映射函数
DECLARE_DISPATCH_MAP()
DECLARE_INTERFACE_MAP()
};
|
23f3b107c304172c185784bb641fe514b20ff469 | 444795313ac4dd280670bac6e5c58d2257bba047 | /src/cubelet.cpp | 053338f41b6eeeec02e9f2f55dbecc9dea4b71da | [] | no_license | alexasensio/rubik_cube | af313f4729448adedb7b747068c4bcc17aef2065 | 1b21a576e7a9e131e94e710a97972df8522936dd | refs/heads/master | 2020-07-02T09:52:21.354082 | 2016-11-29T16:31:43 | 2016-11-29T16:31:43 | 74,311,870 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,827 | cpp | cubelet.cpp | #include "cubelet.h"
#include <iostream>
cubelet::cubelet() //default constructor
{
colourX='-';
colourY='-';
colourZ='-';
}
cubelet::cubelet(char A, char B, char C) //constructor with parameters
{
colourX=A;
colourY=B;
colourZ=C;
}
cubelet::~cubelet() //destructor. Using cout only for debugging purposes
{
//std::cout << "\nThe destructor has been called\n";
}
void cubelet::Charge_colour(char D, int axis) //constructor with parameters
{
if(axis==0){ //in case the rotation is in the axis X
this->colourX=D;
}
else if (axis==1){ //in case the rotation is in the axis Y
this->colourY=D;
}
else if (axis==2){ //in case the rotation is in the axis Z
this->colourZ=D;
}
else{ //error detection since the axis should only be 0, 1 or 2
std::cout << "\nError at Charge_colour when updating colour of " << axis << "\n";
}
}
void cubelet::Rotate_cubelet(int axis) //swaps colours of the cubelet in the 2 axis perpendicular to the one of rotation
{
char temp='1'; //temp variable to storage the value of one of the colours and do not overwrite it and loose it.
if(axis==0){ //in case the rotation is in the axis X
temp = this->colourY;
this->colourY = this->colourZ;
this->colourZ = temp;
}
else if (axis==1){ //in case the rotation is in the axis Y
temp = this->colourX;
this->colourX = this->colourZ;
this->colourZ = temp;
}
else if (axis==2){ //in case the rotation is in the axis Z
temp = this->colourX;
this->colourX = this->colourY;
this->colourY = temp;
}
else{ //error detection since the axis should only be 0, 1 or 2
std::cout << "\nError at Rotate_cubelet when rotating axis" << axis << "\n";
}
}
char cubelet::Colour_cubelet(int axis) //gives back the colour of the cubelet in the corresponding axis
{
char colour = '2';
if(axis==0){ //in case the rotation is in the axis X
colour = this->colourX;
}
else if (axis==1){ //in case the rotation is in the axis Y
colour = this->colourY;
}
else if (axis==2){ //in case the rotation is in the axis Z
colour = this->colourZ;
}
else{ //error detection since the axis should only be 0, 1 or 2
std::cout << "\nError at Colour_cubelet when returning colour of axis " << axis << "\n";
}
return colour;
}
void cubelet::Print_colours()
{
std::cout << "\n Colours of the cubelet:\n"
"View in axis X:\t" << this->colourX
<< "\nView in axis Y:\t" << this->colourY
<< "\nView in axis Z:\t" << this->colourZ;
}
|
96387b02355095cffd8a405d94445f00123b3997 | 2105a3a0f2395f9c790f591cada94186dd92ae53 | /assignment5/TravellingAgency/Hotel.cpp | e86c710576ddc3bd3809d48789a343f42e08a946 | [] | no_license | abdullahcheema63/cp_assignments | 98dfb032356678602059f8c057c73cb5abb45a4b | 7a516edb396d9dbcda2bd5f6722e29b2f967e843 | refs/heads/master | 2021-01-19T16:08:55.522133 | 2017-08-21T20:04:30 | 2017-08-21T20:04:30 | 100,988,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | Hotel.cpp | /*
* Hotel.cpp
*
* Created on: Apr 13, 2017
* Author: abdullah
*/
#include "Hotel.h"
Hotel::Hotel(string n,double fFee,int nN,double ppn):TravelOption(n,fFee) {
// TODO Auto-generated constructor stub
numNights=nN;
pricePerNight=ppn;
}
double Hotel::price()
{
return (numNights*pricePerNight)+flatFee;
}
Hotel::~Hotel() {
// TODO Auto-generated destructor stub
}
|
7d8b7ba643602cde30ff2ae1eed996d4f6dfd26b | b0c9bb1fb35525844297dc509b4b0a010e4c2b48 | /abc193_b.cpp | e71e61dbb6f3050fb8dd79db9dea3c41bfc357b2 | [] | no_license | takumi-zer0/competitiveprogramming | 5768bbb8e8370f5f36ed25e452f8b2d953ff0043 | c9bc21494d26676c7c0103d9d4419e44b75810b6 | refs/heads/master | 2023-07-11T17:46:12.982924 | 2021-08-25T08:32:57 | 2021-08-25T08:32:57 | 386,274,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | abc193_b.cpp | #include <bits/stdc++.h>
#define ll long long
using namespace std;
template<class T>bool chmax(T &a, const T &b){if(a>b){a=b; return 1;} return 0;}
template<class T>bool chmin(T &a, const T &b){if(b<a){a=b; return 1;} return 0;}
int main(){
ll n; cin >> n;
ll a,b,c;
vector<int> d;
for(int i= 0; i< n;i++){
cin >> a >> b >> c;
if(c > a) d.push_back(b);
}
sort(d.begin(), d.end());
if(d.size() > 0) cout << d[0] << endl;
else cout << "-1" << endl;
}
|
89fc83c71d3590492ee3f1b41e37f80d2f10562f | ad40beac422d2b8f10ed74943703fa84fca69b14 | /Google_tests/TestObjects.cpp | a3b85c1b4d04c3fdad82c962dd42a208c5c03165 | [] | no_license | Davide307/Esame_Programmazione | 13ba79c47e813c025d511bada2dd25966027ac2e | 67174f563c3ee2ba2bbcdbd95b3357479ddead4f | refs/heads/master | 2020-08-08T03:20:16.704339 | 2020-02-15T16:21:47 | 2020-02-15T16:21:47 | 213,691,811 | 0 | 1 | null | 2019-10-09T20:21:53 | 2019-10-08T16:11:37 | C++ | UTF-8 | C++ | false | false | 1,811 | cpp | TestObjects.cpp | #include <gtest/gtest.h>
#include <SFML/System.hpp>
#include "../Hero.h"
#include "../GameCharacter.h"
#include "../RectangleShape.h"
#include "../Bullet.h"
//
// Created by davide on 28/09/19.
TEST(Bullet, checkInitObject) {
RectangleShape o1;
o1.init(90,100,sf::Vector2f(10,20));
ASSERT_EQ(90,o1.x);
ASSERT_EQ(100,o1.y);
ASSERT_EQ(10,o1.width);
ASSERT_EQ(20,o1.height);
ASSERT_EQ(90,o1.spawnX);
ASSERT_EQ(100,o1.spawnY);
ASSERT_EQ(o1.hitTop,o1.y);
ASSERT_EQ(o1.hitBottom,o1.y+o1.height);
ASSERT_EQ(o1.hitLeft,o1.x);
ASSERT_EQ(o1.hitRight,o1.x+o1.width);
}
TEST(GameCharacter,checkCharacterInit){
GameCharacter g1;
ASSERT_EQ(g1.velocity.x,0);
ASSERT_EQ(g1.velocity.y,0);
}
TEST(Hero,checkHeroUpdate){
Hero h1;
h1.init(10,10,sf::Vector2f(32,32));
std::vector<Platform> platform;
h1.setMoveSpeed(30);
h1.isOnGround= true;
h1.update(false, false, false, true, &platform);
ASSERT_EQ(h1.velocity.x,1);
h1.update(false, true, false, false, &platform);
ASSERT_EQ(h1.velocity.x,-1);
h1.update(true, false, false, false, &platform);
}
TEST(Bullet,checkBullet){
Bullet b1(false,sf::Vector2f(1,0));
b1.init(10,20,sf::Vector2f(30,30));
b1.fire();
ASSERT_EQ(b1.x,b1.spawnX+b1.bulletSpeed);
Bullet b2(false,sf::Vector2f(-1,0));
b2.init(10,20,sf::Vector2f(30,30));
b2.fire();
ASSERT_EQ(b2.x,b2.spawnX-b2.bulletSpeed);
Bullet b3(false,sf::Vector2f(0,1));
b3.init(10,20,sf::Vector2f(30,30));
b3.fire();
ASSERT_EQ(b3.y,b3.spawnY+b3.bulletSpeed);
Bullet b4(false,sf::Vector2f(0,-1));
b4.init(10,20,sf::Vector2f(30,30));
b4.fire();
ASSERT_EQ(b4.y,b4.spawnY-b4.bulletSpeed);
Bullet b5(true,sf::Vector2f(0,0));
ASSERT_EQ(b5.bulletLife,b1.bulletLife*3);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.