hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1bd3e07889fae7cc84ce637319a07484723a3b68 | 1,017 | hh | C++ | src/server.hh | fusion32/kaplar | c85fc3cfd020b4c7892f9987239cb48eaf1a04a5 | [
"MIT"
] | null | null | null | src/server.hh | fusion32/kaplar | c85fc3cfd020b4c7892f9987239cb48eaf1a04a5 | [
"MIT"
] | null | null | null | src/server.hh | fusion32/kaplar | c85fc3cfd020b4c7892f9987239cb48eaf1a04a5 | [
"MIT"
] | 2 | 2018-08-20T00:59:07.000Z | 2018-08-20T00:59:18.000Z | #ifndef KAPLAR_SERVER_HH_
#define KAPLAR_SERVER_HH_ 1
#include "common.hh"
// ----------------------------------------------------------------
// Server
// ----------------------------------------------------------------
enum ConnectionStatus : u32 {
CONNECTION_STATUS_ALIVE = 0,
CONNECTION_STATUS_CLOSING,
};
typedef void (*OnAccept)(void *userdata, u32 index);
typedef void (*OnDrop)(void *userdata, u32 index);
typedef void (*OnRead)(void *userdata, u32 index, u8 *data, i32 datalen);
typedef void (*RequestOutput)(void *userdata, u32 index, u8 **output, i32 *output_len);
typedef void (*RequestStatus)(void *userdata, u32 index, ConnectionStatus *out_status);
struct ServerParams{
u16 port;
u16 max_connections;
u16 readbuf_size;
OnAccept on_accept;
OnDrop on_drop;
OnRead on_read;
RequestOutput request_output;
RequestStatus request_status;
};
struct Server;
Server *server_init(MemArena *arena, ServerParams *params);
void server_poll(Server *server, void *userdata);
#endif // KAPLAR_SERVER_HH_
| 29.057143 | 87 | 0.668633 | fusion32 |
1bd44f5f4e97bafbba67a4222a1db20ff40b0c30 | 4,133 | cpp | C++ | dali/public-api/images/buffer-image.cpp | tizenorg/platform.core.uifw.dali-core | dd89513b4bb1fdde74a83996c726e10adaf58349 | [
"Apache-2.0"
] | 1 | 2016-08-05T09:58:38.000Z | 2016-08-05T09:58:38.000Z | dali/public-api/images/buffer-image.cpp | tizenorg/platform.core.uifw.dali-core | dd89513b4bb1fdde74a83996c726e10adaf58349 | [
"Apache-2.0"
] | null | null | null | dali/public-api/images/buffer-image.cpp | tizenorg/platform.core.uifw.dali-core | dd89513b4bb1fdde74a83996c726e10adaf58349 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/public-api/images/buffer-image.h>
// INTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/common/dali-common.h>
#include <dali/internal/event/images/buffer-image-impl.h>
namespace Dali
{
BufferImage::BufferImage()
{
}
BufferImage::BufferImage(Internal::BufferImage* internal)
: Image(internal)
{
}
BufferImage BufferImage::DownCast( BaseHandle handle )
{
return BufferImage( dynamic_cast<Dali::Internal::BufferImage*>(handle.GetObjectPtr()) );
}
BufferImage::~BufferImage()
{
}
BufferImage::BufferImage(const BufferImage& handle)
: Image(handle)
{
}
BufferImage& BufferImage::operator=(const BufferImage& rhs)
{
BaseHandle::operator=(rhs);
return *this;
}
const BufferImage BufferImage::WHITE()
{
Internal::BufferImage* internal = new Internal::BufferImage(1,1,Pixel::RGBA8888, Dali::Image::NEVER);
PixelBuffer* pBuf = internal->GetBuffer();
if ( pBuf )
{
pBuf[0] = pBuf[1] = pBuf[2] = pBuf[3] = 0xFF;
}
return BufferImage(internal);
}
BufferImage BufferImage::New(unsigned int width, unsigned int height, Pixel::Format pixelformat)
{
DALI_ASSERT_ALWAYS( 0u != width && "Invalid BufferImage width requested" );
DALI_ASSERT_ALWAYS( 0u != height && "Invalid BufferImage height requested" );
Internal::BufferImagePtr internal = Internal::BufferImage::New(width, height, pixelformat);
return BufferImage(internal.Get());
}
BufferImage BufferImage::New(unsigned int width, unsigned int height, Pixel::Format pixelformat, ReleasePolicy releasePol)
{
DALI_ASSERT_ALWAYS( 0u != width && "Invalid BufferImage width requested" );
DALI_ASSERT_ALWAYS( 0u != height && "Invalid BufferImage height requested" );
Internal::BufferImagePtr internal = Internal::BufferImage::New(width, height, pixelformat, releasePol);
return BufferImage(internal.Get());
}
BufferImage BufferImage::New(PixelBuffer* pixBuf, unsigned int width, unsigned int height, Pixel::Format pixelformat, unsigned int stride)
{
DALI_ASSERT_ALWAYS( 0u != width && "Invalid BufferImage width requested" );
DALI_ASSERT_ALWAYS( 0u != height && "Invalid BufferImage height requested" );
Internal::BufferImagePtr internal = Internal::BufferImage::New(pixBuf, width, height, pixelformat, stride);
return BufferImage(internal.Get());
}
BufferImage BufferImage::New(PixelBuffer* pixBuf, unsigned int width, unsigned int height, Pixel::Format pixelformat, unsigned int stride, ReleasePolicy releasePol)
{
DALI_ASSERT_ALWAYS( 0u != width && "Invalid BufferImage width requested" );
DALI_ASSERT_ALWAYS( 0u != height && "Invalid BufferImage height requested" );
Internal::BufferImagePtr internal = Internal::BufferImage::New(pixBuf, width, height, pixelformat, stride, releasePol);
return BufferImage(internal.Get());
}
PixelBuffer* BufferImage::GetBuffer()
{
return GetImplementation(*this).GetBuffer();
}
unsigned int BufferImage::GetBufferSize() const
{
return GetImplementation(*this).GetBufferSize();
}
unsigned int BufferImage::GetBufferStride() const
{
return GetImplementation(*this).GetBufferStride();
}
Pixel::Format BufferImage::GetPixelFormat() const
{
return GetImplementation(*this).GetPixelFormat();
}
void BufferImage::Update ()
{
RectArea area;
GetImplementation(*this).Update(area);
}
void BufferImage::Update (RectArea updateArea)
{
GetImplementation(*this).Update(updateArea);
}
bool BufferImage::IsDataExternal() const
{
return GetImplementation(*this).IsDataExternal();
}
} // namespace Dali
| 29.312057 | 164 | 0.747641 | tizenorg |
1bd94d73ac682aa309d74778f64f754b9b2f7e96 | 1,875 | cpp | C++ | DinoLasers/UIButton.cpp | QRayarch/DinoLasers | 500f4144fad2a813cd140d6067b41a41f4573e8c | [
"MIT"
] | null | null | null | DinoLasers/UIButton.cpp | QRayarch/DinoLasers | 500f4144fad2a813cd140d6067b41a41f4573e8c | [
"MIT"
] | null | null | null | DinoLasers/UIButton.cpp | QRayarch/DinoLasers | 500f4144fad2a813cd140d6067b41a41f4573e8c | [
"MIT"
] | null | null | null | #include "UIButton.h"
UIButton::UIButton(String name, vector3 c1, vector3 c2) : UI(name)
{
color1 = c1;
color2 = c2;
paddX = 0;
paddY = 0;
invisiblePadY = 0;
isInside = false;
}
UIButton::~UIButton()
{
}
void UIButton::Update(float dt) {
//&& x < (paddX + UI::GetName().length()) * TEXT_SIZE && y < (paddY + 3) * TEXT_SIZE
//&& y > paddY * TEXT_SIZE
int x = sf::Mouse::getPosition().x - SystemSingleton::GetInstance()->GetWindowX();
int y = sf::Mouse::getPosition().y - SystemSingleton::GetInstance()->GetWindowY();
//std::cout << x << " " << paddX * TEXT_SIZE << " " << ((paddX + UI::GetName().length() * 3)) << "\n";
//std::cout << y << " " << (paddY * 3 * TEXT_SIZE) << " " << ((paddY + 1) * 3 * TEXT_SIZE) << "\n\n";
//x > (paddX + UI::GetName().length())* TEXT_SIZE && x < (paddX + UI::GetName().length() * 3) * TEXT_SIZE
if (y > ((paddY - 1 + invisiblePadY) * 3 * TEXT_SIZE) && y < ((paddY + invisiblePadY) * 3 * TEXT_SIZE) && x >(paddX + UI::GetName().length())* TEXT_SIZE && x < (paddX + UI::GetName().length() * 3) * TEXT_SIZE) {
isInside = true;
} else {
isInside = false;
}
}
bool UIButton::IsPressed(){
if (isInside) {
return sf::Mouse::isButtonPressed(sf::Mouse::Button::Left);
}
return false;
}
void UIButton::Render() {
String padding = "";
for (int y = 0; y < paddY; y++) {
padding += "\n";
}
for (int x = 0; x < paddX; x++) {
padding += " ";
}
//MeshManagerSingleton::GetInstance()->AddLineToRenderList(vector3(paddX * TEXT_SIZE, paddY * TEXT_SIZE, 0.0f), vector3((paddX + UI::GetName().size()) * TEXT_SIZE, (paddY + 1) * TEXT_SIZE, 0.0f));
MeshManagerSingleton::GetInstance()->PrintLine(padding+UI::GetName() , isInside?color2:color1);
}
void UIButton::SetPaddingX(uint pX) { paddX = pX; }
void UIButton::SetPaddingY(uint pY) { paddY = pY; }
void UIButton::SetInvisiblePaddingY(uint pY) { invisiblePadY = pY; }
| 32.327586 | 212 | 0.609067 | QRayarch |
1be17a0cfddc77184a80b2c9f9bdc02a1e25d9d8 | 18,955 | cpp | C++ | 3.7.0/lldb-3.7.0.src/source/Commands/CommandObjectExpression.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 3 | 2016-02-10T14:18:40.000Z | 2018-02-05T03:15:56.000Z | 3.7.0/lldb-3.7.0.src/source/Commands/CommandObjectExpression.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 1 | 2016-02-10T15:40:03.000Z | 2016-02-10T15:40:03.000Z | 3.7.0/lldb-3.7.0.src/source/Commands/CommandObjectExpression.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | null | null | null | //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CommandObjectExpression.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/Value.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/DataFormatters/ValueObjectPrinter.h"
#include "lldb/Expression/ClangExpressionVariable.h"
#include "lldb/Expression/ClangUserExpression.h"
#include "lldb/Expression/ClangFunction.h"
#include "lldb/Expression/DWARFExpression.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/StringConvert.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Target/ObjCLanguageRuntime.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
using namespace lldb;
using namespace lldb_private;
CommandObjectExpression::CommandOptions::CommandOptions () :
OptionGroup()
{
}
CommandObjectExpression::CommandOptions::~CommandOptions ()
{
}
static OptionEnumValueElement g_description_verbosity_type[] =
{
{ eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", "Only show the description string"},
{ eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", "Show the full output, including persistent variable's name and type"},
{ 0, NULL, NULL }
};
OptionDefinition
CommandObjectExpression::CommandOptions::g_option_table[] =
{
{ LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Should we run all threads if the execution doesn't complete on one thread."},
{ LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"},
{ LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."},
{ LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "unwind-on-error", 'u', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Clean up program state if the expression causes a crash, or raises a signal. Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."},
{ LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "debug", 'g', OptionParser::eNoArgument , NULL, NULL, 0, eArgTypeNone, "When specified, debug the JIT code by setting a breakpoint on the first instruction and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."},
{ LLDB_OPT_SET_1, false, "description-verbosity", 'v', OptionParser::eOptionalArgument, NULL, g_description_verbosity_type, 0, eArgTypeDescriptionVerbosity, "How verbose should the output of this expression be, if the object description is asked for."},
};
uint32_t
CommandObjectExpression::CommandOptions::GetNumDefinitions ()
{
return llvm::array_lengthof(g_option_table);
}
Error
CommandObjectExpression::CommandOptions::SetOptionValue (CommandInterpreter &interpreter,
uint32_t option_idx,
const char *option_arg)
{
Error error;
const int short_option = g_option_table[option_idx].short_option;
switch (short_option)
{
//case 'l':
//if (language.SetLanguageFromCString (option_arg) == false)
//{
// error.SetErrorStringWithFormat("invalid language option argument '%s'", option_arg);
//}
//break;
case 'a':
{
bool success;
bool result;
result = Args::StringToBoolean(option_arg, true, &success);
if (!success)
error.SetErrorStringWithFormat("invalid all-threads value setting: \"%s\"", option_arg);
else
try_all_threads = result;
}
break;
case 'i':
{
bool success;
bool tmp_value = Args::StringToBoolean(option_arg, true, &success);
if (success)
ignore_breakpoints = tmp_value;
else
error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg);
break;
}
case 't':
{
bool success;
uint32_t result;
result = StringConvert::ToUInt32(option_arg, 0, 0, &success);
if (success)
timeout = result;
else
error.SetErrorStringWithFormat ("invalid timeout setting \"%s\"", option_arg);
}
break;
case 'u':
{
bool success;
bool tmp_value = Args::StringToBoolean(option_arg, true, &success);
if (success)
unwind_on_error = tmp_value;
else
error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg);
break;
}
case 'v':
if (!option_arg)
{
m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
break;
}
m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
if (!error.Success())
error.SetErrorStringWithFormat ("unrecognized value for description-verbosity '%s'", option_arg);
break;
case 'g':
debug = true;
unwind_on_error = false;
ignore_breakpoints = false;
break;
default:
error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
break;
}
return error;
}
void
CommandObjectExpression::CommandOptions::OptionParsingStarting (CommandInterpreter &interpreter)
{
Process *process = interpreter.GetExecutionContext().GetProcessPtr();
if (process != NULL)
{
ignore_breakpoints = process->GetIgnoreBreakpointsInExpressions();
unwind_on_error = process->GetUnwindOnErrorInExpressions();
}
else
{
ignore_breakpoints = true;
unwind_on_error = true;
}
show_summary = true;
try_all_threads = true;
timeout = 0;
debug = false;
m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
}
const OptionDefinition*
CommandObjectExpression::CommandOptions::GetDefinitions ()
{
return g_option_table;
}
CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) :
CommandObjectRaw (interpreter,
"expression",
"Evaluate a C/ObjC/C++ expression in the current program context, using user defined variables and variables currently in scope.",
NULL,
eCommandProcessMustBePaused | eCommandTryTargetAPILock),
IOHandlerDelegate (IOHandlerDelegate::Completion::Expression),
m_option_group (interpreter),
m_format_options (eFormatDefault),
m_command_options (),
m_expr_line_count (0),
m_expr_lines ()
{
SetHelpLong(
R"(
Timeouts:
)" " If the expression can be evaluated statically (without running code) then it will be. \
Otherwise, by default the expression will run on the current thread with a short timeout: \
currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
and resumed with all threads running. You can use the -a option to disable retrying on all \
threads. You can use the -t option to set a shorter timeout." R"(
User defined variables:
)" " You can define your own variables for convenience or to be used in subsequent expressions. \
You define them the same way you would define variables in C. If the first character of \
your user defined variable is a $, then the variable's value will be available in future \
expressions, otherwise it will just be available in the current expression." R"(
Continuing evaluation after a breakpoint:
)" " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
you are done with your investigation, you can either remove the expression execution frames \
from the stack with \"thread return -x\" or if you are still interested in the expression result \
you can issue the \"continue\" command and the expression evaluation will complete and the \
expression result will be available using the \"thread.completed-expression\" key in the thread \
format." R"(
Examples:
expr my_struct->a = my_array[3]
expr -f bin -- (index * 8) + 5
expr unsigned int $foo = 5
expr char c[] = \"foo\"; c[0])"
);
CommandArgumentEntry arg;
CommandArgumentData expression_arg;
// Define the first (and only) variant of this arg.
expression_arg.arg_type = eArgTypeExpression;
expression_arg.arg_repetition = eArgRepeatPlain;
// There is only one variant this argument could be; put it into the argument entry.
arg.push_back (expression_arg);
// Push the data for the first argument into the m_arguments vector.
m_arguments.push_back (arg);
// Add the "--format" and "--gdb-format"
m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1);
m_option_group.Append (&m_command_options);
m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
m_option_group.Finalize();
}
CommandObjectExpression::~CommandObjectExpression ()
{
}
Options *
CommandObjectExpression::GetOptions ()
{
return &m_option_group;
}
bool
CommandObjectExpression::EvaluateExpression
(
const char *expr,
Stream *output_stream,
Stream *error_stream,
CommandReturnObject *result
)
{
// Don't use m_exe_ctx as this might be called asynchronously
// after the command object DoExecute has finished when doing
// multi-line expression that use an input reader...
ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
Target *target = exe_ctx.GetTargetPtr();
if (!target)
target = GetDummyTarget();
if (target)
{
lldb::ValueObjectSP result_valobj_sp;
bool keep_in_memory = true;
EvaluateExpressionOptions options;
options.SetCoerceToId(m_varobj_options.use_objc);
options.SetUnwindOnError(m_command_options.unwind_on_error);
options.SetIgnoreBreakpoints (m_command_options.ignore_breakpoints);
options.SetKeepInMemory(keep_in_memory);
options.SetUseDynamic(m_varobj_options.use_dynamic);
options.SetTryAllThreads(m_command_options.try_all_threads);
options.SetDebug(m_command_options.debug);
// If there is any chance we are going to stop and want to see
// what went wrong with our expression, we should generate debug info
if (!m_command_options.ignore_breakpoints ||
!m_command_options.unwind_on_error)
options.SetGenerateDebugInfo(true);
if (m_command_options.timeout > 0)
options.SetTimeoutUsec(m_command_options.timeout);
else
options.SetTimeoutUsec(0);
target->EvaluateExpression(expr, exe_ctx.GetFramePtr(),
result_valobj_sp, options);
if (result_valobj_sp)
{
Format format = m_format_options.GetFormat();
if (result_valobj_sp->GetError().Success())
{
if (format != eFormatVoid)
{
if (format != eFormatDefault)
result_valobj_sp->SetFormat (format);
DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(m_command_options.m_verbosity,format));
result_valobj_sp->Dump(*output_stream,options);
if (result)
result->SetStatus (eReturnStatusSuccessFinishResult);
}
}
else
{
if (result_valobj_sp->GetError().GetError() == ClangUserExpression::kNoResult)
{
if (format != eFormatVoid && m_interpreter.GetDebugger().GetNotifyVoid())
{
error_stream->PutCString("(void)\n");
}
if (result)
result->SetStatus (eReturnStatusSuccessFinishResult);
}
else
{
const char *error_cstr = result_valobj_sp->GetError().AsCString();
if (error_cstr && error_cstr[0])
{
const size_t error_cstr_len = strlen (error_cstr);
const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
if (strstr(error_cstr, "error:") != error_cstr)
error_stream->PutCString ("error: ");
error_stream->Write(error_cstr, error_cstr_len);
if (!ends_with_newline)
error_stream->EOL();
}
else
{
error_stream->PutCString ("error: unknown error\n");
}
if (result)
result->SetStatus (eReturnStatusFailed);
}
}
}
}
else
{
error_stream->Printf ("error: invalid execution context for expression\n");
return false;
}
return true;
}
void
CommandObjectExpression::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
{
io_handler.SetIsDone(true);
// StreamSP output_stream = io_handler.GetDebugger().GetAsyncOutputStream();
// StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
StreamFileSP output_sp(io_handler.GetOutputStreamFile());
StreamFileSP error_sp(io_handler.GetErrorStreamFile());
EvaluateExpression (line.c_str(),
output_sp.get(),
error_sp.get());
if (output_sp)
output_sp->Flush();
if (error_sp)
error_sp->Flush();
}
LineStatus
CommandObjectExpression::IOHandlerLinesUpdated (IOHandler &io_handler,
StringList &lines,
uint32_t line_idx,
Error &error)
{
if (line_idx == UINT32_MAX)
{
// Remove the last line from "lines" so it doesn't appear
// in our final expression
lines.PopBack();
error.Clear();
return LineStatus::Done;
}
else if (line_idx + 1 == lines.GetSize())
{
// The last line was edited, if this line is empty, then we are done
// getting our multiple lines.
if (lines[line_idx].empty())
return LineStatus::Done;
}
return LineStatus::Success;
}
void
CommandObjectExpression::GetMultilineExpression ()
{
m_expr_lines.clear();
m_expr_line_count = 0;
Debugger &debugger = GetCommandInterpreter().GetDebugger();
bool color_prompt = debugger.GetUseColor();
const bool multiple_lines = true; // Get multiple lines
IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
IOHandler::Type::Expression,
"lldb-expr", // Name of input reader for history
NULL, // No prompt
NULL, // Continuation prompt
multiple_lines,
color_prompt,
1, // Show line numbers starting at 1
*this));
StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile());
if (output_sp)
{
output_sp->PutCString("Enter expressions, then terminate with an empty line to evaluate:\n");
output_sp->Flush();
}
debugger.PushIOHandler(io_handler_sp);
}
bool
CommandObjectExpression::DoExecute
(
const char *command,
CommandReturnObject &result
)
{
m_option_group.NotifyOptionParsingStarting();
const char * expr = NULL;
if (command[0] == '\0')
{
GetMultilineExpression ();
return result.Succeeded();
}
if (command[0] == '-')
{
// We have some options and these options MUST end with --.
const char *end_options = NULL;
const char *s = command;
while (s && s[0])
{
end_options = ::strstr (s, "--");
if (end_options)
{
end_options += 2; // Get past the "--"
if (::isspace (end_options[0]))
{
expr = end_options;
while (::isspace (*expr))
++expr;
break;
}
}
s = end_options;
}
if (end_options)
{
Args args (llvm::StringRef(command, end_options - command));
if (!ParseOptions (args, result))
return false;
Error error (m_option_group.NotifyOptionParsingFinished());
if (error.Fail())
{
result.AppendError (error.AsCString());
result.SetStatus (eReturnStatusFailed);
return false;
}
// No expression following options
if (expr == NULL || expr[0] == '\0')
{
GetMultilineExpression ();
return result.Succeeded();
}
}
}
if (expr == NULL)
expr = command;
if (EvaluateExpression (expr, &(result.GetOutputStream()), &(result.GetErrorStream()), &result))
return true;
result.SetStatus (eReturnStatusFailed);
return false;
}
| 36.24283 | 319 | 0.602427 | androm3da |
1be1ddd7427e434a9ec342b97fe50659291aa67d | 8,077 | cpp | C++ | implementations/ugene/src/plugins/workflow_designer/src/library/SequenceQualityTrimWorker.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/workflow_designer/src/library/SequenceQualityTrimWorker.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/workflow_designer/src/library/SequenceQualityTrimWorker.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "SequenceQualityTrimWorker.h"
#include <U2Designer/DelegateEditors.h>
#include <U2Lang/ActorPrototypeRegistry.h>
#include <U2Lang/BaseActorCategories.h>
#include <U2Lang/BasePorts.h>
#include <U2Lang/BaseSlots.h>
#include <U2Lang/BaseTypes.h>
#include <U2Lang/WorkflowContext.h>
#include <U2Lang/WorkflowEnv.h>
#include <U2Lang/WorkflowMonitor.h>
#include "tasks/SequenceQualityTrimTask.h"
namespace U2 {
namespace LocalWorkflow {
static const QString QUALITY_ID("qual-id");
static const QString LEN_ID("len-id");
static const QString BOTH_ID("both-ends");
SequenceQualityTrimPrompter::SequenceQualityTrimPrompter(Actor *actor)
: SequenceQualityTrimBase(actor) {
}
QString SequenceQualityTrimPrompter::composeRichDoc() {
IntegralBusPort *input = qobject_cast<IntegralBusPort *>(target->getPort(BasePorts::IN_SEQ_PORT_ID()));
const Actor *producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId());
const QString unsetStr = "<font color='red'>" + tr("unset") + "</font>";
const QString producerName = tr("from <u>%1</u>").arg(producer ? producer->getLabel() : unsetStr);
const QString trimSide = getHyperlink(BOTH_ID, tr(getParameter(BOTH_ID).toBool() ? "the both ends" : "the end"));
return tr("Trim input sequence %1 from %2, using the quality threshold.").arg(producerName).arg(trimSide);
}
SequenceQualityTrimWorker::SequenceQualityTrimWorker(Actor *actor)
: BaseThroughWorker(actor, BasePorts::IN_SEQ_PORT_ID(), BasePorts::OUT_SEQ_PORT_ID()) {
}
Task *SequenceQualityTrimWorker::createTask(const Message &message, U2OpStatus &os) {
SequenceQualityTrimTaskSettings settings;
settings.qualityTreshold = getValue<int>(QUALITY_ID);
settings.minSequenceLength = getValue<int>(LEN_ID);
settings.trimBothEnds = getValue<bool>(BOTH_ID);
const QVariantMap dataMap = message.getData().toMap();
const SharedDbiDataHandler sequenceHandler = dataMap[BaseSlots::DNA_SEQUENCE_SLOT().getId()].value<SharedDbiDataHandler>();
settings.sequenceObject = StorageUtils::getSequenceObject(context->getDataStorage(), sequenceHandler);
CHECK_EXT(NULL != settings.sequenceObject, os.setError(tr("There is no sequence object in the message")), NULL);
return new SequenceQualityTrimTask(settings);
}
QList<Message> SequenceQualityTrimWorker::fetchResult(Task *task, U2OpStatus &os) {
QList<Message> messages;
SequenceQualityTrimTask *trimTask = qobject_cast<SequenceQualityTrimTask *>(task);
SAFE_POINT_EXT(NULL != trimTask, os.setError(tr("An unexpected task type")), messages);
QScopedPointer<U2SequenceObject> trimmedSequenceObject(trimTask->takeTrimmedSequence());
SAFE_POINT_EXT(NULL != trimmedSequenceObject, os.setError("Sequence trim task didn't produce any object without any errors"), messages);
if (0 == trimmedSequenceObject->getSequenceLength()) {
monitor()->addError(tr("Sequence was filtered out by quality"), actor->getId(), WorkflowNotification::U2_WARNING);
return messages;
}
SharedDbiDataHandler trimmedSequenceHandler = context->getDataStorage()->putSequence(trimmedSequenceObject.data());
QVariantMap data;
data[BaseSlots::DNA_SEQUENCE_SLOT().getId()] = QVariant::fromValue<SharedDbiDataHandler>(trimmedSequenceHandler);
messages << Message(output->getBusType(), data);
return messages;
}
const QString SequenceQualityTrimWorkerFactory::ACTOR_ID = "SequenceQualityTrim";
SequenceQualityTrimWorkerFactory::SequenceQualityTrimWorkerFactory()
: DomainFactory(ACTOR_ID) {
}
void SequenceQualityTrimWorkerFactory::init() {
Descriptor desc(ACTOR_ID, SequenceQualityTrimWorker::tr("Sequence Quality Trimmer"), SequenceQualityTrimWorker::tr("The workflow scans each input sequence from the end to find the first position where the quality is greater or equal to the minimum quality threshold. "
"Then it trims the sequence to that position. If a the whole sequence has quality less than the threshold or the length of the output sequence less than "
"the minimum length threshold then the sequence is skipped."));
QList<PortDescriptor *> ports;
{
Descriptor inPortDescriptor(BasePorts::IN_SEQ_PORT_ID(), SequenceQualityTrimWorker::tr("Input Sequence"), SequenceQualityTrimWorker::tr("Set of sequences to trim by quality"));
Descriptor outPortDescriptor(BasePorts::OUT_SEQ_PORT_ID(), SequenceQualityTrimWorker::tr("Output Sequence"), SequenceQualityTrimWorker::tr("Trimmed sequences"));
QMap<Descriptor, DataTypePtr> inSlot;
inSlot[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE();
DataTypePtr inType(new MapDataType(BasePorts::IN_SEQ_PORT_ID(), inSlot));
ports << new PortDescriptor(inPortDescriptor, inType, true);
QMap<Descriptor, DataTypePtr> outM;
outM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE();
DataTypePtr outType(new MapDataType(BasePorts::OUT_SEQ_PORT_ID(), inSlot));
ports << new PortDescriptor(outPortDescriptor, outType, false, true);
}
QList<Attribute *> attributes;
{
Descriptor qualityTreshold(QUALITY_ID, SequenceQualityTrimWorker::tr("Trimming quality threshold"), SequenceQualityTrimWorker::tr("Quality threshold for trimming."));
Descriptor minSequenceLength(LEN_ID, SequenceQualityTrimWorker::tr("Min length"), SequenceQualityTrimWorker::tr("Too short reads are discarded by the filter."));
Descriptor trimBothEnds(BOTH_ID, SequenceQualityTrimWorker::tr("Trim both ends"), SequenceQualityTrimWorker::tr("Trim the both ends of a read or not. Usually, you need to set <b>True</b> for <b>Sanger</b> sequencing and <b>False</b> for <b>NGS</b>"));
attributes << new Attribute(qualityTreshold, BaseTypes::NUM_TYPE(), false, QVariant(30));
attributes << new Attribute(minSequenceLength, BaseTypes::NUM_TYPE(), false, QVariant(0));
attributes << new Attribute(trimBothEnds, BaseTypes::BOOL_TYPE(), false, true);
}
QMap<QString, PropertyDelegate *> delegates;
{
QVariantMap intLimitsMap;
intLimitsMap["minimum"] = 0;
intLimitsMap["maximum"] = INT_MAX;
delegates[QUALITY_ID] = new SpinBoxDelegate(intLimitsMap);
delegates[LEN_ID] = new SpinBoxDelegate(intLimitsMap);
delegates[BOTH_ID] = new ComboBoxWithBoolsDelegate();
}
ActorPrototype *proto = new IntegralBusActorPrototype(desc, ports, attributes);
proto->setEditor(new DelegateEditor(delegates));
proto->setPrompter(new SequenceQualityTrimPrompter());
WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto);
DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID);
localDomain->registerEntry(new SequenceQualityTrimWorkerFactory());
}
Worker *SequenceQualityTrimWorkerFactory::createWorker(Actor *actor) {
return new SequenceQualityTrimWorker(actor);
}
} // namespace LocalWorkflow
} // namespace U2
| 50.48125 | 273 | 0.727622 | r-barnes |
1be347460691edb89bcfb1828ef9927d59a3cd21 | 4,052 | cpp | C++ | src/main.cpp | Bolukan/AOC2019 | d91f8ba22cb5f4a08528e6087b15d87170f9f267 | [
"MIT"
] | null | null | null | src/main.cpp | Bolukan/AOC2019 | d91f8ba22cb5f4a08528e6087b15d87170f9f267 | [
"MIT"
] | null | null | null | src/main.cpp | Bolukan/AOC2019 | d91f8ba22cb5f4a08528e6087b15d87170f9f267 | [
"MIT"
] | null | null | null | #include <Arduino.h>
// WiFi
#include <ESP8266WiFi.h>
#include "secrets.h"
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <FS.h>
#include <dayAOC201901.h>
#define APP_NAME "Advent of Code 2019"
#define FILENAME "/input201901"
// wifi
#ifndef SECRETS_H
#define SECRETS_H
const char WIFI_SSID[] = "*** WIFI SSID ***";
const char WIFI_PASSWORD[] = "*** WIFI PASSWORD ***";
#endif
// ************************************ FUNCTION *******************************
// *********************************** WIFI **********************************
// More events: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.h
void onSTAConnected(WiFiEventStationModeConnected e /*String ssid, uint8 bssid[6], uint8 channel*/)
{
Serial.printf("WiFi Connected: SSID %s @ BSSID %.2X:%.2X:%.2X:%.2X:%.2X:%.2X Channel %d\n",
e.ssid.c_str(), e.bssid[0], e.bssid[1], e.bssid[2], e.bssid[3], e.bssid[4], e.bssid[5], e.channel);
}
void onSTADisconnected(WiFiEventStationModeDisconnected e /*String ssid, uint8 bssid[6], WiFiDisconnectReason reason*/)
{
Serial.printf("WiFi Disconnected: SSID %s BSSID %.2X:%.2X:%.2X:%.2X:%.2X:%.2X Reason %d\n",
e.ssid.c_str(), e.bssid[0], e.bssid[1], e.bssid[2], e.bssid[3], e.bssid[4], e.bssid[5], e.reason);
// Reason: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiType.h
}
void onSTAGotIP(WiFiEventStationModeGotIP e /*IPAddress ip, IPAddress mask, IPAddress gw*/)
{
Serial.printf("WiFi GotIP: localIP %s SubnetMask %s GatewayIP %s\n",
e.ip.toString().c_str(), e.mask.toString().c_str(), e.gw.toString().c_str());
}
void SetupWiFi()
{
static WiFiEventHandler e1, e2, e4;
// WiFi events
e1 = WiFi.onStationModeConnected(onSTAConnected);
e2 = WiFi.onStationModeDisconnected(onSTADisconnected);
e4 = WiFi.onStationModeGotIP(onSTAGotIP);
WiFi.mode(WIFI_STA);
WiFi.setAutoConnect(false); // do not automatically connect on power on to the last used access point
WiFi.setAutoReconnect(true); // attempt to reconnect to an access point in case it is disconnected
WiFi.persistent(false); // Store no SSID/PASSWORD in flash
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
// *********************************** OTA ***********************************
void OTAonStart()
{
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
{
type = "sketch";
}
else
{ // U_SPIFFS
type = "filesystem";
}
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("OTA Start. Type: " + type);
}
void OTAonEnd()
{
Serial.println("\nOTA End");
}
void OTAonProgress(unsigned int progress, unsigned int total)
{
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
};
void OTAonError(ota_error_t error)
{
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
{
Serial.println("Auth Failed");
}
else if (error == OTA_BEGIN_ERROR)
{
Serial.println("Begin Failed");
}
else if (error == OTA_CONNECT_ERROR)
{
Serial.println("Connect Failed");
}
else if (error == OTA_RECEIVE_ERROR)
{
Serial.println("Receive Failed");
}
else if (error == OTA_END_ERROR)
{
Serial.println("End Failed");
}
};
void SetupOTA()
{
char hostname[12];
sprintf(hostname, "esp-%06x", ESP.getChipId());
ArduinoOTA.setHostname(hostname);
ArduinoOTA.onStart(OTAonStart);
ArduinoOTA.onEnd(OTAonEnd);
ArduinoOTA.onProgress(OTAonProgress);
ArduinoOTA.onError(OTAonError);
ArduinoOTA.begin();
}
// *********************************** ... ***********************************
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println(APP_NAME);
SetupWiFi();
SetupOTA();
DayAOC201901 day(FILENAME);
day.Part1();
day.Part2();
}
void loop()
{
ArduinoOTA.handle();
} | 27.753425 | 120 | 0.606367 | Bolukan |
1be4982b0eadd62cf3383db7ab05562de1ffb1a1 | 857 | hpp | C++ | tsplp/src/SeparationAlgorithms.hpp | sebrockm/mtsp-vrp | 28955855d253f51fcb9397a0b22c6774f66f8d55 | [
"MIT"
] | null | null | null | tsplp/src/SeparationAlgorithms.hpp | sebrockm/mtsp-vrp | 28955855d253f51fcb9397a0b22c6774f66f8d55 | [
"MIT"
] | null | null | null | tsplp/src/SeparationAlgorithms.hpp | sebrockm/mtsp-vrp | 28955855d253f51fcb9397a0b22c6774f66f8d55 | [
"MIT"
] | null | null | null | #pragma once
#include <optional>
#include <xtensor/xtensor.hpp>
namespace tsplp
{
class LinearConstraint;
class Model;
class Variable;
class WeightManager;
}
namespace tsplp::graph
{
class PiSigmaSupportGraph;
class Separator
{
private:
const xt::xtensor<Variable, 3>& m_variables;
const WeightManager& m_weightManager;
const Model& m_model;
std::unique_ptr<PiSigmaSupportGraph> m_spSupportGraph;
public:
Separator(const xt::xtensor<Variable, 3>& variables, const WeightManager& weightManager, const Model& model);
~Separator() noexcept;
std::optional<LinearConstraint> Ucut() const;
std::optional<LinearConstraint> Pi() const;
std::optional<LinearConstraint> Sigma() const;
std::optional<LinearConstraint> PiSigma() const;
};
}
| 22.552632 | 117 | 0.673279 | sebrockm |
1be6cdd8ac8092889e8379ea5bbcdc540a73b2c6 | 4,960 | cc | C++ | chrome/browser/enterprise/connectors/enterprise_connectors_policy_handler_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/enterprise/connectors/enterprise_connectors_policy_handler_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/enterprise/connectors/enterprise_connectors_policy_handler_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 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 "chrome/browser/enterprise/connectors/enterprise_connectors_policy_handler.h"
#include <memory>
#include <tuple>
#include "base/json/json_reader.h"
#include "base/values.h"
#include "components/policy/core/browser/policy_error_map.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/core/common/schema.h"
#include "components/prefs/pref_value_map.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace enterprise_connectors {
namespace {
const char kTestPref[] = "enterprise_connectors.test_pref";
const char kTestScopePref[] = "enterprise_connectors.scope.test_pref";
const char kPolicyName[] = "PolicyForTesting";
const char kSchema[] = R"(
{
"type": "object",
"properties": {
"PolicyForTesting": {
"type": "array",
"items": {
"type": "object",
"properties": {
"service_provider": { "type": "string" },
"enable": { "type": "boolean" },
}
}
}
}
})";
constexpr char kEmptyPolicy[] = "";
constexpr char kValidPolicy[] = R"(
[
{
"service_provider": "Google",
"enable": true,
},
{
"service_provider": "Alphabet",
"enable": false,
},
])";
// The enable field should be an boolean instead of a string.
constexpr char kInvalidPolicy[] = R"(
[
{
"service_provider": "Google",
"enable": "yes",
},
{
"service_provider": "Alphabet",
"enable": "no",
},
])";
} // namespace
class EnterpriseConnectorsPolicyHandlerTest
: public testing::TestWithParam<
std::tuple<const char*, const char*, policy::PolicySource>> {
public:
const char* policy_scope() const { return std::get<0>(GetParam()); }
const char* policy() const { return std::get<1>(GetParam()); }
policy::PolicySource source() const { return std::get<2>(GetParam()); }
bool expect_valid_policy() const {
if (policy() == kEmptyPolicy)
return true;
if (policy() == kInvalidPolicy)
return false;
return (source() == policy::PolicySource::POLICY_SOURCE_CLOUD ||
source() == policy::PolicySource::POLICY_SOURCE_PRIORITY_CLOUD);
}
absl::optional<base::Value> policy_value() const {
return base::JSONReader::Read(policy(), base::JSON_ALLOW_TRAILING_COMMAS);
}
};
TEST_P(EnterpriseConnectorsPolicyHandlerTest, Test) {
std::string error;
policy::Schema validation_schema = policy::Schema::Parse(kSchema, &error);
ASSERT_TRUE(error.empty());
policy::PolicyMap policy_map;
if (policy() != kEmptyPolicy) {
policy_map.Set(kPolicyName, policy::PolicyLevel::POLICY_LEVEL_MANDATORY,
policy::PolicyScope::POLICY_SCOPE_MACHINE, source(),
policy_value(), nullptr);
}
auto handler = std::make_unique<EnterpriseConnectorsPolicyHandler>(
kPolicyName, kTestPref, policy_scope(), validation_schema);
policy::PolicyErrorMap errors;
ASSERT_EQ(expect_valid_policy(),
handler->CheckPolicySettings(policy_map, &errors));
ASSERT_EQ(expect_valid_policy(), errors.empty());
// Apply the pref and check it matches the policy.
// Real code will not call ApplyPolicySettings if CheckPolicySettings returns
// false, this is just to test that it applies the pref correctly.
PrefValueMap prefs;
base::Value* value_set_in_pref;
int pref_scope = -1;
handler->ApplyPolicySettings(policy_map, &prefs);
bool policy_is_set = policy() != kEmptyPolicy;
ASSERT_EQ(policy_is_set, prefs.GetValue(kTestPref, &value_set_in_pref));
if (policy_scope())
EXPECT_EQ(policy_is_set, prefs.GetInteger(policy_scope(), &pref_scope));
auto* value_set_in_map = policy_map.GetValue(kPolicyName);
if (value_set_in_map) {
ASSERT_TRUE(value_set_in_map->Equals(value_set_in_pref));
if (policy_scope())
ASSERT_EQ(policy::POLICY_SCOPE_MACHINE, pref_scope);
} else {
ASSERT_FALSE(policy_is_set);
if (policy_scope())
ASSERT_EQ(-1, pref_scope);
}
}
INSTANTIATE_TEST_SUITE_P(
EnterpriseConnectorsPolicyHandlerTest,
EnterpriseConnectorsPolicyHandlerTest,
testing::Combine(
testing::Values(kTestScopePref, nullptr),
testing::Values(kValidPolicy, kInvalidPolicy, kEmptyPolicy),
testing::Values(policy::PolicySource::POLICY_SOURCE_CLOUD,
policy::PolicySource::POLICY_SOURCE_PRIORITY_CLOUD,
policy::PolicySource::POLICY_SOURCE_ACTIVE_DIRECTORY,
policy::PolicySource::POLICY_SOURCE_PLATFORM)));
} // namespace enterprise_connectors
| 31.794872 | 86 | 0.66875 | DamieFC |
1be9fb8cdf4ef9e9008a81d432a2df01e0cc1b24 | 1,909 | hpp | C++ | test/common/mocks_provider.hpp | modern-cpp-examples/match3 | bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e | [
"BSL-1.0"
] | 166 | 2016-04-27T19:01:00.000Z | 2022-03-27T02:16:55.000Z | test/common/mocks_provider.hpp | Fuyutsubaki/match3 | bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e | [
"BSL-1.0"
] | 4 | 2016-05-19T07:47:38.000Z | 2018-03-22T04:33:00.000Z | test/common/mocks_provider.hpp | Fuyutsubaki/match3 | bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e | [
"BSL-1.0"
] | 17 | 2016-05-18T21:17:39.000Z | 2022-03-20T22:37:14.000Z | //
// Copyright (c) 2016 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include <boost/di.hpp>
#include <type_traits>
#include "fakeit.hpp"
namespace di = boost::di;
template <class T>
auto& mock(bool reset = true) {
using namespace fakeit;
static Mock<T> mock;
if (reset) {
mock.Reset();
}
When(Dtor(mock)).AlwaysDo([] {});
return mock;
}
struct mocks_provider : di::config {
struct mock_provider {
template <class...>
struct is_creatable {
static constexpr auto value = true;
};
template <class T, class... TArgs>
auto get(const di::type_traits::direct&, const di::type_traits::heap&,
TArgs&&... args) {
return new T(static_cast<TArgs&&>(args)...);
}
template <class T, class... TArgs>
std::enable_if_t<!std::is_polymorphic<T>::value, T*> get(
const di::type_traits::uniform&, const di::type_traits::heap&,
TArgs&&... args) {
return new T{static_cast<TArgs&&>(args)...};
}
template <class T, class... TArgs>
std::enable_if_t<std::is_polymorphic<T>::value, T*> get(
const di::type_traits::uniform&, const di::type_traits::heap&,
TArgs&&...) {
return &mock<T>(false).get();
}
template <class T, class... TArgs>
auto get(const di::type_traits::direct&, const di::type_traits::stack&,
TArgs&&... args) const noexcept {
return T(static_cast<TArgs&&>(args)...);
}
template <class T, class... TArgs>
auto get(const di::type_traits::uniform&, const di::type_traits::stack&,
TArgs&&... args) const noexcept {
return T{static_cast<TArgs&&>(args)...};
}
};
public:
static auto provider(...) noexcept { return mock_provider{}; }
};
| 27.666667 | 76 | 0.618125 | modern-cpp-examples |
1bebc60678a7df62e258a4a942cda60163b19e37 | 344 | hpp | C++ | src/AI/AiCommand.hpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | src/AI/AiCommand.hpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | src/AI/AiCommand.hpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | #pragma once
enum CommandType
{
MoveTo,
Attack
};
struct AiCommand
{
CommandType type;
bool suspendOther;
bool queue;
void* payload;
template<typename T>
T& get() {
return *reinterpret_cast<T*>(payload);
}
};
struct MoveCommand
{
glm::vec4 position;
std::optional<glm::vec4> direction;
};
| 13.230769 | 46 | 0.619186 | LazyFalcon |
1bed0766c3c232027c11a0df8ffd1e1746b92b59 | 6,647 | cpp | C++ | examples/2-show-carriers/2-show-carriers.cpp | particle-iot/CellularHelper | c395735a7d47ab4750adc6b58ca40fec6dfc9e64 | [
"MIT"
] | 2 | 2020-04-28T13:24:03.000Z | 2020-05-22T14:40:46.000Z | examples/2-show-carriers/2-show-carriers.cpp | particle-iot/CellularHelper | c395735a7d47ab4750adc6b58ca40fec6dfc9e64 | [
"MIT"
] | null | null | null | examples/2-show-carriers/2-show-carriers.cpp | particle-iot/CellularHelper | c395735a7d47ab4750adc6b58ca40fec6dfc9e64 | [
"MIT"
] | 1 | 2022-01-05T16:48:29.000Z | 2022-01-05T16:48:29.000Z | #include "Particle.h"
#include "CellularHelper.h"
// STARTUP(cellular_credentials_set("epc.tmobile.com", "", "", NULL));
SYSTEM_MODE(MANUAL);
SYSTEM_THREAD(ENABLED);
SerialLogHandler logHandler;
const unsigned long STARTUP_WAIT_TIME_MS = 4000;
const unsigned long MODEM_ON_WAIT_TIME_MS = 4000;
// Forward declarations
void cellularScan();
void buttonHandler(system_event_t event, int data);
enum State {
STARTUP_WAIT_STATE,
MODEM_ON_STATE,
MODEM_ON_WAIT_STATE,
RUN_TEST_STATE,
COPS_STATE,
DONE_STATE,
IDLE_WAIT_STATE
};
State state = STARTUP_WAIT_STATE;
unsigned long stateTime = 0;
bool buttonClicked = false;
CellularHelperEnvironmentResponseStatic<32> envResp;
void setup() {
Serial.begin(9600);
System.on(button_click, buttonHandler);
}
void loop() {
switch(state) {
case STARTUP_WAIT_STATE:
// This delay is to give you time to connect to the serial port
if (millis() - stateTime >= STARTUP_WAIT_TIME_MS) {
stateTime = millis();
state = MODEM_ON_STATE;
}
break;
case MODEM_ON_STATE:
buttonClicked = false;
Serial.println("turning on modem...");
Cellular.on();
state = MODEM_ON_WAIT_STATE;
stateTime = millis();
break;
case MODEM_ON_WAIT_STATE:
// In system threaded mode you need to wait a little while after turning on the
// cellular mode before it will respond. That's what MODEM_ON_WAIT_TIME_MS is for.
if (millis() - stateTime >= MODEM_ON_WAIT_TIME_MS) {
state = RUN_TEST_STATE;
stateTime = millis();
break;
}
break;
case RUN_TEST_STATE:
cellularScan();
state = DONE_STATE;
break;
case COPS_STATE:
break;
case DONE_STATE:
Serial.println("tests complete!");
Serial.println("press the MODE button to repeat test");
buttonClicked = false;
state = IDLE_WAIT_STATE;
break;
case IDLE_WAIT_STATE:
if (buttonClicked) {
buttonClicked = false;
state = RUN_TEST_STATE;
}
break;
}
}
class OperatorName {
public:
int mcc;
int mnc;
String name;
};
class CellularHelperCOPNResponse : public CellularHelperCommonResponse {
public:
CellularHelperCOPNResponse();
void requestOperator(CellularHelperEnvironmentCellData *data);
void requestOperator(int mcc, int mnc);
void checkOperator(char *buf);
const char *getOperatorName(int mcc, int mnc) const;
virtual int parse(int type, const char *buf, int len);
// Maximum number of operator names that can be looked up
static const size_t MAX_OPERATORS = 16;
private:
size_t numOperators;
OperatorName operators[MAX_OPERATORS];
};
CellularHelperCOPNResponse copnResp;
CellularHelperCOPNResponse::CellularHelperCOPNResponse() : numOperators(0) {
}
void CellularHelperCOPNResponse::requestOperator(CellularHelperEnvironmentCellData *data) {
if (data && data->isValid(true)) {
requestOperator(data->mcc, data->mnc);
}
}
void CellularHelperCOPNResponse::requestOperator(int mcc, int mnc) {
for(size_t ii = 0; ii < numOperators; ii++) {
if (operators[ii].mcc == mcc && operators[ii].mnc == mnc) {
// Already requested
return;
}
}
if (numOperators < MAX_OPERATORS) {
// There is room to request another
operators[numOperators].mcc = mcc;
operators[numOperators].mnc = mnc;
numOperators++;
}
}
const char *CellularHelperCOPNResponse::getOperatorName(int mcc, int mnc) const {
for(size_t ii = 0; ii < numOperators; ii++) {
if (operators[ii].mcc == mcc && operators[ii].mnc == mnc) {
return operators[ii].name.c_str();
}
}
return "unknown";
}
void CellularHelperCOPNResponse::checkOperator(char *buf) {
if (buf[0] == '"') {
char *numStart = &buf[1];
char *numEnd = strchr(numStart, '"');
if (numEnd && ((numEnd - numStart) == 6)) {
char temp[4];
temp[3] = 0;
strncpy(temp, numStart, 3);
int mcc = atoi(temp);
strncpy(temp, numStart + 3, 3);
int mnc = atoi(temp);
*numEnd = 0;
char *nameStart = strchr(numEnd + 1, '"');
if (nameStart) {
nameStart++;
char *nameEnd = strchr(nameStart, '"');
if (nameEnd) {
*nameEnd = 0;
// Log.info("mcc=%d mnc=%d name=%s", mcc, mnc, nameStart);
for(size_t ii = 0; ii < numOperators; ii++) {
if (operators[ii].mcc == mcc && operators[ii].mnc == mnc) {
operators[ii].name = String(nameStart);
}
}
}
}
}
}
}
int CellularHelperCOPNResponse::parse(int type, const char *buf, int len) {
if (enableDebug) {
logCellularDebug(type, buf, len);
}
if (type == TYPE_PLUS) {
// Copy to temporary string to make processing easier
char *copy = (char *) malloc(len + 1);
if (copy) {
strncpy(copy, buf, len);
copy[len] = 0;
/*
0000018684 [app] INFO: +COPN: "901012","MCP Maritime Com"\r\n
0000018694 [app] INFO: cellular response type=TYPE_PLUS len=28
0000018694 [app] INFO: \r\n
0000018695 [app] INFO: +COPN: "901021","Seanet"\r\n
0000018705 [app] INFO: cellular response type=TYPE_ERROR len=39
0000018705 [app] INFO: \r\n
*
*/
char *start = strstr(copy, "\n+COPN: ");
if (start) {
start += 8; // length of COPN string
char *end = strchr(start, '\r');
if (end) {
*end = 0;
checkOperator(start);
}
}
free(copy);
}
}
return WAIT;
}
void printCellData(CellularHelperEnvironmentCellData *data) {
const char *whichG = data->isUMTS ? "3G" : "2G";
// Log.info("mcc=%d mnc=%d", data->mcc, data->mnc);
const char *operatorName = copnResp.getOperatorName(data->mcc, data->mnc);
Serial.printlnf("%s %s %s %d bars (%03d%03d)", whichG, operatorName, data->getBandString().c_str(), data->getBars(), data->mcc, data->mnc);
}
void cellularScan() {
Log.info("starting cellular scan...");
// envResp.enableDebug = true;
envResp.clear();
// Command may take up to 3 minutes to execute!
envResp.resp = Cellular.command(CellularHelperClass::responseCallback, (void *)&envResp, 360000, "AT+COPS=5\r\n");
if (envResp.resp == RESP_OK) {
envResp.logResponse();
copnResp.requestOperator(&envResp.service);
if (envResp.neighbors) {
for(size_t ii = 0; ii < envResp.numNeighbors; ii++) {
copnResp.requestOperator(&envResp.neighbors[ii]);
}
}
}
Log.info("looking up operator names...");
copnResp.enableDebug = false;
copnResp.resp = Cellular.command(CellularHelperClass::responseCallback, (void *)&copnResp, 120000, "AT+COPN\r\n");
Log.info("results...");
printCellData(&envResp.service);
if (envResp.neighbors) {
for(size_t ii = 0; ii < envResp.numNeighbors; ii++) {
if (envResp.neighbors[ii].isValid(true /* ignoreCI */)) {
printCellData(&envResp.neighbors[ii]);
}
}
}
}
void buttonHandler(system_event_t event, int param) {
// int clicks = system_button_clicks(param);
buttonClicked = true;
}
| 23.824373 | 140 | 0.680307 | particle-iot |
1bed7e425a3971ebb71336be68d9b8cf6f818c1c | 165 | hpp | C++ | C++/1_SimUDuck/include/quackBehaviours/muteQuack.hpp | laissezfaireisfair/Pieces-of-code | 9dfaafe0078fdbe270bead56b4c9d0be33224561 | [
"Unlicense"
] | null | null | null | C++/1_SimUDuck/include/quackBehaviours/muteQuack.hpp | laissezfaireisfair/Pieces-of-code | 9dfaafe0078fdbe270bead56b4c9d0be33224561 | [
"Unlicense"
] | null | null | null | C++/1_SimUDuck/include/quackBehaviours/muteQuack.hpp | laissezfaireisfair/Pieces-of-code | 9dfaafe0078fdbe270bead56b4c9d0be33224561 | [
"Unlicense"
] | null | null | null | #pragma once
#include "../quackBehaviour.hpp"
namespace SimUDuck {
class MuteQuack : public QuackBehaviour {
public:
std::string quack() const;
};
}
| 13.75 | 42 | 0.666667 | laissezfaireisfair |
1bedbfdd17c5c9da87d429603df9d057ba5a66cd | 2,843 | cpp | C++ | Hackerrank/Contest/IIITV_STR()/palindrome_love.cpp | ritwik1503/Competitive-Coding-1 | ffefe5f8b299c623af1ef01bf024af339401de0b | [
"MIT"
] | 29 | 2016-09-02T04:48:59.000Z | 2016-09-08T18:13:05.000Z | Hackerrank/Contest/IIITV_STR()/palindrome_love.cpp | ritwik1503/Competitive-Coding-1 | ffefe5f8b299c623af1ef01bf024af339401de0b | [
"MIT"
] | 2 | 2016-09-02T05:20:02.000Z | 2016-10-13T06:31:31.000Z | Hackerrank/Contest/IIITV_STR()/palindrome_love.cpp | ritwik1503/Competitive-Coding-1 | ffefe5f8b299c623af1ef01bf024af339401de0b | [
"MIT"
] | 7 | 2017-04-01T20:07:03.000Z | 2020-10-16T12:28:54.000Z | #include "bits/stdc++.h"
using namespace std;
# define s(n) scanf("%d",&n)
# define sc(n) scanf("%c",&n)
# define sl(n) scanf("%lld",&n)
# define sf(n) scanf("%lf",&n)
# define ss(n) scanf("%s",n)
#define R(i,n) for(int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<=(b);i++)
#define FORD(i,a,b) for(int i=(a);i>=(b);i--)
# define INF (int)1e9
# define EPS 1e-9
# define MOD 1000000007
typedef long long ll;
int oneDigit(int num)
{
// comparison operation is faster than division operation.
// So using following instead of "return num / 10 == 0;"
return (num >= 0 && num < 10);
}
// A recursive function to find out whether num is palindrome
// or not. Initially, dupNum contains address of a copy of num.
bool isPalUtil(int num, int* dupNum)
{
// Base case (needed for recursion termination): This statement
// mainly compares the first digit with the last digit
if (oneDigit(num))
return (num == (*dupNum) % 10);
// This is the key line in this method. Note that all recursive
// calls have a separate copy of num, but they all share same copy
// of *dupNum. We divide num while moving up the recursion tree
if (!isPalUtil(num/10, dupNum))
return false;
// The following statements are executed when we move up the
// recursion call tree
*dupNum /= 10;
// At this point, if num%10 contains i'th digit from beiginning,
// then (*dupNum)%10 contains i'th digit from end
return (num % 10 == (*dupNum) % 10);
}
// The main function that uses recursive function isPalUtil() to
// find out whether num is palindrome or not
int isPal(int num)
{
// If num is negative, make it positive
if (num < 0)
num = -num;
// Create a separate copy of num, so that modifications made
// to address dupNum don't change the input number.
int *dupNum = new int(num); // *dupNum = num
return isPalUtil(num, dupNum);
}
int main()
{
int t;
cin >> t;
int a[100000],b[100000];
while(t--){
int n,m,c;
fill_n(a,100000,0);
fill_n(b,100000,0);
vector<int> v,v1;
int max_a=0,max_b=0;
s(n);
R(i,n){
s(c);
max_a=max(c,max_a);
a[c]++;
}
s(m);
R(i,m){
s(c);
//max_b=max(c,max_b);
b[c]++;
}
int sum=0;
R(i,max_a+1){
if(a[i]>0 && b[i]>0){
v1.push_back(i);
}
}
int j=0,sum2=0;
//printf("%d\n",sum );
if(v1.size()==0){
printf("EMPTY\n");
continue;
} else {
//printf("%d\n",v1[(v1.size()-1)/2]);
if(isPal(v1[(v1.size()-1)/2])){
printf("SORRY\n");
} else {
printf("%d\n",v1[(v1.size()-1)/2]);
}
}
}
return 0;
}
| 24.508621 | 70 | 0.545199 | ritwik1503 |
1beee6b9375aa78b60825afe6ce08e2b9e610a0c | 8,716 | cpp | C++ | src/tool/cppwinrt/test/out_params.cpp | stephenatwork/xlang | 0747c3b362c02a9736b3a4ca1bd3e005b4f52279 | [
"MIT"
] | 1 | 2020-01-20T07:56:28.000Z | 2020-01-20T07:56:28.000Z | test/test/out_params.cpp | shinsetsu/cppwinrt | ae0378373d2318d91448b8697a91d5b65a1fb2e5 | [
"MIT"
] | null | null | null | test/test/out_params.cpp | shinsetsu/cppwinrt | ae0378373d2318d91448b8697a91d5b65a1fb2e5 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "winrt/test_component.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace test_component;
namespace
{
struct Stringable : implements<Stringable, IStringable>
{
hstring ToString()
{
return L"Stringable";
}
};
}
TEST_CASE("out_params")
{
Class object;
{
int value;
object.OutInt32(value);
REQUIRE(value == 123);
}
{
hstring value = L"replace";
object.OutString(value);
REQUIRE(value == L"123");
}
{
IInspectable value = make<Stringable>();
object.OutObject(value);
REQUIRE(value.as<IStringable>().ToString() == L"123");
}
{
IStringable value = make<Stringable>();
object.OutStringable(value);
REQUIRE(value.ToString() == L"123");
}
{
Struct value{ L"First", L"Second" };
object.OutStruct(value);
REQUIRE(value.First == L"1");
REQUIRE(value.Second == L"2");
}
{
Signed value;
object.OutEnum(value);
REQUIRE(value == Signed::First);
}
{
com_array<int32_t> value(10);
object.OutInt32Array(value);
REQUIRE(value.size() == 3);
REQUIRE(value[0] == 1);
REQUIRE(value[1] == 2);
REQUIRE(value[2] == 3);
}
{
com_array<hstring> value(10);
object.OutStringArray(value);
REQUIRE(value.size() == 3);
REQUIRE(value[0] == L"1");
REQUIRE(value[1] == L"2");
REQUIRE(value[2] == L"3");
}
{
com_array<IInspectable> value(10);
object.OutObjectArray(value);
REQUIRE(value.size() == 3);
REQUIRE(value[0].as<IStringable>().ToString() == L"1");
REQUIRE(value[1].as<IStringable>().ToString() == L"2");
REQUIRE(value[2].as<IStringable>().ToString() == L"3");
}
{
com_array<IStringable> value(10);
object.OutStringableArray(value);
REQUIRE(value.size() == 3);
REQUIRE(value[0].ToString() == L"1");
REQUIRE(value[1].ToString() == L"2");
REQUIRE(value[2].ToString() == L"3");
}
{
com_array<Struct> value(10);
object.OutStructArray(value);
REQUIRE(value.size() == 2);
REQUIRE(value[0].First == L"1");
REQUIRE(value[0].Second == L"2");
REQUIRE(value[1].First == L"10");
REQUIRE(value[1].Second == L"20");
}
{
com_array<Signed> value(10);
object.OutEnumArray(value);
REQUIRE(value.size() == 2);
REQUIRE(value[0] == Signed::First);
REQUIRE(value[1] == Signed::Second);
}
{
std::array<int32_t, 4> value{ 0xCC, 0xCC, 0xCC, 0xCC };
object.RefInt32Array(value);
REQUIRE(value[0] == 1);
REQUIRE(value[1] == 2);
REQUIRE(value[2] == 3);
REQUIRE(value[3] == 0xCC);
}
{
std::array<hstring, 4> value{ L"r1", L"r2", L"r3", L"r4" };
object.RefStringArray(value);
REQUIRE(value[0] == L"1");
REQUIRE(value[1] == L"2");
REQUIRE(value[2] == L"3");
REQUIRE(value[3] == L"");
}
{
std::array<IInspectable, 4> value{ make<Stringable>(), make<Stringable>(), make<Stringable>(), make<Stringable>() };
object.RefObjectArray(value);
REQUIRE(value[0].as<IStringable>().ToString() == L"1");
REQUIRE(value[1].as<IStringable>().ToString() == L"2");
REQUIRE(value[2].as<IStringable>().ToString() == L"3");
REQUIRE(value[3] == nullptr);
}
{
std::array<IStringable, 4> value{ make<Stringable>(), make<Stringable>(), make<Stringable>(), make<Stringable>() };
object.RefStringableArray(value);
REQUIRE(value[0].ToString() == L"1");
REQUIRE(value[1].ToString() == L"2");
REQUIRE(value[2].ToString() == L"3");
REQUIRE(value[3] == nullptr);
}
{
std::array<Struct, 3> value{ {L"First", L"Second"} };
object.RefStructArray(value);
REQUIRE(value[0].First == L"1");
REQUIRE(value[0].Second == L"2");
REQUIRE(value[1].First == L"3");
REQUIRE(value[1].Second == L"4");
REQUIRE(value[2].First == L"");
REQUIRE(value[2].Second == L"");
}
{
std::array<Signed, 3> value{};
object.RefEnumArray(value);
REQUIRE(value.size() == 3);
REQUIRE(value[0] == Signed::First);
REQUIRE(value[1] == Signed::Second);
REQUIRE(value[2] == static_cast<Signed>(0));
}
object.Fail(true);
{
int value = 0xCC;
REQUIRE_THROWS_AS(object.OutInt32(value), hresult_invalid_argument);
REQUIRE(value == 0xCC);
}
{
hstring value = L"replace";
REQUIRE_THROWS_AS(object.OutString(value), hresult_invalid_argument);
REQUIRE(value == L"");
}
{
IInspectable value = make<Stringable>();
REQUIRE_THROWS_AS(object.OutObject(value), hresult_invalid_argument);
REQUIRE(value == nullptr);
}
{
IStringable value = make<Stringable>();
REQUIRE_THROWS_AS(object.OutStringable(value), hresult_invalid_argument);
REQUIRE(value == nullptr);
}
{
Struct value{ L"First", L"Second" };
REQUIRE_THROWS_AS(object.OutStruct(value), hresult_invalid_argument);
REQUIRE(value.First == L"");
REQUIRE(value.Second == L"");
}
{
Signed value = static_cast<Signed>(0xCC);
REQUIRE_THROWS_AS(object.OutEnum(value), hresult_invalid_argument);
REQUIRE(static_cast<int32_t>(value) == 0xCC);
}
{
com_array<int32_t> value(10);
REQUIRE_THROWS_AS(object.OutInt32Array(value), hresult_invalid_argument);
REQUIRE(value.size() == 0);
}
{
com_array<hstring> value(10);
REQUIRE_THROWS_AS(object.OutStringArray(value), hresult_invalid_argument);
REQUIRE(value.size() == 0);
}
{
com_array<IInspectable> value(10);
REQUIRE_THROWS_AS(object.OutObjectArray(value), hresult_invalid_argument);
REQUIRE(value.size() == 0);
}
{
com_array<IStringable> value(10);
REQUIRE_THROWS_AS(object.OutStringableArray(value), hresult_invalid_argument);
REQUIRE(value.size() == 0);
}
{
com_array<Struct> value(10);
REQUIRE_THROWS_AS(object.OutStructArray(value), hresult_invalid_argument);
REQUIRE(value.size() == 0);
}
{
com_array<Signed> value(10);
REQUIRE_THROWS_AS(object.OutEnumArray(value), hresult_invalid_argument);
REQUIRE(value.size() == 0);
}
{
std::array<int32_t, 4> value{ 0xCC, 0xCC, 0xCC, 0xCC };
REQUIRE_THROWS_AS(object.RefInt32Array(value), hresult_invalid_argument);
REQUIRE(value[0] == 0xCC);
REQUIRE(value[1] == 0xCC);
REQUIRE(value[2] == 0xCC);
REQUIRE(value[3] == 0xCC);
}
{
std::array<hstring, 4> value{ L"r1", L"r2", L"r3", L"r4" };
REQUIRE_THROWS_AS(object.RefStringArray(value), hresult_invalid_argument);
REQUIRE(value[0] == L"");
REQUIRE(value[1] == L"");
REQUIRE(value[2] == L"");
REQUIRE(value[3] == L"");
}
{
std::array<IInspectable, 4> value{ make<Stringable>(), make<Stringable>(), make<Stringable>(), make<Stringable>() };
REQUIRE_THROWS_AS(object.RefObjectArray(value), hresult_invalid_argument);
REQUIRE(value[0] == nullptr);
REQUIRE(value[1] == nullptr);
REQUIRE(value[2] == nullptr);
REQUIRE(value[3] == nullptr);
}
{
std::array<IStringable, 4> value{ make<Stringable>(), make<Stringable>(), make<Stringable>(), make<Stringable>() };
REQUIRE_THROWS_AS(object.RefStringableArray(value), hresult_invalid_argument);
REQUIRE(value[0] == nullptr);
REQUIRE(value[1] == nullptr);
REQUIRE(value[2] == nullptr);
REQUIRE(value[3] == nullptr);
}
{
std::array<Struct, 3> value{ {L"First", L"Second"} };
REQUIRE_THROWS_AS(object.RefStructArray(value), hresult_invalid_argument);
REQUIRE(value[0].First == L"");
REQUIRE(value[0].Second == L"");
REQUIRE(value[1].First == L"");
REQUIRE(value[1].Second == L"");
REQUIRE(value[2].First == L"");
REQUIRE(value[2].Second == L"");
}
{
std::array<Signed, 2> value{ static_cast<Signed>(0xCC), static_cast<Signed>(0xCC) };
REQUIRE_THROWS_AS(object.RefEnumArray(value), hresult_invalid_argument);
REQUIRE(value[0] == static_cast<Signed>(0xCC));
REQUIRE(value[1] == static_cast<Signed>(0xCC));
}
}
| 32.401487 | 124 | 0.564938 | stephenatwork |
1bf120fc2ff9cfcfe93e00048eb1e5579619dfbe | 46,365 | cpp | C++ | packages/nextclade_cli/src/cli.cpp | bigshr/nextclade | ddffb03e851a68a8d5a7260250a54cc0657da79b | [
"MIT"
] | 108 | 2020-09-29T14:06:08.000Z | 2022-03-19T03:07:35.000Z | packages/nextclade_cli/src/cli.cpp | bigshr/nextclade | ddffb03e851a68a8d5a7260250a54cc0657da79b | [
"MIT"
] | 500 | 2020-09-15T09:45:10.000Z | 2022-03-30T04:28:38.000Z | packages/nextclade_cli/src/cli.cpp | bigshr/nextclade | ddffb03e851a68a8d5a7260250a54cc0657da79b | [
"MIT"
] | 55 | 2020-10-13T11:40:47.000Z | 2022-02-27T04:35:12.000Z | #include <fmt/format.h>
#include <nextalign/nextalign.h>
#include <nextclade/nextclade.h>
#include <tbb/concurrent_vector.h>
#include <tbb/global_control.h>
#include <tbb/parallel_pipeline.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/split.hpp>
#include <cxxopts.hpp>
#include <fstream>
#include "Logger.h"
#include "description.h"
#include "filesystem.h"
struct CliParams {
int jobs{};
std::string verbosity;
bool verbose{};
bool silent{};
bool inOrder{};
std::string inputFasta;
std::string inputRootSeq;
std::string inputTree;
std::string inputQcConfig;
std::optional<std::string> inputGeneMap;
std::optional<std::string> inputPcrPrimers;
std::optional<std::string> outputJson;
std::optional<std::string> outputCsv;
std::optional<std::string> outputTsv;
std::optional<std::string> outputTree;
std::optional<std::string> genes;
std::optional<std::string> outputDir;
std::optional<std::string> outputBasename;
std::optional<std::string> outputFasta;
std::optional<std::string> outputInsertions;
std::optional<std::string> outputErrors;
bool writeReference{};
};
struct Paths {
fs::path outputFasta;
fs::path outputInsertions;
fs::path outputErrors;
std::map<std::string, fs::path> outputGenes;
};
class ErrorCliOptionInvalidValue : public ErrorFatal {
public:
explicit ErrorCliOptionInvalidValue(const std::string &message) : ErrorFatal(message) {}
};
class ErrorIoUnableToWrite : public ErrorFatal {
public:
explicit ErrorIoUnableToWrite(const std::string &message) : ErrorFatal(message) {}
};
template<typename Result>
Result getParamRequired(const cxxopts::ParseResult &cxxOptsParsed, const std::string &name) {
if (!cxxOptsParsed.count(name)) {
throw ErrorCliOptionInvalidValue(fmt::format("Error: argument `--{:s}` is required\n\n", name));
}
return cxxOptsParsed[name].as<Result>();
}
template<typename Result>
std::optional<Result> getParamOptional(const cxxopts::ParseResult &cxxOptsParsed, const std::string &name) {
if (!cxxOptsParsed.count(name)) {
return {};
}
return cxxOptsParsed[name].as<Result>();
}
template<typename ValueType>
ValueType noopValidator([[maybe_unused]] const std::string &name, ValueType value) {
return value;
}
int ensureNonNegative(const std::string &name, int value) {
if (value >= 0) {
return value;
}
throw ErrorCliOptionInvalidValue(
fmt::format("Error: argument `--{:s}` should be non-negative, but got {:d}", name, value));
}
int ensurePositive(const std::string &name, int value) {
if (value > 0) {
return value;
}
throw ErrorCliOptionInvalidValue(
fmt::format("Error: argument `--{:s}` should be positive, but got {:d}", name, value));
}
template<typename Result>
Result getParamRequiredDefaulted(const cxxopts::ParseResult &cxxOptsParsed, const std::string &name,
const std::function<Result(const std::string &, Result)> &validator = &noopValidator<Result>) {
const auto &value = cxxOptsParsed[name].as<Result>();
return validator(name, value);
}
NextalignOptions validateOptions(const cxxopts::ParseResult &cxxOptsParsed) {
NextalignOptions options = getDefaultOptions();
// clang-format off
options.alignment.minimalLength = getParamRequiredDefaulted<int>(cxxOptsParsed, "min-length", ensureNonNegative);
options.alignment.penaltyGapExtend = getParamRequiredDefaulted<int>(cxxOptsParsed, "penalty-gap-extend", ensureNonNegative);
options.alignment.penaltyGapOpen = getParamRequiredDefaulted<int>(cxxOptsParsed, "penalty-gap-open", ensurePositive);
options.alignment.penaltyGapOpenInFrame = getParamRequiredDefaulted<int>(cxxOptsParsed, "penalty-gap-open-in-frame", ensurePositive);
options.alignment.penaltyGapOpenOutOfFrame = getParamRequiredDefaulted<int>(cxxOptsParsed, "penalty-gap-open-out-of-frame", ensurePositive);
options.alignment.penaltyMismatch = getParamRequiredDefaulted<int>(cxxOptsParsed, "penalty-mismatch", ensurePositive);
options.alignment.scoreMatch = getParamRequiredDefaulted<int>(cxxOptsParsed, "score-match", ensurePositive);
options.alignment.maxIndel = getParamRequiredDefaulted<int>(cxxOptsParsed, "max-indel", ensureNonNegative);
options.seedNuc.seedLength = getParamRequiredDefaulted<int>(cxxOptsParsed, "nuc-seed-length", ensurePositive);
options.seedNuc.minSeeds = getParamRequiredDefaulted<int>(cxxOptsParsed, "nuc-min-seeds", ensurePositive);
options.seedNuc.seedSpacing = getParamRequiredDefaulted<int>(cxxOptsParsed, "nuc-seed-spacing", ensureNonNegative);
options.seedNuc.mismatchesAllowed = getParamRequiredDefaulted<int>(cxxOptsParsed, "nuc-mismatches-allowed", ensureNonNegative);
options.seedAa.seedLength = getParamRequiredDefaulted<int>(cxxOptsParsed, "aa-seed-length", ensurePositive);
options.seedAa.minSeeds = getParamRequiredDefaulted<int>(cxxOptsParsed, "aa-min-seeds", ensurePositive);
options.seedAa.seedSpacing = getParamRequiredDefaulted<int>(cxxOptsParsed, "aa-seed-spacing", ensureNonNegative);
options.seedAa.mismatchesAllowed = getParamRequiredDefaulted<int>(cxxOptsParsed, "aa-mismatches-allowed", ensureNonNegative);
// clang-format on
return options;
}
std::tuple<CliParams, NextalignOptions> parseCommandLine(int argc,
char *argv[]) {// NOLINT(cppcoreguidelines-avoid-c-arrays)
const std::string versionNextalign = NEXTALIGN_VERSION;
const std::string versionShort = PROJECT_VERSION;
const std::string versionDetailed =
fmt::format("nextclade {:s}\nbased on libnextclade {:s}\nbased on libnexalign {:s}", PROJECT_VERSION,
Nextclade::getVersion(), NEXTALIGN_VERSION);
cxxopts::Options cxxOpts("nextclade", fmt::format("{:s}\n\n{:s}\n", versionDetailed, PROJECT_DESCRIPTION));
// clang-format off
cxxOpts.add_options()
(
"h,help",
"(optional, boolean) Show this help"
)
(
"v,version",
"(optional, boolean) Show version"
)
(
"version-detailed",
"(optional, boolean) Show detailed version"
)
(
"verbosity",
fmt::format("(optional, string) Set minimum verbosity level of console output."
" Possible values are (from least verbose to most verbose): {}."
" Default: 'warn' (only errors and warnings are shown).",
Logger::getVerbosityLevels()),
cxxopts::value<std::string>()->default_value(Logger::getVerbosityDefaultLevel()),
"VERBOSITY"
)
(
"verbose",
"(optional, boolean) Increase verbosity of the console output. Same as --verbosity=info."
)
(
"silent",
"(optional, boolean) Disable console output entirely. --verbosity=silent."
)
(
"j,jobs",
"(optional, integer) Number of CPU threads used by the algorithm. If not specified or if a non-positive value specified, the algorithm will use all the available threads.",
cxxopts::value<int>()->default_value(std::to_string(0)),
"JOBS"
)
(
"in-order",
"(optional, boolean) Force parallel processing in-order. With this flag the program will wait for results from the previous sequences to be written to the output files before writing the results of the next sequences, preserving the same order as in the input file. Due to variable sequence processing times, this might introduce unnecessary waiting times, but ensures that the resulting sequences are written in the same order as they occur in the inputs (except for sequences which have errors). By default, without this flag, processing might happen out of order, which is faster, due to the elimination of waiting, but might also lead to results written out of order - the order of results is not specified and depends on thread scheduling and processing times of individual sequences. This option is only relevant when `--jobs` is greater than 1. Note: the sequences which trigger errors during processing will be omitted from outputs, regardless of this flag."
)
(
"i,input-fasta",
"(required, string) Path to a .fasta or a .txt file with input sequences. See an example for SARS-CoV-2 at: https://github.com/nextstrain/nextclade/blob/feat/nextclade-cpp/data/sars-cov-2/sequences.fasta", cxxopts::value<std::string>(),
"IN_FASTA"
)
(
"r,input-root-seq",
"Path to a .fasta or a .txt file containing root sequence. Must contain only 1 sequence. See an example for SARS-CoV-2 at: https://github.com/nextstrain/nextclade/blob/master/data/sars-cov-2/reference.fasta",
cxxopts::value<std::string>(),
"IN_ROOT_SEQ"
)
(
"a,input-tree",
"(required, string) Path to Auspice JSON v2 file containing reference tree. See https://nextstrain.org/docs/bioinformatics/data-formats. See an example for SARS-CoV-2 at: https://github.com/nextstrain/nextclade/blob/master/data/sars-cov-2/tree.json",
cxxopts::value<std::string>(),
"IN_TREE"
)
(
"q,input-qc-config",
"(required, string) Path to a JSON file containing configuration of Quality Control rules. See an example for SARS-CoV-2 at: https://github.com/nextstrain/nextclade/blob/feat/nextclade-cpp/data/sars-cov-2/qc.json",
cxxopts::value<std::string>(),
"IN_QC_CONF"
)
(
"genes",
"(optional, string) Comma-separated list of names of genes to use. This defines which peptides will be written into outputs, and which genes will be taken into account during codon-aware alignment and aminoacid mutations detection. Must only contain gene names present in the gene map. If this flag is not supplied or its value is an empty string, then all genes found in the gene map will be used. Requires `--input-gene-map` to be specified. Example for SARS-CoV-2: E,M,N,ORF1a,ORF1b,ORF3a,ORF6,ORF7a,ORF7b,ORF8,ORF9b,S",
cxxopts::value<std::string>(),
"GENES"
)
(
"g,input-gene-map",
R"((optional, string) Path to a .gff file containing gene map. Gene map (sometimes also called "gene annotations") is used to find gene regions. If not supplied, sequences will not be translated, peptides will not be emitted, aminoacid mutations will not be detected and nucleotide sequence alignment will not be informed by codon boundaries. See an example for SARS-CoV-2 at: https://github.com/nextstrain/nextclade/blob/master/data/sars-cov-2/genemap.gff)",
cxxopts::value<std::string>(),
"IN_GENE_MAP"
)
(
"p,input-pcr-primers",
"(optional, string) Path to a CSV file containing a list of custom PCR primer sites. These are used to report mutations in these sites. See an example for SARS-CoV-2 at: https://github.com/nextstrain/nextclade/blob/master/data/sars-cov-2/primers.csv",
cxxopts::value<std::string>(),
"IN_PCR_PRIMERS"
)
(
"o,output-json",
"(optional, string) Path to output JSON results file",
cxxopts::value<std::string>(),
"OUT_JSON"
)
(
"c,output-csv",
"(optional, string) Path to output CSV results file",
cxxopts::value<std::string>(),
"OUT_CSV"
)
(
"t,output-tsv",
"(optional, string) Path to output TSV results file",
cxxopts::value<std::string>(),
"OUT_TSV"
)
(
"T,output-tree",
"(optional, string) Path to output Auspice JSON V2 results file. If the three is not needed, omitting this flag reduces processing time and memory consumption. For file format description see: https://nextstrain.org/docs/bioinformatics/data-formats",
cxxopts::value<std::string>(),
"OUT_TREE"
)
(
"d,output-dir",
"(optional, string) Write output files to this directory. The base filename can be set using `--output-basename` flag. The paths can be overridden on a per-file basis using `--output-*` flags. If the required directory tree does not exist, it will be created.",
cxxopts::value<std::string>(),
"OUTPUT_DIR"
)
(
"n,output-basename",
"(optional, string) Set the base filename to use for output files. To be used together with `--output-dir` flag. By default uses the filename of the sequences file (provided with `--sequences`). The paths can be overridden on a per-file basis using `--output-*` flags.",
cxxopts::value<std::string>(),
"OUTPUT_BASENAME"
)
(
"include-reference",
"(optional, boolean) Whether to include aligned reference nucleotide sequence into output nucleotide sequence fasta file and reference peptides into output peptide files.",
cxxopts::value<bool>(),
"WRITE_REF"
)
(
"output-fasta",
"(optional, string) Path to output aligned sequences in FASTA format (overrides paths given with `--output-dir` and `--output-basename`). If the required directory tree does not exist, it will be created.",
cxxopts::value<std::string>(),
"OUTPUT_FASTA"
)
(
"I,output-insertions",
"(optional, string) Path to output stripped insertions data in CSV format (overrides paths given with `--output-dir` and `--output-basename`). If the required directory tree does not exist, it will be created.",
cxxopts::value<std::string>(),
"OUTPUT_INSERTIONS"
)
(
"E,output-errors",
"(optional, string) Path to output errors and warnings occurred during processing, in CSV format (overrides paths given with `--output-dir` and `--output-basename`). If the required directory tree does not exist, it will be created.",
cxxopts::value<std::string>(),
"OUTPUT_ERRORS"
)
(
"min-length",
"(optional, integer, non-negative) Minimum length of nucleotide sequence to consider for alignment. If a sequence is shorter than that, alignment will not be attempted and a warning will be emitted. When adjusting this parameter, note that alignment of short sequences can be unreliable.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.minimalLength)),
"MIN_LENGTH"
)
(
"penalty-gap-extend",
"(optional, integer, non-negative) Penalty for extending a gap. If zero, all gaps regardless of length incur the same penalty.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.penaltyGapExtend)),
"PENALTY_GAP_EXTEND"
)
(
"penalty-gap-open",
"(optional, integer, positive) Penalty for opening of a gap. A higher penalty results in fewer gaps and more mismatches. Should be less than `--penalty-gap-open-in-frame` to avoid gaps in genes.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.penaltyGapOpen)),
"PENALTY_GAP_OPEN"
)
(
"penalty-gap-open-in-frame",
"(optional, integer, positive) As `--penalty-gap-open`, but for opening gaps at the beginning of a codon. Should be greater than `--penalty-gap-open` and less than `--penalty-gap-open-out-of-frame`, to avoid gaps in genes, but favor gaps that align with codons.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.penaltyGapOpenInFrame)),
"PENALTY_GAP_OPEN_IN_FRAME"
)
(
"penalty-gap-open-out-of-frame",
"(optional, integer, positive) As `--penalty-gap-open`, but for opening gaps in the body of a codon. Should be greater than `--penalty-gap-open-in-frame` to favor gaps that align with codons.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.penaltyGapOpenOutOfFrame)),
"PENALTY_GAP_OPEN_OUT_OF_FRAME"
)
(
"penalty-mismatch",
"(optional, integer, positive) Penalty for aligned nucleotides or aminoacids that differ in state during alignment. Note that this is redundantly parameterized with `--score-match`.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.penaltyMismatch)),
"PENALTY_MISMATCH"
)
(
"score-match",
"(optional, integer, positive) Score for encouraging aligned nucleotides or aminoacids with matching state.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.scoreMatch)),
"SCORE_MATCH"
)
(
"max-indel",
"(optional, integer, non-negative) Maximum length of insertions or deletions allowed to proceed with alignment. Alignments with long indels are slow to compute and require substantial memory in the current implementation. Alignment of sequences with indels longer that this value, will not be attempted and a warning will be emitted.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().alignment.maxIndel)),
"MAX_INDEL"
)
(
"nuc-seed-length",
"(optional, integer, positive) Seed length for nucleotide alignment. Seeds should be long enough to be unique, but short enough to match with high probability.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedNuc.seedLength)),
"NUC_SEED_LENGTH"
)
(
"nuc-min-seeds",
"(optional, integer, positive) Minimum number of seeds to search for during nucleotide alignment. Relevant for short sequences. In long sequences, the number of seeds is determined by `--nuc-seed-spacing`. Should be a positive integer.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedNuc.minSeeds)),
"NUC_MIN_SEEDS"
)
(
"nuc-seed-spacing",
"(optional, integer, non-negative) Spacing between seeds during nucleotide alignment.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedNuc.seedSpacing)),
"NUC_SEED_SPACING"
)
(
"nuc-mismatches-allowed",
"(optional, integer, non-negative) Maximum number of mismatching nucleotides allowed for a seed to be considered a match.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedNuc.mismatchesAllowed)),
"NUC_MISMATCHES_ALLOWED"
)
(
"aa-seed-length",
"(optional, integer, positive) Seed length for aminoacid alignment.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedAa.seedLength)),
"AA_SEED_LENGTH"
)
(
"aa-min-seeds",
"(optional, integer, positive) Minimum number of seeds to search for during aminoacid alignment. Relevant for short sequences. In long sequences, the number of seeds is determined by `--aa-seed-spacing`.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedAa.minSeeds)),
"AA_MIN_SEEDS"
)
(
"aa-seed-spacing",
"(optional, integer, non-negative) Spacing between seeds during aminoacid alignment.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedAa.seedSpacing)),
"AA_SEED_SPACING"
)
(
"aa-mismatches-allowed",
"(optional, integer, non-negative) Maximum number of mismatching aminoacids allowed for a seed to be considered a match.",
cxxopts::value<int>()->default_value(std::to_string(getDefaultOptions().seedAa.mismatchesAllowed)),
"AA_MISMATCHES_ALLOWED"
)
;
// clang-format on
try {
const auto cxxOptsParsed = cxxOpts.parse(argc, argv);
if (cxxOptsParsed.count("help") > 0) {
fmt::print("{:s}\n", cxxOpts.help());
std::exit(0);
}
if (cxxOptsParsed.count("version") > 0) {
fmt::print("{:s}\n", versionShort);
std::exit(0);
}
if (cxxOptsParsed.count("version-detailed") > 0) {
fmt::print("{:s}\n", versionDetailed);
std::exit(0);
}
CliParams cliParams;
cliParams.jobs = getParamRequiredDefaulted<int>(cxxOptsParsed, "jobs");
cliParams.inOrder = getParamRequiredDefaulted<bool>(cxxOptsParsed, "in-order");
cliParams.verbosity = getParamRequiredDefaulted<std::string>(cxxOptsParsed, "verbosity");
cliParams.verbose = getParamRequiredDefaulted<bool>(cxxOptsParsed, "verbose");
cliParams.silent = getParamRequiredDefaulted<bool>(cxxOptsParsed, "silent");
cliParams.outputDir = getParamOptional<std::string>(cxxOptsParsed, "output-dir");
cliParams.outputBasename = getParamOptional<std::string>(cxxOptsParsed, "output-basename");
cliParams.outputFasta = getParamOptional<std::string>(cxxOptsParsed, "output-fasta");
cliParams.writeReference = getParamRequiredDefaulted<bool>(cxxOptsParsed, "include-reference");
cliParams.outputInsertions = getParamOptional<std::string>(cxxOptsParsed, "output-insertions");
cliParams.outputErrors = getParamOptional<std::string>(cxxOptsParsed, "output-errors");
cliParams.inputFasta = getParamRequired<std::string>(cxxOptsParsed, "input-fasta");
cliParams.inputRootSeq = getParamRequired<std::string>(cxxOptsParsed, "input-root-seq");
cliParams.inputTree = getParamRequired<std::string>(cxxOptsParsed, "input-tree");
cliParams.inputQcConfig = getParamRequired<std::string>(cxxOptsParsed, "input-qc-config");
cliParams.genes = getParamOptional<std::string>(cxxOptsParsed, "genes");
cliParams.inputGeneMap = getParamOptional<std::string>(cxxOptsParsed, "input-gene-map");
cliParams.inputPcrPrimers = getParamOptional<std::string>(cxxOptsParsed, "input-pcr-primers");
cliParams.outputJson = getParamOptional<std::string>(cxxOptsParsed, "output-json");
cliParams.outputCsv = getParamOptional<std::string>(cxxOptsParsed, "output-csv");
cliParams.outputTsv = getParamOptional<std::string>(cxxOptsParsed, "output-tsv");
cliParams.outputTree = getParamOptional<std::string>(cxxOptsParsed, "output-tree");
if (bool(cliParams.genes) && !bool(cliParams.inputGeneMap)) {
throw ErrorCliOptionInvalidValue("Parameter `--genes` requires parameter `--input-gene-map` to be specified.");
}
NextalignOptions options = validateOptions(cxxOptsParsed);
return std::make_tuple(cliParams, options);
} catch (const cxxopts::OptionSpecException &e) {
fmt::print(stderr, "Error: OptionSpecException: {:s}\n\n", e.what());
fmt::print(stderr, "{:s}\n", cxxOpts.help());
std::exit(1);
} catch (const cxxopts::OptionParseException &e) {
fmt::print(stderr, "Error: OptionParseException: {:s}\n\n", e.what());
fmt::print(stderr, "{:s}\n", cxxOpts.help());
std::exit(1);
} catch (const ErrorCliOptionInvalidValue &e) {
fmt::print(stderr, "Error: ErrorCliOptionInvalidValue: {:s}\n\n", e.what());
fmt::print(stderr, "{:s}\n", cxxOpts.help());
std::exit(1);
} catch (const std::exception &e) {
fmt::print(stderr, "Error: {:s}\n\n", e.what());
fmt::print(stderr, "{:s}\n", cxxOpts.help());
std::exit(1);
}
}
class ErrorFastaReader : public ErrorFatal {
public:
explicit ErrorFastaReader(const std::string &message) : ErrorFatal(message) {}
};
struct ReferenceSequenceData {
const NucleotideSequence seq;
const std::string name;
const int length;
};
ReferenceSequenceData parseRefFastaFile(const std::string &filename) {
std::ifstream file(filename);
if (!file.good()) {
throw ErrorFastaReader(fmt::format("Error: unable to read \"{:s}\"\n", filename));
}
const auto refSeqs = parseSequences(file, filename);
if (refSeqs.size() != 1) {
throw ErrorFastaReader(
fmt::format("Error: {:d} sequences found in reference sequence file, expected 1", refSeqs.size()));
}
const auto &refSeq = refSeqs.front();
const auto &seq = toNucleotideSequence(refSeq.seq);
const auto length = static_cast<int>(seq.size());
return {.seq = seq, .name = refSeq.seqName, .length = length};
}
class ErrorGffReader : public ErrorFatal {
public:
explicit ErrorGffReader(const std::string &message) : ErrorFatal(message) {}
};
GeneMap parseGeneMapGffFile(const std::string &filename) {
std::ifstream file(filename);
if (!file.good()) {
throw ErrorGffReader(fmt::format("Error: unable to read \"{:s}\"\n", filename));
}
auto geneMap = parseGeneMapGff(file, filename);
if (geneMap.empty()) {
throw ErrorGffReader(fmt::format("Error: gene map is empty"));
}
return geneMap;
}
std::set<std::string> parseGenes(const std::string &genesString) {
std::vector<std::string> genes;
if (!genesString.empty()) {
boost::algorithm::split(genes, genesString, boost::is_any_of(","));
}
for (auto &gene : genes) {
gene = boost::trim_copy(gene);
}
auto result = std::set<std::string>{genes.cbegin(), genes.cend()};
return result;
}
class ErrorGeneMapValidationFailure : public ErrorFatal {
public:
explicit ErrorGeneMapValidationFailure(const std::string &message) : ErrorFatal(message) {}
};
void validateGenes(const std::set<std::string> &genes, const GeneMap &geneMap) {
for (const auto &gene : genes) {
const auto &it = geneMap.find(gene);
if (it == geneMap.end()) {
throw ErrorGeneMapValidationFailure(fmt::format("Error: gene \"{}\" is not in gene map\n", gene));
}
}
}
GeneMap filterGeneMap(const std::set<std::string> &genes, const GeneMap &geneMap) {
GeneMap result;
for (const auto &gene : genes) {
const auto &it = geneMap.find(gene);
if (it != geneMap.end()) {
result.insert(*it);
}
}
return result;
}
std::string formatCliParams(const CliParams &cliParams) {
fmt::memory_buffer buf;
fmt::format_to(buf, "\nParameters:\n");
fmt::format_to(buf, "{:<20s}{:<}\n", "Jobs", cliParams.jobs);
fmt::format_to(buf, "{:<20s}{:<}\n", "In order", cliParams.inOrder ? "yes" : "no");
fmt::format_to(buf, "{:<20s}{:<}\n", "Include reference", cliParams.writeReference ? "yes" : "no");
fmt::format_to(buf, "{:<20s}{:<}\n", "Verbose", cliParams.verbose ? "yes" : "no");
fmt::format_to(buf, "\nInput Files:\n");
fmt::format_to(buf, "{:<20s}{:<}\n", "Reference sequence", cliParams.inputRootSeq);
fmt::format_to(buf, "{:<20s}{:<}\n", "Sequences FASTA", cliParams.inputFasta);
fmt::format_to(buf, "{:<20s}{:<}\n", "Gene map", cliParams.inputGeneMap.value_or("Disabled"));
fmt::format_to(buf, "{:<20s}{:<}\n", "PCR primers", cliParams.inputPcrPrimers.value_or("Disabled"));
fmt::format_to(buf, "{:<20s}{:<}\n", "QC configuration", cliParams.inputQcConfig);
if (cliParams.genes) {
fmt::format_to(buf, "{:<20s}{:<}\n", "Genes to translate", *cliParams.genes);
}
return fmt::to_string(buf);
}
Paths getPaths(const CliParams &cliParams, const std::set<std::string> &genes) {
fs::path sequencesPath = cliParams.inputFasta;
auto outDir = fs::canonical(fs::current_path());
if (cliParams.outputDir) {
outDir = *cliParams.outputDir;
}
if (!outDir.is_absolute()) {
outDir = fs::current_path() / outDir;
}
auto baseName = sequencesPath.stem();
if (cliParams.outputBasename) {
baseName = *cliParams.outputBasename;
}
auto outputFasta = outDir / baseName;
outputFasta += ".aligned.fasta";
if (cliParams.outputFasta) {
outputFasta = *cliParams.outputFasta;
}
auto outputInsertions = outDir / baseName;
outputInsertions += ".insertions.csv";
if (cliParams.outputInsertions) {
outputInsertions = *cliParams.outputInsertions;
}
auto outputErrors = outDir / baseName;
outputErrors += ".errors.csv";
if (cliParams.outputErrors) {
outputErrors = *cliParams.outputErrors;
}
std::map<std::string, fs::path> outputGenes;
for (const auto &gene : genes) {
auto outputGene = outDir / baseName;
outputGene += fmt::format(".gene.{:s}.fasta", gene);
outputGenes.emplace(gene, outputGene);
}
return {
.outputFasta = outputFasta,
.outputInsertions = outputInsertions,
.outputErrors = outputErrors,
.outputGenes = outputGenes,
};
}
std::string formatPaths(const Paths &paths) {
fmt::memory_buffer buf;
fmt::format_to(buf, "\nOutput files:\n");
fmt::format_to(buf, "{:>30s}: \"{:<s}\"\n", "Aligned sequences", paths.outputFasta.string());
fmt::format_to(buf, "{:>30s}: \"{:<s}\"\n", "Stripped insertions", paths.outputInsertions.string());
for (const auto &[geneName, outputGenePath] : paths.outputGenes) {
fmt::memory_buffer bufGene;
fmt::format_to(bufGene, "{:s} {:>10s}", "Translated genes", geneName);
fmt::format_to(buf, "{:>30s}: \"{:<s}\"\n", fmt::to_string(bufGene), outputGenePath.string());
}
return fmt::to_string(buf);
}
std::string formatRef(const ReferenceSequenceData &refData, bool shouldWriteReference) {
return fmt::format("\nReference sequence:\n name: \"{:s}\"\n Length: {:d}\n Write: {:s}\n", refData.name,
refData.length, shouldWriteReference ? "yes" : "no");
}
std::string formatGeneMap(const GeneMap &geneMap, const std::set<std::string> &genes) {
constexpr const auto TABLE_WIDTH = 86;
fmt::memory_buffer buf;
fmt::format_to(buf, "\nGene map:\n");
fmt::format_to(buf, "{:s}\n", std::string(TABLE_WIDTH, '-'));
fmt::format_to(buf, "| {:8s} | {:16s} | {:8s} | {:8s} | {:8s} | {:8s} | {:8s} |\n", "Selected", " Gene Name",
" Start", " End", " Length", " Frame", " Strand");
fmt::format_to(buf, "{:s}\n", std::string(TABLE_WIDTH, '-'));
for (const auto &[geneName, gene] : geneMap) {
const auto selected = std::find(genes.cbegin(), genes.cend(), geneName) != genes.cend();
const std::string selectedStr = selected ? " yes" : " ";
fmt::format_to(buf, "| {:8s} | {:16s} | {:8d} | {:8d} | {:8d} | {:8d} | {:8s} |\n", selectedStr, geneName,
gene.start + 1, gene.end, gene.length, gene.frame + 1, gene.strand);
}
fmt::format_to(buf, "{:s}\n", std::string(TABLE_WIDTH, '-'));
return fmt::to_string(buf);
}
namespace Nextclade {
struct AlgorithmOutput {
int index;
std::string seqName;
bool hasError;
NextcladeResult result;
std::exception_ptr error;
};
}// namespace Nextclade
/**
* Runs nextclade algorithm in a parallel pipeline
*/
void run(
/* in */ int parallelism,
/* in */ bool inOrder,
/* inout */ std::unique_ptr<FastaStream> &inputFastaStream,
/* in */ const ReferenceSequenceData &refData,
/* in */ const Nextclade::QcConfig &qcRulesConfig,
/* in */ const std::string &treeString,
/* in */ const std::vector<Nextclade::PcrPrimer> &pcrPrimers,
/* in */ const GeneMap &geneMap,
/* in */ const NextalignOptions &nextalignOptions,
/* out */ std::unique_ptr<std::ostream> &outputJsonStream,
/* out */ std::unique_ptr<std::ostream> &outputCsvStream,
/* out */ std::unique_ptr<std::ostream> &outputTsvStream,
/* out */ std::unique_ptr<std::ostream> &outputTreeStream,
/* out */ std::ostream &outputFastaStream,
/* out */ std::ostream &outputInsertionsStream,
/* out */ std::ostream &outputErrorsFile,
/* out */ std::map<std::string, std::ofstream> &outputGeneStreams,
/* in */ bool shouldWriteReference,
/* out */ Logger &logger) {
tbb::task_group_context context;
const auto ioFiltersMode = inOrder ? tbb::filter_mode::serial_in_order : tbb::filter_mode::serial_out_of_order;
const auto &ref = refData.seq;
const auto &refName = refData.name;
std::optional<Nextclade::CsvWriter> csv;
if (outputCsvStream) {
csv.emplace(Nextclade::CsvWriter(*outputCsvStream, Nextclade::CsvWriterOptions{.delimiter = ';'}));
}
std::optional<Nextclade::CsvWriter> tsv;
if (outputTsvStream) {
tsv.emplace(Nextclade::CsvWriter(*outputTsvStream, Nextclade::CsvWriterOptions{.delimiter = '\t'}));
}
const Nextclade::NextcladeOptions options = {
.ref = ref,
.treeString = treeString,
.pcrPrimers = pcrPrimers,
.geneMap = geneMap,
.qcRulesConfig = qcRulesConfig,
.nextalignOptions = nextalignOptions,
};
Nextclade::NextcladeAlgorithm nextclade{options};
// TODO(perf): consider using a thread-safe queue instead of a vector,
// or restructuring code to avoid concurrent access entirely
tbb::concurrent_vector<Nextclade::AnalysisResult> resultsConcurrent;
/** Input filter is a serial input filter function, which accepts an input stream,
* reads and parses the contents of it, and returns parsed sequences */
const auto inputFilter = tbb::make_filter<void, AlgorithmInput>(ioFiltersMode,//
[&inputFastaStream](tbb::flow_control &fc) -> AlgorithmInput {
if (!inputFastaStream->good()) {
fc.stop();
return {};
}
return inputFastaStream->next();
});
/** A set of parallel transform filter functions, each accepts a parsed sequence from the input filter,
* runs nextclade algorithm sequentially and returns its result.
* The number of filters is determined by the `--jobs` CLI argument */
const auto transformFilters =
tbb::make_filter<AlgorithmInput, Nextclade::AlgorithmOutput>(tbb::filter_mode::parallel,//
[&nextclade](const AlgorithmInput &input) -> Nextclade::AlgorithmOutput {
const auto &seqName = input.seqName;
try {
const auto seq = toNucleotideSequence(input.seq);
const auto result = nextclade.run(seqName, seq);
return {.index = input.index, .seqName = seqName, .hasError = false, .result = result, .error = nullptr};
} catch (const std::exception &e) {
const auto &error = std::current_exception();
return {.index = input.index, .seqName = seqName, .hasError = true, .result = {}, .error = error};
}
});
// HACK: prevent aligned ref and ref genes from being written multiple times
// TODO: hoist ref sequence transforms - process and write results only once, outside of main loop
bool refsHaveBeenWritten = !shouldWriteReference;
/** Output filter is a serial ordered filter function which accepts the results from transform filters,
* one at a time, displays and writes them to output streams */
const auto outputFilter = tbb::make_filter<Nextclade::AlgorithmOutput, void>(ioFiltersMode,//
[&refName, &outputFastaStream, &outputInsertionsStream, &outputErrorsFile, &outputGeneStreams, &csv, &tsv,
&refsHaveBeenWritten, &logger, &resultsConcurrent, &outputJsonStream,
&outputTreeStream](const Nextclade::AlgorithmOutput &output) {
const auto index = output.index;
const auto &seqName = output.seqName;
const auto &refAligned = output.result.ref;
const auto &queryAligned = output.result.query;
const auto &queryPeptides = output.result.queryPeptides;
const auto &refPeptides = output.result.refPeptides;
const auto &insertions = output.result.analysisResult.insertions;
const auto &warnings = output.result.warnings;
const auto &result = output.result;
logger.info("| {:5d} | {:40s} | {:7d} | {:7d} | {:7d} | {:7d} |",//
index, seqName, result.analysisResult.alignmentScore, result.analysisResult.alignmentStart,
result.analysisResult.alignmentEnd, result.analysisResult.totalInsertions//
);
const auto &error = output.error;
if (error) {
try {
std::rethrow_exception(error);
} catch (const std::exception &e) {
const std::string &errorMessage = e.what();
logger.warn("Warning: In sequence \"{:s}\": {:s}. Note that this sequence will be excluded from results.",
seqName, errorMessage);
outputErrorsFile << fmt::format("\"{:s}\",\"{:s}\",\"{:s}\",\"{:s}\"\n", seqName, e.what(), "", "<<ALL>>");
if (csv) {
csv->addErrorRow(seqName, errorMessage);
}
if (tsv) {
tsv->addErrorRow(seqName, errorMessage);
}
return;
}
} else {
std::vector<std::string> warningsCombined;
std::vector<std::string> failedGeneNames;
for (const auto &warning : warnings.global) {
logger.warn("Warning: in sequence \"{:s}\": {:s}", seqName, warning);
warningsCombined.push_back(warning);
}
for (const auto &warning : warnings.inGenes) {
logger.warn("Warning: in sequence \"{:s}\": {:s}", seqName, warning.message);
warningsCombined.push_back(warning.message);
failedGeneNames.push_back(warning.geneName);
}
auto warningsJoined = boost::join(warningsCombined, ";");
boost::replace_all(warningsJoined, R"(")", R"("")");// escape double quotes
auto failedGeneNamesJoined = boost::join(failedGeneNames, ";");
boost::replace_all(failedGeneNamesJoined, R"(")", R"("")");// escape double quotes
outputErrorsFile << fmt::format("\"{:s}\",\"{:s}\",\"{:s}\",\"{:s}\"\n", seqName, "", warningsJoined,
failedGeneNamesJoined);
// TODO: hoist ref sequence transforms - process and write results only once, outside of main loop
if (!refsHaveBeenWritten) {
outputFastaStream << fmt::format(">{:s}\n{:s}\n", refName, refAligned);
outputFastaStream.flush();
for (const auto &peptide : refPeptides) {
outputGeneStreams[peptide.name] << fmt::format(">{:s}\n{:s}\n", refName, peptide.seq);
outputGeneStreams[peptide.name].flush();
}
refsHaveBeenWritten = true;
}
outputFastaStream << fmt::format(">{:s}\n{:s}\n", seqName, queryAligned);
for (const auto &peptide : queryPeptides) {
outputGeneStreams[peptide.name] << fmt::format(">{:s}\n{:s}\n", seqName, peptide.seq);
}
outputInsertionsStream << fmt::format("\"{:s}\",\"{:s}\"\n", seqName, Nextclade::formatInsertions(insertions));
if (outputJsonStream || outputTreeStream) {
resultsConcurrent.push_back(output.result.analysisResult);
}
if (csv) {
csv->addRow(output.result.analysisResult);
}
if (tsv) {
tsv->addRow(output.result.analysisResult);
}
}
});
try {
tbb::parallel_pipeline(parallelism, inputFilter & transformFilters & outputFilter, context);
} catch (const std::exception &e) {
logger.error("Error: when running the internal parallel pipeline: {:s}", e.what());
}
if (outputJsonStream || outputTreeStream) {
// TODO: try to avoid copy here
std::vector<Nextclade::AnalysisResult> results{resultsConcurrent.cbegin(), resultsConcurrent.cend()};
if (outputJsonStream) {
*outputJsonStream << serializeResults(results);
}
if (outputTreeStream) {
const auto &tree = nextclade.finalize(results);
(*outputTreeStream) << tree.serialize();
}
}
}
std::string readFile(const std::string &filepath) {
std::ifstream stream(filepath);
if (!stream.good()) {
throw std::runtime_error(fmt::format("Error: unable to read \"{:s}\"", filepath));
}
std::stringstream buffer;
buffer << stream.rdbuf();
return buffer.str();
}
/**
* Opens a file stream given filepath and creates target directory tree if does not exist
*/
void openOutputFile(const std::string &filepath, std::ofstream &stream) {
const auto outputJsonParent = fs::path(filepath).parent_path();
if (!outputJsonParent.empty()) {
fs::create_directories(outputJsonParent);
}
stream.open(filepath);
if (!stream.is_open()) {
throw ErrorIoUnableToWrite(fmt::format("Error: unable to write \"{:s}\": {:s}", filepath, strerror(errno)));
}
}
/**
* Opens a file stream, if the given optional filepath contains value, returns nullptr otherwise
*/
std::unique_ptr<std::ostream> openOutputFileMaybe(const std::optional<std::string> &filepath) {
if (!filepath) {
return nullptr;
}
const auto outputJsonParent = fs::path(*filepath).parent_path();
if (!outputJsonParent.empty()) {
fs::create_directories(outputJsonParent);
}
auto stream = std::make_unique<std::ofstream>(*filepath);
if (!stream->is_open()) {
throw ErrorIoUnableToWrite(fmt::format("Error: unable to write \"{:s}\": {:s}", *filepath, strerror(errno)));
}
return stream;
}
int main(int argc, char *argv[]) {
Logger logger{Logger::Options{.linePrefix = "Nextclade", .verbosity = Logger::Verbosity::warn}};
try {
const auto [cliParams, options] = parseCommandLine(argc, argv);
auto verbosity = Logger::convertVerbosity(cliParams.verbosity);
if (cliParams.verbose) {
verbosity = Logger::Verbosity::info;
}
if (cliParams.silent) {
verbosity = Logger::Verbosity::silent;
}
logger.setVerbosity(verbosity);
logger.info(formatCliParams(cliParams));
const auto refData = parseRefFastaFile(cliParams.inputRootSeq);
const auto shouldWriteReference = cliParams.writeReference;
logger.info(formatRef(refData, shouldWriteReference));
GeneMap geneMap;
std::set<std::string> genes;
if (cliParams.inputGeneMap) {
geneMap = parseGeneMapGffFile(*cliParams.inputGeneMap);
if (!cliParams.genes || cliParams.genes->empty()) {
// If `--genes` are omitted or empty, use all genes in the gene map
std::transform(geneMap.cbegin(), geneMap.cend(), std::inserter(genes, genes.end()),
[](const auto &it) { return it.first; });
} else {
genes = parseGenes(*cliParams.genes);
}
validateGenes(genes, geneMap);
const GeneMap geneMapFull = geneMap;
geneMap = filterGeneMap(genes, geneMap);
logger.info(formatGeneMap(geneMapFull, genes));
}
if (!genes.empty()) {
// penaltyGapOpenOutOfFrame > penaltyGapOpenInFrame > penaltyGapOpen
const auto isInFrameGreater = options.alignment.penaltyGapOpenInFrame > options.alignment.penaltyGapOpen;
const auto isOutOfFrameEvenGreater =
options.alignment.penaltyGapOpenOutOfFrame > options.alignment.penaltyGapOpenInFrame;
if (!(isInFrameGreater && isOutOfFrameEvenGreater)) {
throw ErrorCliOptionInvalidValue(
fmt::format("Should verify the condition `--penalty-gap-open-out-of-frame` > `--penalty-gap-open-in-frame` > "
"`--penalty-gap-open`, but got {:d} > {:d} > {:d}, which is false",
options.alignment.penaltyGapOpenOutOfFrame, options.alignment.penaltyGapOpenInFrame,
options.alignment.penaltyGapOpen));
}
}
std::ifstream fastaFile(cliParams.inputFasta);
auto inputFastaStream = makeFastaStream(fastaFile, cliParams.inputFasta);
if (!fastaFile.good()) {
logger.error("Error: unable to read \"{:s}\"", cliParams.inputFasta);
std::exit(1);
}
const auto qcJsonString = readFile(cliParams.inputQcConfig);
const auto qcRulesConfig = Nextclade::parseQcConfig(qcJsonString);
if (!Nextclade::isQcConfigVersionRecent(qcRulesConfig)) {
logger.warn(
"The version of QC configuration file \"{:s}\" (`\"schemaVersion\": \"{:s}\"`) is older than the QC "
"configuration version expected by Nextclade ({:s}). "
"You might be missing out on new features. It is recommended to download the latest QC configuration file.",
cliParams.inputQcConfig, qcRulesConfig.schemaVersion, Nextclade::getQcConfigJsonSchemaVersion());
}
const auto treeString = readFile(cliParams.inputTree);
std::vector<Nextclade::PcrPrimer> pcrPrimers;
if (cliParams.inputPcrPrimers) {
const auto pcrPrimersCsvString = readFile(*cliParams.inputPcrPrimers);
std::vector<std::string> warnings;
pcrPrimers =
Nextclade::parseAndConvertPcrPrimersCsv(pcrPrimersCsvString, *cliParams.inputPcrPrimers, refData.seq, warnings);
}
const auto paths = getPaths(cliParams, genes);
logger.info(formatPaths(paths));
auto outputJsonStream = openOutputFileMaybe(cliParams.outputJson);
auto outputCsvStream = openOutputFileMaybe(cliParams.outputCsv);
auto outputTsvStream = openOutputFileMaybe(cliParams.outputTsv);
auto outputTreeStream = openOutputFileMaybe(cliParams.outputTree);
std::ofstream outputFastaStream;
openOutputFile(paths.outputFasta, outputFastaStream);
std::ofstream outputInsertionsStream;
openOutputFile(paths.outputInsertions, outputInsertionsStream);
outputInsertionsStream << "seqName,insertions\n";
std::ofstream outputErrorsFile(paths.outputErrors);
if (!outputErrorsFile.good()) {
throw ErrorIoUnableToWrite(fmt::format("Error: unable to write \"{:s}\"", paths.outputErrors.string()));
}
outputErrorsFile << "seqName,errors,warnings,failedGenes\n";
std::map<std::string, std::ofstream> outputGeneStreams;
for (const auto &[geneName, outputGenePath] : paths.outputGenes) {
auto result = outputGeneStreams.emplace(std::make_pair(geneName, std::ofstream{}));
auto &outputGeneFile = result.first->second;
openOutputFile(outputGenePath, outputGeneFile);
}
int parallelism = static_cast<int>(std::thread::hardware_concurrency());
if (cliParams.jobs > 0) {
tbb::global_control globalControl{tbb::global_control::max_allowed_parallelism,
static_cast<size_t>(cliParams.jobs)};
parallelism = cliParams.jobs;
}
bool inOrder = cliParams.inOrder;
logger.info("\nParallelism: {:d}\n", parallelism);
if (!cliParams.inputGeneMap) {
logger.warn(
"Warning: Parameter `--input-gene-map` was not specified. Without a gene map sequences will not be "
"translated, there will be no peptides in output files, aminoacid mutations will not be detected and "
"nucleotide sequence alignment will not be informed by codon boundaries.");
} else if (geneMap.empty()) {
logger.warn(
"Warning: Provided gene map is empty. Sequences will not be translated, there will be no peptides in output "
"files, aminoacid mutations will not be detected and nucleotide sequence alignment will not be informed by "
"codon boundaries.");
}
constexpr const auto TABLE_WIDTH = 92;
logger.info("\nSequences:");
logger.info("{:s}", std::string(TABLE_WIDTH, '-'));
logger.info("| {:5s} | {:40s} | {:7s} | {:7s} | {:7s} | {:7s} |",//
"Index", "Seq. name", "A.score", "A.start", "A.end", "Insert." //
);
logger.info("{:s}\n", std::string(TABLE_WIDTH, '-'));
try {
run(parallelism, inOrder, inputFastaStream, refData, qcRulesConfig, treeString, pcrPrimers, geneMap, options,
outputJsonStream, outputCsvStream, outputTsvStream, outputTreeStream, outputFastaStream, outputInsertionsStream,
outputErrorsFile, outputGeneStreams, shouldWriteReference, logger);
} catch (const std::exception &e) {
logger.error("Error: {:>16s} |", e.what());
}
logger.info("{:s}", std::string(TABLE_WIDTH, '-'));
} catch (const std::exception &e) {
logger.error("Error: {:s}", e.what());
std::exit(1);
}
}
| 41.286732 | 972 | 0.684503 | bigshr |
1bf297ab1e3d6b7600df40296ff54278fe627dad | 168 | cpp | C++ | code/Instructions/ZeroRegInstr/ZeroRegInstr.cpp | LLDevLab/LLDevCompiler | f73f13d38069ab5b571fb136e068eb06387caf4c | [
"BSD-3-Clause"
] | 5 | 2019-10-22T18:37:43.000Z | 2020-12-09T14:00:03.000Z | code/Instructions/ZeroRegInstr/ZeroRegInstr.cpp | LLDevLab/LLDevCompiler | f73f13d38069ab5b571fb136e068eb06387caf4c | [
"BSD-3-Clause"
] | 1 | 2020-03-29T15:30:45.000Z | 2020-03-29T15:30:45.000Z | code/Instructions/ZeroRegInstr/ZeroRegInstr.cpp | LLDevLab/LLDevCompiler | f73f13d38069ab5b571fb136e068eb06387caf4c | [
"BSD-3-Clause"
] | 1 | 2019-12-23T06:51:45.000Z | 2019-12-23T06:51:45.000Z | #include "ZeroRegInstr.h"
ZeroRegInstr::ZeroRegInstr(token_pos pos) : Instruction(pos)
{
}
NONTERMINALS ZeroRegInstr::GetInstructionType()
{
return ZERO_REG_INSTR;
} | 16.8 | 60 | 0.785714 | LLDevLab |
1bfb6e1c4a6a9dcb5a1fd46938405d9f1e114e88 | 6,812 | cpp | C++ | src/asiVisu/pipelines/asiVisu_MeshNScalarPipeline.cpp | CadQuery/AnalysisSitus | f3b379ca9158325a21e50fefba8133cab51d9cd9 | [
"BSD-3-Clause"
] | 3 | 2021-11-04T01:36:56.000Z | 2022-03-10T07:11:01.000Z | src/asiVisu/pipelines/asiVisu_MeshNScalarPipeline.cpp | CadQuery/AnalysisSitus | f3b379ca9158325a21e50fefba8133cab51d9cd9 | [
"BSD-3-Clause"
] | null | null | null | src/asiVisu/pipelines/asiVisu_MeshNScalarPipeline.cpp | CadQuery/AnalysisSitus | f3b379ca9158325a21e50fefba8133cab51d9cd9 | [
"BSD-3-Clause"
] | 1 | 2021-09-25T18:14:30.000Z | 2021-09-25T18:14:30.000Z | //-----------------------------------------------------------------------------
// Created on: 13 November 2015
//-----------------------------------------------------------------------------
// Copyright (c) 2015-present, Sergey Slyadnev
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder(s) nor the
// names of all contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
// Own include
#include <asiVisu_MeshNScalarPipeline.h>
// asiVisu includes
#include <asiVisu_MeshNScalarFilter.h>
#include <asiVisu_MeshResultUtils.h>
#include <asiVisu_MeshUtils.h>
#include <asiVisu_NodeInfo.h>
#include <asiVisu_TriangulationSource.h>
// Active Data includes
#include <ActData_MeshParameter.h>
#include <ActData_ParameterFactory.h>
// OCCT includes
#include <Precision.hxx>
#include <Standard_ProgramError.hxx>
// VTK includes
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkProperty.h>
//-----------------------------------------------------------------------------
asiVisu_MeshNScalarPipeline::asiVisu_MeshNScalarPipeline()
//
: asiVisu_Pipeline( vtkSmartPointer<vtkPolyDataMapper>::New(),
vtkSmartPointer<vtkActor>::New() ),
m_fToler(0.)
{
/* Prepare custom filters */
// Allocate filter populating scalar arrays.
vtkSmartPointer<asiVisu_MeshNScalarFilter>
scFilter = vtkSmartPointer<asiVisu_MeshNScalarFilter>::New();
// Allocate Normals Calculation filter.
vtkSmartPointer<vtkPolyDataNormals>
normalsFilter = vtkSmartPointer<vtkPolyDataNormals>::New();
/* Register custom filters */
m_filterMap.Bind(Filter_NScalar, scFilter);
m_filterMap.Bind(Filter_Normals, normalsFilter);
// Append custom filters to the pipeline.
this->append( m_filterMap.Find(Filter_NScalar) );
this->append( m_filterMap.Find(Filter_Normals) );
}
//-----------------------------------------------------------------------------
void asiVisu_MeshNScalarPipeline::SetInput(const Handle(asiVisu_DataProvider)& dp)
{
Handle(asiVisu_MeshNScalarDataProvider)
meshDp = Handle(asiVisu_MeshNScalarDataProvider)::DownCast(dp);
// Lazy update.
if ( meshDp->MustExecute( this->GetMTime() ) )
{
// Prepare source.
vtkSmartPointer<asiVisu_TriangulationSource>
trisSource = vtkSmartPointer<asiVisu_TriangulationSource>::New();
//
trisSource->CollectEdgesModeOff();
trisSource->CollectVerticesModeOff();
trisSource->SetInputTriangulation( meshDp->GetTriangulation() );
// Initialize safety range.
m_fToler = meshDp->GetTolerance();
// Initialize scalar range.
m_fMinScalar = meshDp->GetMinScalar();
m_fMaxScalar = meshDp->GetMaxScalar();
// Initialize scalars filter.
asiVisu_MeshNScalarFilter*
scFilter = asiVisu_MeshNScalarFilter::SafeDownCast( m_filterMap.Find(Filter_NScalar) );
//
scFilter->SetScalarArrays( meshDp->GetNodeIDs(),
meshDp->GetNodeScalars() );
// Complete pipeline.
this->SetInputConnection( trisSource->GetOutputPort() );
// Bind actor to owning Node ID. Thus we set back reference from VTK
// entity to data object.
asiVisu_NodeInfo::Store( meshDp->GetNodeID(), this->Actor() );
}
// Update modification timestamp.
this->Modified();
}
//-----------------------------------------------------------------------------
void asiVisu_MeshNScalarPipeline::initLookupTable()
{
// Get scalar filter to access the scalar range.
asiVisu_MeshNScalarFilter*
scFilter = asiVisu_MeshNScalarFilter::SafeDownCast( m_filterMap.Find(Filter_NScalar) );
//
scFilter->Update();
// Get scalar range.
const double minScalar = Precision::IsInfinite(m_fMinScalar) ? scFilter->GetMinScalar() : m_fMinScalar;
const double maxScalar = Precision::IsInfinite(m_fMaxScalar) ? scFilter->GetMaxScalar() : m_fMaxScalar;
const double range = maxScalar - minScalar;
// Extra variables.
const int numColors = 256;
// Build and initialize lookup table.
m_lookupTable = vtkSmartPointer<vtkLookupTable>::New();
//
m_lookupTable->SetTableRange(minScalar, maxScalar);
m_lookupTable->SetScaleToLinear();
m_lookupTable->SetNumberOfTableValues(numColors + 1);
// Populate table.
double r, g, b;
for ( int i = 0; i < numColors + 1; i++ )
{
const double val = minScalar + ( (double) i / numColors ) * range;
asiVisu_MeshResultUtils::GetColdHotColorForValue(val, minScalar, maxScalar, m_fToler, r, g, b);
m_lookupTable->SetTableValue(i, r, g, b);
}
}
//-----------------------------------------------------------------------------
void asiVisu_MeshNScalarPipeline::callback_add_to_renderer(vtkRenderer*)
{
this->Actor()->GetProperty()->SetInterpolationToGouraud();
}
//-----------------------------------------------------------------------------
void asiVisu_MeshNScalarPipeline::callback_remove_from_renderer(vtkRenderer*)
{}
//-----------------------------------------------------------------------------
void asiVisu_MeshNScalarPipeline::callback_update()
{
// Initialize lookup table.
this->initLookupTable();
// Bind lookup table to mapper.
asiVisu_MeshResultUtils::InitPointScalarMapper(m_mapper, m_lookupTable,
ARRNAME_MESH_N_SCALARS,
true);
}
| 36.623656 | 105 | 0.653993 | CadQuery |
1bfbeeefd46d791cb9aacd4dcd3c9e3f22b5598d | 5,236 | cpp | C++ | laboratory/1064/Seminar_10/Source.cpp | catalinboja/catalinboja-cpp_2020 | ff1d2dc8620ff722aef151c9c823ec20f766d5b2 | [
"MIT"
] | 4 | 2020-10-13T13:37:15.000Z | 2021-07-10T15:40:40.000Z | laboratory/1064/Seminar_10/Source.cpp | catalinboja/catalinboja-cpp_2020 | ff1d2dc8620ff722aef151c9c823ec20f766d5b2 | [
"MIT"
] | null | null | null | laboratory/1064/Seminar_10/Source.cpp | catalinboja/catalinboja-cpp_2020 | ff1d2dc8620ff722aef151c9c823ec20f766d5b2 | [
"MIT"
] | 7 | 2020-10-16T08:32:42.000Z | 2021-03-02T14:38:28.000Z | #include <iostream>
#include <string>
#include <fstream>
using namespace std;
class InvalidEmailException {
string message = "";
public:
InvalidEmailException() {
}
InvalidEmailException(string msg) {
this->message = msg;
}
string getMessage() {
return this->message;
}
};
class Util {
public:
static void setEmail(string from, string& emailAddress ) {
//test@ase.ro
//test.test@csie.ase.ro
//not valid: test@asero; test.test@ase
int indexAt = from.find("@");
int indexLastDot = from.find_last_of(".");
if (indexAt == -1) {
throw new InvalidEmailException("Missing @");
}
if (indexLastDot == -1) {
throw InvalidEmailException("Missing .");
}
if (indexAt > indexLastDot) {
throw InvalidEmailException("The email is invalid. Missing domain");
}
emailAddress = from;
}
};
class Email {
string from = "";
char subject[100] = "";
string content = "";
bool requestReadConfirmation = false;
public:
Email(string from, const char* subject, string content) {
this->setFrom(from);
//this->subject = subject;
strcpy_s(this->subject, 100, subject);
this->subject[99] = '\0'; //in case you copy 100 chars
this->content = content;
}
private:
Email() {
}
public:
void setFrom(string from) {
//test@ase.ro
//test.test@csie.ase.ro
//not valid: test@asero; test.test@ase
int indexAt = from.find("@");
int indexLastDot = from.find_last_of(".");
if (indexAt == -1) {
throw new InvalidEmailException("Missing @");
}
if (indexLastDot == -1) {
throw InvalidEmailException("Missing .");
}
if (indexAt > indexLastDot) {
throw InvalidEmailException("The email is invalid. Missing domain");
}
this->from = from;
}
friend class Inbox;
friend void operator<<(ostream& console, Email& email);
};
class Inbox {
std::string account;
Email* emails = nullptr; //composition - "has a" relations
int noEmails = 0;
public:
Inbox(string account) {
//this->account = account;
Util::setEmail(account, this->account);
}
~Inbox() {
if (emails != nullptr) {
delete[] emails;
}
}
Inbox(const Inbox& inbox) {
this->account = inbox.account;
//don't
//this->emails = inbox.emails;
this->emails = new Email[inbox.noEmails];
for (int i = 0; i < inbox.noEmails; i++) {
this->emails[i] = inbox.emails[i]; //operator = from Email
}
this->noEmails = inbox.noEmails;
}
void operator=(const Inbox& inbox) {
if (this != &inbox) {
if (this->emails) {
delete[] this->emails;
}
this->account = inbox.account;
this->emails = new Email[inbox.noEmails];
for (int i = 0; i < inbox.noEmails; i++) {
this->emails[i] = inbox.emails[i]; //operator = from Email
}
this->noEmails = inbox.noEmails;
}
}
void operator<<(Email email) {
Email* newEmails = new Email[this->noEmails + 1];
for (int i = 0; i < this->noEmails; i++) {
newEmails[i] = this->emails[i];
}
newEmails[this->noEmails] = email;
this->noEmails += 1;
if (this->emails) {
delete[] this->emails;
}
this->emails = newEmails;
}
void operator+=(Email email) {
*this << email;
}
friend void operator<<(ostream& console, Inbox& inbox);
friend void operator<<(ofstream& console, Inbox& inbox);
};
void operator<<(ostream& console, Inbox& inbox) {
console << endl << "Inbox for account " << inbox.account;
if (inbox.noEmails > 0) {
console << endl << "Emails: ";
for (int i = 0; i < inbox.noEmails; i++) {
console << inbox.emails[i];
}
}
}
void operator<<(ofstream& console, Inbox& inbox) {
console << endl << "**************Inbox for account " << inbox.account;
if (inbox.noEmails > 0) {
console << endl << "Emails: ";
for (int i = 0; i < inbox.noEmails; i++) {
console << inbox.emails[i];
}
}
}
void operator<<(ostream& console, Email& email) {
console << endl << "-----------------------";
console << endl << "From: " << email.from;
console << endl << "Subject: " << email.subject;
console << endl << "Content: " << email.content;
console << endl << (email.requestReadConfirmation ? "*** Send confirmation ***" : "");
}
int main(int argc, char* argv[]) {
try {
Email email1("john@stud.ase.ro", "Zoom link", "Here is the lab zoom link");
Email email2("alicestud", "Zoom link", "Here is the lab zoom link");
cout << endl << "End of try block";
}
catch (InvalidEmailException ex) {
cout << endl << ex.getMessage();
}
catch (InvalidEmailException* pEx) {
cout << endl << "*****" << pEx->getMessage();
}
while (true) {
try {
string emailAddr;
cout << endl << "Give me your email: ";
cin >> emailAddr;
Email email3(emailAddr, "Test email", "Hello");
break;
}
catch (...) {
cout << endl << "Wrong email. Try again.";
}
}
Inbox inbox("me@ase.ro");
Email email1("john@stud.ase.ro", "Zoom link", "Here is the lab zoom link");
Email email2("alice@stud.ase.ro", "Project class", "Here is the class");
cout << inbox;
//inbox = inbox + email1;
//inbox = email1 + inbox;
inbox += email1;
inbox << email1;
inbox << email2;
cout << inbox;
ofstream report;
report.open("My emails.txt", ios::out | ios::trunc);
if (report.is_open()) {
report << inbox;
report.close();
}
else {
cout << endl << "We have a problem with the file";
}
} | 22.765217 | 87 | 0.620321 | catalinboja |
1bfd6941b75814d644114996193a344f528e87e2 | 3,243 | cpp | C++ | test/storage/cache_revalidate.cpp | donpark/mapbox-gl-native | efa7dad89c61fe0fcc01a492e8db8e36b8f27f53 | [
"BSD-2-Clause"
] | 1 | 2015-07-01T21:59:13.000Z | 2015-07-01T21:59:13.000Z | test/storage/cache_revalidate.cpp | donpark/mapbox-gl-native | efa7dad89c61fe0fcc01a492e8db8e36b8f27f53 | [
"BSD-2-Clause"
] | null | null | null | test/storage/cache_revalidate.cpp | donpark/mapbox-gl-native | efa7dad89c61fe0fcc01a492e8db8e36b8f27f53 | [
"BSD-2-Clause"
] | null | null | null | #include "storage.hpp"
#include <uv.h>
#include <mbgl/storage/default_file_source.hpp>
#include <mbgl/storage/sqlite_cache.hpp>
TEST_F(Storage, CacheRevalidate) {
SCOPED_TEST(CacheRevalidateSame)
SCOPED_TEST(CacheRevalidateModified)
SCOPED_TEST(CacheRevalidateEtag)
using namespace mbgl;
SQLiteCache cache(":memory:");
DefaultFileSource fs(&cache);
const Resource revalidateSame { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" };
fs.request(revalidateSame, uv_default_loop(), [&](const Response &res) {
EXPECT_EQ(Response::Successful, res.status);
EXPECT_EQ("Response", res.data);
EXPECT_EQ(0, res.expires);
EXPECT_EQ(0, res.modified);
EXPECT_EQ("snowfall", res.etag);
EXPECT_EQ("", res.message);
fs.request(revalidateSame, uv_default_loop(), [&, res](const Response &res2) {
EXPECT_EQ(Response::Successful, res2.status);
EXPECT_EQ("Response", res2.data);
// We use this to indicate that a 304 reply came back.
EXPECT_LT(0, res2.expires);
EXPECT_EQ(0, res2.modified);
// We're not sending the ETag in the 304 reply, but it should still be there.
EXPECT_EQ("snowfall", res2.etag);
EXPECT_EQ("", res2.message);
CacheRevalidateSame.finish();
});
});
const Resource revalidateModified{ Resource::Unknown,
"http://127.0.0.1:3000/revalidate-modified" };
fs.request(revalidateModified, uv_default_loop(), [&](const Response &res) {
EXPECT_EQ(Response::Successful, res.status);
EXPECT_EQ("Response", res.data);
EXPECT_EQ(0, res.expires);
EXPECT_EQ(1420070400, res.modified);
EXPECT_EQ("", res.etag);
EXPECT_EQ("", res.message);
fs.request(revalidateModified, uv_default_loop(), [&, res](const Response &res2) {
EXPECT_EQ(Response::Successful, res2.status);
EXPECT_EQ("Response", res2.data);
// We use this to indicate that a 304 reply came back.
EXPECT_LT(0, res2.expires);
EXPECT_EQ(1420070400, res2.modified);
EXPECT_EQ("", res2.etag);
EXPECT_EQ("", res2.message);
CacheRevalidateModified.finish();
});
});
const Resource revalidateEtag { Resource::Unknown, "http://127.0.0.1:3000/revalidate-etag" };
fs.request(revalidateEtag, uv_default_loop(), [&](const Response &res) {
EXPECT_EQ(Response::Successful, res.status);
EXPECT_EQ("Response 1", res.data);
EXPECT_EQ(0, res.expires);
EXPECT_EQ(0, res.modified);
EXPECT_EQ("response-1", res.etag);
EXPECT_EQ("", res.message);
fs.request(revalidateEtag, uv_default_loop(), [&, res](const Response &res2) {
EXPECT_EQ(Response::Successful, res2.status);
EXPECT_EQ("Response 2", res2.data);
EXPECT_EQ(0, res2.expires);
EXPECT_EQ(0, res2.modified);
EXPECT_EQ("response-2", res2.etag);
EXPECT_EQ("", res2.message);
CacheRevalidateEtag.finish();
});
});
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
| 37.275862 | 97 | 0.612704 | donpark |
1bfe12517e51e14adf9670811267d0c6da4d2bf8 | 16,774 | cpp | C++ | src/context.cpp | ShaderKitty/geodesuka | 1578f2fe3e5a7102d2e314406c89a48132a71675 | [
"MIT"
] | 3 | 2021-08-07T15:11:35.000Z | 2021-11-17T18:59:45.000Z | src/context.cpp | ShaderKitty/geodesuka | 1578f2fe3e5a7102d2e314406c89a48132a71675 | [
"MIT"
] | null | null | null | src/context.cpp | ShaderKitty/geodesuka | 1578f2fe3e5a7102d2e314406c89a48132a71675 | [
"MIT"
] | null | null | null | #include <geodesuka/engine.h>
#include <geodesuka/core/gcl/context.h>
#include <cstdlib>
#include <climits>
#include <GLFW/glfw3.h>
namespace geodesuka::core::gcl {
context::context(engine* aEngine, device* aDevice, uint32_t aExtensionCount, const char** aExtensionList) {
// List of operations.
// Check for support of required extensions requested i
// 1: Check for extensions.
// 2: Queue Create Info.
// 3: Create Logical Device.
this->Engine = aEngine;
this->Device = aDevice;
if ((this->Engine == nullptr) || (this->Device == nullptr)) return;
VkResult Result = VkResult::VK_SUCCESS;
// If -1, then the option is not supported by the device.
this->QFI[0] = this->Device->qfi(device::qfs::TRANSFER);
this->QFI[1] = this->Device->qfi(device::qfs::COMPUTE);
this->QFI[2] = this->Device->qfi(device::qfs::GRAPHICS);
this->QFI[3] = this->Device->qfi(device::qfs::PRESENT);
// Register this with context.h
this->Support = 0;
if (this->QFI[0] >= 0) {
this->Support |= device::qfs::TRANSFER;
}
if (this->QFI[1] >= 0) {
this->Support |= device::qfs::COMPUTE;
}
if (this->QFI[2] >= 0) {
this->Support |= device::qfs::GRAPHICS;
}
if (this->QFI[3] >= 0) {
this->Support |= device::qfs::PRESENT;
}
// UQFI set to -1, as default. Do not use.
this->UQFI[0] = -1;
this->UQFI[1] = -1;
this->UQFI[2] = -1;
this->UQFI[3] = -1;
for (int i = 0; i < 4; i++) {
if (this->QFI[i] == -1) continue;
if (this->UQFICount == 0) {
this->UQFI[this->UQFICount] = this->QFI[i];
this->UQFICount += 1;
}
bool AlreadyExists = false;
for (size_t j = 0; j < this->UQFICount; j++) {
if (this->QFI[i] == this->UQFI[j]) {
AlreadyExists = true;
break;
}
}
if (!AlreadyExists) {
this->UQFI[this->UQFICount] = this->QFI[i];
this->UQFICount += 1;
}
}
// With UQFI found, generate queues for selected indices.
uint32_t QueueFamilyCount = 0;
const VkQueueFamilyProperties *QueueFamilyProperty = this->Device->get_queue_families(&QueueFamilyCount);
this->QueueCount = 0;
for (int i = 0; i < this->UQFICount; i++) {
this->QueueCount += QueueFamilyProperty[this->UQFI[i]].queueCount;
}
this->QueueFamilyPriority = (float**)malloc(this->UQFICount * sizeof(float*));
if (this->QueueFamilyPriority != NULL) {
for (int i = 0; i < this->UQFICount; i++) {
this->QueueFamilyPriority[i] = (float*)malloc(QueueFamilyProperty[this->UQFI[i]].queueCount * sizeof(float));
if (this->QueueFamilyPriority[i] != NULL) {
for (uint32_t j = 0; j < QueueFamilyProperty[this->UQFI[i]].queueCount; j++) {
this->QueueFamilyPriority[i][j] = 1.0f;
}
}
}
}
this->QueueCreateInfo = (VkDeviceQueueCreateInfo*)malloc(this->UQFICount * sizeof(VkDeviceQueueCreateInfo));
this->Queue = new queue[this->QueueCount];
// Check for allocation failure.
bool Allocated = true;
Allocated = (this->QueueFamilyPriority != NULL) && (this->QueueCreateInfo != NULL) && (this->Queue != nullptr);
if (Allocated) {
for (int i = 0; i < this->UQFICount; i++) {
Allocated = Allocated && (this->QueueFamilyPriority[i] != NULL);
}
}
// Fail condition
if (!Allocated) {
delete[] this->Queue; this->Queue = nullptr;
free(this->QueueCreateInfo); this->QueueCreateInfo = NULL;
if (this->QueueFamilyPriority != NULL) {
for (int i = 0; i < this->UQFICount; i++) {
free(this->QueueFamilyPriority[i]); this->QueueFamilyPriority = NULL;
}
}
free(this->QueueFamilyPriority); this->QueueFamilyPriority = NULL;
return;
}
// Loads all create info.
for (int i = 0; i < this->UQFICount; i++) {
this->QueueCreateInfo[i].sType = VkStructureType::VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
this->QueueCreateInfo[i].pNext = NULL;
this->QueueCreateInfo[i].flags = 0;
this->QueueCreateInfo[i].queueFamilyIndex = this->UQFI[i];
this->QueueCreateInfo[i].queueCount = QueueFamilyProperty[this->UQFI[i]].queueCount;
this->QueueCreateInfo[i].pQueuePriorities = this->QueueFamilyPriority[i];
}
// Load VkDevice Create Info.
this->CreateInfo.sType = VkStructureType::VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
this->CreateInfo.pNext = NULL;
this->CreateInfo.flags = 0;
this->CreateInfo.queueCreateInfoCount = this->UQFICount;
this->CreateInfo.pQueueCreateInfos = this->QueueCreateInfo;
this->CreateInfo.enabledLayerCount = 0;
this->CreateInfo.ppEnabledLayerNames = NULL;
if (this->Device->is_extension_list_supported(aExtensionCount, aExtensionList)) {
this->CreateInfo.enabledExtensionCount = aExtensionCount;
this->CreateInfo.ppEnabledExtensionNames = aExtensionList;
}
else {
this->CreateInfo.enabledExtensionCount = 0;
this->CreateInfo.ppEnabledExtensionNames = NULL;
}
this->CreateInfo.pEnabledFeatures = &this->Device->Features;
Result = vkCreateDevice(this->Device->handle(), &this->CreateInfo, NULL, &this->Handle);
// Now get queues from device.
size_t QueueArrayOffset = 0;
for (int i = 0; i < this->UQFICount; i++) {
for (uint32_t j = 0; j < QueueFamilyProperty[this->UQFI[i]].queueCount; j++) {
size_t Index = j + QueueArrayOffset;
this->Queue[Index].i = this->UQFI[i];
this->Queue[Index].j = j;
vkGetDeviceQueue(this->Handle, this->UQFI[i], j, &this->Queue[Index].Handle);
}
QueueArrayOffset += QueueFamilyProperty[this->UQFI[i]].queueCount;
}
for (int i = 0; i < 3; i++) {
this->PoolCreateInfo[i].sType = VkStructureType::VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
this->PoolCreateInfo[i].pNext = NULL;
}
// VK_COMMAND_POOL_CREATE_TRANSIENT_BIT
// Will be used for one time submits and short lived command buffers.
// This will be useful in object construction and uploading.
// VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT
// Allows individual command buffers to be reset.
// One time submit pool
// Transfer operations.
this->PoolCreateInfo[0].flags = VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
this->PoolCreateInfo[0].queueFamilyIndex = this->qfi(device::qfs::TRANSFER);
// Compute operations.
this->PoolCreateInfo[1].flags = VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
this->PoolCreateInfo[1].queueFamilyIndex = this->qfi(device::qfs::COMPUTE);
// Graphics operations.
this->PoolCreateInfo[2].flags = VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
this->PoolCreateInfo[2].queueFamilyIndex = this->qfi(device::qfs::GRAPHICS);
for (int i = 0; i < 3; i++) {
if (this->QFI[i] != -1) {
Result = vkCreateCommandPool(this->Handle, &this->PoolCreateInfo[i], NULL, &this->Pool[i]);
}
else {
this->Pool[i] = VK_NULL_HANDLE;
}
this->CommandBufferCount[i] = 0;
this->CommandBuffer[i] = NULL;
}
this->Engine->submit(this);
}
context::~context() {
// lock so context can be safely removed from engine instance.
this->Mutex.lock();
this->Engine->remove(this);
// Clear all command buffers and pools.
for (int i = 0; i < 3; i++) {
if (this->CommandBufferCount[i] > 0) {
vkFreeCommandBuffers(this->Handle, this->Pool[i], this->CommandBufferCount[i], this->CommandBuffer[i]);
}
free(this->CommandBuffer[i]); this->CommandBuffer[i] = NULL;
this->CommandBufferCount[i] = 0;
vkDestroyCommandPool(this->Handle, this->Pool[i], NULL);
this->Pool[i] = VK_NULL_HANDLE;
}
delete[] this->Queue; this->Queue = nullptr;
this->QueueCount = 0;
vkDestroyDevice(this->Handle, NULL); this->Handle = VK_NULL_HANDLE;
free(this->QueueCreateInfo); this->QueueCreateInfo = NULL;
if (this->QueueFamilyPriority != NULL) {
for (int i = 0; i < this->UQFICount; i++) {
free(this->QueueFamilyPriority[i]); this->QueueFamilyPriority[i] = NULL;
}
}
free(this->QueueFamilyPriority); this->QueueFamilyPriority = NULL;
for (int i = 0; i < 4; i++) {
this->QFI[i] = -1;
this->UQFI[i] = -1;
}
this->UQFICount = 0;
this->Support = 0;
this->Engine = nullptr;
this->Device = nullptr;
this->Mutex.unlock();
}
int context::qfi(device::qfs aQFS) {
switch (aQFS) {
default : return -1;
case device::qfs::TRANSFER : return this->QFI[0];
case device::qfs::COMPUTE : return this->QFI[1];
case device::qfs::GRAPHICS : return this->QFI[2];
case device::qfs::PRESENT : return this->QFI[3];
}
return 0;
}
bool context::available(device::qfs aQFS) {
return (this->qfi(aQFS) != -1);
}
VkCommandBuffer context::create(device::qfs aQFS) {
VkCommandBuffer temp = VK_NULL_HANDLE;
this->create(aQFS, 1, &temp);
return temp;
}
VkResult context::create(device::qfs aQFS, uint32_t aCommandBufferCount, VkCommandBuffer* aCommandBuffer) {
VkResult Result = VkResult::VK_INCOMPLETE;
if ((this->qfi(aQFS) < 0) || (aCommandBufferCount == 0) || (aCommandBuffer == NULL)) return Result;
int i;
switch (aQFS) {
default: return Result;
case device::qfs::TRANSFER: i = 0; break;
case device::qfs::COMPUTE: i = 1; break;
case device::qfs::GRAPHICS: i = 2; break;
}
// Pool is invalid.
if (this->Pool[i] == VK_NULL_HANDLE) return Result;
VkCommandBufferAllocateInfo AllocateInfo{};
AllocateInfo.sType = VkStructureType::VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
AllocateInfo.pNext = NULL;
AllocateInfo.commandPool = this->Pool[i];
AllocateInfo.level = VkCommandBufferLevel::VK_COMMAND_BUFFER_LEVEL_PRIMARY;
AllocateInfo.commandBufferCount = aCommandBufferCount;
this->Mutex.lock();
// Check if allocation is succesful.
Result = vkAllocateCommandBuffers(this->Handle, &AllocateInfo, aCommandBuffer);
if (Result != VkResult::VK_SUCCESS) {
this->Mutex.unlock();
return Result;
}
// alloc/realloc command buffer memory pool.
void* nptr = NULL;
if (this->CommandBuffer[i] == NULL) {
nptr = malloc(aCommandBufferCount * sizeof(VkCommandBuffer));
}
else {
nptr = realloc(this->CommandBuffer[i], (aCommandBufferCount + this->CommandBufferCount[i]) * sizeof(VkCommandBuffer));
}
// Out of host memory.
if (nptr == NULL) {
Result = VkResult::VK_ERROR_OUT_OF_HOST_MEMORY;
vkFreeCommandBuffers(this->Handle, this->Pool[i], aCommandBufferCount, aCommandBuffer);
for (size_t j = 0; j < aCommandBufferCount; j++) {
aCommandBuffer[j] = VK_NULL_HANDLE;
}
this->Mutex.unlock();
return Result;
}
// Copy new pointer over.
this->CommandBuffer[i] = (VkCommandBuffer*)nptr;
// Store new command buffers.
std::memcpy(&(this->CommandBuffer[i][this->CommandBufferCount[i]]), aCommandBuffer, aCommandBufferCount * sizeof(VkCommandBuffer));
//for (int j = this->CommandBufferCount[i]; j < aCommandBufferCount + this->CommandBufferCount[i]; j++) {
// this->CommandBuffer[i][j] = aCommandBuffer[j - this->CommandBufferCount[i]];
//}
// Account for new buffer count.
this->CommandBufferCount[i] += aCommandBufferCount;
this->Mutex.unlock();
return Result;
}
void context::destroy(device::qfs aQFS, VkCommandBuffer& aCommandBuffer) {
this->destroy(aQFS, 1, &aCommandBuffer);
}
void context::destroy(device::qfs aQFS, uint32_t aCommandBufferCount, VkCommandBuffer* aCommandBuffer) {
if ((this->qfi(aQFS) < 0) || (aCommandBufferCount == 0) || (aCommandBuffer == NULL)) return;
// Takes a list of aggregated command buffers and cross references them
// with already created command buffers.
int Index;
switch (aQFS) {
default: return;
case device::qfs::TRANSFER: Index = 0; break;
case device::qfs::COMPUTE: Index = 1; break;
case device::qfs::GRAPHICS: Index = 2; break;
}
if (this->Pool[Index] == VK_NULL_HANDLE) return;
// Match
int MatchCount = 0;
VkCommandBuffer* MatchBuffer = NULL;
VkCommandBuffer* NewBuffer = NULL;
this->Mutex.lock();
// Count number of matches.
for (uint32_t i = 0; i < this->CommandBufferCount[Index]; i++) {
for (uint32_t j = 0; j < aCommandBufferCount; j++) {
if (this->CommandBuffer[Index][i] == aCommandBuffer[j]) {
MatchCount += 1;
}
}
}
// No command buffers matched.
if (MatchCount == 0) {
this->Mutex.unlock();
return;
}
// Clears all command buffer with family in question.
if (MatchCount == this->CommandBufferCount[Index]) {
for (uint32_t i = 0; i < this->CommandBufferCount[Index]; i++) {
for (uint32_t j = 0; j < aCommandBufferCount; j++) {
if (this->CommandBuffer[Index][i] == aCommandBuffer[j]) {
aCommandBuffer[j] = VK_NULL_HANDLE;
}
}
}
vkFreeCommandBuffers(this->Handle, this->Pool[Index], aCommandBufferCount, aCommandBuffer);
free(this->CommandBuffer[Index]);
this->CommandBuffer[Index] = NULL;
this->CommandBufferCount[Index] = 0;
this->Mutex.unlock();
return;
}
MatchBuffer = (VkCommandBuffer*)malloc(MatchCount * sizeof(VkCommandBuffer));
NewBuffer = (VkCommandBuffer*)malloc((this->CommandBufferCount[Index] - MatchCount) * sizeof(VkCommandBuffer));
// Memory allocation failure.
if ((MatchBuffer == NULL) || (NewBuffer == NULL)) {
free(MatchBuffer);
MatchBuffer = NULL;
free(NewBuffer);
NewBuffer = NULL;
this->Mutex.unlock();
return;
}
int m = 0;
int n = 0;
// Iterate through pre existing buffers and compare.
for (uint32_t i = 0; i < this->CommandBufferCount[Index]; i++) {
bool isFound = false;
int FoundIndex = -1;
// Compare to proposed buffers.
for (uint32_t j = 0; j < aCommandBufferCount; j++) {
if (this->CommandBuffer[Index][i] == aCommandBuffer[j]) {
isFound = true;
FoundIndex = j;
break;
}
}
if (isFound) {
// If match, move to MatchBuffer;
MatchBuffer[m] = aCommandBuffer[FoundIndex];
aCommandBuffer[FoundIndex] = VK_NULL_HANDLE;
m += 1;
}
else {
NewBuffer[n] = this->CommandBuffer[Index][i];
n += 1;
}
}
vkFreeCommandBuffers(this->Handle, this->Pool[Index], MatchCount, MatchBuffer);
free(MatchBuffer);
MatchBuffer = NULL;
free(this->CommandBuffer[Index]);
this->CommandBuffer[Index] = NewBuffer;
this->CommandBufferCount[Index] = this->CommandBufferCount[Index] - MatchCount;
this->Mutex.unlock();
return;
}
VkResult context::submit(device::qfs aQFS, uint32_t aSubmissionCount, VkSubmitInfo* aSubmission, VkFence aFence) {
VkResult Result = VkResult::VK_INCOMPLETE;
if ((aSubmissionCount < 1) || (aSubmission == NULL) || (this->qfi(aQFS) == -1)) return Result;
// When placing an execution submission, thread must find
// and available queue to submit to.
uint32_t QueueFamilyCount = 0;
const VkQueueFamilyProperties* QueueFamilyProperty = this->Device->get_queue_families(&QueueFamilyCount);
int lQFI = this->qfi(aQFS);
int Offset = 0;
int lQueueCount = 0;
for (int i = 0; i < this->UQFICount; i++) {
if (this->UQFI[i] == lQFI) {
lQueueCount = QueueFamilyProperty[this->UQFI[i]].queueCount;
break;
}
Offset += QueueFamilyProperty[this->UQFI[i]].queueCount;
}
int i = 0;
while (true) {
int Index = i + Offset;
if (this->Queue[Index].Mutex.try_lock()) {
Result = vkQueueSubmit(this->Queue[Index].Handle, aSubmissionCount, aSubmission, aFence);
this->Queue[Index].Mutex.unlock();
break;
}
i += 1;
if (i == lQueueCount) {
i = 0;
}
}
return Result;
}
VkResult context::present(VkPresentInfoKHR* aPresentation) {
VkResult Result = VkResult::VK_INCOMPLETE;
if ((aPresentation == NULL) || (this->qfi(device::qfs::PRESENT) == -1)) return Result;
uint32_t QueueFamilyCount = 0;
const VkQueueFamilyProperties* QueueFamilyProperty = this->Device->get_queue_families(&QueueFamilyCount);
int lQFI = this->qfi(device::qfs::PRESENT);
int Offset = 0;
int lQueueCount = 0;
for (int i = 0; i < this->UQFICount; i++) {
if (this->UQFI[i] == lQFI) {
lQueueCount = QueueFamilyProperty[this->UQFI[i]].queueCount;
break;
}
Offset += QueueFamilyProperty[this->UQFI[i]].queueCount;
}
int i = 0;
while (true) {
int Index = i + Offset;
if (this->Queue[Index].Mutex.try_lock()) {
Result = vkQueuePresentKHR(this->Queue[Index].Handle, aPresentation);
this->Queue[Index].Mutex.unlock();
break;
}
i += 1;
if (i == lQueueCount) {
i = 0;
}
}
return Result;
}
VkInstance context::inst() {
return this->Device->inst();
}
device* context::parent() {
return this->Device;
}
VkDevice context::handle() {
return this->Handle;
}
context::queue::queue() {
this->i = 0;
this->j = 0;
this->Handle = VK_NULL_HANDLE;
}
}
| 31.768939 | 182 | 0.670442 | ShaderKitty |
4001eb3c7bd2196ab1f7e6840bcae7bf762de7e6 | 587 | cpp | C++ | VGP242/02_HelloDirectX/TestState.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | VGP242/02_HelloDirectX/TestState.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | VGP242/02_HelloDirectX/TestState.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | #include "TestState.h"
using namespace JimmyGod::Input;
using namespace JimmyGod::Graphics;
void RedState::Initialize()
{
GraphicsSystem::Get()->SetClearColor(Colors::Red);
}
void RedState::Update(float deltaTime)
{
if (InputSystem::Get()->IsKeyPressed(KeyCode::SPACE))
JimmyGod::MainApp().ChangeState("BlueState");
}
void BlueState::Initialize()
{
GraphicsSystem::Get()->SetClearColor(Colors::Blue);
}
void BlueState::Update(float deltaTime)
{
if (InputSystem::Get()->IsKeyPressed(KeyCode::SPACE))
JimmyGod::MainApp().ChangeState("RedState");
}
| 20.964286 | 55 | 0.701874 | TheJimmyGod |
400357caa5cc97dc4d72de2eb2724fffb0c1ae0e | 1,857 | cpp | C++ | dev/Gems/PythonAssetBuilder/Code/Source/PythonBuilderMessageSink.cpp | brianherrera/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/PythonAssetBuilder/Code/Source/PythonBuilderMessageSink.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/PythonAssetBuilder/Code/Source/PythonBuilderMessageSink.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <PythonBuilderMessageSink.h>
#include <AssetBuilderSDK/AssetBuilderBusses.h>
#include <PythonAssetBuilder/PythonAssetBuilderBus.h>
namespace PythonAssetBuilder
{
PythonBuilderMessageSink::PythonBuilderMessageSink()
{
AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect();
}
PythonBuilderMessageSink::~PythonBuilderMessageSink()
{
AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect();
}
void PythonBuilderMessageSink::OnTraceMessage(AZStd::string_view message)
{
if (message.empty() == false)
{
AZ_TracePrintf(AssetBuilderSDK::InfoWindow, "%.*s", static_cast<int>(message.size()), message.data());
}
}
void PythonBuilderMessageSink::OnErrorMessage(AZStd::string_view message)
{
if (message.empty() == false)
{
AZ_Error(AssetBuilderSDK::ErrorWindow, false, "ERROR: %.*s", static_cast<int>(message.size()), message.data());
}
}
void PythonBuilderMessageSink::OnExceptionMessage(AZStd::string_view message)
{
if (message.empty() == false)
{
AZ_Error(AssetBuilderSDK::ErrorWindow, false, "EXCEPTION: %.*s", static_cast<int>(message.size()), message.data());
}
}
}
| 34.388889 | 127 | 0.692515 | brianherrera |
4006e199b952cc9f344a2d5ba1ae31e1c8f437a3 | 34,885 | cpp | C++ | libsyndicate/driver.cpp | jcnelson/syndicate | 4837265be3e0aa18cdf4ee50316dbfc2d1f06e5b | [
"Apache-2.0"
] | 16 | 2015-01-02T15:39:04.000Z | 2016-03-17T06:38:46.000Z | libsyndicate/driver.cpp | jcnelson/syndicate | 4837265be3e0aa18cdf4ee50316dbfc2d1f06e5b | [
"Apache-2.0"
] | 37 | 2015-01-28T20:58:05.000Z | 2016-03-22T04:01:32.000Z | libsyndicate/driver.cpp | jcnelson/syndicate | 4837265be3e0aa18cdf4ee50316dbfc2d1f06e5b | [
"Apache-2.0"
] | 8 | 2015-04-08T02:26:03.000Z | 2016-03-04T05:56:24.000Z | /*
Copyright 2015 The Trustees of Princeton University
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "libsyndicate/libsyndicate.h"
#include "libsyndicate/driver.h"
#include "libsyndicate/crypt.h"
#include "libsyndicate/gateway.h"
struct SG_driver {
SG_driver_conf_t* driver_conf; // driver config params
SG_driver_secrets_t* driver_secrets; // driver secrets
struct SG_chunk driver_text; // driver code
void* cls; // supplied by the driver on initialization
int running; // set to non-zero of this driver is initialized
pthread_rwlock_t reload_lock; // if write-locked, no method can be called here (i.e. the driver is reloading)
// driver processes: map role to group of processes that implement it
SG_driver_proc_group_t* groups;
// driver info
char* exec_str;
char** roles;
size_t num_roles;
int num_instances; // number of instances of each role
// pointer to global conf
struct md_syndicate_conf* conf;
};
// alloc a driver
struct SG_driver* SG_driver_alloc(void) {
return SG_CALLOC( struct SG_driver, 1 );
}
// convert a reqdat to a fully-qualified chunk path, to be fed into the driver worker.
// the string will be terminated with a newline, and a null.
// return the null-terminated string on success
// return NULL on OOM or invalid request
char* SG_driver_reqdat_to_path( struct SG_request_data* reqdat ) {
char* ret = NULL;
size_t len = 0;
if( reqdat->user_id == SG_INVALID_USER_ID ) {
return NULL;
}
if( SG_request_is_block( reqdat ) ) {
// include owner, volume, file, version, block, block version
len = 51 + 51 + 51 + 51 + 51 + 51 + 11;
ret = SG_CALLOC( char, len + 1 );
if( ret == NULL ) {
return NULL;
}
snprintf( ret, len, "%" PRIu64 ":/%" PRIu64 "/%" PRIX64 ".%" PRId64 "[%" PRIu64 ".%" PRId64 "]",
reqdat->user_id, reqdat->volume_id, reqdat->file_id, reqdat->file_version, reqdat->block_id, reqdat->block_version );
return ret;
}
else if( SG_request_is_manifest( reqdat ) ) {
// include owner, volume, file, version, manifest timestamp
len = 51 + 51 + 51 + 51 + 51 + 51 + 11;
ret = SG_CALLOC( char, len + 1 );
if( ret == NULL ) {
return NULL;
}
snprintf( ret, len, "%" PRIu64 ":/%" PRIu64 "/%" PRIX64 ".%" PRId64 "/manifest.%ld.%ld",
reqdat->user_id, reqdat->volume_id, reqdat->file_id, reqdat->file_version, reqdat->manifest_timestamp.tv_sec, reqdat->manifest_timestamp.tv_nsec );
return ret;
}
else {
return NULL;
}
}
// load a string as a JSON object
// return 0 on success, and fill in *jobj_ret
// return -ENOMEM on OOM
// return -EINVAL if we failed to parses
static int SG_parse_json_object( struct json_object** jobj_ret, char const* obj_json, size_t obj_json_len ) {
char* tmp = SG_CALLOC( char, obj_json_len + 1 );
if( tmp == NULL ) {
return -ENOMEM;
}
memcpy( tmp, obj_json, obj_json_len );
// obj_json should be a valid json string that contains a single dictionary.
struct json_tokener* tok = json_tokener_new();
if( tok == NULL ) {
SG_safe_free( tmp );
return -ENOMEM;
}
struct json_object* jobj = json_tokener_parse_ex( tok, tmp, obj_json_len );
json_tokener_free( tok );
if( jobj == NULL ) {
SG_error("Failed to parse JSON object %p '%s'\n", obj_json, tmp );
SG_safe_free( tmp );
return -EINVAL;
}
SG_safe_free( tmp );
// should be an object
enum json_type jtype = json_object_get_type( jobj );
if( jtype != json_type_object ) {
SG_error("%s", "JSON config is not a JSON object\n");
json_object_put( jobj );
return -EINVAL;
}
*jobj_ret = jobj;
return 0;
}
// load a base64-encoded string into a JSON object.
// return 0 on success, and set *jobj_ret
// return -ENOMEM on OOM
// return -EINVAL on failure to parse the string (either from base64 to binary, or from binary to json)
static int SG_parse_b64_object( struct json_object** jobj_ret, char const* obj_b64, size_t obj_b64_len ) {
// deserialize...
char* obj_json = NULL;
size_t obj_json_len = 0;
int rc = 0;
rc = md_base64_decode( obj_b64, obj_b64_len, &obj_json, &obj_json_len );
if( rc != 0 ) {
SG_error("md_base64_decode rc = %d\n", rc );
if( rc != -ENOMEM ) {
return -EINVAL;
}
else {
return rc;
}
}
rc = SG_parse_json_object( jobj_ret, obj_json, obj_json_len );
if( rc != 0 ) {
SG_error("SG_parse_json_object rc = %d\n", rc );
}
SG_safe_free( obj_json );
return rc;
}
// parse the config
// return 0 on success
// return -ENOMEM on OOM
// return -EINVAL on parse error
static int SG_parse_driver_config( SG_driver_conf_t* driver_conf, char const* driver_conf_b64, size_t driver_conf_b64_len ) {
struct json_object* jobj = NULL;
int rc = SG_parse_b64_object( &jobj, driver_conf_b64, driver_conf_b64_len );
if( rc != 0 ) {
SG_error("Failed to parse JSON object, rc = %d\n", rc );
return rc;
}
// iterate through the fields
json_object_object_foreach( jobj, key, val ) {
// each field needs to be a string...
enum json_type jtype = json_object_get_type( val );
if( jtype != json_type_string ) {
SG_error("%s is not a JSON string\n", key );
rc = -EINVAL;
break;
}
// get the value
char const* value = json_object_get_string( val );
if( value == NULL ) {
// OOM
rc = -ENOMEM;
break;
}
size_t value_len = strlen(value); // json_object_get_string_len( val );
try {
// put it into the config
string key_s( key );
string value_s( value, value_len );
(*driver_conf)[ key_s ] = value_s;
}
catch( bad_alloc& ba ) {
// OOM
rc = -ENOMEM;
break;
}
}
// done with this
json_object_put( jobj );
return rc;
}
// decode and decrypt secrets and put the plaintext into an mlock'ed buffer
// return 0 on success
// return -ENOMEM on OOM
// return -EINVAL on failure to parse
int SG_driver_decrypt_secrets( EVP_PKEY* gateway_pubkey, EVP_PKEY* gateway_pkey, char** ret_obj_json, size_t* ret_obj_json_len, char const* driver_secrets_b64, size_t driver_secrets_b64_len ) {
// deserialize...
char* obj_ctext = NULL;
size_t obj_ctext_len = 0;
int rc = 0;
rc = md_base64_decode( driver_secrets_b64, driver_secrets_b64_len, &obj_ctext, &obj_ctext_len );
if( rc != 0 ) {
SG_error("md_base64_decode rc = %d\n", rc );
return -EINVAL;
}
// decrypt...
char* obj_json = NULL;
size_t obj_json_len = 0;
rc = md_decrypt( gateway_pubkey, gateway_pkey, obj_ctext, obj_ctext_len, &obj_json, &obj_json_len );
SG_safe_free( obj_ctext );
if( rc != 0 ) {
SG_error("md_decrypt rc = %d\n", rc );
return -EINVAL;
}
*ret_obj_json = obj_json;
*ret_obj_json_len = obj_json_len;
return rc;
}
// parse the secrets
// return 0 on success
// return -ENOMEM on OOM
// return -EINVAL on failure to parse
static int SG_parse_driver_secrets( EVP_PKEY* gateway_pubkey, EVP_PKEY* gateway_pkey, SG_driver_secrets_t* driver_secrets, char const* driver_secrets_b64, size_t driver_secrets_b64_len ) {
char* obj_json = NULL;
size_t obj_json_len = 0;
struct json_object* jobj = NULL;
int rc = 0;
// decrypt json
rc = SG_driver_decrypt_secrets( gateway_pubkey, gateway_pkey, &obj_json, &obj_json_len, driver_secrets_b64, driver_secrets_b64_len );
if( rc != 0 ) {
SG_error("Failed to decrypt, rc = %d\n", rc );
return rc;
}
// parse json
rc = SG_parse_json_object( &jobj, obj_json, obj_json_len );
SG_safe_free( obj_json );
if( rc != 0 ) {
SG_error("SG_parse_json_object rc = %d\n", rc );
return rc;
}
// iterate through the fields
json_object_object_foreach( jobj, key, val ) {
// each field needs to be a string...
enum json_type jtype = json_object_get_type( val );
if( jtype != json_type_string ) {
SG_error("%s is not a JSON string\n", key );
rc = -EINVAL;
break;
}
// get the value
char const* encrypted_value = json_object_get_string( val );
if( encrypted_value == NULL ) {
rc = -ENOMEM;
break;
}
size_t encrypted_value_len = strlen(encrypted_value);
try {
// put it into the secrets
string key_s( key );
string value_s( encrypted_value, encrypted_value_len );
(*driver_secrets)[ key_s ] = value_s;
}
catch( bad_alloc& ba ) {
rc = -ENOMEM;
break;
}
}
// done with this
json_object_put( jobj );
return rc;
}
// load a string by key
// returns a reference to the value in the json object on success (do NOT free or modify it)
// return NULL if not found, or if OOM
static char const* SG_load_json_string_by_key( struct json_object* obj, char const* key, size_t* _val_len ) {
// look up the keyed value
struct json_object* key_obj = NULL;
json_object_object_get_ex( obj, key, &key_obj );
if( key_obj == NULL ) {
SG_error("No such key '%s'\n", key );
return NULL;
}
// verify it's a string
enum json_type jtype = json_object_get_type( key_obj );
if( jtype != json_type_string ) {
SG_error("'%s' is not a string\n", key );
return NULL;
}
char const* val = json_object_get_string( key_obj );
if( val == NULL ) {
// OOM
return NULL;
}
*_val_len = strlen(val); // json_object_get_string_len( val );
return val;
}
// load a chunk of data by key directly
// return 0 on success, and set *val and *val_len to the value
// return -ENOENT if there is no such key
// return -EINVAL on parse error
// return -ENOMEM if OOM
static int SG_parse_json_b64_string( struct json_object* toplevel_obj, char const* key, char** val, size_t* val_len ) {
int rc = 0;
// look up the keyed value
size_t b64_len = 0;
char const* b64 = SG_load_json_string_by_key( toplevel_obj, key, &b64_len );
if( b64 == NULL || b64_len == 0 ) {
SG_error("No value for '%s'\n", key);
rc = -ENOENT;
}
else {
char* tmp = NULL;
size_t tmp_len = 0;
// load it directly...
rc = md_base64_decode( b64, b64_len, &tmp, &tmp_len );
if( rc != 0 ) {
SG_error("md_base64_decode('%s') rc = %d\n", key, rc );
}
else {
*val = tmp;
*val_len = tmp_len;
}
}
return rc;
}
// parse a serialized driver, encoded as a JSON object
// A driver is a JSON object that can have a "config", "secrets", and/or "driver" fields.
// A "config" field is JSON object that maps string keys to string values--it gets loaded as an SG_driver_conf_t.
// A "secrets" field is an base64-encoded *encrypted* string that decrypts to a JSON object that maps string keys to string values.
// The ciphertext gets verified with the given public key, and decrypted with the given private key. It gets parsed to an SG_driver_secrets_t.
// A "driver" field is a base64-encoded binary string that encodes some gateway-specific functionality.
// return 0 on success, and populate *driver
// return -ENOMEM on OOM
static int SG_parse_driver( struct SG_driver* driver, char const* driver_full, size_t driver_full_len, EVP_PKEY* pubkey, EVP_PKEY* privkey ) {
// driver_text should be a JSON object...
struct json_object* toplevel_obj = NULL;
char* driver_text = NULL;
size_t driver_text_len = 0;
char const* json_b64 = NULL;
size_t json_b64_len = 0;
SG_driver_conf_t* driver_conf = SG_safe_new( SG_driver_conf_t() );
SG_driver_secrets_t* driver_secrets = SG_safe_new( SG_driver_secrets_t() );
if( driver_conf == NULL || driver_secrets == NULL ) {
SG_safe_delete( driver_conf );
SG_safe_delete( driver_secrets );
return -ENOMEM;
}
int rc = SG_parse_json_object( &toplevel_obj, driver_full, driver_full_len );
if( rc != 0 ) {
SG_error("SG_parse_json_object rc = %d\n", rc );
return -EINVAL;
}
// get the driver conf JSON
json_b64 = SG_load_json_string_by_key( toplevel_obj, "config", &json_b64_len );
if( json_b64 != NULL && json_b64_len != 0 ) {
// load it
rc = SG_parse_driver_config( driver_conf, json_b64, json_b64_len );
if( rc != 0 ) {
SG_error("SG_parse_driver_config rc = %d\n", rc );
SG_safe_delete( driver_conf );
SG_safe_delete( driver_secrets );
json_object_put( toplevel_obj );
return rc;
}
}
// get the driver secrets JSON
json_b64 = SG_load_json_string_by_key( toplevel_obj, "secrets", &json_b64_len );
if( json_b64 != NULL || json_b64_len != 0 ) {
// load it
rc = SG_parse_driver_secrets( pubkey, privkey, driver_secrets, json_b64, json_b64_len );
if( rc != 0 ) {
SG_error("SG_parse_driver_config rc = %d\n", rc );
SG_safe_delete( driver_conf );
SG_safe_delete( driver_secrets );
json_object_put( toplevel_obj );
return rc;
}
}
// requested driver?
rc = SG_parse_json_b64_string( toplevel_obj, "driver", &driver_text, &driver_text_len );
// not an error if not present...
if( rc == -ENOENT ) {
rc = 0;
}
else if( rc != 0 ) {
SG_error("SG_parse_json_b64_string('driver') rc = %d\n", rc );
SG_safe_delete( driver_conf );
SG_safe_delete( driver_secrets );
json_object_put( toplevel_obj );
return rc;
}
// instantiate driver
if( driver->driver_conf != NULL ) {
SG_safe_delete( driver->driver_conf );
}
driver->driver_conf = driver_conf;
if( driver->driver_secrets != NULL ) {
SG_safe_delete( driver->driver_secrets );
}
driver->driver_secrets = driver_secrets;
if( driver->driver_text.data != NULL ) {
SG_chunk_free( &driver->driver_text );
}
driver->driver_text.data = driver_text;
driver->driver_text.len = driver_text_len;
// free memory
json_object_put( toplevel_obj );
return rc;
}
// given a JSON object, decode and load a base64-encoded binary field into a stream of bytes (decoded)
// return 0 on success
// return -EINVAL if we could not load the JSON for some reason
int SG_driver_load_binary_field( char* specfile_json, size_t specfile_json_len, char const* field_name, char** field_value, size_t* field_value_len ) {
struct json_object* toplevel_obj = NULL;
int rc = SG_parse_json_object( &toplevel_obj, specfile_json, specfile_json_len );
if( rc != 0 ) {
SG_error("SG_parse_json_object rc = %d\n", rc );
return -EINVAL;
}
rc = SG_parse_json_b64_string( toplevel_obj, field_name, field_value, field_value_len );
if( rc != 0 ) {
SG_error("SG_parse_json_b64_string rc = %d\n", rc );
}
json_object_put( toplevel_obj );
return rc;
}
// read-lock a driver
int SG_driver_rlock( struct SG_driver* driver ) {
return pthread_rwlock_rdlock( &driver->reload_lock );
}
// write-lock a driver
int SG_driver_wlock( struct SG_driver* driver ) {
return pthread_rwlock_wrlock( &driver->reload_lock );
}
// unlock a driver
int SG_driver_unlock( struct SG_driver* driver ) {
return pthread_rwlock_unlock( &driver->reload_lock );
}
// initialize a driver's worker processes
// gift it a set of initialized process groups
// return 0 on success
// return -ENOMEM on OOM
static int SG_driver_init_procs( struct SG_driver* driver, char** const roles, struct SG_proc_group** groups, size_t num_groups ) {
driver->groups = SG_safe_new( SG_driver_proc_group_t() );
if( driver->groups == NULL ) {
return -ENOMEM;
}
for( size_t i = 0; i < num_groups; i++ ) {
try {
(*driver->groups)[ string(roles[i]) ] = groups[i];
}
catch( bad_alloc& ba ) {
SG_safe_delete( driver->groups );
memset( driver, 0, sizeof(struct SG_driver) );
return -ENOMEM;
}
}
return 0;
}
// initialize a driver from a JSON object representation
// validate it using the given public key.
// decrypt the driver secrets using the private key.
// return 0 on success, and populate *driver
// return -ENOMEM on OOM
int SG_driver_init( struct SG_driver* driver, struct md_syndicate_conf* conf,
EVP_PKEY* pubkey, EVP_PKEY* privkey,
char const* exec_str, char** const roles, size_t num_roles, int num_instances,
char const* driver_text, size_t driver_text_len ) {
SG_debug("Initialize driver sandbox '%s'\n", exec_str);
memset( driver, 0, sizeof(struct SG_driver) );
char* exec_str_dup = SG_strdup_or_null( exec_str );
char** roles_dup = SG_CALLOC( char*, num_roles );
if( roles_dup != NULL ) {
for( size_t i = 0; i < num_roles; i++ ) {
roles_dup[i] = SG_strdup_or_null( roles[i] );
if( roles_dup[i] == NULL ) {
SG_FREE_LISTV( roles_dup, num_roles, free );
break;
}
}
}
if( exec_str_dup == NULL || roles_dup == NULL ) {
SG_safe_delete( exec_str_dup );
SG_safe_free( roles_dup );
return -ENOMEM;
}
// load up the config, secrets, and driver
int rc = SG_parse_driver( driver, driver_text, driver_text_len, pubkey, privkey );
if( rc != 0 ) {
SG_error("SG_parse_driver rc = %d\n", rc );
return rc;
}
// intialize the driver
rc = pthread_rwlock_init( &driver->reload_lock, NULL );
if( rc != 0 ) {
return rc;
}
// load the information into the driver
driver->exec_str = exec_str_dup;
driver->roles = roles_dup;
driver->num_roles = num_roles;
driver->num_instances = num_instances;
driver->conf = conf;
return rc;
}
// convert config/secrets into a JSON object string
// return 0 on success, and populate *chunk
// return -ENOMEM on OOM
// return -EOVERFLOW if there are too many bytes to serialize
static int SG_driver_conf_serialize( SG_driver_conf_t* conf, struct SG_chunk* chunk ) {
char* data = NULL;
// build up a JSON object and serialize it
struct json_object* conf_json = json_object_new_object();
if( conf_json == NULL ) {
return -ENOMEM;
}
for( SG_driver_conf_t::iterator itr = conf->begin(); itr != conf->end(); itr++ ) {
// serialize
struct json_object* strobj = json_object_new_string( itr->second.c_str() );
if( strobj == NULL ) {
json_object_put( conf_json );
return -ENOMEM;
}
// put
json_object_object_add( conf_json, itr->first.c_str(), strobj );
}
// serialize...
data = SG_strdup_or_null( json_object_to_json_string( conf_json ) );
json_object_put( conf_json );
if( data == NULL ) {
return -ENOMEM;
}
SG_chunk_init( chunk, data, strlen(data) );
return 0;
}
// spawn a driver's process groups
// return 0 on success
// return -ENOMEM on OOM
// NOT THREAD SAFE: the driver must be under mutual exclusion
int SG_driver_procs_start( struct SG_driver* driver ) {
int rc = 0;
struct SG_proc_group** groups = NULL;
struct SG_proc** initial_procs = NULL;
int wait_rc = 0;
// do we even have a driver?
if( driver->driver_text.data == NULL ) {
driver->groups = NULL;
return 0;
}
groups = SG_CALLOC( struct SG_proc_group*, driver->num_roles );
if( groups == NULL ) {
return -ENOMEM;
}
initial_procs = SG_CALLOC( struct SG_proc*, driver->num_roles * driver->num_instances );
if( initial_procs == NULL ) {
SG_safe_free( groups );
return -ENOMEM;
}
struct SG_chunk config;
struct SG_chunk secrets;
memset( &config, 0, sizeof(struct SG_chunk) );
memset( &secrets, 0, sizeof(struct SG_chunk) );
// config from driver
rc = SG_driver_conf_serialize( driver->driver_conf, &config );
if( rc != 0 ) {
SG_error("SG_driver_conf_serialize rc = %d\n", rc );
SG_safe_free( groups );
SG_safe_free( initial_procs );
return rc;
}
// secrets from driver
rc = SG_driver_conf_serialize( driver->driver_secrets, &secrets );
if( rc != 0 ) {
SG_error("SG_driver_conf_serialize rc = %d\n", rc );
SG_safe_free( groups );
SG_safe_free( initial_procs );
SG_chunk_free( &config );
return rc;
}
for( size_t i = 0; i < driver->num_roles; i++ ) {
// each role gets its own group
groups[i] = SG_proc_group_alloc( 1 );
if( groups[i] == NULL ) {
// OOM
rc = -ENOMEM;
goto SG_driver_procs_start_finish;
}
// set it up
rc = SG_proc_group_init( groups[i] );
if( rc != 0 ) {
goto SG_driver_procs_start_finish;
}
// create all instances of this role
for( int j = 0; j < driver->num_instances; j++ ) {
int proc_idx = i * driver->num_instances + j;
// create all instances of this process
initial_procs[proc_idx] = SG_proc_alloc( 1 );
if( initial_procs[proc_idx] == NULL ) {
rc = -ENOMEM;
goto SG_driver_procs_start_finish;
}
}
}
for( size_t i = 0; i < driver->num_roles; i++ ) {
for( int j = 0; j < driver->num_instances; j++ ) {
int proc_idx = i * driver->num_instances + j;
SG_debug("Start: %s %s (instance %d)\n", driver->exec_str, driver->roles[i], j );
// start this process
rc = SG_proc_start( initial_procs[proc_idx], driver->exec_str, driver->roles[i], driver->conf->helper_env, &config, &secrets, &driver->driver_text );
if( rc != 0 ) {
SG_debug("Wait for instance '%s' (%d) to die\n", driver->roles[i], SG_proc_pid( initial_procs[proc_idx] ) );
wait_rc = SG_proc_stop( initial_procs[proc_idx], 0 );
if( wait_rc != 0 ) {
SG_error("SG_proc_wait('%s' %d) rc = %d\n", driver->roles[i], SG_proc_pid( initial_procs[proc_idx] ), wait_rc );
}
SG_proc_free( initial_procs[proc_idx] );
initial_procs[proc_idx] = NULL;
if( rc == -ENOSYS ) {
SG_warn("Driver does not implement '%s'\n", driver->roles[i] );
rc = 0;
continue;
}
else {
SG_error("SG_proc_start('%s %s') rc = %d\n", driver->exec_str, driver->roles[i], rc );
goto SG_driver_procs_start_finish;
}
}
else {
rc = SG_proc_group_add( groups[i], initial_procs[proc_idx] );
if( rc != 0 ) {
SG_error("SG_proc_group_insert(%zu, %d) rc = %d\n", i, SG_proc_pid( initial_procs[proc_idx] ), rc );
goto SG_driver_procs_start_finish;
}
}
}
}
SG_driver_procs_start_finish:
if( rc != 0 ) {
// failed to start helpers
// shut them all down
for( size_t i = 0; i < driver->num_roles; i++ ) {
if( groups[i] == NULL ) {
continue;
}
if( SG_proc_group_size( groups[i] ) > 0 ) {
SG_proc_group_stop( groups[i], 1 );
}
else {
for( int j = 0; j < driver->num_instances; j++ ) {
int proc_idx = i * driver->num_instances + j;
if( initial_procs[proc_idx] != NULL ) {
SG_proc_stop( initial_procs[proc_idx], 1 );
SG_proc_free( initial_procs[proc_idx] );
}
}
}
SG_proc_group_free( groups[i] );
SG_safe_free( groups[i] );
groups[i] = NULL;
}
SG_safe_free( groups );
}
else {
// install to driver
SG_driver_init_procs( driver, driver->roles, groups, driver->num_roles );
}
// free memory
SG_chunk_free( &config );
munlock( secrets.data, secrets.len );
SG_chunk_free( &secrets );
SG_safe_free( initial_procs );
return rc;
}
// stop a driver's running processes
// return 0 on success
// NOT THREAD SAFE--caller must lock the driver
int SG_driver_procs_stop( struct SG_driver* driver ) {
struct SG_proc_group* group = NULL;
int rc = 0;
// if there are no processes, then do nothing
if( driver->groups == NULL ) {
return 0;
}
// ask the workers to stop
for( size_t i = 0; i < driver->num_roles; i++ ) {
SG_debug("Stop process group (role '%s')\n", driver->roles[i]);
try {
group = (*driver->groups)[ string(driver->roles[i]) ];
}
catch( bad_alloc& ba ) {
return -ENOMEM;
}
SG_proc_group_kill( group, SIGINT );
}
// wait for children to get the signal...
sleep(1);
for( size_t i = 0; i < driver->num_roles; i++ ) {
try {
string role(driver->roles[i]);
group = (*driver->groups)[ role ];
driver->groups->erase( role );
}
catch( bad_alloc& ba ) {
return -ENOMEM;
}
rc = SG_proc_group_tryjoin( group );
if( rc > 0 ) {
// kill the stragglers
SG_debug("Killing process group (role '%s')\n", driver->roles[i]);
SG_proc_group_kill( group, SIGKILL );
SG_proc_group_tryjoin( group );
}
// clean up
SG_proc_group_free( group );
SG_safe_free( group );
}
SG_safe_delete( driver->groups );
driver->groups = NULL;
return 0;
}
// reload the driver from a JSON object representation.
// return 0 on success
// return -ENOMEM on OOM
// return -EINVAL on failure to parse, or if driver_text is NULL
// return -EPERM if we were unable to start the driver processes
int SG_driver_reload( struct SG_driver* driver, EVP_PKEY* pubkey, EVP_PKEY* privkey, char const* driver_text, size_t driver_text_len ) {
if( driver_text == NULL ) {
SG_error("%s", "BUG: no driver text given\n");
exit(1);
return -EINVAL;
}
SG_driver_wlock( driver );
int reload_rc = 0;
struct SG_chunk serialized_conf;
struct SG_chunk serialized_secrets;
int rc = 0;
rc = SG_parse_driver( driver, driver_text, driver_text_len, pubkey, privkey );
if( rc != 0 ) {
SG_error("SG_parse_driver rc = %d\n", rc );
SG_driver_unlock( driver );
return -EPERM;
}
rc = SG_driver_conf_serialize( driver->driver_conf, &serialized_conf );
if( rc != 0 ) {
SG_error("SG_driver_conf_serialize rc = %d\n", rc );
SG_driver_unlock( driver );
return -EPERM;
}
rc = SG_driver_conf_serialize( driver->driver_secrets, &serialized_secrets );
if( rc != 0 ) {
SG_error("SG_driver_conf_serialize rc = %d\n", rc );
SG_driver_unlock( driver );
SG_chunk_free( &serialized_conf );
return -EPERM;
}
// restart the workers, if they're running
if( driver->groups != NULL ) {
for( SG_driver_proc_group_t::iterator itr = driver->groups->begin(); itr != driver->groups->end(); itr++ ) {
struct SG_proc_group* group = itr->second;
SG_debug("Reload process group %p (%s)\n", group, itr->first.c_str() );
// do not allow any subsequent requests for this group
SG_proc_group_wlock( group );
rc = SG_proc_group_reload( group, driver->exec_str, &serialized_conf, &serialized_secrets, &driver->driver_text );
SG_proc_group_unlock( group );
if( rc != 0 ) {
SG_error("SG_proc_group_reload('%s', '%s') rc = %d\n", driver->exec_str, itr->first.c_str(), rc );
reload_rc = -EPERM;
break;
}
}
}
if( rc == 0 ) {
rc = reload_rc;
}
SG_chunk_free( &serialized_conf );
SG_chunk_free( &serialized_secrets );
SG_driver_unlock( driver );
return rc;
}
// shut down the driver
// stop any running processes
// alwyas succeeds
int SG_driver_shutdown( struct SG_driver* driver ) {
// call the driver shutdown...
int rc = 0;
SG_driver_wlock( driver );
SG_safe_delete( driver->driver_conf );
SG_safe_delete( driver->driver_secrets );
if( driver->groups != NULL ) {
// running!
SG_driver_procs_stop( driver );
}
SG_FREE_LISTV( driver->roles, driver->num_roles, free );
SG_safe_free( driver->exec_str );
SG_chunk_free( &driver->driver_text );
SG_driver_unlock( driver );
pthread_rwlock_destroy( &driver->reload_lock );
memset( driver, 0, sizeof(struct SG_driver) );
return rc;
}
// get a config value
// return 0 on success, and put the value and length into *value and *len (*value will be malloc'ed)
// return -ENONET if no such config key exists
// return -ENOMEM if OOM
int SG_driver_get_config( struct SG_driver* driver, char const* key, char** value, size_t* len ) {
SG_driver_rlock( driver );
if( driver->driver_conf == NULL ) {
SG_driver_unlock( driver );
return -ENOENT;
}
int rc = 0;
try {
SG_driver_conf_t::iterator itr = driver->driver_conf->find( string(key) );
if( itr != driver->driver_conf->end() ) {
size_t ret_len = itr->second.size() + 1;
char* ret = SG_CALLOC( char, ret_len );
if( ret == NULL ) {
rc = -ENOMEM;
}
else {
memcpy( ret, itr->second.data(), ret_len );
*value = ret;
*len = ret_len;
}
}
else {
rc = -ENOENT;
}
}
catch( bad_alloc& ba ) {
rc = -ENOMEM;
}
SG_driver_unlock( driver );
return rc;
}
// get a secret value
// return 0 on success, and put the value and length in *value and *len (*value will be malloc'ed)
// return -ENOENT if there is no such secret
// return -ENOMEM if OOM
int SG_driver_get_secret( struct SG_driver* driver, char const* key, char** value, size_t* len ) {
SG_driver_rlock( driver );
if( driver->driver_secrets == NULL ) {
SG_driver_unlock( driver );
return -ENOENT;
}
int rc = 0;
try {
SG_driver_conf_t::iterator itr = driver->driver_secrets->find( string(key) );
if( itr != driver->driver_secrets->end() ) {
size_t ret_len = itr->second.size() + 1;
char* ret = SG_CALLOC( char, ret_len );
if( ret == NULL ) {
rc = -ENOMEM;
}
else {
memcpy( ret, itr->second.data(), ret_len );
*value = ret;
*len = ret_len;
}
}
else {
rc = -ENOENT;
}
}
catch( bad_alloc& ba ) {
rc = -ENOMEM;
}
SG_driver_unlock( driver );
return rc;
}
// get the value of a driver parameter (e.g. 'config', 'secrets', etc). It will not be decoded in any way (i.e. it might be b64-encoded)
// return 0 on success, and set *value and *value_len accordingly
// return -ENOMEM on OOM
// return -ENOENT if the key is not specified
// return -EINVAL if driver_text isn't parseable json
int SG_driver_get_string( char const* driver_text, size_t driver_text_len, char const* key, char** value, size_t* value_len ) {
int rc = 0;
// driver_text should be a JSON object...
struct json_object* toplevel_obj = NULL;
rc = SG_parse_json_object( &toplevel_obj, driver_text, driver_text_len );
if( rc != 0 ) {
SG_error("SG_parse_json_object rc = %d\n", rc );
return -EINVAL;
}
// get the driver conf JSON
size_t json_len = 0;
char const* json_text = SG_load_json_string_by_key( toplevel_obj, key, &json_len );
if( json_text == NULL ) {
// not found
return -ENOENT;
}
char* ret = SG_CALLOC( char, json_len + 1 );
if( ret == NULL ) {
// OOM
return -ENOMEM;
}
memcpy( ret, json_text, json_len );
*value = ret;
*value_len = json_len;
return rc;
}
// get the value of a driver parameter as an SG_chunk.
// base64-decode it, and put the decoded data into the *chunk
// return 0 on success, and populate *chunk
// return -ENOMEM on OOM
// return -EINVAL if the field is not base64-encoded
int SG_driver_get_chunk( char const* driver_text, size_t driver_text_len, char const* key, struct SG_chunk* chunk ) {
int rc = 0;
char* ret_data = NULL;
size_t ret_data_len = 0;
char* chunk_data = NULL;
size_t chunk_len = 0;
// look up the value
rc = SG_driver_get_string( driver_text, driver_text_len, key, &ret_data, &ret_data_len );
if( rc != 0 ) {
return rc;
}
// decode it
rc = md_base64_decode( ret_data, ret_data_len, &chunk_data, &chunk_len );
SG_safe_free( ret_data );
if( rc != 0 ) {
return rc;
}
chunk->data = chunk_data;
chunk->len = chunk_len;
return rc;
}
// get a pointer to a proc group
// NOT THREAD SAFE
struct SG_proc_group* SG_driver_get_proc_group( struct SG_driver* driver, char const* proc_group_name ) {
if( driver->groups == NULL ) {
return NULL;
}
try {
SG_driver_proc_group_t::iterator itr = driver->groups->find( string(proc_group_name) );
if( itr == driver->groups->end() ) {
return NULL;
}
return itr->second;
}
catch( bad_alloc& ba ) {
return NULL;
}
}
| 27.533544 | 193 | 0.598882 | jcnelson |
40097bbe2ad5f27fcbf7571e80c39d1b31db7630 | 3,628 | cpp | C++ | src/DetectorConstruction.cpp | tgblackburn/dreamt | 71adf27ad276dc1c949831c28a510c256b18e86c | [
"MIT"
] | 1 | 2021-02-08T12:37:59.000Z | 2021-02-08T12:37:59.000Z | src/DetectorConstruction.cpp | tgblackburn/dreamt | 71adf27ad276dc1c949831c28a510c256b18e86c | [
"MIT"
] | null | null | null | src/DetectorConstruction.cpp | tgblackburn/dreamt | 71adf27ad276dc1c949831c28a510c256b18e86c | [
"MIT"
] | null | null | null | #include <DetectorConstruction.hpp>
#include <G4NistManager.hh>
#include <G4Material.hh>
#include <G4Box.hh>
#include <G4LogicalVolume.hh>
#include <G4VPhysicalVolume.hh>
#include <G4PVPlacement.hh>
using namespace CLHEP;
static G4Material *PPMI (void);
DetectorConstruction::DetectorConstruction (const G4String &materialName, G4double thickness)
{
fMaterialName = materialName;
fThickness = thickness;
}
DetectorConstruction::~DetectorConstruction ()
{
}
G4VPhysicalVolume *DetectorConstruction::Construct()
{
G4NistManager *nist = G4NistManager::Instance();
G4Material *material = NULL;
if (fMaterialName == "PPMI")
material = PPMI();
else
material = nist->FindOrBuildMaterial (fMaterialName);
if (!material)
G4cerr << "Material " << fMaterialName << " not found." << G4endl;
G4Material *vacuum = new G4Material ("intergalactic", // name
1, // atomic number
1.008 * g/mole, // mass per mole
1.0e-25 * g/cm3, // mass density
kStateGas,
2.73 * kelvin, // temperature
3.0e-18 * pascal); // pressure
// Start by making the world.
G4Box *worldBox = new G4Box ("worldBox", 0.1*m, 0.1*m, 0.1*m);
G4LogicalVolume *logicWorld = new G4LogicalVolume (worldBox, vacuum, "world");
G4VPhysicalVolume *physWorld = new G4PVPlacement (0, // no rotation
G4ThreeVector(), // at origin
logicWorld, // which logical vol
"world", // name of above
0, // no mother volume
false, // not used!
0); // copy ID
// Make targets etc
if (material)
{
G4Box *foilBox = new G4Box ("foilBox", 0.5 * fThickness, 0.08*m, 0.08*m);
G4LogicalVolume *logicFoil = new G4LogicalVolume (foilBox, material, "foil");
G4VPhysicalVolume *physFoil = new G4PVPlacement (0,
G4ThreeVector(),
logicFoil,
"foil",
logicWorld, // world is mother
false,
0);
G4cout << "Loaded foil of " << fMaterialName << ", thickness " << fThickness/CLHEP::um << " microns." << G4endl;
G4cout << material << G4endl;
}
return physWorld;
}
G4Material *PPMI (void)
{
G4Element *hydrogen = new G4Element ("Hydrogen", "H", 1.0, 1.01*g/mole);
G4Element *carbon = new G4Element ("Carbon", "C", 6.0, 12.01*g/mole);
G4Element *nitrogen = new G4Element ("Nitrogen", "N", 7.0, 14.01*g/mole);
G4Element *oxygen = new G4Element ("Oxygen", "O", 8.0, 16.01*g/mole);
G4Material *PPMI = new G4Material ("Polypyromellitimide", 1.4*g/cm3, 4);
PPMI->AddElement (carbon, 22);
PPMI->AddElement (hydrogen, 10);
PPMI->AddElement (nitrogen, 2);
PPMI->AddElement (oxygen, 5);
return PPMI;
}
/*
G4Material *makeKapton (void)
{
G4String name, symbol;
G4double a, z;
G4double density;
G4int nel, ncomponents;
// define Elements
a = 1.01*g/mole;
G4Element* elH = new G4Element(name="Hydrogen",symbol="H" , z= 1., a);
a = 12.01*g/mole;
G4Element* elC = new G4Element(name="Carbon", symbol="C", z=6., a);
a = 14.01*g/mole;
G4Element* elN = new G4Element(name="Nitrogen",symbol="N" , z= 7., a);
a = 16.00*g/mole;
G4Element* elO = new G4Element(name="Oxygen" ,symbol="O" , z= 8., a);
// Kapton Dupont de Nemur (density: 1.396-1.430, get middle )
density = 1.413*g/cm3;
G4Material* Kapton = new G4Material(name="Kapton", density, nel=4);
Kapton->AddElement(elO,5);
Kapton->AddElement(elC,22);
Kapton->AddElement(elN,2);
Kapton->AddElement(elH,10);
return Kapton;
}
*/
| 27.694656 | 116 | 0.615215 | tgblackburn |
400cafb29de8d2ada3448fc4330c922ab0c3c713 | 1,747 | cpp | C++ | llvm-project/clang/test/Parser/pragma-fp.cpp | AgesX/llvm | 841024dce9c0263f302491b5c27fa0df6ef222df | [
"MIT"
] | 305 | 2019-09-14T17:16:05.000Z | 2022-03-31T15:05:20.000Z | llvm-project/clang/test/Parser/pragma-fp.cpp | AgesX/llvm | 841024dce9c0263f302491b5c27fa0df6ef222df | [
"MIT"
] | 11 | 2019-10-17T21:11:52.000Z | 2022-02-17T20:10:00.000Z | llvm-project/clang/test/Parser/pragma-fp.cpp | AgesX/llvm | 841024dce9c0263f302491b5c27fa0df6ef222df | [
"MIT"
] | 24 | 2019-10-03T11:22:11.000Z | 2022-01-25T09:59:30.000Z | // RUN: %clang_cc1 -std=c++11 -verify %s
void test_0(int *List, int Length) {
/* expected-error@+1 {{missing option; expected 'contract' or 'reassociate'}} */
#pragma clang fp
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_1(int *List, int Length) {
/* expected-error@+1 {{invalid option 'blah'; expected 'contract' or 'reassociate'}} */
#pragma clang fp blah
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_3(int *List, int Length) {
/* expected-error@+1 {{expected '('}} */
#pragma clang fp contract on
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_4(int *List, int Length) {
/* expected-error@+1 {{unexpected argument 'while' to '#pragma clang fp contract'; expected 'fast' or 'on' or 'off'}} */
#pragma clang fp contract(while)
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_5(int *List, int Length) {
/* expected-error@+1 {{unexpected argument 'maybe' to '#pragma clang fp contract'; expected 'fast' or 'on' or 'off'}} */
#pragma clang fp contract(maybe)
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_6(int *List, int Length) {
/* expected-error@+1 {{expected ')'}} */
#pragma clang fp contract(fast
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_7(int *List, int Length) {
/* expected-warning@+1 {{extra tokens at end of '#pragma clang fp' - ignored}} */
#pragma clang fp contract(fast) *
for (int i = 0; i < Length; i++) {
List[i] = i;
}
}
void test_8(int *List, int Length) {
for (int i = 0; i < Length; i++) {
List[i] = i;
/* expected-error@+1 {{'#pragma clang fp' can only appear at file scope or at the start of a compound statement}} */
#pragma clang fp contract(fast)
}
}
| 26.876923 | 120 | 0.599886 | AgesX |
400f599213347756100576bd82cf44058f69d32c | 2,567 | cpp | C++ | src/math/perlin.cpp | minalear/Kingdom | b4f7f235d37764ffa0ba6d1a42a7d7b9b1f83d5a | [
"MIT"
] | null | null | null | src/math/perlin.cpp | minalear/Kingdom | b4f7f235d37764ffa0ba6d1a42a7d7b9b1f83d5a | [
"MIT"
] | null | null | null | src/math/perlin.cpp | minalear/Kingdom | b4f7f235d37764ffa0ba6d1a42a7d7b9b1f83d5a | [
"MIT"
] | null | null | null | #include "perlin.h"
#include <cmath>
#include <random>
#include <algorithm>
#include <numeric>
#include "func.h"
Perlin::Perlin() {
// initalize permutation vector
p = {
151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,
8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,
35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,
134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,
55,46,245,40,244,102,143,54, 65,25,63,161,1,216,80,73,209,76,132,187,208, 89,
18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,
250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,
189,28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167,
43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,
97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,
107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 };
// duplicate the permutation
p.insert(p.end(), p.begin(), p.end());
}
Perlin::Perlin(uint32_t seed) {
SetNewSeed(seed);
}
float Perlin::fade(float t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
float Perlin::grad(int hash, float x, float y, float z) {
int h = hash & 15;
float u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
float Perlin::Noise(float x, float y, float z) const {
int X = (int)floor(x) & 255;
int Y = (int)floor(y) & 255;
int Z = (int)floor(z) & 255;
x -= floor(x);
y -= floor(y);
z -= floor(z);
float u = fade(x);
float v = fade(y);
float w = fade(z);
int A = p[X] + Y;
int AA = p[A] + Z;
int AB = p[A + 1] + Z;
int B = p[X + 1] + Y;
int BA = p[B] + Z;
int BB = p[B + 1] + Z;
float res = lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x-1, y, z)), lerp(u, grad(p[AB], x, y-1, z), grad(p[BB], x-1, y-1, z))), lerp(v, lerp(u, grad(p[AA+1], x, y, z-1), grad(p[BA+1], x-1, y, z-1)), lerp(u, grad(p[AB+1], x, y-1, z-1), grad(p[BB+1], x-1, y-1, z-1))));
return (res + 1.f) / 2.f;
}
void Perlin::SetNewSeed(uint32_t seed) {
p.clear();
p.resize(256);
std::iota(p.begin(), p.end(), 0);
std::default_random_engine engine(seed);
std::shuffle(p.begin(), p.end(), engine);
p.insert(p.end(), p.begin(), p.end());
}
| 34.226667 | 284 | 0.574211 | minalear |
401171c9a255897b243d6e2816efd5b19a918089 | 3,500 | cpp | C++ | tests/class/methods.test.cpp | pshoben/reflang | bf3532bbd8e18d43ac538d44d13c37ee6fbc6a35 | [
"MIT"
] | 263 | 2016-12-31T22:17:16.000Z | 2022-03-25T06:28:27.000Z | tests/class/methods.test.cpp | pshoben/reflang | bf3532bbd8e18d43ac538d44d13c37ee6fbc6a35 | [
"MIT"
] | 2 | 2018-04-06T15:09:38.000Z | 2022-03-21T07:23:51.000Z | tests/class/methods.test.cpp | pshoben/reflang | bf3532bbd8e18d43ac538d44d13c37ee6fbc6a35 | [
"MIT"
] | 27 | 2017-01-01T00:06:43.000Z | 2022-01-10T14:32:33.000Z | #include "methods.src.hpp"
#include "methods.gen.hpp"
#define CATCH_CONFIG_MAIN
#include "tests/catch.hpp"
using namespace reflang;
using namespace std;
// MyClass method implementations
int global_int = 0;
void MyClass::Method0() { ++global_int; }
void MyClass::Method1(bool b, int i)
{
if (b)
{
global_int = i;
}
}
bool MyClass::RMethod0() { ++global_int; return true; }
bool MyClass::RMethod1(bool b, int i) { global_int = i; return b; }
void MyClass::VirtualMethod() { ++global_int; }
void MyClass::ConstMethod() const { ++global_int; }
void MyClass::MethodWithClassArg(ComplexArgument arg) { global_int = arg.i; }
void MyClass::MethodWithPointerArg(int* p) { global_int = *p; }
void MyClass::MethodWithConstReferenceArg0(const int& i) { global_int = i; }
void MyClass::MethodWithConstReferenceArg1(const ComplexArgument& arg) { global_int = arg.i; }
TEST_CASE("simple-methods")
{
MyClass c;
Method<decltype(&MyClass::Method0), &MyClass::Method0> m0;
global_int = 0;
Object result = m0(c);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 1);
Method<decltype(&MyClass::Method1), &MyClass::Method1> m1;
global_int = 0;
result = m1(c, false, 100);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 0);
result = m1(c, true, 100);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 100);
}
TEST_CASE("return-value-methods")
{
MyClass c;
Method<decltype(&MyClass::RMethod0), &MyClass::RMethod0> rm0;
global_int = 0;
Object result = rm0(c);
REQUIRE(result.GetT<bool>() == true);
REQUIRE(global_int == 1);
Method<decltype(&MyClass::RMethod1), &MyClass::RMethod1> rm1;
global_int = 0;
result = rm1(c, true, 100);
REQUIRE(result.GetT<bool>() == true);
REQUIRE(global_int == 100);
result = rm1(c, false, 200);
REQUIRE(result.GetT<bool>() == false);
REQUIRE(global_int == 200);
}
TEST_CASE("virtual-method")
{
MyClass c;
Method<decltype(&MyClass::VirtualMethod), &MyClass::VirtualMethod> vm;
global_int = 0;
Object result = vm(c);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 1);
}
TEST_CASE("const-method")
{
MyClass c;
Method<decltype(&MyClass::ConstMethod), &MyClass::ConstMethod> cm;
global_int = 0;
Object result = cm(c);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 1);
}
TEST_CASE("class-argument")
{
MyClass c;
Method<decltype(&MyClass::MethodWithClassArg), &MyClass::MethodWithClassArg> carg;
global_int = 0;
Object result = carg(c, ComplexArgument{ 123 });
REQUIRE(result.IsVoid());
REQUIRE(global_int == 123);
}
TEST_CASE("pointer-argument")
{
MyClass c;
Method<decltype(&MyClass::MethodWithPointerArg), &MyClass::MethodWithPointerArg> pm;
global_int = 0;
int i = 123;
Object result = pm(c, &i);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 123);
}
TEST_CASE("const-ref-argument")
{
MyClass c;
Method<decltype(&MyClass::MethodWithConstReferenceArg0), &MyClass::MethodWithConstReferenceArg0> cr0;
global_int = 0;
Object result = cr0(c, 123);
REQUIRE(result.IsVoid());
REQUIRE(global_int == 123);
Method<decltype(&MyClass::MethodWithConstReferenceArg1), &MyClass::MethodWithConstReferenceArg1> cr1;
global_int = 0;
result = cr1(c, ComplexArgument{ 456 });
REQUIRE(result.IsVoid());
REQUIRE(global_int == 456);
}
TEST_CASE("get-method")
{
MyClass c;
Class<MyClass> metadata;
REQUIRE(metadata.GetMethod("non-existing").empty());
auto methods = metadata.GetMethod("Method0");
REQUIRE(methods.size() == 1);
global_int = 0;
auto& method = *(methods[0].get());
method(c);
REQUIRE(global_int == 1);
}
| 24.137931 | 102 | 0.705143 | pshoben |
40155b03f24c2a388f9880b5d5b236795592c817 | 3,508 | hpp | C++ | src/Elliptic/BoundaryConditions/Tags/BoundaryFields.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/Elliptic/BoundaryConditions/Tags/BoundaryFields.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/Elliptic/BoundaryConditions/Tags/BoundaryFields.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include "DataStructures/DataBox/PrefixHelpers.hpp"
#include "DataStructures/DataBox/Prefixes.hpp"
#include "DataStructures/DataBox/Tag.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/SliceVariables.hpp"
#include "Domain/Structure/Element.hpp"
#include "Domain/Structure/IndexToSliceAt.hpp"
#include "Domain/Tags.hpp"
#include "Domain/Tags/FaceNormal.hpp"
#include "Domain/Tags/Faces.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/NormalDotFlux.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"
namespace elliptic::Tags {
/// The `FieldsTag` on external boundaries
template <size_t Dim, typename FieldsTag>
struct BoundaryFieldsCompute : db::ComputeTag,
domain::Tags::Faces<Dim, FieldsTag> {
using base = domain::Tags::Faces<Dim, FieldsTag>;
using return_type = typename base::type;
using argument_tags = tmpl::list<FieldsTag, domain::Tags::Mesh<Dim>,
domain::Tags::Element<Dim>>;
static void function(const gsl::not_null<return_type*> vars_on_face,
const typename FieldsTag::type& vars,
const Mesh<Dim>& mesh, const Element<Dim>& element) {
ASSERT(mesh.quadrature(0) == Spectral::Quadrature::GaussLobatto,
"Slicing fields to the boundary currently supports only "
"Gauss-Lobatto grids. Add support to "
"'elliptic::Tags::BoundaryFieldsCompute'.");
for (const auto& direction : element.external_boundaries()) {
data_on_slice(make_not_null(&((*vars_on_face)[direction])), vars,
mesh.extents(), direction.dimension(),
index_to_slice_at(mesh.extents(), direction));
}
}
};
/// The `::Tags::NormalDotFlux<FieldsTag>` on external boundaries
template <size_t Dim, typename FieldsTag, typename FluxesTag>
struct BoundaryFluxesCompute
: db::ComputeTag,
domain::Tags::Faces<
Dim, db::add_tag_prefix<::Tags::NormalDotFlux, FieldsTag>> {
using base =
domain::Tags::Faces<Dim,
db::add_tag_prefix<::Tags::NormalDotFlux, FieldsTag>>;
using return_type = typename base::type;
using argument_tags =
tmpl::list<FluxesTag,
domain::Tags::Faces<Dim, domain::Tags::FaceNormal<Dim>>,
domain::Tags::Mesh<Dim>, domain::Tags::Element<Dim>>;
static void function(
const gsl::not_null<return_type*> normal_dot_fluxes,
const typename FluxesTag::type& fluxes,
const DirectionMap<Dim, tnsr::i<DataVector, Dim>>& face_normals,
const Mesh<Dim>& mesh, const Element<Dim>& element) {
ASSERT(mesh.quadrature(0) == Spectral::Quadrature::GaussLobatto,
"Slicing fluxes to the boundary currently supports only "
"Gauss-Lobatto grids. Add support to "
"'elliptic::Tags::BoundaryFluxesCompute'.");
for (const auto& direction : element.external_boundaries()) {
const auto fluxes_on_face =
data_on_slice(fluxes, mesh.extents(), direction.dimension(),
index_to_slice_at(mesh.extents(), direction));
normal_dot_flux(make_not_null(&((*normal_dot_fluxes)[direction])),
face_normals.at(direction), fluxes_on_face);
}
}
};
} // namespace elliptic::Tags
| 42.26506 | 80 | 0.673318 | nilsvu |
401709d78f3a7cf5b0e3b10491de5b83609989a1 | 20,580 | cpp | C++ | src/webots/editor/WbTextEditor.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1 | 2020-09-28T08:34:32.000Z | 2020-09-28T08:34:32.000Z | src/webots/editor/WbTextEditor.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 2 | 2020-05-18T12:49:14.000Z | 2020-12-01T15:13:43.000Z | src/webots/editor/WbTextEditor.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1 | 2022-02-25T12:34:18.000Z | 2022-02-25T12:34:18.000Z | // Copyright 1996-2020 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WbTextEditor.hpp"
#include "WbClipboard.hpp"
#include "WbFindReplaceDialog.hpp"
#include "WbMessageBox.hpp"
#include "WbProject.hpp"
#include "WbProjectRelocationDialog.hpp"
#include "WbSimulationState.hpp"
#include "WbStandardPaths.hpp"
#include "WbTextBuffer.hpp"
#include "WbVariant.hpp"
#include <QtCore/QDir>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrintPreviewDialog>
#include <QtPrintSupport/QPrinter>
#include <QtWidgets/QAction>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QTabBar>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QVBoxLayout>
#include <cassert>
WbTextEditor::WbTextEditor(QWidget *parent, const QString &toolBarAlign) : WbDockWidget(parent) {
setObjectName("TextEditor");
setTabbedTitle("Text Editor");
mCurrentBuffer = NULL;
mFindDialog = NULL;
mReplaceDialog = NULL;
mTextFind = new WbTextFind(NULL);
connect(mTextFind, &WbTextFind::findStringChanged, this, &WbTextEditor::highlightSearchText);
mPrinter = NULL; // we create it only when needed to avoid heavy initialization overhead (including networking)
// setup for main window
QAction *action = toggleViewAction();
action->setText("&Text Editor");
action->setStatusTip("Toggle the view of the text editor.");
action->setShortcut(Qt::CTRL + Qt::Key_E);
connectActions();
mToolBar = createToolBar();
mTabWidget = new QTabWidget(this);
mTabWidget->setMovable(true);
mTabWidget->setTabsClosable(true);
connect(mTabWidget, &QTabWidget::currentChanged, this, &WbTextEditor::tabChanged);
connect(mTabWidget, &QTabWidget::tabCloseRequested, this, &WbTextEditor::closeBufferIfAccepted);
QVBoxLayout *layout = new QVBoxLayout();
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
mToolBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
if (toolBarAlign == "center") {
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->addWidget(mToolBar);
layout->addLayout(hlayout, 0);
} else // assuming left alignment
layout->addWidget(mToolBar);
layout->addWidget(mTabWidget);
QWidget *widget = new QWidget(this);
setWidget(widget);
widget->setLayout(layout);
}
WbTextEditor::~WbTextEditor() {
delete mPrinter;
delete mTextFind;
}
QToolBar *WbTextEditor::createToolBar() {
QToolBar *mToolBar = new QToolBar(this);
WbActionManager *actionManager = WbActionManager::instance();
QAction *action = actionManager->action(WbAction::NEW_FILE);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
action = actionManager->action(WbAction::OPEN_FILE);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
action = actionManager->action(WbAction::SAVE_FILE);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
action = actionManager->action(WbAction::SAVE_FILE_AS);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
action = actionManager->action(WbAction::REVERT_FILE);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
mToolBar->addSeparator();
action = actionManager->action(WbAction::FIND);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
action = actionManager->action(WbAction::REPLACE);
mToolBar->addAction(action);
mToolBar->widgetForAction(action)->setObjectName("editorButton");
return mToolBar;
}
void WbTextEditor::connectActions() {
WbActionManager *actionManager = WbActionManager::instance();
connect(actionManager->action(WbAction::NEW_FILE), &QAction::triggered, this, &WbTextEditor::newFile);
connect(actionManager->action(WbAction::OPEN_FILE), &QAction::triggered, this, &WbTextEditor::openFileDialog);
connect(actionManager->action(WbAction::SAVE_FILE), &QAction::triggered, this, &WbTextEditor::saveFile);
connect(actionManager->action(WbAction::SAVE_FILE_AS), &QAction::triggered, this, &WbTextEditor::saveFileAs);
connect(actionManager->action(WbAction::REVERT_FILE), &QAction::triggered, this, &WbTextEditor::revertFile);
connect(actionManager->action(WbAction::REPLACE), &QAction::triggered, this, &WbTextEditor::openReplaceDialog);
connect(actionManager->action(WbAction::GO_TO_LINE), &QAction::triggered, this, &WbTextEditor::goToLine);
connect(actionManager->action(WbAction::TOGGLE_LINE_COMMENT), &QAction::triggered, this, &WbTextEditor::toggleLineComment);
connect(actionManager->action(WbAction::DUPLICATE_SELECTION), &QAction::triggered, this, &WbTextEditor::duplicateSelection);
connect(actionManager->action(WbAction::TRANSPOSE_LINE), &QAction::triggered, this, &WbTextEditor::transposeCurrentLine);
connect(actionManager->action(WbAction::PRINT), &QAction::triggered, this, &WbTextEditor::print);
connect(actionManager->action(WbAction::PRINT_PREVIEW), &QAction::triggered, this, &WbTextEditor::printPreview);
connect(actionManager, &WbActionManager::userTextEditCommandReceived, this, &WbTextEditor::handleUserCommand);
}
void WbTextEditor::updateGui() {
WbActionManager *actionManager = WbActionManager::instance();
actionManager->setEnabled(WbAction::SAVE_FILE, mCurrentBuffer && mCurrentBuffer->isModified());
actionManager->setEnabled(WbAction::SAVE_FILE_AS, mCurrentBuffer);
actionManager->setEnabled(WbAction::REVERT_FILE, mCurrentBuffer);
updateFileNames();
updateEditMenu();
}
void WbTextEditor::updateFileNames() {
if (bufferCount() == 0) {
setWindowTitle("Text Editor");
return;
}
// update tabs titles
for (int i = 0; i < bufferCount(); i++) {
WbTextBuffer *b = buffer(i);
QString tabText(b->shortName());
if (b->document()->isModified())
tabText += "*";
mTabWidget->setTabText(i, tabText);
}
// update window title
WbTextBuffer *selectedBuffer = currentBuffer();
if (selectedBuffer) {
QString windowTitle(QDir::toNativeSeparators(selectedBuffer->fileName()));
if (selectedBuffer->document()->isModified())
windowTitle += "*";
setWindowTitle(windowTitle);
} else
setWindowTitle(tr("Text Editor"));
}
void WbTextEditor::updateEditMenu() {
WbActionManager::instance()->setEnabled(WbAction::TOGGLE_LINE_COMMENT, mCurrentBuffer);
WbActionManager::instance()->setEnabled(WbAction::DUPLICATE_SELECTION, mCurrentBuffer);
WbActionManager::instance()->setEnabled(WbAction::TRANSPOSE_LINE, mCurrentBuffer);
WbActionManager::instance()->enableTextEditActions(mCurrentBuffer);
WbActionManager::instance()->setFocusObject(this);
updateApplicationActions();
}
void WbTextEditor::updateApplicationActions() {
QTextDocument *doc = NULL;
if (mCurrentBuffer)
doc = mCurrentBuffer->document();
enableUndo(doc && doc->isUndoAvailable());
enableRedo(doc && doc->isRedoAvailable());
enableCopy(mCurrentBuffer && mCurrentBuffer->hasSelection());
WbActionManager::instance()->setEnabled(WbAction::PASTE, mCurrentBuffer && !WbClipboard::instance()->isEmpty());
WbActionManager::instance()->setEnabled(WbAction::SELECT_ALL, mCurrentBuffer);
}
void WbTextEditor::enableCopy(bool enabled) {
WbActionManager::instance()->setEnabled(WbAction::CUT, enabled);
WbActionManager::instance()->setEnabled(WbAction::COPY, enabled);
}
void WbTextEditor::enableUndo(bool enabled) {
WbActionManager::instance()->setEnabled(WbAction::UNDO, enabled);
}
void WbTextEditor::enableRedo(bool enabled) {
WbActionManager::instance()->setEnabled(WbAction::REDO, enabled);
}
void WbTextEditor::modificationChanged(bool changed) {
updateFileNames();
WbActionManager::instance()->setEnabled(WbAction::SAVE_FILE, mCurrentBuffer && changed);
}
void WbTextEditor::tabChanged(int tab) {
if (mCurrentBuffer) {
disconnect(mCurrentBuffer, 0, this, 0);
}
mCurrentBuffer = buffer(tab);
if (mCurrentBuffer) {
mCurrentBuffer->setFocusPolicy(Qt::ClickFocus);
mTextFind->setEditor(mCurrentBuffer);
WbActionManager::instance()->setEnabled(WbAction::SAVE_FILE, mCurrentBuffer->isModified());
connect(mCurrentBuffer, &WbTextBuffer::undoAvailable, this, &WbTextEditor::enableUndo);
connect(mCurrentBuffer, &WbTextBuffer::redoAvailable, this, &WbTextEditor::enableRedo);
connect(mCurrentBuffer, &WbTextBuffer::copyAvailable, this, &WbTextEditor::enableCopy);
connect(mCurrentBuffer, &WbTextBuffer::modificationChanged, this, &WbTextEditor::modificationChanged);
connect(mCurrentBuffer, &WbTextBuffer::focusIn, this, &WbTextEditor::updateEditMenu);
}
updateGui();
}
void WbTextEditor::handleUserCommand(WbAction::WbActionKind action) {
switch (action) {
case WbAction::CUT:
mCurrentBuffer->cut();
break;
case WbAction::COPY:
mCurrentBuffer->copy();
break;
case WbAction::PASTE:
mCurrentBuffer->paste();
break;
case WbAction::SELECT_ALL:
mCurrentBuffer->selectAll();
break;
case WbAction::UNDO:
mCurrentBuffer->undo();
break;
case WbAction::REDO:
mCurrentBuffer->redo();
break;
case WbAction::FIND:
openFindDialog();
break;
case WbAction::FIND_NEXT:
if (mFindDialog != NULL)
mFindDialog->next();
else if (mReplaceDialog != NULL)
mReplaceDialog->next();
else
WbFindReplaceDialog::findNext(mTextFind, this);
break;
case WbAction::FIND_PREVIOUS:
if (mFindDialog != NULL)
mFindDialog->previous();
else if (mReplaceDialog != NULL)
mReplaceDialog->previous();
else
WbFindReplaceDialog::findPrevious(mTextFind, this);
break;
default:
break;
}
updateApplicationActions();
}
void WbTextEditor::newFile() {
WbTextBuffer *buffer = new WbTextBuffer(this);
connectBuffer(buffer);
mTabWidget->addTab(buffer, "New");
selectTab(mTabWidget->count() - 1);
if (!isVisible())
toggleViewAction()->trigger();
}
void WbTextEditor::selectTab(int tab) {
if (tab < 0 || tab >= mTabWidget->count())
return;
mTabWidget->setCurrentIndex(tab);
updateGui();
}
bool WbTextEditor::openFile(const QString &path) {
// see if this file is already open in a tab
int n = bufferCount();
if (n > 0) {
QFileInfo info(path);
QString canonical = info.canonicalFilePath();
for (int i = 0; i < n; i++) {
WbTextBuffer *buf = buffer(i);
if (canonical == buf->fileName()) {
selectTab(i);
return true;
}
}
}
// add a new tab
WbTextBuffer *buf = new WbTextBuffer(this);
connectBuffer(buf);
if (!buf->load(path))
return false;
mTabWidget->addTab(buf, buf->shortName());
selectTab(mTabWidget->count() - 1);
return true;
}
void WbTextEditor::openFileDialog() {
WbSimulationState *simulationState = WbSimulationState::instance();
simulationState->pauseSimulation();
// find a smart dir
QString dir;
WbTextBuffer *buffer = currentBuffer();
if (buffer)
dir = buffer->path();
else if (WbProject::current())
dir = WbProject::current()->path();
else
dir = QDir::homePath();
// get list of files
QStringList list = QFileDialog::getOpenFileNames(this, tr("Open File..."), dir, tr("All Files (*)"));
if (!list.isEmpty()) {
// open all existing files
for (int i = 0; i < list.size(); ++i) {
const QString &name = list.at(i);
if (QFile::exists(name)) {
openFile(name);
if (!isVisible())
toggleViewAction()->trigger();
}
}
updateGui();
}
simulationState->resumeSimulation();
}
void WbTextEditor::revertFile() {
mCurrentBuffer->revert(true);
updateGui();
}
void WbTextEditor::selectTab() {
WbTextBuffer *b = dynamic_cast<WbTextBuffer *>(sender());
if (!b)
return;
selectBuffer(b);
}
void WbTextEditor::selectBuffer(WbTextBuffer *buffer) {
int count = mTabWidget->count();
for (int i = 0; i < count; i++)
if (buffer == this->buffer(i)) {
selectTab(i);
break;
}
}
void WbTextEditor::connectBuffer(WbTextBuffer *buffer) {
connect(buffer, &WbTextBuffer::fileNameChanged, this, &WbTextEditor::updateGui);
connect(buffer, &WbTextBuffer::showRequested, this, &WbTextEditor::showModifiedTextBuffer);
}
void WbTextEditor::showModifiedTextBuffer() {
if (!isHidden())
return;
// show text editor and reset selected tab
WbTextBuffer *b = dynamic_cast<WbTextBuffer *>(sender());
selectBuffer(b);
show();
}
void WbTextEditor::openFindDialog() {
if (mReplaceDialog != NULL) {
// find and replace dialog already open
if (mCurrentBuffer->hasSingleBlockSelection())
mReplaceDialog->setFindString(mCurrentBuffer->textCursor().selectedText());
mReplaceDialog->show();
mReplaceDialog->raise();
mReplaceDialog->activateWindow();
return;
}
if (mFindDialog == NULL) {
mFindDialog = new WbFindReplaceDialog(mTextFind, false, tr("Text Editor"), this);
connect(mFindDialog, &WbFindReplaceDialog::finished, this, &WbTextEditor::deleteFindDialog);
}
if (mCurrentBuffer->hasSingleBlockSelection()) {
QString selectedText = mCurrentBuffer->textCursor().selectedText();
if (!selectedText.isEmpty())
mFindDialog->setFindString(mCurrentBuffer->textCursor().selectedText());
}
mFindDialog->show();
mFindDialog->raise();
mFindDialog->activateWindow();
}
void WbTextEditor::openReplaceDialog() {
if (mFindDialog != NULL) {
// close find open
mFindDialog->close();
mFindDialog = NULL;
}
if (mReplaceDialog == NULL) {
mReplaceDialog = new WbFindReplaceDialog(mTextFind, true, tr("Text Editor"), this);
connect(mReplaceDialog, &WbFindReplaceDialog::finished, this, &WbTextEditor::deleteReplaceDialog);
}
if (mCurrentBuffer->hasSingleBlockSelection()) {
QString selectedText = mCurrentBuffer->textCursor().selectedText();
if (!selectedText.isEmpty())
mReplaceDialog->setFindString(mCurrentBuffer->textCursor().selectedText());
}
mReplaceDialog->show();
mReplaceDialog->raise();
mReplaceDialog->activateWindow();
}
void WbTextEditor::deleteFindDialog() {
// WbFindReplaceDialog deletes automatically on close
mFindDialog = NULL;
}
void WbTextEditor::deleteReplaceDialog() {
// WbFindReplaceDialog deletes automatically on close
mReplaceDialog = NULL;
}
void WbTextEditor::highlightSearchText(QRegExp regExp) {
WbTextBuffer *buffer = dynamic_cast<WbTextBuffer *>(mTabWidget->currentWidget());
if (buffer)
buffer->updateSearchTextHighlighting(regExp);
}
void WbTextEditor::goToLine() {
mCurrentBuffer->goToLine();
}
void WbTextEditor::toggleLineComment() {
mCurrentBuffer->toggleLineComment();
}
void WbTextEditor::duplicateSelection() {
mCurrentBuffer->duplicateSelection();
}
void WbTextEditor::transposeCurrentLine() {
mCurrentBuffer->transposeCurrentLine();
}
void WbTextEditor::print() {
WbSimulationState *simulationState = WbSimulationState::instance();
simulationState->pauseSimulation();
if (!mPrinter)
mPrinter = new QPrinter(QPrinter::HighResolution);
QPrintDialog *dialog = new QPrintDialog(mPrinter, this);
if (mCurrentBuffer->textCursor().hasSelection())
dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection);
dialog->setWindowTitle(tr("Print Document"));
if (dialog->exec() == QDialog::Accepted)
mCurrentBuffer->print(mPrinter);
delete dialog;
simulationState->resumeSimulation();
}
void WbTextEditor::printPreview() {
WbSimulationState *simulationState = WbSimulationState::instance();
simulationState->pauseSimulation();
if (!mPrinter)
mPrinter = new QPrinter(QPrinter::HighResolution);
QPrintPreviewDialog preview(mPrinter, this);
connect(&preview, &QPrintPreviewDialog::paintRequested, this, &WbTextEditor::preview);
preview.exec();
simulationState->resumeSimulation();
}
void WbTextEditor::preview() {
assert(mPrinter);
mCurrentBuffer->print(mPrinter);
}
void WbTextEditor::saveFile() {
saveBuffer(mCurrentBuffer);
updateGui();
}
void WbTextEditor::saveFileAs() {
saveBuffer(mCurrentBuffer, true);
updateGui();
}
bool WbTextEditor::saveAllFiles() {
int tab = mTabWidget->currentIndex();
int count = mTabWidget->count();
for (int i = 0; i < count; i++) {
// only status of selected tab is automatically updated
mTabWidget->setCurrentIndex(i);
WbTextBuffer *b = buffer(i);
if ((b->isModified() || !QFile::exists(b->fileName())) && !saveBuffer(b))
return false;
}
// restore original selected tab
selectTab(tab);
updateGui();
return true;
}
bool WbTextEditor::saveBuffer(WbTextBuffer *buffer, bool saveAs) {
WbSimulationState *simulationState = WbSimulationState::instance();
simulationState->pauseSimulation();
QString fileName = buffer->fileName();
if (buffer->isUnnamed() || QFileInfo(fileName).isRelative() || saveAs) {
fileName =
QFileDialog::getSaveFileName(this, tr("Save as..."), WbProject::computeBestPathForSaveAs(fileName), tr("All Files (*)"));
if (fileName.isEmpty()) {
simulationState->resumeSimulation();
return false;
}
}
simulationState->resumeSimulation();
// is the file located in Webots installation directory
// if relocation is needed, then fileName will be updated to match the new text file
if (!WbProjectRelocationDialog::validateLocation(this, fileName)) {
simulationState->resumeSimulation();
return false;
}
fileName = QFileInfo(fileName).path() + "/" + QFileInfo(fileName).fileName();
if (saveAs || buffer->isModified() || !QFile::exists(fileName))
buffer->saveAs(fileName);
return true;
}
void WbTextEditor::closeBufferIfAccepted(int tab) {
closeBuffer(tab, false);
}
void WbTextEditor::closeBuffer(int tab, bool closeAnyway) {
WbTextBuffer *buf = buffer(tab);
if (buf->isModified()) {
QMessageBox::StandardButtons buttons = QMessageBox::Save | QMessageBox::Discard;
if (!closeAnyway)
buttons |= QMessageBox::Cancel;
QString message(tr("The file '%1' is not saved.\nDo you want to save it before closing?").arg(buf->shortName()));
int ret = WbMessageBox::question(message, this, tr("Question"), QMessageBox::Save, buttons);
if (ret == QMessageBox::Cancel)
return;
else if (ret == QMessageBox::Save)
saveBuffer(buf);
}
mTabWidget->removeTab(tab);
delete buf;
}
void WbTextEditor::closeAllBuffers() {
while (mTabWidget->count() > 0)
closeBuffer(0, true);
}
int WbTextEditor::bufferCount() const {
return mTabWidget->count();
}
WbTextBuffer *WbTextEditor::buffer(int tab) const {
return static_cast<WbTextBuffer *>(mTabWidget->widget(tab));
}
void WbTextEditor::ignoreFileChangedEvent() {
int count = mTabWidget->count();
for (int i = 0; i < count; i++)
buffer(i)->ignoreFileChangedEvent();
}
QStringList WbTextEditor::openFiles() const {
QStringList list;
int count = mTabWidget->count();
for (int i = 0; i < count; i++) {
WbTextBuffer *buf = buffer(i);
list << buf->fileName();
}
return list;
}
void WbTextEditor::openFiles(const QStringList &list, int selectedTab) {
closeAllBuffers();
foreach (QString file, list) {
WbTextBuffer *newBuffer = new WbTextBuffer(this);
connectBuffer(newBuffer);
bool success = newBuffer->load(file);
if (success)
mTabWidget->addTab(newBuffer, newBuffer->shortName());
else
delete newBuffer;
}
selectTab(selectedTab);
}
int WbTextEditor::selectedTab() const {
return mTabWidget->currentIndex();
}
void WbTextEditor::updateProjectPath(const QString &oldPath, const QString &newPath) {
int count = mTabWidget->count();
for (int i = 0; i < count; i++) {
WbTextBuffer *buf = buffer(i);
QString filename = buf->fileName();
if (filename.startsWith(oldPath)) {
filename.replace(oldPath, newPath);
if (QFile::exists(filename))
buf->setFileName(filename);
}
}
updateGui();
}
| 31.276596 | 127 | 0.714723 | victorhu3 |
40199d1578252878431d6e1524ed70d951155d49 | 4,359 | cpp | C++ | yellow/w2_02_01_func_test.cpp | avptin/coursera-c-plus-plus | 18146f023998a073ee8e34315789d049b7fa0d7c | [
"MIT"
] | null | null | null | yellow/w2_02_01_func_test.cpp | avptin/coursera-c-plus-plus | 18146f023998a073ee8e34315789d049b7fa0d7c | [
"MIT"
] | null | null | null | yellow/w2_02_01_func_test.cpp | avptin/coursera-c-plus-plus | 18146f023998a073ee8e34315789d049b7fa0d7c | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
template <class T>
ostream& operator<<(ostream& os, const vector<T>& s) {
os << "{";
bool first = true;
for (const auto& x : s) {
if (!first) {
os << ", ";
}
first = false;
os << x;
}
return os << "}";
}
template <class T>
ostream& operator<<(ostream& os, const set<T>& s) {
os << "{";
bool first = true;
for (const auto& x : s) {
if (!first) {
os << ", ";
}
first = false;
os << x;
}
return os << "}";
}
template <class K, class V>
ostream& operator<<(ostream& os, const map<K, V>& m) {
os << "{";
bool first = true;
for (const auto& kv : m) {
if (!first) {
os << ", ";
}
first = false;
os << kv.first << ": " << kv.second;
}
return os << "}";
}
template <class T, class U>
void AssertEqual(const T& t, const U& u, const string& hint = {}) {
if (t != u) {
ostringstream os;
os << "Assertion failed: " << t << " != " << u;
if (!hint.empty()) {
os << " hint: " << hint;
}
throw runtime_error(os.str());
}
}
void Assert(bool b, const string& hint) { AssertEqual(b, true, hint); }
class TestRunner {
public:
template <class TestFunc>
void RunTest(TestFunc func, const string& test_name) {
try {
func();
cerr << test_name << " OK" << endl;
} catch (exception& e) {
++fail_count;
cerr << test_name << " fail: " << e.what() << endl;
} catch (...) {
++fail_count;
cerr << "Unknown exception caught" << endl;
}
}
~TestRunner() {
if (fail_count > 0) {
cerr << fail_count << " unit tests failed. Terminate" << endl;
exit(1);
}
}
private:
int fail_count = 0;
};
/*
// 4x^2 + 3 = 0
// a = 4, b = 0, c = 3
int GetDistinctRealRootCount(double A, double B, double C) {
// найдём дискриминант
double D = B * B - 4 * A * C;
int result = 0;
// если A равно нулю, то уравнение линейное: Bx + C = 0
if (A == 0) {
// Bx = -C => x = -C / B
if (B != 0) {
// cout << -C / B << endl;
result = 1;
}
// если B равно нулю, корней нет
} else if (D == 0) { // случай с нулевым дискриминантом
// корень ровно один
// cout << -B / (2 * A) << endl;
result = 1;
} else if (D > 0) { // в случае с положительным дискриминантом корня два
double r1 = (-B + sqrt(D)) / (2 * A);
double r2 = (-B - sqrt(D)) / (2 * A);
// cout << r1 << " " << r2 << endl;
result = (r1 != r2) ? 2 : 1;
}
return result;
}
*/
void TestFunction(void) {
// double D = B * B - 4 * A * C;
// D = 0
AssertEqual(GetDistinctRealRootCount(2, 4, 2), 1,
"a = 2, b = 4, where c = 2 has 1 real root(s).");
AssertEqual(GetDistinctRealRootCount(-2, 4, -2), 1,
"a = -2, b = 4, where c = -2 has 1 real root(s).");
// D < 0
AssertEqual(GetDistinctRealRootCount(4, 2, 2), 0,
"a = 4, b = 2, where c = 2 has 0 real root(s).");
// D > 0
AssertEqual(GetDistinctRealRootCount(4, 1, 0), 2,
"a = 4, b = 1, where c = 0 has 2 real root(s).");
AssertEqual(GetDistinctRealRootCount(4, 4, 0), 2,
"a = 4, b = 4, where c = 0 has 2 real root(s).");
AssertEqual(GetDistinctRealRootCount(0, 2, 1), 1,
"a = 0, b = 2, where c = 1 has 1 real root(s).");
AssertEqual(GetDistinctRealRootCount(0, 2, 10000), 1,
"a = 0, b = 2, where c = 10000 has 1 real root(s).");
AssertEqual(GetDistinctRealRootCount(4, 0, 3), 0,
"a = 4, b = 0, where c = 3 has 0 real root(s).");
AssertEqual(GetDistinctRealRootCount(-4, 0, 36), 2,
"a = -4, b = 0, where c = 36 has 2 real root(s).");
AssertEqual(GetDistinctRealRootCount(-4, 0, -36), 0,
"a = -4, b = 0, where c = -36 has 0 real root(s).");
AssertEqual(GetDistinctRealRootCount(0, 0, 1), 0,
"a = 0, b = 0, where c = 1 has 0 real roots.");
AssertEqual(GetDistinctRealRootCount(0, 0, -10), 0,
"a = 0, b = 0, where c = -10 has 0 real roots.");
AssertEqual(GetDistinctRealRootCount(0, 0, 189238910), 0,
"a = 0, b = 0, where c = 189238910 has 0 real roots.");
}
int main() {
TestRunner runner;
runner.RunTest(TestFunction, "TestFunction");
return 0;
}
| 25.196532 | 75 | 0.523056 | avptin |
401c69831c8bcc90efbd102bd8ad4130c6dc0e6f | 751 | cpp | C++ | Source/CurlFunctions.cpp | Mizugola/MeltingSagaUpdater | b9ebd8b4db39574526fff2703077ee4f76e9a65d | [
"MIT"
] | null | null | null | Source/CurlFunctions.cpp | Mizugola/MeltingSagaUpdater | b9ebd8b4db39574526fff2703077ee4f76e9a65d | [
"MIT"
] | null | null | null | Source/CurlFunctions.cpp | Mizugola/MeltingSagaUpdater | b9ebd8b4db39574526fff2703077ee4f76e9a65d | [
"MIT"
] | null | null | null | #include "CurlFunctions.hpp"
namespace fn
{
namespace Curl
{
size_t write_data(void * ptr, size_t size, size_t nmemb, FILE * stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
void downloadFile(const std::string& link, const std::string& file)
{
CURL *curl;
FILE *fp;
CURLcode res;
const char* url = link.c_str();
const char* outfilename = file.c_str();
curl = curl_easy_init();
if (curl) {
fopen_s(&fp, outfilename, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
}
}
}
| 22.757576 | 73 | 0.667111 | Mizugola |
401cbd8ebf8b328b95d6358951d0f90c6c27305d | 310 | cpp | C++ | 2-Structural/08.Composite/src/Composite/Add.cpp | gfa99/gof_design_patterns | a33ee7f344f8e382bb9fc676b77b22a5a123bca0 | [
"Apache-2.0"
] | 21 | 2017-11-08T11:32:48.000Z | 2021-03-29T08:58:04.000Z | 2-Structural/08.Composite/src/Composite/Add.cpp | gfa99/gof_design_patterns | a33ee7f344f8e382bb9fc676b77b22a5a123bca0 | [
"Apache-2.0"
] | null | null | null | 2-Structural/08.Composite/src/Composite/Add.cpp | gfa99/gof_design_patterns | a33ee7f344f8e382bb9fc676b77b22a5a123bca0 | [
"Apache-2.0"
] | 8 | 2017-11-26T13:57:50.000Z | 2021-08-23T06:52:57.000Z | #include "Composite/Add.h"
namespace GoF {
namespace Composite {
Add::Add(IOperand * left, IOperand * right)
: Expression(left, right)
{ }
double Add::calculate()
{
return leftOperand->calculate() + rightOperand->calculate();
}
}
}
| 16.315789 | 72 | 0.532258 | gfa99 |
401e7eb777810b37ec4e0b40ce29181b149c08eb | 9,504 | cpp | C++ | GTE/Samples/Graphics/BlendedTerrain/BlendedTerrainWindow3.cpp | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | null | null | null | GTE/Samples/Graphics/BlendedTerrain/BlendedTerrainWindow3.cpp | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | 1 | 2022-03-18T00:34:13.000Z | 2022-03-18T00:34:13.000Z | GTE/Samples/Graphics/BlendedTerrain/BlendedTerrainWindow3.cpp | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | 1 | 2022-03-17T21:54:55.000Z | 2022-03-17T21:54:55.000Z | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#include "BlendedTerrainWindow3.h"
#include <Applications/WICFileIO.h>
#include <random>
BlendedTerrainWindow3::BlendedTerrainWindow3(Parameters& parameters)
:
Window3(parameters),
mFlowDelta(0.00002f),
mPowerDelta(1.125f),
mZAngle(0.0f),
mZDeltaAngle(0.00002f)
{
if (!SetEnvironment() || !CreateTerrain())
{
parameters.created = false;
return;
}
mWireState = std::make_shared<RasterizerState>();
mWireState->fill = RasterizerState::Fill::WIREFRAME;
CreateSkyDome();
InitializeCamera(60.0f, GetAspectRatio(), 0.01f, 100.0f, 0.005f, 0.002f,
{ 0.0f, -7.0f, 1.5f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f });
mPVWMatrices.Update();
}
void BlendedTerrainWindow3::OnIdle()
{
mTimer.Measure();
if (mCameraRig.Move())
{
mPVWMatrices.Update();
}
Update();
mEngine->ClearBuffers();
mEngine->Draw(mTerrain);
mEngine->Draw(mSkyDome);
mEngine->Draw(8, GetYSize() - 8, { 0.0f, 0.0f, 0.0f, 1.0f }, mTimer.GetFPS());
mEngine->DisplayColorBuffer(0);
mTimer.UpdateFrameCount();
}
bool BlendedTerrainWindow3::OnCharPress(uint8_t key, int32_t x, int32_t y)
{
switch (key)
{
case 'w':
case 'W':
if (mEngine->GetRasterizerState() == mWireState)
{
mEngine->SetDefaultRasterizerState();
}
else
{
mEngine->SetRasterizerState(mWireState);
}
return true;
case 'p':
case 'P':
mTerrainEffect->SetPowerFactor(mTerrainEffect->GetPowerFactor() * mPowerDelta);
mEngine->Update(mTerrainEffect->GetPowerFactorConstant());
return true;
case 'm':
case 'M':
mTerrainEffect->SetPowerFactor(mTerrainEffect->GetPowerFactor() / mPowerDelta);
mEngine->Update(mTerrainEffect->GetPowerFactorConstant());
return true;
}
return Window3::OnCharPress(key, x, y);
}
bool BlendedTerrainWindow3::SetEnvironment()
{
std::string path = GetGTEPath();
if (path == "")
{
return false;
}
mEnvironment.Insert(path + "/Samples/Graphics/BlendedTerrain/Shaders/");
mEnvironment.Insert(path + "/Samples/Data/");
std::vector<std::string> inputs =
{
"BTHeightField.png",
"BTGrass.png",
"BTStone.png",
"BTCloud.png",
"SkyDome.png",
"SkyDome.txt"
};
for (auto const& input : inputs)
{
if (mEnvironment.GetPath(input) == "")
{
LogError("Cannot find file " + input);
return false;
}
}
return true;
}
bool BlendedTerrainWindow3::CreateTerrain()
{
// Load the height field for vertex displacement.
std::string heightFile = mEnvironment.GetPath("BTHeightField.png");
// Create the visual effect.
bool created = false;
mTerrainEffect = std::make_shared<BlendedTerrainEffect>(mEngine,
mProgramFactory, mEnvironment, created);
if (!created)
{
LogError("Failed to create the terrain effect.");
return false;
}
// Create the vertex buffer for terrain.
uint32_t const numSamples0 = 64, numSamples1 = 64;
uint32_t const numVertices = numSamples0 * numSamples1;
struct TerrainVertex
{
Vector3<float> position;
Vector2<float> tcoord0;
float tcoord1;
Vector2<float> tcoord2;
};
VertexFormat vformat;
vformat.Bind(VASemantic::POSITION, DF_R32G32B32_FLOAT, 0);
vformat.Bind(VASemantic::TEXCOORD, DF_R32G32_FLOAT, 0);
vformat.Bind(VASemantic::TEXCOORD, DF_R32_FLOAT, 1);
vformat.Bind(VASemantic::TEXCOORD, DF_R32G32_FLOAT, 2);
auto vbuffer = std::make_shared<VertexBuffer>(vformat, numVertices);
// Generate the geometry for a flat height field.
TerrainVertex* vertex = vbuffer->Get<TerrainVertex>();
float const extent0 = 8.0f, extent1 = 8.0f;
float const inv0 = 1.0f / (static_cast<float>(numSamples0) - 1.0f);
float const inv1 = 1.0f / (static_cast<float>(numSamples1) - 1.0f);
Vector3<float> position{};
Vector2<float> tcoord{};
uint32_t i, i0, i1;
for (i1 = 0, i = 0; i1 < numSamples1; ++i1)
{
tcoord[1] = i1 * inv1;
position[1] = (2.0f * tcoord[1] - 1.0f) * extent1;
for (i0 = 0; i0 < numSamples0; ++i0, ++i)
{
tcoord[0] = i0 * inv0;
position[0] = (2.0f * tcoord[0] - 1.0f) * extent0;
vertex[i].position = position;
vertex[i].tcoord0 = tcoord;
vertex[i].tcoord1 = 0.0f;
vertex[i].tcoord2 = tcoord;
}
}
// Use a Mersenne twister engine for random numbers.
std::mt19937 mte;
std::uniform_real_distribution<float> symrnd(-1.0f, 1.0f);
// Set the heights based on a precomputed height field. The image is
// known to be 64x64, which matches numSamples0 and numSamples1. It is
// also gray scale, so we use only the red channel.
auto texture = WICFileIO::Load(heightFile, false);
uint8_t* image = texture->Get<uint8_t>();
for (i = 0; i < numVertices; i++)
{
float height = static_cast<float>(image[4 * i]) / 255.0f;
float perturb = 0.05f * symrnd(mte);
vertex[i].position[2] = 3.0f * height + perturb;
vertex[i].tcoord0 *= 8.0f;
vertex[i].tcoord1 = height;
}
// Generate the index array for a regular grid of squares, each square a
// pair of triangles.
uint32_t const numTriangles = 2 * (numSamples0 - 1) * (numSamples1 - 1);
auto ibuffer = std::make_shared<IndexBuffer>(IP_TRIMESH, numTriangles, sizeof(uint32_t));
uint32_t* indices = ibuffer->Get<uint32_t>();
for (i1 = 0, i = 0; i1 < numSamples1 - 1; ++i1)
{
for (i0 = 0; i0 < numSamples0 - 1; ++i0)
{
int32_t v0 = i0 + numSamples0 * i1;
int32_t v1 = v0 + 1;
int32_t v2 = v1 + numSamples0;
int32_t v3 = v0 + numSamples0;
*indices++ = v0;
*indices++ = v1;
*indices++ = v2;
*indices++ = v0;
*indices++ = v2;
*indices++ = v3;
}
}
// Create the visual object.
mTerrain = std::make_shared<Visual>(vbuffer, ibuffer, mTerrainEffect);
mPVWMatrices.Subscribe(mTerrain->worldTransform, mTerrainEffect->GetPVWMatrixConstant());
mTrackBall.Attach(mTerrain);
return true;
}
void BlendedTerrainWindow3::CreateSkyDome()
{
// Load the vertices and indices from file for the sky dome trimesh.
std::string name = mEnvironment.GetPath("SkyDome.txt");
std::ifstream inFile(name.c_str());
uint32_t numVertices, numIndices, i;
inFile >> numVertices;
inFile >> numIndices;
struct SkyDomeVertex
{
Vector3<float> position;
Vector2<float> tcoord;
};
VertexFormat vformat;
vformat.Bind(VASemantic::POSITION, DF_R32G32B32_FLOAT, 0);
vformat.Bind(VASemantic::TEXCOORD, DF_R32G32_FLOAT, 0);
auto vbuffer = std::make_shared<VertexBuffer>(vformat, numVertices);
auto* vertices = vbuffer->Get<SkyDomeVertex>();
for (i = 0; i < numVertices; ++i)
{
inFile >> vertices[i].position[0];
inFile >> vertices[i].position[1];
inFile >> vertices[i].position[2];
inFile >> vertices[i].tcoord[0];
inFile >> vertices[i].tcoord[1];
}
int32_t const numTriangles = numIndices / 3;
auto ibuffer = std::make_shared<IndexBuffer>(IP_TRIMESH, numTriangles, sizeof(uint32_t));
auto* indices = ibuffer->Get<int32_t>();
for (i = 0; i < numIndices; ++i, ++indices)
{
inFile >> *indices;
}
inFile.close();
// Load the sky texture.
name = mEnvironment.GetPath("SkyDome.png");
auto sky = WICFileIO::Load(name, true);
sky->AutogenerateMipmaps();
// Create the visual effect.
mSkyDomeEffect = std::make_shared<Texture2Effect>(mProgramFactory, sky,
SamplerState::Filter::MIN_L_MAG_L_MIP_L, SamplerState::Mode::WRAP, SamplerState::Mode::WRAP);
// Create the visual object.
mSkyDome = std::make_shared<Visual>(vbuffer, ibuffer, mSkyDomeEffect);
// The sky dome needs to be translated and scaled for this sample.
mSkyDome->localTransform.SetUniformScale(7.9f);
mSkyDome->localTransform.SetTranslation(0.0f, 0.0f, -0.1f);
mSkyDome->Update();
mPVWMatrices.Subscribe(mSkyDome->worldTransform, mSkyDomeEffect->GetPVWMatrixConstant());
mTrackBall.Attach(mSkyDome);
}
void BlendedTerrainWindow3::Update()
{
// Animate the cloud layer.
Vector2<float> flowDirection = mTerrainEffect->GetFlowDirection();
flowDirection[0] += mFlowDelta;
if (0.0f > flowDirection[0])
{
flowDirection[0] += 1.0f;
}
else if (1.0f < flowDirection[0])
{
flowDirection[0] -= 1.0f;
}
mTerrainEffect->SetFlowDirection(flowDirection);
mEngine->Update(mTerrainEffect->GetFlowDirectionConstant());
// Rotate the sky dome.
mZAngle -= mZDeltaAngle;
if (mZAngle < (float)-GTE_C_TWO_PI)
{
mZAngle += (float)GTE_C_TWO_PI;
}
mSkyDome->localTransform.SetRotation(
AxisAngle<4, float>({ 0.0f, 0.0f, 1.0f, 0.0f }, -mZAngle));
mSkyDome->Update();
mPVWMatrices.Update();
}
| 30.658065 | 101 | 0.622475 | lakinwecker |
402112e3986c735b4885a7824a3e0496331b9cbc | 825 | cpp | C++ | demos/tutorial/alphabets/assignment_1_solution.cpp | JensUweUlrich/seqan | fa609a123d3dc5d8166c12f6849281813438dd39 | [
"BSD-3-Clause"
] | 409 | 2015-01-12T22:02:01.000Z | 2022-03-29T06:17:05.000Z | demos/tutorial/alphabets/assignment_1_solution.cpp | JensUweUlrich/seqan | fa609a123d3dc5d8166c12f6849281813438dd39 | [
"BSD-3-Clause"
] | 1,269 | 2015-01-02T22:42:25.000Z | 2022-03-08T13:31:46.000Z | demos/tutorial/alphabets/assignment_1_solution.cpp | JensUweUlrich/seqan | fa609a123d3dc5d8166c12f6849281813438dd39 | [
"BSD-3-Clause"
] | 193 | 2015-01-14T16:21:27.000Z | 2022-03-19T22:47:02.000Z | #include <seqan/sequence.h>
#include <seqan/basic.h>
#include <iostream>
using namespace seqan;
// We define a function which takes
// the alphabet type as an argument
template <typename TAlphabet>
void showAllLettersOfMyAlphabet(TAlphabet const &)
{
typedef typename ValueSize<TAlphabet>::Type TSize;
// We need to determine the alphabet size
// using the metafunction ValueSize
TSize alphSize = ValueSize<TAlphabet>::VALUE;
// We iterate over all characters of the alphabet
// and output them
for (TSize i = 0; i < alphSize; ++i)
std::cout << static_cast<unsigned>(i) << ',' << TAlphabet(i) << " ";
std::cout << std::endl;
}
int main()
{
showAllLettersOfMyAlphabet(AminoAcid());
showAllLettersOfMyAlphabet(Dna());
showAllLettersOfMyAlphabet(Dna5());
return 0;
}
| 26.612903 | 77 | 0.686061 | JensUweUlrich |
402154859b3dee824f2c145cb39ecaedd54458b8 | 5,031 | cc | C++ | src/browser/util/renderer_preferences_util.cc | spolu/exo_browser_save | d1ef13f2735405154b6c2e56db829e81effe6ed1 | [
"MIT"
] | 7 | 2015-02-01T05:07:20.000Z | 2017-09-12T07:55:40.000Z | src/browser/util/renderer_preferences_util.cc | spolu/exo_browser_save | d1ef13f2735405154b6c2e56db829e81effe6ed1 | [
"MIT"
] | null | null | null | src/browser/util/renderer_preferences_util.cc | spolu/exo_browser_save | d1ef13f2735405154b6c2e56db829e81effe6ed1 | [
"MIT"
] | null | null | null | // Copyright (c) 2014 Stanislas Polu.
// Copyright (c) 2012 The Chromium Authors.
// See the LICENSE file.
#include "exo_browser/src/browser/util/renderer_preferences_util.h"
#include "base/prefs/pref_service.h"
#include "content/public/common/renderer_preferences.h"
#include "third_party/skia/include/core/SkColor.h"
#if defined(OS_LINUX) || defined(OS_ANDROID)
#include "ui/gfx/font_render_params_linux.h"
#endif
#if defined(TOOLKIT_GTK)
#include "ui/gfx/gtk_util.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "ui/views/controls/textfield/textfield.h"
#endif
#if defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#include "ui/views/linux_ui/linux_ui.h"
#endif
namespace renderer_preferences_util {
namespace {
#if defined(TOOLKIT_GTK)
// Dividing GTK's cursor blink cycle time (in milliseconds) by this value yields
// an appropriate value for content::RendererPreferences::caret_blink_interval.
// This matches the logic in the WebKit GTK port.
const double kGtkCursorBlinkCycleFactor = 2000.0;
#endif // defined(TOOLKIT_GTK)
#if defined(OS_LINUX) || defined(OS_ANDROID)
content::RendererPreferencesHintingEnum
GetRendererPreferencesHintingEnum(
gfx::FontRenderParams::Hinting hinting)
{
switch (hinting) {
case gfx::FontRenderParams::HINTING_NONE:
return content::RENDERER_PREFERENCES_HINTING_NONE;
case gfx::FontRenderParams::HINTING_SLIGHT:
return content::RENDERER_PREFERENCES_HINTING_SLIGHT;
case gfx::FontRenderParams::HINTING_MEDIUM:
return content::RENDERER_PREFERENCES_HINTING_MEDIUM;
case gfx::FontRenderParams::HINTING_FULL:
return content::RENDERER_PREFERENCES_HINTING_FULL;
default:
NOTREACHED() << "Unhandled hinting style " << hinting;
return content::RENDERER_PREFERENCES_HINTING_SYSTEM_DEFAULT;
}
}
content::RendererPreferencesSubpixelRenderingEnum
GetRendererPreferencesSubpixelRenderingEnum(
gfx::FontRenderParams::SubpixelRendering subpixel_rendering)
{
switch (subpixel_rendering) {
case gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE:
return content::RENDERER_PREFERENCES_SUBPIXEL_RENDERING_NONE;
case gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB:
return content::RENDERER_PREFERENCES_SUBPIXEL_RENDERING_RGB;
case gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR:
return content::RENDERER_PREFERENCES_SUBPIXEL_RENDERING_BGR;
case gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB:
return content::RENDERER_PREFERENCES_SUBPIXEL_RENDERING_VRGB;
case gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR:
return content::RENDERER_PREFERENCES_SUBPIXEL_RENDERING_VBGR;
default:
NOTREACHED() << "Unhandled subpixel rendering style "
<< subpixel_rendering;
return content::RENDERER_PREFERENCES_SUBPIXEL_RENDERING_SYSTEM_DEFAULT;
}
}
#endif // defined(OS_LINUX) || defined(OS_ANDROID)
} // namespace
void
UpdateFromSystemSettings(
content::RendererPreferences* prefs)
{
#if defined(TOOLKIT_GTK)
// Dividing GTK's cursor blink cycle time (in milliseconds) by this value
// yields an appropriate value for RendererPreferences::caret_blink_interval.
// This matches the logic in the WebKit GTK port.
const double kGtkCursorBlinkCycleFactor = 2000.0;
const base::TimeDelta cursor_blink_time = gfx::GetCursorBlinkCycle();
prefs->caret_blink_interval =
cursor_blink_time.InMilliseconds() ?
cursor_blink_time.InMilliseconds() / kGtkCursorBlinkCycleFactor :
0;
#elif defined(USE_DEFAULT_RENDER_THEME)
prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE);
#if defined(OS_CHROMEOS)
// This color is 0x544d90fe modulated with 0xffffff.
prefs->active_selection_bg_color = SkColorSetRGB(0xCB, 0xE4, 0xFA);
prefs->active_selection_fg_color = SK_ColorBLACK;
prefs->inactive_selection_bg_color = SkColorSetRGB(0xEA, 0xEA, 0xEA);
prefs->inactive_selection_fg_color = SK_ColorBLACK;
#endif
#endif
#if defined(TOOLKIT_VIEWS)
prefs->caret_blink_interval = views::Textfield::GetCaretBlinkMs() / 1000.0;
#endif
#if defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
views::LinuxUI* linux_ui = views::LinuxUI::instance();
if (linux_ui) {
// If we have a linux_ui object, set the caret blink interval regardless of
// whether we're in native theme mode.
prefs->caret_blink_interval = linux_ui->GetCursorBlinkInterval();
}
#endif
#if defined(OS_LINUX) || defined(OS_ANDROID)
const gfx::FontRenderParams& params = gfx::GetDefaultWebKitFontRenderParams();
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = GetRendererPreferencesHintingEnum(params.hinting);
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering =
GetRendererPreferencesSubpixelRenderingEnum(params.subpixel_rendering);
#endif
#if !defined(OS_MACOSX)
prefs->plugin_fullscreen_allowed = true;
#endif
}
} // namespace renderer_preferences_util
| 35.680851 | 80 | 0.77738 | spolu |
40218141af0f7035e669f3a22d1ab9faa558bfa3 | 821 | hpp | C++ | third-party/include/tao/json/jaxn/is_identifier.hpp | ludchieng/IMAC-Lihowar | e5f551ab9958fa7d8fa4cbe07d0aa3555842b4fb | [
"BSL-1.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2 | 2020-03-09T06:24:46.000Z | 2022-02-04T23:09:23.000Z | third-party/include/tao/json/jaxn/is_identifier.hpp | ludchieng/IMAC-Lihowar | e5f551ab9958fa7d8fa4cbe07d0aa3555842b4fb | [
"BSL-1.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | third-party/include/tao/json/jaxn/is_identifier.hpp | ludchieng/IMAC-Lihowar | e5f551ab9958fa7d8fa4cbe07d0aa3555842b4fb | [
"BSL-1.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2 | 2020-09-07T03:04:36.000Z | 2022-02-04T23:09:24.000Z | // Copyright (c) 2017-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/json/
#ifndef TAO_JSON_JAXN_IS_IDENTIFIER_HPP
#define TAO_JSON_JAXN_IS_IDENTIFIER_HPP
#include <cctype>
#include "../external/string_view.hpp"
namespace tao
{
namespace json
{
namespace jaxn
{
inline bool is_identifier( const tao::string_view v ) noexcept
{
if( v.empty() || std::isdigit( v[ 0 ] ) ) { // NOLINT
return false;
}
for( const auto c : v ) {
if( !std::isalnum( c ) && c != '_' ) { // NOLINT
return false;
}
}
return true;
}
} // namespace jaxn
} // namespace json
} // namespace tao
#endif
| 22.189189 | 74 | 0.538368 | ludchieng |
4023760fa55783ed4c72fceb095545d788e03167 | 1,774 | cpp | C++ | CMDResponse/TestMain.cpp | ahidaka/CMDResponse | 939c28717f277aff1fb8894c9713e9ec9b8035b4 | [
"MIT"
] | null | null | null | CMDResponse/TestMain.cpp | ahidaka/CMDResponse | 939c28717f277aff1fb8894c9713e9ec9b8035b4 | [
"MIT"
] | null | null | null | CMDResponse/TestMain.cpp | ahidaka/CMDResponse | 939c28717f277aff1fb8894c9713e9ec9b8035b4 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <tchar.h>
#include <windows.h>
//
// Defines
//
#define BUFFER_SIZE (4 * 1024 * 1024) // 4MB
#define COMMAND_TIMEOUT (100) //dwMilliseconds
DWORD CMDResponse(PCTSTR* cmdline, PSTR buf, DWORD size, DWORD timeout);
//
// Test Main
//
INT _tmain
(
INT argc, _TCHAR* argv[]
)
{
HANDLE hBuffer;
PSTR buffer;
TCHAR cmdline[] = _T("tasklist");
BOOL result;
printf("Start...\n");
hBuffer = HeapCreate(NULL, 0, 0);
if (hBuffer == NULL) {
fprintf(stderr, "Cannot create handle\n");
return(1);
}
buffer = (PSTR)HeapAlloc(
hBuffer,
HEAP_ZERO_MEMORY,
BUFFER_SIZE
);
if (buffer == NULL) {
fprintf(stderr, "Cannot allocate buffer, size=%d\n", BUFFER_SIZE);
return(1);
}
result = CMDResponse(
(PCTSTR*)cmdline,
buffer,
BUFFER_SIZE,
COMMAND_TIMEOUT
);
if (result == 0) {
fprintf(stderr, "CMDResponse error\n");
return(1);
}
printf("CMDResponse:<<%s>> length:%d\n", buffer, result);
#if _OUTPUT_DEBUG_
for (INT i = 0; i < 32; i++) {
printf(" %02X", (BYTE)buffer[i]);
}
printf("\n");
#endif
//
// Output to file
//
DWORD writtenSize = 0;
HANDLE h = CreateFile(
L"C:\\Windows\\Temp\\OutFile.txt",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (h == INVALID_HANDLE_VALUE) {
fprintf(stderr, "CreateFile error!\n");
return(1);
}
if (WriteFile(h, buffer, result, &writtenSize, NULL) == 0) {
fprintf(stderr, "WriteFile error!\n");
return(1);
}
CloseHandle(h);
printf("End.\n");
return(0);
}
| 18.479167 | 74 | 0.543405 | ahidaka |
402729069d1c25e64a45384682bf48eb1bfb83bf | 4,076 | hpp | C++ | src/main/include/control/ElevatorController.hpp | MattSa952073/PubSubLub | a20bd82d72f3d5a1599234d638afd578259f3553 | [
"BSD-2-Clause"
] | null | null | null | src/main/include/control/ElevatorController.hpp | MattSa952073/PubSubLub | a20bd82d72f3d5a1599234d638afd578259f3553 | [
"BSD-2-Clause"
] | null | null | null | src/main/include/control/ElevatorController.hpp | MattSa952073/PubSubLub | a20bd82d72f3d5a1599234d638afd578259f3553 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2018-2019 FRC Team 3512. All Rights Reserved.
#pragma once
#include <Eigen/Core>
#include <frc/controller/StateSpaceController.h>
#include <frc/controller/StateSpaceObserver.h>
#include <frc/controller/StateSpacePlant.h>
#include "Constants.hpp"
#include "control/ElevatorClimbCoeffs.hpp"
#include "control/ElevatorCoeffs.hpp"
#include "control/TrapezoidalMotionProfile.hpp"
#include "logging/CsvLogger.hpp"
namespace frc3512 {
class ElevatorController {
public:
// State tolerances in meters and meters/sec respectively.
static constexpr double kPositionTolerance = 0.05;
static constexpr double kVelocityTolerance = 2.0;
ElevatorController();
ElevatorController(const ElevatorController&) = delete;
ElevatorController& operator=(const ElevatorController&) = delete;
void Enable();
void Disable();
void SetScoringIndex();
void SetClimbingIndex();
void SetGoal(double goal);
/**
* Sets the references.
*
* @param position Position of the carriage in meters.
* @param velocity Velocity of the carriage in meters per second.
*/
void SetReferences(units::meter_t position,
units::meters_per_second_t velocity);
bool AtReferences() const;
bool AtGoal() const;
/**
* Sets the current encoder measurement.
*
* @param measuredPosition Position of the carriage in meters.
*/
void SetMeasuredPosition(double measuredPosition);
/**
* Returns the control loop calculated voltage.
*/
double ControllerVoltage() const;
/**
* Returns the estimated position.
*/
double EstimatedPosition() const;
/**
* Returns the estimated velocity.
*/
double EstimatedVelocity() const;
/**
* Returns the error between the position reference and the position
* estimate.
*/
double PositionError() const;
/**
* Returns the error between the velocity reference and the velocity
* estimate.
*/
double VelocityError() const;
/**
* Returns the current reference set by the profile
*/
double PositionReference();
/**
* Executes the control loop for a cycle.
*/
void Update();
/**
* Resets any internal state.
*/
void Reset();
void SetClimbingProfile();
void SetScoringProfile();
private:
// The current sensor measurement.
Eigen::Matrix<double, 1, 1> m_Y;
TrapezoidalMotionProfile::State m_goal;
TrapezoidalMotionProfile::Constraints scoringConstraints{
Constants::Elevator::kMaxV, Constants::Elevator::kMaxA};
TrapezoidalMotionProfile::Constraints climbingConstraints{
Constants::Elevator::kClimbMaxV, Constants::Elevator::kClimbMaxA};
TrapezoidalMotionProfile::Constraints m_activeConstraints =
scoringConstraints;
TrapezoidalMotionProfile m_positionProfile{scoringConstraints,
{0_m, 0_mps}};
TrapezoidalMotionProfile::State m_profiledReference;
frc::StateSpacePlant<2, 1, 1> m_plant = [&] {
frc::StateSpacePlant<2, 1, 1> plant{MakeElevatorPlantCoeffs()};
plant.AddCoefficients(MakeElevatorClimbPlantCoeffs());
return plant;
}();
frc::StateSpaceController<2, 1, 1> m_controller = [&] {
frc::StateSpaceController<2, 1, 1> controller{
MakeElevatorControllerCoeffs(), m_plant};
controller.AddCoefficients(MakeElevatorClimbControllerCoeffs());
return controller;
}();
frc::StateSpaceObserver<2, 1, 1> m_observer = [&] {
frc::StateSpaceObserver<2, 1, 1> observer{MakeElevatorObserverCoeffs(),
m_plant};
observer.AddCoefficients(MakeElevatorClimbObserverCoeffs());
return observer;
}();
Eigen::Matrix<double, 2, 1> m_nextR;
bool m_atReferences = false;
CsvLogger elevatorLogger{"/home/lvuser/Elevator.csv",
"Time,EstPos,PosRef,Voltage"};
};
} // namespace frc3512
| 27.355705 | 79 | 0.660206 | MattSa952073 |
402c7528f4e2867bc6b8aec754a50a192888704d | 251 | cpp | C++ | unit_test/comma.cpp | jhasse/coffeepp | 35b18e200641847f7756bdb6d9a146238d6d385c | [
"Zlib"
] | 30 | 2015-09-22T13:12:40.000Z | 2022-01-10T09:25:56.000Z | unit_test/comma.cpp | jhasse/coffeepp | 35b18e200641847f7756bdb6d9a146238d6d385c | [
"Zlib"
] | 6 | 2017-07-22T00:28:11.000Z | 2019-05-08T21:17:19.000Z | unit_test/comma.cpp | jhasse/coffeepp | 35b18e200641847f7756bdb6d9a146238d6d385c | [
"Zlib"
] | 3 | 2017-07-21T20:12:25.000Z | 2019-10-08T17:21:33.000Z | #include "check.hpp"
BOOST_AUTO_TEST_CASE(CommaTest) {
checkCompiler("Comma.cf++", R"(include cstdio
int main():
printf("foo",)
)", R"(#pragma once
int main();
)", R"(#include "Comma.hpp"
#include <cstdio>
int main() {
printf("foo");
}
)");
}
| 12.55 | 46 | 0.625498 | jhasse |
402c90a52d070ea28b238e903f82e1a2d75acb51 | 4,900 | cpp | C++ | qtparallelogram.cpp | tilast/courseWork | e6e76a46c0525f9c8425fda59b30107b709d8e92 | [
"MIT"
] | 4 | 2018-03-09T10:18:14.000Z | 2020-11-14T08:07:39.000Z | qtparallelogram.cpp | tilast/courseWork | e6e76a46c0525f9c8425fda59b30107b709d8e92 | [
"MIT"
] | 1 | 2016-12-06T06:54:27.000Z | 2016-12-06T06:54:27.000Z | qtparallelogram.cpp | tilast/courseWork | e6e76a46c0525f9c8425fda59b30107b709d8e92 | [
"MIT"
] | 2 | 2016-11-23T10:41:25.000Z | 2021-12-09T16:28:55.000Z | #include "qtparallelogram.h"
#include <QDebug>
QtParallelogram::QtParallelogram(const Point2D& p1, const Point2D& p2, const float& cp) : Parallelogram(p1, p2, cp) {
}
QtParallelogram::QtParallelogram(const Point2D& p1, const Point2D& p2) : Parallelogram(p1, p2) {
setControlPoint(25.);
}
void QtParallelogram::draw(QPainter &painter) const {
Point2D tl = Parallelogram::center - Parallelogram::size * 0.5;
Color p = getStyle().lineColor;
Color f = getStyle().fillColor;
if (isSelected()) f.alpha = 0.5;
painter.setPen(QColor(p.red * 255, p.green * 255, p.blue * 255, p.alpha * 255));
painter.setBrush(QBrush(QColor(f.red * 255, f.green * 255, f.blue * 255, f.alpha * 255)));
Point2D a;
a.x = tl.x + Parallelogram::controlPoint;
a.y = tl.y;
Point2D br = Parallelogram::center + Parallelogram::size * 0.5;
br.x += Parallelogram::controlPoint;
Point2D b;
b.x = br.x;
b.y = tl.y;
Point2D c;
c.x = br.x - Parallelogram::controlPoint;
c.y = br.y;
Point2D d;
d.x = tl.x;
d.y = br.y;
QPointF points[4] = {
QPointF(a.x, a.y),
QPointF(b.x, b.y),
QPointF(c.x, c.y),
QPointF(d.x, d.y)
};
painter.drawPolygon(points, 4);
if(selected) {
painter.setBrush(QBrush(QColor(255, 180, 120)));
painter.drawEllipse(QPoint(tl.x, tl.y), 2, 2);
painter.drawEllipse(QPoint(c.x, c.y), 2, 2);
painter.drawEllipse(QPoint(a.x, a.y), 2, 2);
}
}
bool QtParallelogram::isTopLeft(Point2D pressedPoint, Point2D epsilon) const {
Point2D tl = Parallelogram::center - Parallelogram::size * 0.5;
Point2D minTL = tl - epsilon;
Point2D maxTL = tl + epsilon;
return ((pressedPoint.x > minTL.x) && (pressedPoint.y > minTL.y) && (pressedPoint.x < maxTL.x) && (pressedPoint.y < maxTL.y));
}
bool QtParallelogram::isTopRight(Point2D pressedPoint, Point2D epsilon) const {
return false;
}
void QtParallelogram::reflect() {
Parallelogram::reflect();
}
bool QtParallelogram::isBottomLeft(Point2D pressedPoint, Point2D epsilon) const {
return false;
}
bool QtParallelogram::isControlPoint(Point2D pressedPoint, Point2D epsilon) const {
Point2D tl = Parallelogram::center - Parallelogram::size * 0.5;
Point2D cp;
cp.x = tl.x + Parallelogram::controlPoint;
cp.y = tl.y;
Point2D minCP = cp - epsilon;
Point2D maxCP = cp + epsilon;
return ((pressedPoint.x > minCP.x) && (pressedPoint.y > minCP.y) && (pressedPoint.x < maxCP.x) && (pressedPoint.y < maxCP.y));
}
bool QtParallelogram::isBottomRight(Point2D pressedPoint, Point2D epsilon) const {
Point2D br = Parallelogram::center + Parallelogram::size * 0.5;
Point2D minBR = br - epsilon;
Point2D maxBR = br + epsilon;
return ((pressedPoint.x > minBR.x) && (pressedPoint.y > minBR.y) && (pressedPoint.x < maxBR.x) && (pressedPoint.y < maxBR.y));
}
void QtParallelogram::select(bool sel) {
QtShape2D::select(sel);
}
bool QtParallelogram::isSelected() const {
return QtShape2D::isSelected();
}
DrawStyle& QtParallelogram::getStyle() {
return Parallelogram::getStyle();
}
const DrawStyle& QtParallelogram::getStyle() const {
return Parallelogram::getStyle();
}
Point2D QtParallelogram::getCenter() const {
return Parallelogram::getCenter();
}
Point2D QtParallelogram::getSize() const {
return Parallelogram::getSize();
}
void QtParallelogram::setBounds(const Point2D& p1, const Point2D& p2) {
Parallelogram::setBounds(p1, p2);
}
void QtParallelogram::setControlPoint(const float& cp) {
Parallelogram::setControlPoint(cp);
}
void QtParallelogram::move(const Point2D& destination) {
Parallelogram::move(destination);
}
void QtParallelogram::resize(const Point2D& destination, short t) {
Parallelogram::resize(destination, t);
}
bool QtParallelogram::belongs(const Point2D& p) {
return Parallelogram::belongs(p);
}
void QtParallelogram::setType() {
Parallelogram::setType();
}
int QtParallelogram::getType() {
return Parallelogram::getType();
}
QString QtParallelogram::svgElementCode() const {
Point2D tl = Parallelogram::center - Parallelogram::size * 0.5;
Point2D a;
a.x = tl.x + Parallelogram::controlPoint;
a.y = tl.y;
Point2D br = Parallelogram::center + Parallelogram::size * 0.5;
br.x += Parallelogram::controlPoint;
Point2D b;
b.x = br.x;
b.y = tl.y;
Point2D c;
c.x = br.x - Parallelogram::controlPoint;
c.y = br.y;
Point2D d;
d.x = tl.x;
d.y = br.y;
return QString("<polygon points=\"%1,%2 %3,%4 %5,%6 %7,%8\" style=\"fill:rgb(%9, %10, %11)\" abki=\"parallelogram\" />")
.arg(a.x).arg(a.y)
.arg(b.x).arg(b.y)
.arg(c.x).arg(c.y)
.arg(d.x).arg(d.y)
.arg(getStyle().fillColor.red*255).arg(getStyle().fillColor.green*255).arg(getStyle().fillColor.blue*255);
}
| 30.06135 | 130 | 0.650612 | tilast |
402f907031fdda19e0020db380671f24e02b0515 | 13,673 | cpp | C++ | demos/multichannel_face_detection/main.cpp | mypopydev/open_model_zoo | e238a1ac6bfacf133be223dd9debade7bfcf7dc5 | [
"Apache-2.0"
] | 12 | 2019-02-09T02:01:12.000Z | 2022-03-11T09:34:56.000Z | demos/multichannel_face_detection/main.cpp | mypopydev/open_model_zoo | e238a1ac6bfacf133be223dd9debade7bfcf7dc5 | [
"Apache-2.0"
] | null | null | null | demos/multichannel_face_detection/main.cpp | mypopydev/open_model_zoo | e238a1ac6bfacf133be223dd9debade7bfcf7dc5 | [
"Apache-2.0"
] | 6 | 2019-04-09T03:59:40.000Z | 2021-06-02T06:32:15.000Z | /*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
/**
* \brief The entry point for the Inference Engine multichannel_face_detection demo application
* \file multichannel_face_detection/main.cpp
* \example multichannel_face_detection/main.cpp
*/
#include <iostream>
#include <vector>
#include <utility>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <atomic>
#include <queue>
#include <chrono>
#include <sstream>
#include <memory>
#include <string>
#include <opencv2/opencv.hpp>
#include <samples/slog.hpp>
#include "multichannel_face_detection.hpp"
#include "input.hpp"
#include "output.hpp"
#include "graph.hpp"
bool ParseAndCheckCommandLine(int argc, char *argv[]) {
// ---------------------------Parsing and validation of input args--------------------------------------
gflags::ParseCommandLineNonHelpFlags(&argc, &argv, true);
if (FLAGS_h) {
showUsage();
return false;
}
slog::info << "Parsing input parameters" << slog::endl;
if (FLAGS_m.empty()) {
throw std::logic_error("Parameter -m is not set");
}
if (FLAGS_nc*(1+FLAGS_duplicate_num) > 16 - ((FLAGS_show_stats&&!FLAGS_no_show)?1:0)) {
throw std::logic_error("Final number of channels exceed maximum [16]");
}
if (FLAGS_nc == 0) {
throw std::logic_error("Number of input cameras must be greater 0");
}
slog::info << "\tDetection model: " << FLAGS_m << slog::endl;
slog::info << "\tDetection threshold: " << FLAGS_t << slog::endl;
slog::info << "\tUtilizing device: " << FLAGS_d << slog::endl;
if (!FLAGS_l.empty()) {
slog::info << "\tCPU extension library: " << FLAGS_l << slog::endl;
}
if (!FLAGS_c.empty()) {
slog::info << "\tCLDNN custom kernels map: " << FLAGS_c << slog::endl;
}
slog::info << "\tNumber of input channels: " << FLAGS_nc << slog::endl;
slog::info << "\tBatch size: " << FLAGS_bs << slog::endl;
slog::info << "\tNumber of infer requests: " << FLAGS_n_ir << slog::endl;
return true;
}
namespace {
void drawDetections(cv::Mat& img, const std::vector<Face>& detections) {
for (const Face& f : detections) {
if (f.confidence > FLAGS_t) {
cv::Rect ri(f.rect.x*img.cols, f.rect.y*img.rows,
f.rect.width*img.cols, f.rect.height*img.rows);
cv::rectangle(img, ri, cv::Scalar(255, 0, 0), 2);
}
}
}
const size_t DISP_WIDTH = 1920;
const size_t DISP_HEIGHT = 1080;
void displayNSources(const std::string& name,
const std::vector<std::shared_ptr<VideoFrame>>& data,
size_t count,
float time,
const std::string& stats
) {
size_t showStatsDec = (FLAGS_show_stats ? 1 : 0);
assert(count <= (16 - showStatsDec));
assert(data.size() <= (16 - showStatsDec));
static const cv::Size window_size = cv::Size(DISP_WIDTH, DISP_HEIGHT);
cv::Mat window_image = cv::Mat::zeros(window_size, CV_8UC3);
static const cv::Point points4[] = {
cv::Point(0, 0),
cv::Point(0, window_size.height/2),
cv::Point(window_size.width/2, 0),
cv::Point(window_size.width/2, window_size.height/2), // Reserve for show stats option
};
static const cv::Point points9[] = {
cv::Point(0, 0),
cv::Point(0, window_size.height/3),
cv::Point(0, 2*window_size.height/3),
cv::Point(window_size.width/3, 0),
cv::Point(window_size.width/3, window_size.height/3),
cv::Point(window_size.width/3, 2*window_size.height/3),
cv::Point(2*window_size.width/3, 0),
cv::Point(2*window_size.width/3, window_size.height/3),
cv::Point(2*window_size.width/3, 2*window_size.height/3), // Reserve for show stats option
};
static const cv::Point points16[] = {
cv::Point(0, 0),
cv::Point(0, window_size.height/4),
cv::Point(0, window_size.height/2),
cv::Point(0, window_size.height*3/4),
cv::Point(window_size.width/4, 0),
cv::Point(window_size.width/4, window_size.height/4),
cv::Point(window_size.width/4, window_size.height/2),
cv::Point(window_size.width/4, window_size.height*3/4),
cv::Point(window_size.width/2, 0),
cv::Point(window_size.width/2, window_size.height/4),
cv::Point(window_size.width/2, window_size.height/2),
cv::Point(window_size.width/2, window_size.height*3/4),
cv::Point(window_size.width*3/4, 0),
cv::Point(window_size.width*3/4, window_size.height/4),
cv::Point(window_size.width*3/4, window_size.height/2),
cv::Point(window_size.width*3/4, window_size.height*3/4), // Reserve for show stats option
};
static cv::Size frame_size;
const cv::Point* points;
size_t lastPos;
if (count <= (4 - showStatsDec)) {
frame_size = cv::Size(window_size/2);
points = points4;
lastPos = 3;
} else if (count <= (9 - showStatsDec)) {
frame_size = cv::Size(window_size/3);
points = points9;
lastPos = 8;
} else {
frame_size = cv::Size(window_size/4);
points = points16;
lastPos = 15;
}
for (size_t i = 0; i < data.size(); ++i) {
auto& elem = data[i];
if (!elem->frame->empty()) {
cv::Rect rect_frame1 = cv::Rect(points[i], frame_size);
cv::Mat window_part = window_image(rect_frame1);
cv::resize(*elem->frame.get(), window_part, frame_size);
drawDetections(window_part, elem->detections);
}
}
char str[256];
snprintf(str, sizeof(str), "%5.2f fps", static_cast<double>(1000.0f/time));
cv::putText(window_image, str, cv::Point(800, 100), cv::HersheyFonts::FONT_HERSHEY_COMPLEX, 2.0, cv::Scalar(0, 255, 0), 2);
if (FLAGS_show_stats && !stats.empty()) {
auto pos = points[lastPos] + cv::Point(0, 25);
size_t curr_pos = 0;
while (true) {
auto new_pos = stats.find('\n', curr_pos);
cv::putText(window_image, stats.substr(curr_pos, new_pos - curr_pos), pos, cv::HersheyFonts::FONT_HERSHEY_COMPLEX, 0.8, cv::Scalar(0, 0, 255), 1);
if (new_pos == std::string::npos) {
break;
}
pos += cv::Point(0, 25);
curr_pos = new_pos + 1;
}
}
cv::imshow(name, window_image);
}
} // namespace
int main(int argc, char* argv[]) {
try {
slog::info << "InferenceEngine: " << InferenceEngine::GetInferenceEngineVersion() << slog::endl;
// ------------------------------ Parsing and validation of input args ---------------------------------
if (!ParseAndCheckCommandLine(argc, argv)) {
return 0;
}
size_t inputPollingTimeout = 1000; // msec
VideoSources sources(/*async*/true, FLAGS_duplicate_num, FLAGS_show_stats,
FLAGS_n_iqs, inputPollingTimeout, FLAGS_real_input_fps);
slog::info << "Trying to connect " << FLAGS_nc << " web cams ..." << slog::endl;
for (size_t i = 0; i < FLAGS_nc; ++i) {
if (!sources.openVideo(std::to_string(i))) {
slog::info << "Web cam" << i << ": returned false" << slog::endl;
return -1;
}
}
sources.start();
std::string weights_path;
std::string model_path = FLAGS_m;
std::size_t found = model_path.find_last_of(".");
if (found > model_path.size()) {
slog::info << "Invalid model name: " << model_path << slog::endl;
slog::info << "Expected to be <model_name>.xml" << slog::endl;
return -1;
}
weights_path = model_path.substr(0, found) + ".bin";
slog::info << "Model path: " << model_path << slog::endl;
slog::info << "Weights path: " << weights_path << slog::endl;
std::shared_ptr<IEGraph> network(new IEGraph(
FLAGS_show_stats,
FLAGS_n_ir,
FLAGS_bs,
model_path,
weights_path,
FLAGS_l,
FLAGS_c,
FLAGS_d,
[&](VideoFrame& img) {
return sources.getFrame(img);
}));
network->setDetectionConfidence(FLAGS_t);
std::atomic<float> average_fps = {0.0f};
std::vector<std::shared_ptr<VideoFrame>> batchRes;
std::mutex statMutex;
std::stringstream statStream;
const size_t outputQueueSize = 1;
AsyncOutput output(FLAGS_show_stats, outputQueueSize,
[&](const std::vector<std::shared_ptr<VideoFrame>>& result) {
std::string str;
if (FLAGS_show_stats) {
std::unique_lock<std::mutex> lock(statMutex);
str = statStream.str();
}
displayNSources("Demo",
result, FLAGS_nc*(1 + FLAGS_duplicate_num),
average_fps, str);
return (cv::waitKey(1) != 27);
});
output.start();
using timer = std::chrono::high_resolution_clock;
using duration = std::chrono::duration<float, std::milli>;
timer::time_point lastTime = timer::now();
duration samplingTimeout(FLAGS_fps_sp);
size_t fpsCounter = 0;
size_t perfItersCounter = 0;
while (true) {
bool read_data = true;
while (read_data) {
auto br = network->getBatchData();
for (size_t i = 0; i < br.size(); i++) {
unsigned int val = br[i]->source_idx;
auto it = find_if(batchRes.begin(), batchRes.end(), [val] (const std::shared_ptr<VideoFrame>& vf) { return vf->source_idx == val; } );
if (it != batchRes.end()) {
if (!FLAGS_no_show) {
output.push(std::move(batchRes));
}
batchRes.clear();
read_data = false;
}
batchRes.push_back(std::move(br[i]));
}
}
++fpsCounter;
if (!output.isAlive()) {
break;
}
auto currTime = timer::now();
auto deltaTime = (currTime - lastTime);
if (deltaTime >= samplingTimeout) {
auto durMsec =
std::chrono::duration_cast<duration>(deltaTime).count();
auto frameTime = durMsec / static_cast<float>(fpsCounter);
fpsCounter = 0;
lastTime = currTime;
if (FLAGS_no_show) {
slog::info << "Average Throughput : " << 1000.f/frameTime << " fps" << slog::endl;
if (++perfItersCounter >= FLAGS_n_sp) {
break;
}
} else {
average_fps = frameTime;
}
if (FLAGS_show_stats) {
auto inputStat = sources.getStats();
auto inferStat = network->getStats();
auto outputStat = output.getStats();
std::unique_lock<std::mutex> lock(statMutex);
statStream.str(std::string());
statStream << std::fixed << std::setprecision(1);
statStream << "Input reads: ";
for (size_t i = 0; i < inputStat.read_times.size(); ++i) {
if (0 == (i % 4)) {
statStream << std::endl;
}
statStream << inputStat.read_times[i] << "ms ";
}
statStream << std::endl;
statStream << "Preprocess time: "
<< inferStat.preprocess_time << "ms";
statStream << std::endl;
statStream << "Plugin latency: "
<< inferStat.infer_time << "ms";
statStream << std::endl;
statStream << "Render time: " << outputStat.render_time
<< "ms" << std::endl;
if (FLAGS_no_show) {
slog::info << statStream.str() << slog::endl;
}
}
}
}
}
catch (const std::exception& error) {
slog::err << error.what() << slog::endl;
return 1;
}
catch (...) {
slog::err << "Unknown/internal exception happened." << slog::endl;
return 1;
}
slog::info << "Execution successful" << slog::endl;
return 0;
}
| 37.460274 | 159 | 0.525196 | mypopydev |
403247304ccdf8d64e3b9eab32551817bba28c6b | 356 | cpp | C++ | CodeForces-Contest/155/A.cpp | Tech-Intellegent/CodeForces-Solution | 2f291a38b80b8ff2a2595b2e526716468ff26bf8 | [
"MIT"
] | 1 | 2022-01-23T07:18:07.000Z | 2022-01-23T07:18:07.000Z | CodeForces-Contest/155/A.cpp | Tech-Intellegent/CodeForces-Solution | 2f291a38b80b8ff2a2595b2e526716468ff26bf8 | [
"MIT"
] | null | null | null | CodeForces-Contest/155/A.cpp | Tech-Intellegent/CodeForces-Solution | 2f291a38b80b8ff2a2595b2e526716468ff26bf8 | [
"MIT"
] | 1 | 2022-02-05T11:53:04.000Z | 2022-02-05T11:53:04.000Z | #include <iostream>
using namespace std;
int main() {
int n,a;
cin>>n>>a;
int min = a, max = a, ans = 0;
for(int i = 1; i<n; i++){
int num;
cin>>num;
if(num>max){
ans++;
max = num;
}
if(num<min){
ans++;
min = num;
}
}
cout<<ans<<endl;
} | 17.8 | 34 | 0.370787 | Tech-Intellegent |
40332982e39299e23497c74992500aea4d87277e | 1,185 | cpp | C++ | leetcode/Algorithms/valid-parentheses.cpp | Doarakko/competitive-programming | 5ae78c501664af08a3f16c81dbd54c68310adec8 | [
"MIT"
] | 1 | 2017-07-11T16:47:29.000Z | 2017-07-11T16:47:29.000Z | leetcode/Algorithms/valid-parentheses.cpp | Doarakko/Competitive-Programming | 10642a4bd7266c828dd2fc6e311284e86bdf2968 | [
"MIT"
] | 1 | 2021-02-07T09:10:26.000Z | 2021-02-07T09:10:26.000Z | leetcode/Algorithms/valid-parentheses.cpp | Doarakko/Competitive-Programming | 10642a4bd7266c828dd2fc6e311284e86bdf2968 | [
"MIT"
] | null | null | null | class Solution
{
public:
bool isValid(string s)
{
stack<char> v;
for (int i = 0; i < s.length(); i++)
{
switch (s[i])
{
case '(':
case '[':
case '{':
v.push(s[i]);
break;
case ']':
if (v.size() == 0 || v.top() != '[')
{
return false;
}
else
{
v.pop();
}
break;
case '}':
if (v.size() == 0 || v.top() != '{')
{
return false;
}
else
{
v.pop();
}
break;
case ')':
if (v.size() == 0 || v.top() != '(')
{
return false;
}
else
{
v.pop();
}
break;
}
}
if (v.size() == 0)
{
return true;
}
return false;
}
}; | 21.944444 | 52 | 0.206751 | Doarakko |
403551d98ffbfdc5f494910a4346be0ff61501c8 | 418 | hpp | C++ | src/SivComponent/Utils.hpp | mak1a/SivComponent | 1043cde67a5dc14f2d4e0128aecfee7f54ed7002 | [
"MIT"
] | 1 | 2021-01-24T08:55:59.000Z | 2021-01-24T08:55:59.000Z | src/SivComponent/Utils.hpp | mak1a/SivComponent | 1043cde67a5dc14f2d4e0128aecfee7f54ed7002 | [
"MIT"
] | 2 | 2021-01-24T06:12:12.000Z | 2021-01-24T14:37:10.000Z | src/SivComponent/Utils.hpp | mak1a/SivComponent | 1043cde67a5dc14f2d4e0128aecfee7f54ed7002 | [
"MIT"
] | null | null | null | #pragma once
#define NO_USING_S3D
#include <Siv3D.hpp>
#include "../ComponentEngine/ComponentEngine.hpp"
namespace ComponentEngine::Siv
{
class MouseChase : public ComponentEngine::AttachableComponent
{
void Start() override {}
void Update() override
{
this->gameobject.lock()->SetWorldPosition(s3d::Cursor::Pos());
}
};
} // namespace ComponentEngine::Siv
| 22 | 74 | 0.65311 | mak1a |
403613f942362c3e6a0ff07194ef8f2c119f0adb | 20,573 | cpp | C++ | DGPortImpl.cpp | yoann01/SpliceAPI | d1fabdb296ffcdbaddf31a00993e97dea7db114e | [
"BSD-3-Clause"
] | null | null | null | DGPortImpl.cpp | yoann01/SpliceAPI | d1fabdb296ffcdbaddf31a00993e97dea7db114e | [
"BSD-3-Clause"
] | null | null | null | DGPortImpl.cpp | yoann01/SpliceAPI | d1fabdb296ffcdbaddf31a00993e97dea7db114e | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved.
#include "DGPortImpl.h"
#include "SceneManagementImpl.h"
using namespace FabricSpliceImpl;
DGPortImpl::DGPortImpl(
DGGraphImplPtr graph,
const std::string & name,
const std::string & member,
FabricCore::DGNode dgNode,
const std::string & dgNodeName,
Mode mode,
uint32_t dataSize,
bool shallow,
bool autoInitObjects
) {
const FabricCore::Client * client = DGGraphImpl::getClient();
mGraph = DGGraphImplWeakPtr(graph);
mGraphName = graph->getName();
setName(name);
mMember = member;
mDGNode = dgNode;
mDGNodeName = dgNodeName;
mMode = mode;
// mManipulatable = -1;
mAutoInitObjects = autoInitObjects;
mKey = StringUtilityImpl::replaceString(mGraphName, '.', '_');
mKey += "." + StringUtilityImpl::replaceString(getName(), '.', '_');
mIsShallow = shallow;
mDataType = graph->getDGNodeMemberDataType(mMember, dgNodeName);
mIsArray = StringUtilityImpl::endsWith(mDataType, "[]");
if(mIsArray)
mDataType = mDataType.substr(0, mDataType.length() - 2);
mDataSize = dataSize;
try
{
mIsStruct = FabricCore::GetRegisteredTypeIsStruct(*client, mDataType.c_str());
}
catch(FabricCore::Exception e)
{
mIsStruct = false;
}
try
{
mIsObject = FabricCore::GetRegisteredTypeIsObject(*client, mDataType.c_str());
}
catch(FabricCore::Exception e)
{
mIsObject = false;
}
try
{
mIsInterface = FabricCore::GetRegisteredTypeIsInterface(*client, mDataType.c_str());
}
catch(FabricCore::Exception e)
{
mIsInterface = false;
}
// if the DGPort uses a KL object, let's initiate it
if(!mIsArray && isObject() && doesAutoInitObjects()) {
try
{
FabricCore::RTVal rt = getRTVal();
if(rt.isNullObject())
{
rt = FabricCore::RTVal::Create(*client, mDataType.c_str(), 0, 0);
setRTVal( rt );
LoggingImpl::log(("DGPort '"+getName()+"' on Node '"+mGraphName+"' initiated "+mDataType+" reference.").c_str());
}
}
catch(FabricCore::Exception e)
{
std::string message = e.getDesc_cstr();
LoggingImpl::reportError((message+" - "+mDataType+" not initiated.").c_str());
LoggingImpl::clearError();
}
}
}
DGPortImpl::~DGPortImpl()
{
LoggingImpl::log("DGPort '"+getName()+"' on Node '"+mGraphName+"' destroyed.");
}
DGGraphImplPtr DGPortImpl::getDGGraph()
{
if(mGraph.expired())
return DGGraphImplPtr();
return DGGraphImplPtr(mGraph);
}
uint32_t DGPortImpl::getSliceCount(std::string * errorOut)
{
DGGraphImplPtr node = getDGGraph();
if(!node)
{
LoggingImpl::reportError("DGPortImpl::getSliceCount, Node '"+mGraphName+"' already destroyed.");
return 0;
}
return mDGNode.getSize();
}
bool DGPortImpl::setSliceCount(uint32_t count, std::string * errorOut)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set a slice count on an output DGPort.", errorOut);
mDGNode.setSize(count);
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::setSliceCount, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
FabricCore::Variant DGPortImpl::getVariant(uint32_t slice, std::string * errorOut)
{
if(slice > getSliceCount())
{
LoggingImpl::reportError("Slice out of bounds.", errorOut);
return FabricCore::Variant();
}
DGGraphImplPtr node = getDGGraph();
if(!node)
{
LoggingImpl::reportError("DGPortImpl::getVariant, Node '"+mGraphName+"' already destroyed.");
return FabricCore::Variant();
}
if(mMode != Mode_IN)
if(!node->evaluate(mDGNode, errorOut))
return FabricCore::Variant();
try
{
FabricCore::Variant result = mDGNode.getMemberSliceData_Variant(mMember.c_str(), slice);
return result;
}
catch(FabricCore::Exception e)
{
LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
return FabricCore::Variant();
}
bool DGPortImpl::setVariant(FabricCore::Variant value, uint32_t slice, std::string * errorOut)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
if(slice > mDGNode.getSize())
return LoggingImpl::reportError("Slice out of bounds.", errorOut);
// add missing dictionary members using the previous value
if(value.isDict()) {
FabricCore::Variant prevValue = getVariant();
for(FabricCore::Variant::DictIter keyIter(prevValue); !keyIter.isDone(); keyIter.next())
{
std::string key = keyIter.getKey()->getStringData();
const FabricCore::Variant * newValue = value.getDictValue(key.c_str());
if(newValue == NULL) {
const FabricCore::Variant * oldValue = keyIter.getValue();
value.setDictValue(key.c_str(), *oldValue);
}
}
}
try
{
mDGNode.setMemberSliceData_Variant(mMember.c_str(), slice, value);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::setVariant, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
std::string DGPortImpl::getJSON(uint32_t slice, std::string * errorOut)
{
if(mMode == Mode_IN)
{
LoggingImpl::reportError("Cannot get data on an input DGPort.", errorOut);
return "";
}
FabricCore::Variant result = getVariant(slice, errorOut);
if(result.isNull())
return "";
return result.getJSONEncoding().getStringData();
}
bool DGPortImpl::setJSON(const std::string & json, uint32_t slice, std::string * errorOut)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
try
{
FabricCore::Variant variant = FabricCore::Variant::CreateFromJSON(json);
return setVariant(variant, slice, errorOut);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::setJSON, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return false;
}
FabricCore::Variant DGPortImpl::getDefault(std::string * errorOut)
{
FabricCore::Variant result;
if(mIsObject)
return result;
DGGraphImplPtr node = getDGGraph();
if(!node)
{
LoggingImpl::reportError("DGPortImpl::getDefault, Node '"+mGraphName+"' already destroyed.");
return result;
}
try
{
result = mDGNode.getMemberDefaultData_Variant(mMember.c_str());
if(result.isNull())
result = mDGNode.getMemberSliceData_Variant(mMember.c_str(), 0);
}
catch(FabricCore::Exception e)
{
LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
return result;
}
FabricCore::RTVal DGPortImpl::getRTVal(
bool evaluate,
uint32_t slice,
std::string * errorOut
)
{
if(slice > getSliceCount())
{
LoggingImpl::reportError("Slice out of bounds.", errorOut);
return FabricCore::RTVal();
}
DGGraphImplPtr node = getDGGraph();
if(!node)
{
LoggingImpl::reportError("DGPortImpl::getRTVal, Node '"+mGraphName+"' already destroyed.");
return FabricCore::RTVal();
}
if(mMode != Mode_IN && evaluate)
if(!node->evaluate(mDGNode, errorOut))
return FabricCore::RTVal();
try
{
FabricCore::RTVal result =
mDGNode.getMemberSliceValue(mMember.c_str(), slice);
return result;
}
catch(FabricCore::Exception e)
{
LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
return FabricCore::RTVal();
}
bool DGPortImpl::setRTVal(
FabricCore::RTVal value,
uint32_t slice,
std::string * errorOut
)
{
// if(mMode == Mode_OUT)
// return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
if(slice > mDGNode.getSize())
return LoggingImpl::reportError("Slice out of bounds.", errorOut);
try
{
mDGNode.setMemberSliceValue(mMember.c_str(), slice, value);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::setRTVal, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
uint32_t DGPortImpl::getArrayCount(uint32_t slice, std::string * errorOut)
{
if(mMode == Mode_IN)
{
LoggingImpl::reportError("Cannot get data on an input DGPort.", errorOut);
return 0;
}
if(!mIsArray)
return 1;
if(slice > getSliceCount())
{
LoggingImpl::reportError("Slice out of bounds.", errorOut);
return 0;
}
DGGraphImplPtr node = getDGGraph();
if(!node)
{
LoggingImpl::reportError("DGPortImpl::getArrayCount, Node '"+mGraphName+"' already destroyed.");
return 0;
}
if(!node->evaluate(mDGNode, errorOut))
return 0;
try
{
uint32_t result = mDGNode.getMemberSliceArraySize(mMember.c_str(), slice);
return result;
}
catch(FabricCore::Exception e)
{
LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
return 0;
}
bool DGPortImpl::getArrayData(
void * buffer,
uint32_t bufferSize,
uint32_t slice,
std::string * errorOut
)
{
if(mMode == Mode_IN)
return LoggingImpl::reportError("Cannot get data on an input DGPort.", errorOut);
if(!mIsArray)
return LoggingImpl::reportError("DGPort is not an array.", errorOut);
if(!mIsShallow)
return LoggingImpl::reportError("DGPort is not shallow.", errorOut);
if(slice > getSliceCount())
return LoggingImpl::reportError("Slice out of bounds.", errorOut);
if(buffer == NULL && bufferSize != 0)
return LoggingImpl::reportError("No valid buffer / bufferSize provided.", errorOut);
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::getArrayData, Node '"+mGraphName+"' already destroyed.");
if(!node->evaluate(mDGNode, errorOut))
return false;
uint32_t count = 0;
try
{
count = mDGNode.getMemberSliceArraySize(mMember.c_str(), slice);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
uint32_t bufferCount = bufferSize / mDataSize;
if(bufferCount * mDataSize != bufferSize)
return LoggingImpl::reportError("Invalid buffer size.", errorOut);
if(bufferCount != count)
return LoggingImpl::reportError("The buffer size does not match the array size.", errorOut);
try
{
mDGNode.getMemberSliceArrayData(mMember.c_str(), slice, bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
return true;
}
bool DGPortImpl::setArrayData(
void * buffer,
uint32_t bufferSize,
uint32_t slice,
std::string * errorOut
)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
if(!mIsArray)
return LoggingImpl::reportError("DGPort is not an array.", errorOut);
if(!mIsShallow)
return LoggingImpl::reportError("DGPort is not shallow.", errorOut);
if(slice > getSliceCount())
return LoggingImpl::reportError("Slice out of bounds.", errorOut);
if(buffer == NULL && bufferSize != 0)
return LoggingImpl::reportError("No valid buffer / bufferSize provided.", errorOut);
uint32_t bufferCount = bufferSize / mDataSize;
if(bufferCount * mDataSize != bufferSize)
return LoggingImpl::reportError("Invalid buffer size.", errorOut);
try
{
if ( mDGNode.getMemberSliceArraySize( mMember.c_str(), slice ) != bufferCount )
mDGNode.setMemberSliceArraySize( mMember.c_str(), slice, bufferCount );
if(bufferCount > 0)
mDGNode.setMemberSliceArrayData(mMember.c_str(), slice, bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::setArrayData, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
bool DGPortImpl::getAllSlicesData(void * buffer, uint32_t bufferSize, std::string * errorOut)
{
if(mMode == Mode_IN)
return LoggingImpl::reportError("Cannot get data on an input DGPort.", errorOut);
if(mIsArray)
return LoggingImpl::reportError("DGPort is an array.", errorOut);
if(!mIsShallow)
return LoggingImpl::reportError("DGPort is not shallow.", errorOut);
if(buffer == NULL && bufferSize != 0)
return LoggingImpl::reportError("No valid buffer / bufferSize provided.", errorOut);
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::getAllSlicesData, Node '"+mGraphName+"' already destroyed.");
if(!node->evaluate(mDGNode, errorOut))
return false;
uint32_t sliceCount = mDGNode.getSize();
if(sliceCount * mDataSize != bufferSize)
return LoggingImpl::reportError("Buffer size does not match slice count.", errorOut);
try
{
mDGNode.getMemberAllSlicesData(mMember.c_str(), bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
return true;
}
bool DGPortImpl::setAllSlicesData(void * buffer, uint32_t bufferSize, std::string * errorOut)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
if(mIsArray)
return LoggingImpl::reportError("DGPort is an array.", errorOut);
if(!mIsShallow)
return LoggingImpl::reportError("DGPort is not shallow.", errorOut);
if(buffer == NULL && bufferSize != 0)
return LoggingImpl::reportError("No valid buffer / bufferSize provided.", errorOut);
uint32_t sliceCount = mDGNode.getSize();
uint32_t bufferCount = bufferSize / mDataSize;
if(bufferCount * mDataSize != bufferSize)
return LoggingImpl::reportError("Invalid buffer size.", errorOut);
if(bufferCount != sliceCount)
return LoggingImpl::reportError("The buffer size does not match the slice count.", errorOut);
try
{
mDGNode.setMemberAllSlicesData(mMember.c_str(), bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::setAllSlicesData, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
bool DGPortImpl::copyArrayDataFromDGPort(DGPortImplPtr other, uint32_t slice, uint32_t otherSliceHint, std::string * errorOut)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
if(!mIsArray)
return LoggingImpl::reportError("DGPort is not an array.", errorOut);
if(!mIsShallow)
return LoggingImpl::reportError("DGPort is not shallow.", errorOut);
if(!other)
return LoggingImpl::reportError("Other DGPort is not valid.", errorOut);
if(other->mMode == Mode_IN)
return LoggingImpl::reportError("Other DGPort is not an out DGPort.", errorOut);
if(!other->mIsShallow)
return LoggingImpl::reportError("Other DGPort is not shallow.", errorOut);
if(!other->mIsArray)
return LoggingImpl::reportError("Other DGPort is not an array.", errorOut);
if(other->mDataType != mDataType)
return LoggingImpl::reportError("DGPorts' data types don't match.", errorOut);
if(other->mDataSize != mDataSize)
return LoggingImpl::reportError("DGPorts' data sizes don't match.", errorOut);
if(slice > getSliceCount())
return LoggingImpl::reportError("Slice out of bounds.", errorOut);
DGGraphImplPtr otherNode = other->getDGGraph();
if(!otherNode)
return LoggingImpl::reportError("DGPortImpl::copyArrayDataFromDGPort, Node '"+other->mGraphName+"' already destroyed.");
if(!otherNode->evaluate(other->mDGNode, errorOut))
return false;
uint32_t otherSlice = otherSliceHint;
if(otherSlice == UINT_MAX)
otherSlice = slice;
if(otherSlice > other->getSliceCount())
return LoggingImpl::reportError("Other DGPort's slice out of bounds.", errorOut);
uint32_t arrayCount = 0;
try
{
arrayCount = other->mDGNode.getMemberSliceArraySize(other->mMember.c_str(), otherSlice);
}
catch(FabricCore::Exception e)
{
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
uint32_t bufferSize = mDataSize * arrayCount;
void * buffer = NULL;
if(bufferSize > 0)
{
buffer = malloc(bufferSize);
try
{
other->mDGNode.getMemberSliceArrayData(
other->mMember.c_str(), otherSlice, bufferSize, buffer
);
}
catch(FabricCore::Exception e)
{
free(buffer);
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
}
try
{
mDGNode.setMemberSliceArraySize(mMember.c_str(), slice, arrayCount);
if(bufferSize > 0)
mDGNode.setMemberSliceArrayData(mMember.c_str(), slice, bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
free(buffer);
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
free(buffer);
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::copyArrayDataFromDGPort, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
bool DGPortImpl::copyAllSlicesDataFromDGPort(DGPortImplPtr other, bool resizeTarget, std::string * errorOut)
{
if(mMode == Mode_OUT)
return LoggingImpl::reportError("Cannot set data on an output DGPort.", errorOut);
if(mIsArray)
return LoggingImpl::reportError("DGPort is an array.", errorOut);
if(!mIsShallow)
return LoggingImpl::reportError("DGPort is not shallow.", errorOut);
if(!other)
return LoggingImpl::reportError("Other DGPort is not valid.", errorOut);
if(other->mMode == Mode_IN)
return LoggingImpl::reportError("Other DGPort is not an out DGPort.", errorOut);
if(!other->mIsShallow)
return LoggingImpl::reportError("Other DGPort is not shallow.", errorOut);
if(other->mIsArray)
return LoggingImpl::reportError("Other DGPort is an array.", errorOut);
if(other->mDataType != mDataType)
return LoggingImpl::reportError("DGPorts' data types don't match.", errorOut);
if(other->mDataSize != mDataSize)
return LoggingImpl::reportError("DGPorts' data sizes don't match.", errorOut);
uint32_t sliceCount = other->mDGNode.getSize();
if(sliceCount != mDGNode.getSize())
{
if(resizeTarget)
mDGNode.setSize(sliceCount);
else
return LoggingImpl::reportError("Slice counts don't match.", errorOut);
}
if(sliceCount == 0)
return true;
DGGraphImplPtr otherNode = other->getDGGraph();
if(!otherNode)
return LoggingImpl::reportError("DGPortImpl::copyAllSlicesDataFromDGPort, Node '"+other->mGraphName+"' already destroyed.");
if(!otherNode->evaluate(other->mDGNode, errorOut))
return false;
uint32_t bufferSize = mDataSize * sliceCount;
void * buffer = malloc(bufferSize);
try
{
other->mDGNode.getMemberAllSlicesData(other->mMember.c_str(), bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
free(buffer);
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
try
{
mDGNode.setMemberAllSlicesData(mMember.c_str(), bufferSize, buffer);
}
catch(FabricCore::Exception e)
{
free(buffer);
return LoggingImpl::reportError(e.getDesc_cstr(), errorOut);
}
free(buffer);
DGGraphImplPtr node = getDGGraph();
if(!node)
return LoggingImpl::reportError("DGPortImpl::copyAllSlicesDataFromDGPort, Node '"+mGraphName+"' already destroyed.");
node->requireEvaluate();
return true;
}
void DGPortImpl::setOption(const std::string & name, const FabricCore::Variant & value)
{
std::map<std::string,FabricCore::Variant>::iterator it = mOptions.find(name);
if(it == mOptions.end())
mOptions.insert(std::pair<std::string,FabricCore::Variant>(name, value));
else
it->second = value;
}
FabricCore::Variant DGPortImpl::getOption(const std::string & name)
{
std::map<std::string,FabricCore::Variant>::iterator it = mOptions.find(name);
if(it == mOptions.end())
return FabricCore::Variant();
return it->second;
}
FabricCore::Variant DGPortImpl::getAllOptions()
{
FabricCore::Variant result;
if(mOptions.size() == 0)
return result;
result = FabricCore::Variant::CreateDict();
std::map<std::string,FabricCore::Variant>::iterator it = mOptions.begin();
for(;it!=mOptions.end();it++)
{
result.setDictValue(it->first.c_str(), it->second);
}
return result;
}
| 29.902616 | 128 | 0.696593 | yoann01 |
40387aae864c8cca2621ee11224839ee155a0ffa | 93,724 | cpp | C++ | selfdrive/locationd/models/generated/live.cpp | lth1436/nirotest | 390b8d92493ff50827eaa1987bac07101d257dd9 | [
"MIT"
] | null | null | null | selfdrive/locationd/models/generated/live.cpp | lth1436/nirotest | 390b8d92493ff50827eaa1987bac07101d257dd9 | [
"MIT"
] | null | null | null | selfdrive/locationd/models/generated/live.cpp | lth1436/nirotest | 390b8d92493ff50827eaa1987bac07101d257dd9 | [
"MIT"
] | null | null | null | extern "C" {
#include <math.h>
/******************************************************************************
* Code generated with sympy 1.4 *
* *
* See http://www.sympy.org/ for more information. *
* *
* This file is part of 'ekf' *
******************************************************************************/
void err_fun(double *nom_x, double *delta_x, double *out_1870969132376137805) {
out_1870969132376137805[0] = delta_x[0] + nom_x[0];
out_1870969132376137805[1] = delta_x[1] + nom_x[1];
out_1870969132376137805[2] = delta_x[2] + nom_x[2];
out_1870969132376137805[3] = -0.5*delta_x[3]*nom_x[4] - 0.5*delta_x[4]*nom_x[5] - 0.5*delta_x[5]*nom_x[6] + 1.0*nom_x[3];
out_1870969132376137805[4] = 0.5*delta_x[3]*nom_x[3] + 0.5*delta_x[4]*nom_x[6] - 0.5*delta_x[5]*nom_x[5] + 1.0*nom_x[4];
out_1870969132376137805[5] = -0.5*delta_x[3]*nom_x[6] + 0.5*delta_x[4]*nom_x[3] + 0.5*delta_x[5]*nom_x[4] + 1.0*nom_x[5];
out_1870969132376137805[6] = 0.5*delta_x[3]*nom_x[5] - 0.5*delta_x[4]*nom_x[4] + 0.5*delta_x[5]*nom_x[3] + 1.0*nom_x[6];
out_1870969132376137805[7] = delta_x[6] + nom_x[7];
out_1870969132376137805[8] = delta_x[7] + nom_x[8];
out_1870969132376137805[9] = delta_x[8] + nom_x[9];
out_1870969132376137805[10] = delta_x[9] + nom_x[10];
out_1870969132376137805[11] = delta_x[10] + nom_x[11];
out_1870969132376137805[12] = delta_x[11] + nom_x[12];
out_1870969132376137805[13] = delta_x[12] + nom_x[13];
out_1870969132376137805[14] = delta_x[13] + nom_x[14];
out_1870969132376137805[15] = delta_x[14] + nom_x[15];
out_1870969132376137805[16] = delta_x[15] + nom_x[16];
out_1870969132376137805[17] = delta_x[16] + nom_x[17];
out_1870969132376137805[18] = delta_x[17] + nom_x[18];
out_1870969132376137805[19] = delta_x[18] + nom_x[19];
out_1870969132376137805[20] = delta_x[19] + nom_x[20];
out_1870969132376137805[21] = delta_x[20] + nom_x[21];
out_1870969132376137805[22] = delta_x[21] + nom_x[22];
}
void inv_err_fun(double *nom_x, double *true_x, double *out_3802553487131977071) {
out_3802553487131977071[0] = -nom_x[0] + true_x[0];
out_3802553487131977071[1] = -nom_x[1] + true_x[1];
out_3802553487131977071[2] = -nom_x[2] + true_x[2];
out_3802553487131977071[3] = 2*nom_x[3]*true_x[4] - 2*nom_x[4]*true_x[3] + 2*nom_x[5]*true_x[6] - 2*nom_x[6]*true_x[5];
out_3802553487131977071[4] = 2*nom_x[3]*true_x[5] - 2*nom_x[4]*true_x[6] - 2*nom_x[5]*true_x[3] + 2*nom_x[6]*true_x[4];
out_3802553487131977071[5] = 2*nom_x[3]*true_x[6] + 2*nom_x[4]*true_x[5] - 2*nom_x[5]*true_x[4] - 2*nom_x[6]*true_x[3];
out_3802553487131977071[6] = -nom_x[7] + true_x[7];
out_3802553487131977071[7] = -nom_x[8] + true_x[8];
out_3802553487131977071[8] = -nom_x[9] + true_x[9];
out_3802553487131977071[9] = -nom_x[10] + true_x[10];
out_3802553487131977071[10] = -nom_x[11] + true_x[11];
out_3802553487131977071[11] = -nom_x[12] + true_x[12];
out_3802553487131977071[12] = -nom_x[13] + true_x[13];
out_3802553487131977071[13] = -nom_x[14] + true_x[14];
out_3802553487131977071[14] = -nom_x[15] + true_x[15];
out_3802553487131977071[15] = -nom_x[16] + true_x[16];
out_3802553487131977071[16] = -nom_x[17] + true_x[17];
out_3802553487131977071[17] = -nom_x[18] + true_x[18];
out_3802553487131977071[18] = -nom_x[19] + true_x[19];
out_3802553487131977071[19] = -nom_x[20] + true_x[20];
out_3802553487131977071[20] = -nom_x[21] + true_x[21];
out_3802553487131977071[21] = -nom_x[22] + true_x[22];
}
void H_mod_fun(double *state, double *out_3762111176001179456) {
out_3762111176001179456[0] = 1.0;
out_3762111176001179456[1] = 0.0;
out_3762111176001179456[2] = 0.0;
out_3762111176001179456[3] = 0.0;
out_3762111176001179456[4] = 0.0;
out_3762111176001179456[5] = 0.0;
out_3762111176001179456[6] = 0.0;
out_3762111176001179456[7] = 0.0;
out_3762111176001179456[8] = 0.0;
out_3762111176001179456[9] = 0.0;
out_3762111176001179456[10] = 0.0;
out_3762111176001179456[11] = 0.0;
out_3762111176001179456[12] = 0.0;
out_3762111176001179456[13] = 0.0;
out_3762111176001179456[14] = 0.0;
out_3762111176001179456[15] = 0.0;
out_3762111176001179456[16] = 0.0;
out_3762111176001179456[17] = 0.0;
out_3762111176001179456[18] = 0.0;
out_3762111176001179456[19] = 0.0;
out_3762111176001179456[20] = 0.0;
out_3762111176001179456[21] = 0.0;
out_3762111176001179456[22] = 0.0;
out_3762111176001179456[23] = 1.0;
out_3762111176001179456[24] = 0.0;
out_3762111176001179456[25] = 0.0;
out_3762111176001179456[26] = 0.0;
out_3762111176001179456[27] = 0.0;
out_3762111176001179456[28] = 0.0;
out_3762111176001179456[29] = 0.0;
out_3762111176001179456[30] = 0.0;
out_3762111176001179456[31] = 0.0;
out_3762111176001179456[32] = 0.0;
out_3762111176001179456[33] = 0.0;
out_3762111176001179456[34] = 0.0;
out_3762111176001179456[35] = 0.0;
out_3762111176001179456[36] = 0.0;
out_3762111176001179456[37] = 0.0;
out_3762111176001179456[38] = 0.0;
out_3762111176001179456[39] = 0.0;
out_3762111176001179456[40] = 0.0;
out_3762111176001179456[41] = 0.0;
out_3762111176001179456[42] = 0.0;
out_3762111176001179456[43] = 0.0;
out_3762111176001179456[44] = 0.0;
out_3762111176001179456[45] = 0.0;
out_3762111176001179456[46] = 1.0;
out_3762111176001179456[47] = 0.0;
out_3762111176001179456[48] = 0.0;
out_3762111176001179456[49] = 0.0;
out_3762111176001179456[50] = 0.0;
out_3762111176001179456[51] = 0.0;
out_3762111176001179456[52] = 0.0;
out_3762111176001179456[53] = 0.0;
out_3762111176001179456[54] = 0.0;
out_3762111176001179456[55] = 0.0;
out_3762111176001179456[56] = 0.0;
out_3762111176001179456[57] = 0.0;
out_3762111176001179456[58] = 0.0;
out_3762111176001179456[59] = 0.0;
out_3762111176001179456[60] = 0.0;
out_3762111176001179456[61] = 0.0;
out_3762111176001179456[62] = 0.0;
out_3762111176001179456[63] = 0.0;
out_3762111176001179456[64] = 0.0;
out_3762111176001179456[65] = 0.0;
out_3762111176001179456[66] = 0.0;
out_3762111176001179456[67] = 0.0;
out_3762111176001179456[68] = 0.0;
out_3762111176001179456[69] = -0.5*state[4];
out_3762111176001179456[70] = -0.5*state[5];
out_3762111176001179456[71] = -0.5*state[6];
out_3762111176001179456[72] = 0.0;
out_3762111176001179456[73] = 0.0;
out_3762111176001179456[74] = 0.0;
out_3762111176001179456[75] = 0.0;
out_3762111176001179456[76] = 0.0;
out_3762111176001179456[77] = 0.0;
out_3762111176001179456[78] = 0.0;
out_3762111176001179456[79] = 0.0;
out_3762111176001179456[80] = 0.0;
out_3762111176001179456[81] = 0.0;
out_3762111176001179456[82] = 0.0;
out_3762111176001179456[83] = 0.0;
out_3762111176001179456[84] = 0.0;
out_3762111176001179456[85] = 0.0;
out_3762111176001179456[86] = 0.0;
out_3762111176001179456[87] = 0.0;
out_3762111176001179456[88] = 0.0;
out_3762111176001179456[89] = 0.0;
out_3762111176001179456[90] = 0.0;
out_3762111176001179456[91] = 0.5*state[3];
out_3762111176001179456[92] = 0.5*state[6];
out_3762111176001179456[93] = -0.5*state[5];
out_3762111176001179456[94] = 0.0;
out_3762111176001179456[95] = 0.0;
out_3762111176001179456[96] = 0.0;
out_3762111176001179456[97] = 0.0;
out_3762111176001179456[98] = 0.0;
out_3762111176001179456[99] = 0.0;
out_3762111176001179456[100] = 0.0;
out_3762111176001179456[101] = 0.0;
out_3762111176001179456[102] = 0.0;
out_3762111176001179456[103] = 0.0;
out_3762111176001179456[104] = 0.0;
out_3762111176001179456[105] = 0.0;
out_3762111176001179456[106] = 0.0;
out_3762111176001179456[107] = 0.0;
out_3762111176001179456[108] = 0.0;
out_3762111176001179456[109] = 0.0;
out_3762111176001179456[110] = 0.0;
out_3762111176001179456[111] = 0.0;
out_3762111176001179456[112] = 0.0;
out_3762111176001179456[113] = -0.5*state[6];
out_3762111176001179456[114] = 0.5*state[3];
out_3762111176001179456[115] = 0.5*state[4];
out_3762111176001179456[116] = 0.0;
out_3762111176001179456[117] = 0.0;
out_3762111176001179456[118] = 0.0;
out_3762111176001179456[119] = 0.0;
out_3762111176001179456[120] = 0.0;
out_3762111176001179456[121] = 0.0;
out_3762111176001179456[122] = 0.0;
out_3762111176001179456[123] = 0.0;
out_3762111176001179456[124] = 0.0;
out_3762111176001179456[125] = 0.0;
out_3762111176001179456[126] = 0.0;
out_3762111176001179456[127] = 0.0;
out_3762111176001179456[128] = 0.0;
out_3762111176001179456[129] = 0.0;
out_3762111176001179456[130] = 0.0;
out_3762111176001179456[131] = 0.0;
out_3762111176001179456[132] = 0.0;
out_3762111176001179456[133] = 0.0;
out_3762111176001179456[134] = 0.0;
out_3762111176001179456[135] = 0.5*state[5];
out_3762111176001179456[136] = -0.5*state[4];
out_3762111176001179456[137] = 0.5*state[3];
out_3762111176001179456[138] = 0.0;
out_3762111176001179456[139] = 0.0;
out_3762111176001179456[140] = 0.0;
out_3762111176001179456[141] = 0.0;
out_3762111176001179456[142] = 0.0;
out_3762111176001179456[143] = 0.0;
out_3762111176001179456[144] = 0.0;
out_3762111176001179456[145] = 0.0;
out_3762111176001179456[146] = 0.0;
out_3762111176001179456[147] = 0.0;
out_3762111176001179456[148] = 0.0;
out_3762111176001179456[149] = 0.0;
out_3762111176001179456[150] = 0.0;
out_3762111176001179456[151] = 0.0;
out_3762111176001179456[152] = 0.0;
out_3762111176001179456[153] = 0.0;
out_3762111176001179456[154] = 0.0;
out_3762111176001179456[155] = 0.0;
out_3762111176001179456[156] = 0.0;
out_3762111176001179456[157] = 0.0;
out_3762111176001179456[158] = 0.0;
out_3762111176001179456[159] = 0.0;
out_3762111176001179456[160] = 1.0;
out_3762111176001179456[161] = 0.0;
out_3762111176001179456[162] = 0.0;
out_3762111176001179456[163] = 0.0;
out_3762111176001179456[164] = 0.0;
out_3762111176001179456[165] = 0.0;
out_3762111176001179456[166] = 0.0;
out_3762111176001179456[167] = 0.0;
out_3762111176001179456[168] = 0.0;
out_3762111176001179456[169] = 0.0;
out_3762111176001179456[170] = 0.0;
out_3762111176001179456[171] = 0.0;
out_3762111176001179456[172] = 0.0;
out_3762111176001179456[173] = 0.0;
out_3762111176001179456[174] = 0.0;
out_3762111176001179456[175] = 0.0;
out_3762111176001179456[176] = 0.0;
out_3762111176001179456[177] = 0.0;
out_3762111176001179456[178] = 0.0;
out_3762111176001179456[179] = 0.0;
out_3762111176001179456[180] = 0.0;
out_3762111176001179456[181] = 0.0;
out_3762111176001179456[182] = 0.0;
out_3762111176001179456[183] = 1.0;
out_3762111176001179456[184] = 0.0;
out_3762111176001179456[185] = 0.0;
out_3762111176001179456[186] = 0.0;
out_3762111176001179456[187] = 0.0;
out_3762111176001179456[188] = 0.0;
out_3762111176001179456[189] = 0.0;
out_3762111176001179456[190] = 0.0;
out_3762111176001179456[191] = 0.0;
out_3762111176001179456[192] = 0.0;
out_3762111176001179456[193] = 0.0;
out_3762111176001179456[194] = 0.0;
out_3762111176001179456[195] = 0.0;
out_3762111176001179456[196] = 0.0;
out_3762111176001179456[197] = 0.0;
out_3762111176001179456[198] = 0.0;
out_3762111176001179456[199] = 0.0;
out_3762111176001179456[200] = 0.0;
out_3762111176001179456[201] = 0.0;
out_3762111176001179456[202] = 0.0;
out_3762111176001179456[203] = 0.0;
out_3762111176001179456[204] = 0.0;
out_3762111176001179456[205] = 0.0;
out_3762111176001179456[206] = 1.0;
out_3762111176001179456[207] = 0.0;
out_3762111176001179456[208] = 0.0;
out_3762111176001179456[209] = 0.0;
out_3762111176001179456[210] = 0.0;
out_3762111176001179456[211] = 0.0;
out_3762111176001179456[212] = 0.0;
out_3762111176001179456[213] = 0.0;
out_3762111176001179456[214] = 0.0;
out_3762111176001179456[215] = 0.0;
out_3762111176001179456[216] = 0.0;
out_3762111176001179456[217] = 0.0;
out_3762111176001179456[218] = 0.0;
out_3762111176001179456[219] = 0.0;
out_3762111176001179456[220] = 0.0;
out_3762111176001179456[221] = 0.0;
out_3762111176001179456[222] = 0.0;
out_3762111176001179456[223] = 0.0;
out_3762111176001179456[224] = 0.0;
out_3762111176001179456[225] = 0.0;
out_3762111176001179456[226] = 0.0;
out_3762111176001179456[227] = 0.0;
out_3762111176001179456[228] = 0.0;
out_3762111176001179456[229] = 1.0;
out_3762111176001179456[230] = 0.0;
out_3762111176001179456[231] = 0.0;
out_3762111176001179456[232] = 0.0;
out_3762111176001179456[233] = 0.0;
out_3762111176001179456[234] = 0.0;
out_3762111176001179456[235] = 0.0;
out_3762111176001179456[236] = 0.0;
out_3762111176001179456[237] = 0.0;
out_3762111176001179456[238] = 0.0;
out_3762111176001179456[239] = 0.0;
out_3762111176001179456[240] = 0.0;
out_3762111176001179456[241] = 0.0;
out_3762111176001179456[242] = 0.0;
out_3762111176001179456[243] = 0.0;
out_3762111176001179456[244] = 0.0;
out_3762111176001179456[245] = 0.0;
out_3762111176001179456[246] = 0.0;
out_3762111176001179456[247] = 0.0;
out_3762111176001179456[248] = 0.0;
out_3762111176001179456[249] = 0.0;
out_3762111176001179456[250] = 0.0;
out_3762111176001179456[251] = 0.0;
out_3762111176001179456[252] = 1.0;
out_3762111176001179456[253] = 0.0;
out_3762111176001179456[254] = 0.0;
out_3762111176001179456[255] = 0.0;
out_3762111176001179456[256] = 0.0;
out_3762111176001179456[257] = 0.0;
out_3762111176001179456[258] = 0.0;
out_3762111176001179456[259] = 0.0;
out_3762111176001179456[260] = 0.0;
out_3762111176001179456[261] = 0.0;
out_3762111176001179456[262] = 0.0;
out_3762111176001179456[263] = 0.0;
out_3762111176001179456[264] = 0.0;
out_3762111176001179456[265] = 0.0;
out_3762111176001179456[266] = 0.0;
out_3762111176001179456[267] = 0.0;
out_3762111176001179456[268] = 0.0;
out_3762111176001179456[269] = 0.0;
out_3762111176001179456[270] = 0.0;
out_3762111176001179456[271] = 0.0;
out_3762111176001179456[272] = 0.0;
out_3762111176001179456[273] = 0.0;
out_3762111176001179456[274] = 0.0;
out_3762111176001179456[275] = 1.0;
out_3762111176001179456[276] = 0.0;
out_3762111176001179456[277] = 0.0;
out_3762111176001179456[278] = 0.0;
out_3762111176001179456[279] = 0.0;
out_3762111176001179456[280] = 0.0;
out_3762111176001179456[281] = 0.0;
out_3762111176001179456[282] = 0.0;
out_3762111176001179456[283] = 0.0;
out_3762111176001179456[284] = 0.0;
out_3762111176001179456[285] = 0.0;
out_3762111176001179456[286] = 0.0;
out_3762111176001179456[287] = 0.0;
out_3762111176001179456[288] = 0.0;
out_3762111176001179456[289] = 0.0;
out_3762111176001179456[290] = 0.0;
out_3762111176001179456[291] = 0.0;
out_3762111176001179456[292] = 0.0;
out_3762111176001179456[293] = 0.0;
out_3762111176001179456[294] = 0.0;
out_3762111176001179456[295] = 0.0;
out_3762111176001179456[296] = 0.0;
out_3762111176001179456[297] = 0.0;
out_3762111176001179456[298] = 1.0;
out_3762111176001179456[299] = 0.0;
out_3762111176001179456[300] = 0.0;
out_3762111176001179456[301] = 0.0;
out_3762111176001179456[302] = 0.0;
out_3762111176001179456[303] = 0.0;
out_3762111176001179456[304] = 0.0;
out_3762111176001179456[305] = 0.0;
out_3762111176001179456[306] = 0.0;
out_3762111176001179456[307] = 0.0;
out_3762111176001179456[308] = 0.0;
out_3762111176001179456[309] = 0.0;
out_3762111176001179456[310] = 0.0;
out_3762111176001179456[311] = 0.0;
out_3762111176001179456[312] = 0.0;
out_3762111176001179456[313] = 0.0;
out_3762111176001179456[314] = 0.0;
out_3762111176001179456[315] = 0.0;
out_3762111176001179456[316] = 0.0;
out_3762111176001179456[317] = 0.0;
out_3762111176001179456[318] = 0.0;
out_3762111176001179456[319] = 0.0;
out_3762111176001179456[320] = 0.0;
out_3762111176001179456[321] = 1.0;
out_3762111176001179456[322] = 0.0;
out_3762111176001179456[323] = 0.0;
out_3762111176001179456[324] = 0.0;
out_3762111176001179456[325] = 0.0;
out_3762111176001179456[326] = 0.0;
out_3762111176001179456[327] = 0.0;
out_3762111176001179456[328] = 0.0;
out_3762111176001179456[329] = 0.0;
out_3762111176001179456[330] = 0.0;
out_3762111176001179456[331] = 0.0;
out_3762111176001179456[332] = 0.0;
out_3762111176001179456[333] = 0.0;
out_3762111176001179456[334] = 0.0;
out_3762111176001179456[335] = 0.0;
out_3762111176001179456[336] = 0.0;
out_3762111176001179456[337] = 0.0;
out_3762111176001179456[338] = 0.0;
out_3762111176001179456[339] = 0.0;
out_3762111176001179456[340] = 0.0;
out_3762111176001179456[341] = 0.0;
out_3762111176001179456[342] = 0.0;
out_3762111176001179456[343] = 0.0;
out_3762111176001179456[344] = 1.0;
out_3762111176001179456[345] = 0.0;
out_3762111176001179456[346] = 0.0;
out_3762111176001179456[347] = 0.0;
out_3762111176001179456[348] = 0.0;
out_3762111176001179456[349] = 0.0;
out_3762111176001179456[350] = 0.0;
out_3762111176001179456[351] = 0.0;
out_3762111176001179456[352] = 0.0;
out_3762111176001179456[353] = 0.0;
out_3762111176001179456[354] = 0.0;
out_3762111176001179456[355] = 0.0;
out_3762111176001179456[356] = 0.0;
out_3762111176001179456[357] = 0.0;
out_3762111176001179456[358] = 0.0;
out_3762111176001179456[359] = 0.0;
out_3762111176001179456[360] = 0.0;
out_3762111176001179456[361] = 0.0;
out_3762111176001179456[362] = 0.0;
out_3762111176001179456[363] = 0.0;
out_3762111176001179456[364] = 0.0;
out_3762111176001179456[365] = 0.0;
out_3762111176001179456[366] = 0.0;
out_3762111176001179456[367] = 1.0;
out_3762111176001179456[368] = 0.0;
out_3762111176001179456[369] = 0.0;
out_3762111176001179456[370] = 0.0;
out_3762111176001179456[371] = 0.0;
out_3762111176001179456[372] = 0.0;
out_3762111176001179456[373] = 0.0;
out_3762111176001179456[374] = 0.0;
out_3762111176001179456[375] = 0.0;
out_3762111176001179456[376] = 0.0;
out_3762111176001179456[377] = 0.0;
out_3762111176001179456[378] = 0.0;
out_3762111176001179456[379] = 0.0;
out_3762111176001179456[380] = 0.0;
out_3762111176001179456[381] = 0.0;
out_3762111176001179456[382] = 0.0;
out_3762111176001179456[383] = 0.0;
out_3762111176001179456[384] = 0.0;
out_3762111176001179456[385] = 0.0;
out_3762111176001179456[386] = 0.0;
out_3762111176001179456[387] = 0.0;
out_3762111176001179456[388] = 0.0;
out_3762111176001179456[389] = 0.0;
out_3762111176001179456[390] = 1.0;
out_3762111176001179456[391] = 0.0;
out_3762111176001179456[392] = 0.0;
out_3762111176001179456[393] = 0.0;
out_3762111176001179456[394] = 0.0;
out_3762111176001179456[395] = 0.0;
out_3762111176001179456[396] = 0.0;
out_3762111176001179456[397] = 0.0;
out_3762111176001179456[398] = 0.0;
out_3762111176001179456[399] = 0.0;
out_3762111176001179456[400] = 0.0;
out_3762111176001179456[401] = 0.0;
out_3762111176001179456[402] = 0.0;
out_3762111176001179456[403] = 0.0;
out_3762111176001179456[404] = 0.0;
out_3762111176001179456[405] = 0.0;
out_3762111176001179456[406] = 0.0;
out_3762111176001179456[407] = 0.0;
out_3762111176001179456[408] = 0.0;
out_3762111176001179456[409] = 0.0;
out_3762111176001179456[410] = 0.0;
out_3762111176001179456[411] = 0.0;
out_3762111176001179456[412] = 0.0;
out_3762111176001179456[413] = 1.0;
out_3762111176001179456[414] = 0.0;
out_3762111176001179456[415] = 0.0;
out_3762111176001179456[416] = 0.0;
out_3762111176001179456[417] = 0.0;
out_3762111176001179456[418] = 0.0;
out_3762111176001179456[419] = 0.0;
out_3762111176001179456[420] = 0.0;
out_3762111176001179456[421] = 0.0;
out_3762111176001179456[422] = 0.0;
out_3762111176001179456[423] = 0.0;
out_3762111176001179456[424] = 0.0;
out_3762111176001179456[425] = 0.0;
out_3762111176001179456[426] = 0.0;
out_3762111176001179456[427] = 0.0;
out_3762111176001179456[428] = 0.0;
out_3762111176001179456[429] = 0.0;
out_3762111176001179456[430] = 0.0;
out_3762111176001179456[431] = 0.0;
out_3762111176001179456[432] = 0.0;
out_3762111176001179456[433] = 0.0;
out_3762111176001179456[434] = 0.0;
out_3762111176001179456[435] = 0.0;
out_3762111176001179456[436] = 1.0;
out_3762111176001179456[437] = 0.0;
out_3762111176001179456[438] = 0.0;
out_3762111176001179456[439] = 0.0;
out_3762111176001179456[440] = 0.0;
out_3762111176001179456[441] = 0.0;
out_3762111176001179456[442] = 0.0;
out_3762111176001179456[443] = 0.0;
out_3762111176001179456[444] = 0.0;
out_3762111176001179456[445] = 0.0;
out_3762111176001179456[446] = 0.0;
out_3762111176001179456[447] = 0.0;
out_3762111176001179456[448] = 0.0;
out_3762111176001179456[449] = 0.0;
out_3762111176001179456[450] = 0.0;
out_3762111176001179456[451] = 0.0;
out_3762111176001179456[452] = 0.0;
out_3762111176001179456[453] = 0.0;
out_3762111176001179456[454] = 0.0;
out_3762111176001179456[455] = 0.0;
out_3762111176001179456[456] = 0.0;
out_3762111176001179456[457] = 0.0;
out_3762111176001179456[458] = 0.0;
out_3762111176001179456[459] = 1.0;
out_3762111176001179456[460] = 0.0;
out_3762111176001179456[461] = 0.0;
out_3762111176001179456[462] = 0.0;
out_3762111176001179456[463] = 0.0;
out_3762111176001179456[464] = 0.0;
out_3762111176001179456[465] = 0.0;
out_3762111176001179456[466] = 0.0;
out_3762111176001179456[467] = 0.0;
out_3762111176001179456[468] = 0.0;
out_3762111176001179456[469] = 0.0;
out_3762111176001179456[470] = 0.0;
out_3762111176001179456[471] = 0.0;
out_3762111176001179456[472] = 0.0;
out_3762111176001179456[473] = 0.0;
out_3762111176001179456[474] = 0.0;
out_3762111176001179456[475] = 0.0;
out_3762111176001179456[476] = 0.0;
out_3762111176001179456[477] = 0.0;
out_3762111176001179456[478] = 0.0;
out_3762111176001179456[479] = 0.0;
out_3762111176001179456[480] = 0.0;
out_3762111176001179456[481] = 0.0;
out_3762111176001179456[482] = 1.0;
out_3762111176001179456[483] = 0.0;
out_3762111176001179456[484] = 0.0;
out_3762111176001179456[485] = 0.0;
out_3762111176001179456[486] = 0.0;
out_3762111176001179456[487] = 0.0;
out_3762111176001179456[488] = 0.0;
out_3762111176001179456[489] = 0.0;
out_3762111176001179456[490] = 0.0;
out_3762111176001179456[491] = 0.0;
out_3762111176001179456[492] = 0.0;
out_3762111176001179456[493] = 0.0;
out_3762111176001179456[494] = 0.0;
out_3762111176001179456[495] = 0.0;
out_3762111176001179456[496] = 0.0;
out_3762111176001179456[497] = 0.0;
out_3762111176001179456[498] = 0.0;
out_3762111176001179456[499] = 0.0;
out_3762111176001179456[500] = 0.0;
out_3762111176001179456[501] = 0.0;
out_3762111176001179456[502] = 0.0;
out_3762111176001179456[503] = 0.0;
out_3762111176001179456[504] = 0.0;
out_3762111176001179456[505] = 1.0;
}
void f_fun(double *state, double dt, double *out_2480536562585758481) {
out_2480536562585758481[0] = dt*state[7] + state[0];
out_2480536562585758481[1] = dt*state[8] + state[1];
out_2480536562585758481[2] = dt*state[9] + state[2];
out_2480536562585758481[3] = dt*(-0.5*state[4]*state[10] - 0.5*state[5]*state[11] - 0.5*state[6]*state[12]) + state[3];
out_2480536562585758481[4] = dt*(0.5*state[3]*state[10] + 0.5*state[5]*state[12] - 0.5*state[6]*state[11]) + state[4];
out_2480536562585758481[5] = dt*(0.5*state[3]*state[11] - 0.5*state[4]*state[12] + 0.5*state[6]*state[10]) + state[5];
out_2480536562585758481[6] = dt*(0.5*state[3]*state[12] + 0.5*state[4]*state[11] - 0.5*state[5]*state[10]) + state[6];
out_2480536562585758481[7] = dt*((2*state[3]*state[5] + 2*state[4]*state[6])*state[19] + (-2*state[3]*state[6] + 2*state[4]*state[5])*state[18] + (pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[17]) + state[7];
out_2480536562585758481[8] = dt*((-2*state[3]*state[4] + 2*state[5]*state[6])*state[19] + (2*state[3]*state[6] + 2*state[4]*state[5])*state[17] + (pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[18]) + state[8];
out_2480536562585758481[9] = dt*((2*state[3]*state[4] + 2*state[5]*state[6])*state[18] + (-2*state[3]*state[5] + 2*state[4]*state[6])*state[17] + (pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[19]) + state[9];
out_2480536562585758481[10] = state[10];
out_2480536562585758481[11] = state[11];
out_2480536562585758481[12] = state[12];
out_2480536562585758481[13] = state[13];
out_2480536562585758481[14] = state[14];
out_2480536562585758481[15] = state[15];
out_2480536562585758481[16] = state[16];
out_2480536562585758481[17] = state[17];
out_2480536562585758481[18] = state[18];
out_2480536562585758481[19] = state[19];
out_2480536562585758481[20] = state[20];
out_2480536562585758481[21] = state[21];
out_2480536562585758481[22] = state[22];
}
void F_fun(double *state, double dt, double *out_1425722008230317098) {
out_1425722008230317098[0] = 1;
out_1425722008230317098[1] = 0;
out_1425722008230317098[2] = 0;
out_1425722008230317098[3] = 0;
out_1425722008230317098[4] = 0;
out_1425722008230317098[5] = 0;
out_1425722008230317098[6] = dt;
out_1425722008230317098[7] = 0;
out_1425722008230317098[8] = 0;
out_1425722008230317098[9] = 0;
out_1425722008230317098[10] = 0;
out_1425722008230317098[11] = 0;
out_1425722008230317098[12] = 0;
out_1425722008230317098[13] = 0;
out_1425722008230317098[14] = 0;
out_1425722008230317098[15] = 0;
out_1425722008230317098[16] = 0;
out_1425722008230317098[17] = 0;
out_1425722008230317098[18] = 0;
out_1425722008230317098[19] = 0;
out_1425722008230317098[20] = 0;
out_1425722008230317098[21] = 0;
out_1425722008230317098[22] = 0;
out_1425722008230317098[23] = 1;
out_1425722008230317098[24] = 0;
out_1425722008230317098[25] = 0;
out_1425722008230317098[26] = 0;
out_1425722008230317098[27] = 0;
out_1425722008230317098[28] = 0;
out_1425722008230317098[29] = dt;
out_1425722008230317098[30] = 0;
out_1425722008230317098[31] = 0;
out_1425722008230317098[32] = 0;
out_1425722008230317098[33] = 0;
out_1425722008230317098[34] = 0;
out_1425722008230317098[35] = 0;
out_1425722008230317098[36] = 0;
out_1425722008230317098[37] = 0;
out_1425722008230317098[38] = 0;
out_1425722008230317098[39] = 0;
out_1425722008230317098[40] = 0;
out_1425722008230317098[41] = 0;
out_1425722008230317098[42] = 0;
out_1425722008230317098[43] = 0;
out_1425722008230317098[44] = 0;
out_1425722008230317098[45] = 0;
out_1425722008230317098[46] = 1;
out_1425722008230317098[47] = 0;
out_1425722008230317098[48] = 0;
out_1425722008230317098[49] = 0;
out_1425722008230317098[50] = 0;
out_1425722008230317098[51] = 0;
out_1425722008230317098[52] = dt;
out_1425722008230317098[53] = 0;
out_1425722008230317098[54] = 0;
out_1425722008230317098[55] = 0;
out_1425722008230317098[56] = 0;
out_1425722008230317098[57] = 0;
out_1425722008230317098[58] = 0;
out_1425722008230317098[59] = 0;
out_1425722008230317098[60] = 0;
out_1425722008230317098[61] = 0;
out_1425722008230317098[62] = 0;
out_1425722008230317098[63] = 0;
out_1425722008230317098[64] = 0;
out_1425722008230317098[65] = 0;
out_1425722008230317098[66] = 0;
out_1425722008230317098[67] = 0;
out_1425722008230317098[68] = 0;
out_1425722008230317098[69] = 1;
out_1425722008230317098[70] = dt*((2*state[3]*state[4] + 2*state[5]*state[6])*state[11] + (-2*state[3]*state[5] + 2*state[4]*state[6])*state[10] + (pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[12]);
out_1425722008230317098[71] = dt*((2*state[3]*state[4] - 2*state[5]*state[6])*state[12] + (-2*state[3]*state[6] - 2*state[4]*state[5])*state[10] + (-pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[11]);
out_1425722008230317098[72] = 0;
out_1425722008230317098[73] = 0;
out_1425722008230317098[74] = 0;
out_1425722008230317098[75] = dt*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2));
out_1425722008230317098[76] = dt*(-2*state[3]*state[6] + 2*state[4]*state[5]);
out_1425722008230317098[77] = dt*(2*state[3]*state[5] + 2*state[4]*state[6]);
out_1425722008230317098[78] = 0;
out_1425722008230317098[79] = 0;
out_1425722008230317098[80] = 0;
out_1425722008230317098[81] = 0;
out_1425722008230317098[82] = 0;
out_1425722008230317098[83] = 0;
out_1425722008230317098[84] = 0;
out_1425722008230317098[85] = 0;
out_1425722008230317098[86] = 0;
out_1425722008230317098[87] = 0;
out_1425722008230317098[88] = 0;
out_1425722008230317098[89] = 0;
out_1425722008230317098[90] = 0;
out_1425722008230317098[91] = dt*(-(2*state[3]*state[4] + 2*state[5]*state[6])*state[11] - (-2*state[3]*state[5] + 2*state[4]*state[6])*state[10] - (pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[12]);
out_1425722008230317098[92] = 1;
out_1425722008230317098[93] = dt*((2*state[3]*state[5] + 2*state[4]*state[6])*state[12] + (-2*state[3]*state[6] + 2*state[4]*state[5])*state[11] + (pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[10]);
out_1425722008230317098[94] = 0;
out_1425722008230317098[95] = 0;
out_1425722008230317098[96] = 0;
out_1425722008230317098[97] = dt*(2*state[3]*state[6] + 2*state[4]*state[5]);
out_1425722008230317098[98] = dt*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2));
out_1425722008230317098[99] = dt*(-2*state[3]*state[4] + 2*state[5]*state[6]);
out_1425722008230317098[100] = 0;
out_1425722008230317098[101] = 0;
out_1425722008230317098[102] = 0;
out_1425722008230317098[103] = 0;
out_1425722008230317098[104] = 0;
out_1425722008230317098[105] = 0;
out_1425722008230317098[106] = 0;
out_1425722008230317098[107] = 0;
out_1425722008230317098[108] = 0;
out_1425722008230317098[109] = 0;
out_1425722008230317098[110] = 0;
out_1425722008230317098[111] = 0;
out_1425722008230317098[112] = 0;
out_1425722008230317098[113] = dt*((-2*state[3]*state[4] + 2*state[5]*state[6])*state[12] + (2*state[3]*state[6] + 2*state[4]*state[5])*state[10] + (pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[11]);
out_1425722008230317098[114] = dt*((-2*state[3]*state[5] - 2*state[4]*state[6])*state[12] + (2*state[3]*state[6] - 2*state[4]*state[5])*state[11] + (-pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) + pow(state[6], 2))*state[10]);
out_1425722008230317098[115] = 1;
out_1425722008230317098[116] = 0;
out_1425722008230317098[117] = 0;
out_1425722008230317098[118] = 0;
out_1425722008230317098[119] = dt*(-2*state[3]*state[5] + 2*state[4]*state[6]);
out_1425722008230317098[120] = dt*(2*state[3]*state[4] + 2*state[5]*state[6]);
out_1425722008230317098[121] = dt*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2));
out_1425722008230317098[122] = 0;
out_1425722008230317098[123] = 0;
out_1425722008230317098[124] = 0;
out_1425722008230317098[125] = 0;
out_1425722008230317098[126] = 0;
out_1425722008230317098[127] = 0;
out_1425722008230317098[128] = 0;
out_1425722008230317098[129] = 0;
out_1425722008230317098[130] = 0;
out_1425722008230317098[131] = 0;
out_1425722008230317098[132] = 0;
out_1425722008230317098[133] = 0;
out_1425722008230317098[134] = 0;
out_1425722008230317098[135] = 0;
out_1425722008230317098[136] = dt*((2*state[3]*state[4] + 2*state[5]*state[6])*state[18] + (-2*state[3]*state[5] + 2*state[4]*state[6])*state[17] + (pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[19]);
out_1425722008230317098[137] = dt*((2*state[3]*state[4] - 2*state[5]*state[6])*state[19] + (-2*state[3]*state[6] - 2*state[4]*state[5])*state[17] + (-pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[18]);
out_1425722008230317098[138] = 1;
out_1425722008230317098[139] = 0;
out_1425722008230317098[140] = 0;
out_1425722008230317098[141] = 0;
out_1425722008230317098[142] = 0;
out_1425722008230317098[143] = 0;
out_1425722008230317098[144] = 0;
out_1425722008230317098[145] = 0;
out_1425722008230317098[146] = 0;
out_1425722008230317098[147] = 0;
out_1425722008230317098[148] = dt*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2));
out_1425722008230317098[149] = dt*(-2*state[3]*state[6] + 2*state[4]*state[5]);
out_1425722008230317098[150] = dt*(2*state[3]*state[5] + 2*state[4]*state[6]);
out_1425722008230317098[151] = 0;
out_1425722008230317098[152] = 0;
out_1425722008230317098[153] = 0;
out_1425722008230317098[154] = 0;
out_1425722008230317098[155] = 0;
out_1425722008230317098[156] = 0;
out_1425722008230317098[157] = dt*(-(2*state[3]*state[4] + 2*state[5]*state[6])*state[18] - (-2*state[3]*state[5] + 2*state[4]*state[6])*state[17] - (pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[19]);
out_1425722008230317098[158] = 0;
out_1425722008230317098[159] = dt*((2*state[3]*state[5] + 2*state[4]*state[6])*state[19] + (-2*state[3]*state[6] + 2*state[4]*state[5])*state[18] + (pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[17]);
out_1425722008230317098[160] = 0;
out_1425722008230317098[161] = 1;
out_1425722008230317098[162] = 0;
out_1425722008230317098[163] = 0;
out_1425722008230317098[164] = 0;
out_1425722008230317098[165] = 0;
out_1425722008230317098[166] = 0;
out_1425722008230317098[167] = 0;
out_1425722008230317098[168] = 0;
out_1425722008230317098[169] = 0;
out_1425722008230317098[170] = dt*(2*state[3]*state[6] + 2*state[4]*state[5]);
out_1425722008230317098[171] = dt*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2));
out_1425722008230317098[172] = dt*(-2*state[3]*state[4] + 2*state[5]*state[6]);
out_1425722008230317098[173] = 0;
out_1425722008230317098[174] = 0;
out_1425722008230317098[175] = 0;
out_1425722008230317098[176] = 0;
out_1425722008230317098[177] = 0;
out_1425722008230317098[178] = 0;
out_1425722008230317098[179] = dt*((-2*state[3]*state[4] + 2*state[5]*state[6])*state[19] + (2*state[3]*state[6] + 2*state[4]*state[5])*state[17] + (pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[18]);
out_1425722008230317098[180] = dt*((-2*state[3]*state[5] - 2*state[4]*state[6])*state[19] + (2*state[3]*state[6] - 2*state[4]*state[5])*state[18] + (-pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) + pow(state[6], 2))*state[17]);
out_1425722008230317098[181] = 0;
out_1425722008230317098[182] = 0;
out_1425722008230317098[183] = 0;
out_1425722008230317098[184] = 1;
out_1425722008230317098[185] = 0;
out_1425722008230317098[186] = 0;
out_1425722008230317098[187] = 0;
out_1425722008230317098[188] = 0;
out_1425722008230317098[189] = 0;
out_1425722008230317098[190] = 0;
out_1425722008230317098[191] = 0;
out_1425722008230317098[192] = dt*(-2*state[3]*state[5] + 2*state[4]*state[6]);
out_1425722008230317098[193] = dt*(2*state[3]*state[4] + 2*state[5]*state[6]);
out_1425722008230317098[194] = dt*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2));
out_1425722008230317098[195] = 0;
out_1425722008230317098[196] = 0;
out_1425722008230317098[197] = 0;
out_1425722008230317098[198] = 0;
out_1425722008230317098[199] = 0;
out_1425722008230317098[200] = 0;
out_1425722008230317098[201] = 0;
out_1425722008230317098[202] = 0;
out_1425722008230317098[203] = 0;
out_1425722008230317098[204] = 0;
out_1425722008230317098[205] = 0;
out_1425722008230317098[206] = 0;
out_1425722008230317098[207] = 1;
out_1425722008230317098[208] = 0;
out_1425722008230317098[209] = 0;
out_1425722008230317098[210] = 0;
out_1425722008230317098[211] = 0;
out_1425722008230317098[212] = 0;
out_1425722008230317098[213] = 0;
out_1425722008230317098[214] = 0;
out_1425722008230317098[215] = 0;
out_1425722008230317098[216] = 0;
out_1425722008230317098[217] = 0;
out_1425722008230317098[218] = 0;
out_1425722008230317098[219] = 0;
out_1425722008230317098[220] = 0;
out_1425722008230317098[221] = 0;
out_1425722008230317098[222] = 0;
out_1425722008230317098[223] = 0;
out_1425722008230317098[224] = 0;
out_1425722008230317098[225] = 0;
out_1425722008230317098[226] = 0;
out_1425722008230317098[227] = 0;
out_1425722008230317098[228] = 0;
out_1425722008230317098[229] = 0;
out_1425722008230317098[230] = 1;
out_1425722008230317098[231] = 0;
out_1425722008230317098[232] = 0;
out_1425722008230317098[233] = 0;
out_1425722008230317098[234] = 0;
out_1425722008230317098[235] = 0;
out_1425722008230317098[236] = 0;
out_1425722008230317098[237] = 0;
out_1425722008230317098[238] = 0;
out_1425722008230317098[239] = 0;
out_1425722008230317098[240] = 0;
out_1425722008230317098[241] = 0;
out_1425722008230317098[242] = 0;
out_1425722008230317098[243] = 0;
out_1425722008230317098[244] = 0;
out_1425722008230317098[245] = 0;
out_1425722008230317098[246] = 0;
out_1425722008230317098[247] = 0;
out_1425722008230317098[248] = 0;
out_1425722008230317098[249] = 0;
out_1425722008230317098[250] = 0;
out_1425722008230317098[251] = 0;
out_1425722008230317098[252] = 0;
out_1425722008230317098[253] = 1;
out_1425722008230317098[254] = 0;
out_1425722008230317098[255] = 0;
out_1425722008230317098[256] = 0;
out_1425722008230317098[257] = 0;
out_1425722008230317098[258] = 0;
out_1425722008230317098[259] = 0;
out_1425722008230317098[260] = 0;
out_1425722008230317098[261] = 0;
out_1425722008230317098[262] = 0;
out_1425722008230317098[263] = 0;
out_1425722008230317098[264] = 0;
out_1425722008230317098[265] = 0;
out_1425722008230317098[266] = 0;
out_1425722008230317098[267] = 0;
out_1425722008230317098[268] = 0;
out_1425722008230317098[269] = 0;
out_1425722008230317098[270] = 0;
out_1425722008230317098[271] = 0;
out_1425722008230317098[272] = 0;
out_1425722008230317098[273] = 0;
out_1425722008230317098[274] = 0;
out_1425722008230317098[275] = 0;
out_1425722008230317098[276] = 1;
out_1425722008230317098[277] = 0;
out_1425722008230317098[278] = 0;
out_1425722008230317098[279] = 0;
out_1425722008230317098[280] = 0;
out_1425722008230317098[281] = 0;
out_1425722008230317098[282] = 0;
out_1425722008230317098[283] = 0;
out_1425722008230317098[284] = 0;
out_1425722008230317098[285] = 0;
out_1425722008230317098[286] = 0;
out_1425722008230317098[287] = 0;
out_1425722008230317098[288] = 0;
out_1425722008230317098[289] = 0;
out_1425722008230317098[290] = 0;
out_1425722008230317098[291] = 0;
out_1425722008230317098[292] = 0;
out_1425722008230317098[293] = 0;
out_1425722008230317098[294] = 0;
out_1425722008230317098[295] = 0;
out_1425722008230317098[296] = 0;
out_1425722008230317098[297] = 0;
out_1425722008230317098[298] = 0;
out_1425722008230317098[299] = 1;
out_1425722008230317098[300] = 0;
out_1425722008230317098[301] = 0;
out_1425722008230317098[302] = 0;
out_1425722008230317098[303] = 0;
out_1425722008230317098[304] = 0;
out_1425722008230317098[305] = 0;
out_1425722008230317098[306] = 0;
out_1425722008230317098[307] = 0;
out_1425722008230317098[308] = 0;
out_1425722008230317098[309] = 0;
out_1425722008230317098[310] = 0;
out_1425722008230317098[311] = 0;
out_1425722008230317098[312] = 0;
out_1425722008230317098[313] = 0;
out_1425722008230317098[314] = 0;
out_1425722008230317098[315] = 0;
out_1425722008230317098[316] = 0;
out_1425722008230317098[317] = 0;
out_1425722008230317098[318] = 0;
out_1425722008230317098[319] = 0;
out_1425722008230317098[320] = 0;
out_1425722008230317098[321] = 0;
out_1425722008230317098[322] = 1;
out_1425722008230317098[323] = 0;
out_1425722008230317098[324] = 0;
out_1425722008230317098[325] = 0;
out_1425722008230317098[326] = 0;
out_1425722008230317098[327] = 0;
out_1425722008230317098[328] = 0;
out_1425722008230317098[329] = 0;
out_1425722008230317098[330] = 0;
out_1425722008230317098[331] = 0;
out_1425722008230317098[332] = 0;
out_1425722008230317098[333] = 0;
out_1425722008230317098[334] = 0;
out_1425722008230317098[335] = 0;
out_1425722008230317098[336] = 0;
out_1425722008230317098[337] = 0;
out_1425722008230317098[338] = 0;
out_1425722008230317098[339] = 0;
out_1425722008230317098[340] = 0;
out_1425722008230317098[341] = 0;
out_1425722008230317098[342] = 0;
out_1425722008230317098[343] = 0;
out_1425722008230317098[344] = 0;
out_1425722008230317098[345] = 1;
out_1425722008230317098[346] = 0;
out_1425722008230317098[347] = 0;
out_1425722008230317098[348] = 0;
out_1425722008230317098[349] = 0;
out_1425722008230317098[350] = 0;
out_1425722008230317098[351] = 0;
out_1425722008230317098[352] = 0;
out_1425722008230317098[353] = 0;
out_1425722008230317098[354] = 0;
out_1425722008230317098[355] = 0;
out_1425722008230317098[356] = 0;
out_1425722008230317098[357] = 0;
out_1425722008230317098[358] = 0;
out_1425722008230317098[359] = 0;
out_1425722008230317098[360] = 0;
out_1425722008230317098[361] = 0;
out_1425722008230317098[362] = 0;
out_1425722008230317098[363] = 0;
out_1425722008230317098[364] = 0;
out_1425722008230317098[365] = 0;
out_1425722008230317098[366] = 0;
out_1425722008230317098[367] = 0;
out_1425722008230317098[368] = 1;
out_1425722008230317098[369] = 0;
out_1425722008230317098[370] = 0;
out_1425722008230317098[371] = 0;
out_1425722008230317098[372] = 0;
out_1425722008230317098[373] = 0;
out_1425722008230317098[374] = 0;
out_1425722008230317098[375] = 0;
out_1425722008230317098[376] = 0;
out_1425722008230317098[377] = 0;
out_1425722008230317098[378] = 0;
out_1425722008230317098[379] = 0;
out_1425722008230317098[380] = 0;
out_1425722008230317098[381] = 0;
out_1425722008230317098[382] = 0;
out_1425722008230317098[383] = 0;
out_1425722008230317098[384] = 0;
out_1425722008230317098[385] = 0;
out_1425722008230317098[386] = 0;
out_1425722008230317098[387] = 0;
out_1425722008230317098[388] = 0;
out_1425722008230317098[389] = 0;
out_1425722008230317098[390] = 0;
out_1425722008230317098[391] = 1;
out_1425722008230317098[392] = 0;
out_1425722008230317098[393] = 0;
out_1425722008230317098[394] = 0;
out_1425722008230317098[395] = 0;
out_1425722008230317098[396] = 0;
out_1425722008230317098[397] = 0;
out_1425722008230317098[398] = 0;
out_1425722008230317098[399] = 0;
out_1425722008230317098[400] = 0;
out_1425722008230317098[401] = 0;
out_1425722008230317098[402] = 0;
out_1425722008230317098[403] = 0;
out_1425722008230317098[404] = 0;
out_1425722008230317098[405] = 0;
out_1425722008230317098[406] = 0;
out_1425722008230317098[407] = 0;
out_1425722008230317098[408] = 0;
out_1425722008230317098[409] = 0;
out_1425722008230317098[410] = 0;
out_1425722008230317098[411] = 0;
out_1425722008230317098[412] = 0;
out_1425722008230317098[413] = 0;
out_1425722008230317098[414] = 1;
out_1425722008230317098[415] = 0;
out_1425722008230317098[416] = 0;
out_1425722008230317098[417] = 0;
out_1425722008230317098[418] = 0;
out_1425722008230317098[419] = 0;
out_1425722008230317098[420] = 0;
out_1425722008230317098[421] = 0;
out_1425722008230317098[422] = 0;
out_1425722008230317098[423] = 0;
out_1425722008230317098[424] = 0;
out_1425722008230317098[425] = 0;
out_1425722008230317098[426] = 0;
out_1425722008230317098[427] = 0;
out_1425722008230317098[428] = 0;
out_1425722008230317098[429] = 0;
out_1425722008230317098[430] = 0;
out_1425722008230317098[431] = 0;
out_1425722008230317098[432] = 0;
out_1425722008230317098[433] = 0;
out_1425722008230317098[434] = 0;
out_1425722008230317098[435] = 0;
out_1425722008230317098[436] = 0;
out_1425722008230317098[437] = 1;
out_1425722008230317098[438] = 0;
out_1425722008230317098[439] = 0;
out_1425722008230317098[440] = 0;
out_1425722008230317098[441] = 0;
out_1425722008230317098[442] = 0;
out_1425722008230317098[443] = 0;
out_1425722008230317098[444] = 0;
out_1425722008230317098[445] = 0;
out_1425722008230317098[446] = 0;
out_1425722008230317098[447] = 0;
out_1425722008230317098[448] = 0;
out_1425722008230317098[449] = 0;
out_1425722008230317098[450] = 0;
out_1425722008230317098[451] = 0;
out_1425722008230317098[452] = 0;
out_1425722008230317098[453] = 0;
out_1425722008230317098[454] = 0;
out_1425722008230317098[455] = 0;
out_1425722008230317098[456] = 0;
out_1425722008230317098[457] = 0;
out_1425722008230317098[458] = 0;
out_1425722008230317098[459] = 0;
out_1425722008230317098[460] = 1;
out_1425722008230317098[461] = 0;
out_1425722008230317098[462] = 0;
out_1425722008230317098[463] = 0;
out_1425722008230317098[464] = 0;
out_1425722008230317098[465] = 0;
out_1425722008230317098[466] = 0;
out_1425722008230317098[467] = 0;
out_1425722008230317098[468] = 0;
out_1425722008230317098[469] = 0;
out_1425722008230317098[470] = 0;
out_1425722008230317098[471] = 0;
out_1425722008230317098[472] = 0;
out_1425722008230317098[473] = 0;
out_1425722008230317098[474] = 0;
out_1425722008230317098[475] = 0;
out_1425722008230317098[476] = 0;
out_1425722008230317098[477] = 0;
out_1425722008230317098[478] = 0;
out_1425722008230317098[479] = 0;
out_1425722008230317098[480] = 0;
out_1425722008230317098[481] = 0;
out_1425722008230317098[482] = 0;
out_1425722008230317098[483] = 1;
}
void h_3(double *state, double *unused, double *out_580480245261766277) {
out_580480245261766277[0] = sqrt(pow(state[7], 2) + pow(state[8], 2) + pow(state[9], 2) + 9.9999999999999995e-7)*state[16];
}
void H_3(double *state, double *unused, double *out_8039239072597041883) {
out_8039239072597041883[0] = 0;
out_8039239072597041883[1] = 0;
out_8039239072597041883[2] = 0;
out_8039239072597041883[3] = 0;
out_8039239072597041883[4] = 0;
out_8039239072597041883[5] = 0;
out_8039239072597041883[6] = 0;
out_8039239072597041883[7] = state[7]*state[16]/sqrt(pow(state[7], 2) + pow(state[8], 2) + pow(state[9], 2) + 9.9999999999999995e-7);
out_8039239072597041883[8] = state[8]*state[16]/sqrt(pow(state[7], 2) + pow(state[8], 2) + pow(state[9], 2) + 9.9999999999999995e-7);
out_8039239072597041883[9] = state[9]*state[16]/sqrt(pow(state[7], 2) + pow(state[8], 2) + pow(state[9], 2) + 9.9999999999999995e-7);
out_8039239072597041883[10] = 0;
out_8039239072597041883[11] = 0;
out_8039239072597041883[12] = 0;
out_8039239072597041883[13] = 0;
out_8039239072597041883[14] = 0;
out_8039239072597041883[15] = 0;
out_8039239072597041883[16] = sqrt(pow(state[7], 2) + pow(state[8], 2) + pow(state[9], 2) + 9.9999999999999995e-7);
out_8039239072597041883[17] = 0;
out_8039239072597041883[18] = 0;
out_8039239072597041883[19] = 0;
out_8039239072597041883[20] = 0;
out_8039239072597041883[21] = 0;
out_8039239072597041883[22] = 0;
}
void h_4(double *state, double *unused, double *out_4245608367930427789) {
out_4245608367930427789[0] = state[10] + state[13];
out_4245608367930427789[1] = state[11] + state[14];
out_4245608367930427789[2] = state[12] + state[15];
}
void H_4(double *state, double *unused, double *out_7691622073353942749) {
out_7691622073353942749[0] = 0;
out_7691622073353942749[1] = 0;
out_7691622073353942749[2] = 0;
out_7691622073353942749[3] = 0;
out_7691622073353942749[4] = 0;
out_7691622073353942749[5] = 0;
out_7691622073353942749[6] = 0;
out_7691622073353942749[7] = 0;
out_7691622073353942749[8] = 0;
out_7691622073353942749[9] = 0;
out_7691622073353942749[10] = 1;
out_7691622073353942749[11] = 0;
out_7691622073353942749[12] = 0;
out_7691622073353942749[13] = 1;
out_7691622073353942749[14] = 0;
out_7691622073353942749[15] = 0;
out_7691622073353942749[16] = 0;
out_7691622073353942749[17] = 0;
out_7691622073353942749[18] = 0;
out_7691622073353942749[19] = 0;
out_7691622073353942749[20] = 0;
out_7691622073353942749[21] = 0;
out_7691622073353942749[22] = 0;
out_7691622073353942749[23] = 0;
out_7691622073353942749[24] = 0;
out_7691622073353942749[25] = 0;
out_7691622073353942749[26] = 0;
out_7691622073353942749[27] = 0;
out_7691622073353942749[28] = 0;
out_7691622073353942749[29] = 0;
out_7691622073353942749[30] = 0;
out_7691622073353942749[31] = 0;
out_7691622073353942749[32] = 0;
out_7691622073353942749[33] = 0;
out_7691622073353942749[34] = 1;
out_7691622073353942749[35] = 0;
out_7691622073353942749[36] = 0;
out_7691622073353942749[37] = 1;
out_7691622073353942749[38] = 0;
out_7691622073353942749[39] = 0;
out_7691622073353942749[40] = 0;
out_7691622073353942749[41] = 0;
out_7691622073353942749[42] = 0;
out_7691622073353942749[43] = 0;
out_7691622073353942749[44] = 0;
out_7691622073353942749[45] = 0;
out_7691622073353942749[46] = 0;
out_7691622073353942749[47] = 0;
out_7691622073353942749[48] = 0;
out_7691622073353942749[49] = 0;
out_7691622073353942749[50] = 0;
out_7691622073353942749[51] = 0;
out_7691622073353942749[52] = 0;
out_7691622073353942749[53] = 0;
out_7691622073353942749[54] = 0;
out_7691622073353942749[55] = 0;
out_7691622073353942749[56] = 0;
out_7691622073353942749[57] = 0;
out_7691622073353942749[58] = 1;
out_7691622073353942749[59] = 0;
out_7691622073353942749[60] = 0;
out_7691622073353942749[61] = 1;
out_7691622073353942749[62] = 0;
out_7691622073353942749[63] = 0;
out_7691622073353942749[64] = 0;
out_7691622073353942749[65] = 0;
out_7691622073353942749[66] = 0;
out_7691622073353942749[67] = 0;
out_7691622073353942749[68] = 0;
}
void h_9(double *state, double *unused, double *out_6350337263133992527) {
out_6350337263133992527[0] = state[10];
out_6350337263133992527[1] = state[11];
out_6350337263133992527[2] = state[12];
}
void H_9(double *state, double *unused, double *out_2203357074039413582) {
out_2203357074039413582[0] = 0;
out_2203357074039413582[1] = 0;
out_2203357074039413582[2] = 0;
out_2203357074039413582[3] = 0;
out_2203357074039413582[4] = 0;
out_2203357074039413582[5] = 0;
out_2203357074039413582[6] = 0;
out_2203357074039413582[7] = 0;
out_2203357074039413582[8] = 0;
out_2203357074039413582[9] = 0;
out_2203357074039413582[10] = 1;
out_2203357074039413582[11] = 0;
out_2203357074039413582[12] = 0;
out_2203357074039413582[13] = 0;
out_2203357074039413582[14] = 0;
out_2203357074039413582[15] = 0;
out_2203357074039413582[16] = 0;
out_2203357074039413582[17] = 0;
out_2203357074039413582[18] = 0;
out_2203357074039413582[19] = 0;
out_2203357074039413582[20] = 0;
out_2203357074039413582[21] = 0;
out_2203357074039413582[22] = 0;
out_2203357074039413582[23] = 0;
out_2203357074039413582[24] = 0;
out_2203357074039413582[25] = 0;
out_2203357074039413582[26] = 0;
out_2203357074039413582[27] = 0;
out_2203357074039413582[28] = 0;
out_2203357074039413582[29] = 0;
out_2203357074039413582[30] = 0;
out_2203357074039413582[31] = 0;
out_2203357074039413582[32] = 0;
out_2203357074039413582[33] = 0;
out_2203357074039413582[34] = 1;
out_2203357074039413582[35] = 0;
out_2203357074039413582[36] = 0;
out_2203357074039413582[37] = 0;
out_2203357074039413582[38] = 0;
out_2203357074039413582[39] = 0;
out_2203357074039413582[40] = 0;
out_2203357074039413582[41] = 0;
out_2203357074039413582[42] = 0;
out_2203357074039413582[43] = 0;
out_2203357074039413582[44] = 0;
out_2203357074039413582[45] = 0;
out_2203357074039413582[46] = 0;
out_2203357074039413582[47] = 0;
out_2203357074039413582[48] = 0;
out_2203357074039413582[49] = 0;
out_2203357074039413582[50] = 0;
out_2203357074039413582[51] = 0;
out_2203357074039413582[52] = 0;
out_2203357074039413582[53] = 0;
out_2203357074039413582[54] = 0;
out_2203357074039413582[55] = 0;
out_2203357074039413582[56] = 0;
out_2203357074039413582[57] = 0;
out_2203357074039413582[58] = 1;
out_2203357074039413582[59] = 0;
out_2203357074039413582[60] = 0;
out_2203357074039413582[61] = 0;
out_2203357074039413582[62] = 0;
out_2203357074039413582[63] = 0;
out_2203357074039413582[64] = 0;
out_2203357074039413582[65] = 0;
out_2203357074039413582[66] = 0;
out_2203357074039413582[67] = 0;
out_2203357074039413582[68] = 0;
}
void h_10(double *state, double *unused, double *out_5883173185422846693) {
out_5883173185422846693[0] = 398600500000000.0*(-2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2] + 398600500000000.0*(2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1] + 398600500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[0] + state[17];
out_5883173185422846693[1] = 398600500000000.0*(2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2] + 398600500000000.0*(-2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0] + 398600500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[1] + state[18];
out_5883173185422846693[2] = 398600500000000.0*(-2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1] + 398600500000000.0*(2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0] + 398600500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[2] + state[19];
}
void H_10(double *state, double *unused, double *out_6275558625866197697) {
out_6275558625866197697[0] = -1195801500000000.0*(-2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[2] - 1195801500000000.0*(2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[1] - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*pow(state[0], 2) + 398600500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2));
out_6275558625866197697[1] = -1195801500000000.0*(-2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[1]*state[2] - 1195801500000000.0*(2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*pow(state[1], 2) + 398600500000000.0*(2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5) - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[0]*state[1];
out_6275558625866197697[2] = -1195801500000000.0*(-2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*pow(state[2], 2) + 398600500000000.0*(-2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5) - 1195801500000000.0*(2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[1]*state[2] - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[0]*state[2];
out_6275558625866197697[3] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[3] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[6] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[5];
out_6275558625866197697[4] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[4] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[5] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[6];
out_6275558625866197697[5] = -797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[5] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[4] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[3];
out_6275558625866197697[6] = -797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[6] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[3] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[4];
out_6275558625866197697[7] = 0;
out_6275558625866197697[8] = 0;
out_6275558625866197697[9] = 0;
out_6275558625866197697[10] = 0;
out_6275558625866197697[11] = 0;
out_6275558625866197697[12] = 0;
out_6275558625866197697[13] = 0;
out_6275558625866197697[14] = 0;
out_6275558625866197697[15] = 0;
out_6275558625866197697[16] = 0;
out_6275558625866197697[17] = 1;
out_6275558625866197697[18] = 0;
out_6275558625866197697[19] = 0;
out_6275558625866197697[20] = 0;
out_6275558625866197697[21] = 0;
out_6275558625866197697[22] = 0;
out_6275558625866197697[23] = -1195801500000000.0*(2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[2] - 1195801500000000.0*(-2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*pow(state[0], 2) + 398600500000000.0*(-2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5) - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[0]*state[1];
out_6275558625866197697[24] = -1195801500000000.0*(2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[1]*state[2] - 1195801500000000.0*(-2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[1] - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*pow(state[1], 2) + 398600500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2));
out_6275558625866197697[25] = -1195801500000000.0*(2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*pow(state[2], 2) + 398600500000000.0*(2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5) - 1195801500000000.0*(-2*state[3]*state[6] + 2*state[4]*state[5])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[2] - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[1]*state[2];
out_6275558625866197697[26] = -797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[6] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[3] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[4];
out_6275558625866197697[27] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[5] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[4] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[3];
out_6275558625866197697[28] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[4] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[5] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[6];
out_6275558625866197697[29] = -797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[3] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[6] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[5];
out_6275558625866197697[30] = 0;
out_6275558625866197697[31] = 0;
out_6275558625866197697[32] = 0;
out_6275558625866197697[33] = 0;
out_6275558625866197697[34] = 0;
out_6275558625866197697[35] = 0;
out_6275558625866197697[36] = 0;
out_6275558625866197697[37] = 0;
out_6275558625866197697[38] = 0;
out_6275558625866197697[39] = 0;
out_6275558625866197697[40] = 0;
out_6275558625866197697[41] = 1;
out_6275558625866197697[42] = 0;
out_6275558625866197697[43] = 0;
out_6275558625866197697[44] = 0;
out_6275558625866197697[45] = 0;
out_6275558625866197697[46] = -1195801500000000.0*(-2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[1] - 1195801500000000.0*(2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*pow(state[0], 2) + 398600500000000.0*(2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5) - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[0]*state[2];
out_6275558625866197697[47] = -1195801500000000.0*(-2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*pow(state[1], 2) + 398600500000000.0*(-2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5) - 1195801500000000.0*(2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[1] - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[1]*state[2];
out_6275558625866197697[48] = -1195801500000000.0*(-2*state[3]*state[4] + 2*state[5]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[1]*state[2] - 1195801500000000.0*(2*state[3]*state[5] + 2*state[4]*state[6])*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*state[0]*state[2] - 1195801500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -2.5)*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*pow(state[2], 2) + 398600500000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*(pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2));
out_6275558625866197697[49] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[5] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[4] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[3];
out_6275558625866197697[50] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[6] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[3] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[4];
out_6275558625866197697[51] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[3] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[6] - 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[5];
out_6275558625866197697[52] = 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[0]*state[4] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[1]*state[5] + 797201000000000.0*pow(pow(state[0], 2) + pow(state[1], 2) + pow(state[2], 2), -1.5)*state[2]*state[6];
out_6275558625866197697[53] = 0;
out_6275558625866197697[54] = 0;
out_6275558625866197697[55] = 0;
out_6275558625866197697[56] = 0;
out_6275558625866197697[57] = 0;
out_6275558625866197697[58] = 0;
out_6275558625866197697[59] = 0;
out_6275558625866197697[60] = 0;
out_6275558625866197697[61] = 0;
out_6275558625866197697[62] = 0;
out_6275558625866197697[63] = 0;
out_6275558625866197697[64] = 0;
out_6275558625866197697[65] = 1;
out_6275558625866197697[66] = 0;
out_6275558625866197697[67] = 0;
out_6275558625866197697[68] = 0;
}
void h_12(double *state, double *unused, double *out_1029741073182827027) {
out_1029741073182827027[0] = state[0];
out_1029741073182827027[1] = state[1];
out_1029741073182827027[2] = state[2];
}
void H_12(double *state, double *unused, double *out_3005095031555557250) {
out_3005095031555557250[0] = 1;
out_3005095031555557250[1] = 0;
out_3005095031555557250[2] = 0;
out_3005095031555557250[3] = 0;
out_3005095031555557250[4] = 0;
out_3005095031555557250[5] = 0;
out_3005095031555557250[6] = 0;
out_3005095031555557250[7] = 0;
out_3005095031555557250[8] = 0;
out_3005095031555557250[9] = 0;
out_3005095031555557250[10] = 0;
out_3005095031555557250[11] = 0;
out_3005095031555557250[12] = 0;
out_3005095031555557250[13] = 0;
out_3005095031555557250[14] = 0;
out_3005095031555557250[15] = 0;
out_3005095031555557250[16] = 0;
out_3005095031555557250[17] = 0;
out_3005095031555557250[18] = 0;
out_3005095031555557250[19] = 0;
out_3005095031555557250[20] = 0;
out_3005095031555557250[21] = 0;
out_3005095031555557250[22] = 0;
out_3005095031555557250[23] = 0;
out_3005095031555557250[24] = 1;
out_3005095031555557250[25] = 0;
out_3005095031555557250[26] = 0;
out_3005095031555557250[27] = 0;
out_3005095031555557250[28] = 0;
out_3005095031555557250[29] = 0;
out_3005095031555557250[30] = 0;
out_3005095031555557250[31] = 0;
out_3005095031555557250[32] = 0;
out_3005095031555557250[33] = 0;
out_3005095031555557250[34] = 0;
out_3005095031555557250[35] = 0;
out_3005095031555557250[36] = 0;
out_3005095031555557250[37] = 0;
out_3005095031555557250[38] = 0;
out_3005095031555557250[39] = 0;
out_3005095031555557250[40] = 0;
out_3005095031555557250[41] = 0;
out_3005095031555557250[42] = 0;
out_3005095031555557250[43] = 0;
out_3005095031555557250[44] = 0;
out_3005095031555557250[45] = 0;
out_3005095031555557250[46] = 0;
out_3005095031555557250[47] = 0;
out_3005095031555557250[48] = 1;
out_3005095031555557250[49] = 0;
out_3005095031555557250[50] = 0;
out_3005095031555557250[51] = 0;
out_3005095031555557250[52] = 0;
out_3005095031555557250[53] = 0;
out_3005095031555557250[54] = 0;
out_3005095031555557250[55] = 0;
out_3005095031555557250[56] = 0;
out_3005095031555557250[57] = 0;
out_3005095031555557250[58] = 0;
out_3005095031555557250[59] = 0;
out_3005095031555557250[60] = 0;
out_3005095031555557250[61] = 0;
out_3005095031555557250[62] = 0;
out_3005095031555557250[63] = 0;
out_3005095031555557250[64] = 0;
out_3005095031555557250[65] = 0;
out_3005095031555557250[66] = 0;
out_3005095031555557250[67] = 0;
out_3005095031555557250[68] = 0;
}
void h_31(double *state, double *unused, double *out_6461370520649494816) {
out_6461370520649494816[0] = state[7];
out_6461370520649494816[1] = state[8];
out_6461370520649494816[2] = state[9];
}
void H_31(double *state, double *unused, double *out_5474853234853266326) {
out_5474853234853266326[0] = 0;
out_5474853234853266326[1] = 0;
out_5474853234853266326[2] = 0;
out_5474853234853266326[3] = 0;
out_5474853234853266326[4] = 0;
out_5474853234853266326[5] = 0;
out_5474853234853266326[6] = 0;
out_5474853234853266326[7] = 1;
out_5474853234853266326[8] = 0;
out_5474853234853266326[9] = 0;
out_5474853234853266326[10] = 0;
out_5474853234853266326[11] = 0;
out_5474853234853266326[12] = 0;
out_5474853234853266326[13] = 0;
out_5474853234853266326[14] = 0;
out_5474853234853266326[15] = 0;
out_5474853234853266326[16] = 0;
out_5474853234853266326[17] = 0;
out_5474853234853266326[18] = 0;
out_5474853234853266326[19] = 0;
out_5474853234853266326[20] = 0;
out_5474853234853266326[21] = 0;
out_5474853234853266326[22] = 0;
out_5474853234853266326[23] = 0;
out_5474853234853266326[24] = 0;
out_5474853234853266326[25] = 0;
out_5474853234853266326[26] = 0;
out_5474853234853266326[27] = 0;
out_5474853234853266326[28] = 0;
out_5474853234853266326[29] = 0;
out_5474853234853266326[30] = 0;
out_5474853234853266326[31] = 1;
out_5474853234853266326[32] = 0;
out_5474853234853266326[33] = 0;
out_5474853234853266326[34] = 0;
out_5474853234853266326[35] = 0;
out_5474853234853266326[36] = 0;
out_5474853234853266326[37] = 0;
out_5474853234853266326[38] = 0;
out_5474853234853266326[39] = 0;
out_5474853234853266326[40] = 0;
out_5474853234853266326[41] = 0;
out_5474853234853266326[42] = 0;
out_5474853234853266326[43] = 0;
out_5474853234853266326[44] = 0;
out_5474853234853266326[45] = 0;
out_5474853234853266326[46] = 0;
out_5474853234853266326[47] = 0;
out_5474853234853266326[48] = 0;
out_5474853234853266326[49] = 0;
out_5474853234853266326[50] = 0;
out_5474853234853266326[51] = 0;
out_5474853234853266326[52] = 0;
out_5474853234853266326[53] = 0;
out_5474853234853266326[54] = 0;
out_5474853234853266326[55] = 1;
out_5474853234853266326[56] = 0;
out_5474853234853266326[57] = 0;
out_5474853234853266326[58] = 0;
out_5474853234853266326[59] = 0;
out_5474853234853266326[60] = 0;
out_5474853234853266326[61] = 0;
out_5474853234853266326[62] = 0;
out_5474853234853266326[63] = 0;
out_5474853234853266326[64] = 0;
out_5474853234853266326[65] = 0;
out_5474853234853266326[66] = 0;
out_5474853234853266326[67] = 0;
out_5474853234853266326[68] = 0;
}
void h_32(double *state, double *unused, double *out_2101340024716927954) {
out_2101340024716927954[0] = state[3];
out_2101340024716927954[1] = state[4];
out_2101340024716927954[2] = state[5];
out_2101340024716927954[3] = state[6];
}
void H_32(double *state, double *unused, double *out_4491552036411005924) {
out_4491552036411005924[0] = 0;
out_4491552036411005924[1] = 0;
out_4491552036411005924[2] = 0;
out_4491552036411005924[3] = 1;
out_4491552036411005924[4] = 0;
out_4491552036411005924[5] = 0;
out_4491552036411005924[6] = 0;
out_4491552036411005924[7] = 0;
out_4491552036411005924[8] = 0;
out_4491552036411005924[9] = 0;
out_4491552036411005924[10] = 0;
out_4491552036411005924[11] = 0;
out_4491552036411005924[12] = 0;
out_4491552036411005924[13] = 0;
out_4491552036411005924[14] = 0;
out_4491552036411005924[15] = 0;
out_4491552036411005924[16] = 0;
out_4491552036411005924[17] = 0;
out_4491552036411005924[18] = 0;
out_4491552036411005924[19] = 0;
out_4491552036411005924[20] = 0;
out_4491552036411005924[21] = 0;
out_4491552036411005924[22] = 0;
out_4491552036411005924[23] = 0;
out_4491552036411005924[24] = 0;
out_4491552036411005924[25] = 0;
out_4491552036411005924[26] = 0;
out_4491552036411005924[27] = 1;
out_4491552036411005924[28] = 0;
out_4491552036411005924[29] = 0;
out_4491552036411005924[30] = 0;
out_4491552036411005924[31] = 0;
out_4491552036411005924[32] = 0;
out_4491552036411005924[33] = 0;
out_4491552036411005924[34] = 0;
out_4491552036411005924[35] = 0;
out_4491552036411005924[36] = 0;
out_4491552036411005924[37] = 0;
out_4491552036411005924[38] = 0;
out_4491552036411005924[39] = 0;
out_4491552036411005924[40] = 0;
out_4491552036411005924[41] = 0;
out_4491552036411005924[42] = 0;
out_4491552036411005924[43] = 0;
out_4491552036411005924[44] = 0;
out_4491552036411005924[45] = 0;
out_4491552036411005924[46] = 0;
out_4491552036411005924[47] = 0;
out_4491552036411005924[48] = 0;
out_4491552036411005924[49] = 0;
out_4491552036411005924[50] = 0;
out_4491552036411005924[51] = 1;
out_4491552036411005924[52] = 0;
out_4491552036411005924[53] = 0;
out_4491552036411005924[54] = 0;
out_4491552036411005924[55] = 0;
out_4491552036411005924[56] = 0;
out_4491552036411005924[57] = 0;
out_4491552036411005924[58] = 0;
out_4491552036411005924[59] = 0;
out_4491552036411005924[60] = 0;
out_4491552036411005924[61] = 0;
out_4491552036411005924[62] = 0;
out_4491552036411005924[63] = 0;
out_4491552036411005924[64] = 0;
out_4491552036411005924[65] = 0;
out_4491552036411005924[66] = 0;
out_4491552036411005924[67] = 0;
out_4491552036411005924[68] = 0;
out_4491552036411005924[69] = 0;
out_4491552036411005924[70] = 0;
out_4491552036411005924[71] = 0;
out_4491552036411005924[72] = 0;
out_4491552036411005924[73] = 0;
out_4491552036411005924[74] = 0;
out_4491552036411005924[75] = 1;
out_4491552036411005924[76] = 0;
out_4491552036411005924[77] = 0;
out_4491552036411005924[78] = 0;
out_4491552036411005924[79] = 0;
out_4491552036411005924[80] = 0;
out_4491552036411005924[81] = 0;
out_4491552036411005924[82] = 0;
out_4491552036411005924[83] = 0;
out_4491552036411005924[84] = 0;
out_4491552036411005924[85] = 0;
out_4491552036411005924[86] = 0;
out_4491552036411005924[87] = 0;
out_4491552036411005924[88] = 0;
out_4491552036411005924[89] = 0;
out_4491552036411005924[90] = 0;
out_4491552036411005924[91] = 0;
}
void h_13(double *state, double *unused, double *out_2424738802151988478) {
out_2424738802151988478[0] = (-2*state[3]*state[5] + 2*state[4]*state[6])*state[9] + (2*state[3]*state[6] + 2*state[4]*state[5])*state[8] + (pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2))*state[7];
out_2424738802151988478[1] = (2*state[3]*state[4] + 2*state[5]*state[6])*state[9] + (-2*state[3]*state[6] + 2*state[4]*state[5])*state[7] + (pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2))*state[8];
out_2424738802151988478[2] = (-2*state[3]*state[4] + 2*state[5]*state[6])*state[8] + (2*state[3]*state[5] + 2*state[4]*state[6])*state[7] + (pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2))*state[9];
}
void H_13(double *state, double *unused, double *out_8550083838302739916) {
out_8550083838302739916[0] = 0;
out_8550083838302739916[1] = 0;
out_8550083838302739916[2] = 0;
out_8550083838302739916[3] = 2*state[3]*state[7] - 2*state[5]*state[9] + 2*state[6]*state[8];
out_8550083838302739916[4] = 2*state[4]*state[7] + 2*state[5]*state[8] + 2*state[6]*state[9];
out_8550083838302739916[5] = -2*state[3]*state[9] + 2*state[4]*state[8] - 2*state[5]*state[7];
out_8550083838302739916[6] = 2*state[3]*state[8] + 2*state[4]*state[9] - 2*state[6]*state[7];
out_8550083838302739916[7] = pow(state[3], 2) + pow(state[4], 2) - pow(state[5], 2) - pow(state[6], 2);
out_8550083838302739916[8] = 2*state[3]*state[6] + 2*state[4]*state[5];
out_8550083838302739916[9] = -2*state[3]*state[5] + 2*state[4]*state[6];
out_8550083838302739916[10] = 0;
out_8550083838302739916[11] = 0;
out_8550083838302739916[12] = 0;
out_8550083838302739916[13] = 0;
out_8550083838302739916[14] = 0;
out_8550083838302739916[15] = 0;
out_8550083838302739916[16] = 0;
out_8550083838302739916[17] = 0;
out_8550083838302739916[18] = 0;
out_8550083838302739916[19] = 0;
out_8550083838302739916[20] = 0;
out_8550083838302739916[21] = 0;
out_8550083838302739916[22] = 0;
out_8550083838302739916[23] = 0;
out_8550083838302739916[24] = 0;
out_8550083838302739916[25] = 0;
out_8550083838302739916[26] = 2*state[3]*state[8] + 2*state[4]*state[9] - 2*state[6]*state[7];
out_8550083838302739916[27] = 2*state[3]*state[9] - 2*state[4]*state[8] + 2*state[5]*state[7];
out_8550083838302739916[28] = 2*state[4]*state[7] + 2*state[5]*state[8] + 2*state[6]*state[9];
out_8550083838302739916[29] = -2*state[3]*state[7] + 2*state[5]*state[9] - 2*state[6]*state[8];
out_8550083838302739916[30] = -2*state[3]*state[6] + 2*state[4]*state[5];
out_8550083838302739916[31] = pow(state[3], 2) - pow(state[4], 2) + pow(state[5], 2) - pow(state[6], 2);
out_8550083838302739916[32] = 2*state[3]*state[4] + 2*state[5]*state[6];
out_8550083838302739916[33] = 0;
out_8550083838302739916[34] = 0;
out_8550083838302739916[35] = 0;
out_8550083838302739916[36] = 0;
out_8550083838302739916[37] = 0;
out_8550083838302739916[38] = 0;
out_8550083838302739916[39] = 0;
out_8550083838302739916[40] = 0;
out_8550083838302739916[41] = 0;
out_8550083838302739916[42] = 0;
out_8550083838302739916[43] = 0;
out_8550083838302739916[44] = 0;
out_8550083838302739916[45] = 0;
out_8550083838302739916[46] = 0;
out_8550083838302739916[47] = 0;
out_8550083838302739916[48] = 0;
out_8550083838302739916[49] = 2*state[3]*state[9] - 2*state[4]*state[8] + 2*state[5]*state[7];
out_8550083838302739916[50] = -2*state[3]*state[8] - 2*state[4]*state[9] + 2*state[6]*state[7];
out_8550083838302739916[51] = 2*state[3]*state[7] - 2*state[5]*state[9] + 2*state[6]*state[8];
out_8550083838302739916[52] = 2*state[4]*state[7] + 2*state[5]*state[8] + 2*state[6]*state[9];
out_8550083838302739916[53] = 2*state[3]*state[5] + 2*state[4]*state[6];
out_8550083838302739916[54] = -2*state[3]*state[4] + 2*state[5]*state[6];
out_8550083838302739916[55] = pow(state[3], 2) - pow(state[4], 2) - pow(state[5], 2) + pow(state[6], 2);
out_8550083838302739916[56] = 0;
out_8550083838302739916[57] = 0;
out_8550083838302739916[58] = 0;
out_8550083838302739916[59] = 0;
out_8550083838302739916[60] = 0;
out_8550083838302739916[61] = 0;
out_8550083838302739916[62] = 0;
out_8550083838302739916[63] = 0;
out_8550083838302739916[64] = 0;
out_8550083838302739916[65] = 0;
out_8550083838302739916[66] = 0;
out_8550083838302739916[67] = 0;
out_8550083838302739916[68] = 0;
}
void h_14(double *state, double *unused, double *out_6350337263133992527) {
out_6350337263133992527[0] = state[10];
out_6350337263133992527[1] = state[11];
out_6350337263133992527[2] = state[12];
}
void H_14(double *state, double *unused, double *out_2203357074039413582) {
out_2203357074039413582[0] = 0;
out_2203357074039413582[1] = 0;
out_2203357074039413582[2] = 0;
out_2203357074039413582[3] = 0;
out_2203357074039413582[4] = 0;
out_2203357074039413582[5] = 0;
out_2203357074039413582[6] = 0;
out_2203357074039413582[7] = 0;
out_2203357074039413582[8] = 0;
out_2203357074039413582[9] = 0;
out_2203357074039413582[10] = 1;
out_2203357074039413582[11] = 0;
out_2203357074039413582[12] = 0;
out_2203357074039413582[13] = 0;
out_2203357074039413582[14] = 0;
out_2203357074039413582[15] = 0;
out_2203357074039413582[16] = 0;
out_2203357074039413582[17] = 0;
out_2203357074039413582[18] = 0;
out_2203357074039413582[19] = 0;
out_2203357074039413582[20] = 0;
out_2203357074039413582[21] = 0;
out_2203357074039413582[22] = 0;
out_2203357074039413582[23] = 0;
out_2203357074039413582[24] = 0;
out_2203357074039413582[25] = 0;
out_2203357074039413582[26] = 0;
out_2203357074039413582[27] = 0;
out_2203357074039413582[28] = 0;
out_2203357074039413582[29] = 0;
out_2203357074039413582[30] = 0;
out_2203357074039413582[31] = 0;
out_2203357074039413582[32] = 0;
out_2203357074039413582[33] = 0;
out_2203357074039413582[34] = 1;
out_2203357074039413582[35] = 0;
out_2203357074039413582[36] = 0;
out_2203357074039413582[37] = 0;
out_2203357074039413582[38] = 0;
out_2203357074039413582[39] = 0;
out_2203357074039413582[40] = 0;
out_2203357074039413582[41] = 0;
out_2203357074039413582[42] = 0;
out_2203357074039413582[43] = 0;
out_2203357074039413582[44] = 0;
out_2203357074039413582[45] = 0;
out_2203357074039413582[46] = 0;
out_2203357074039413582[47] = 0;
out_2203357074039413582[48] = 0;
out_2203357074039413582[49] = 0;
out_2203357074039413582[50] = 0;
out_2203357074039413582[51] = 0;
out_2203357074039413582[52] = 0;
out_2203357074039413582[53] = 0;
out_2203357074039413582[54] = 0;
out_2203357074039413582[55] = 0;
out_2203357074039413582[56] = 0;
out_2203357074039413582[57] = 0;
out_2203357074039413582[58] = 1;
out_2203357074039413582[59] = 0;
out_2203357074039413582[60] = 0;
out_2203357074039413582[61] = 0;
out_2203357074039413582[62] = 0;
out_2203357074039413582[63] = 0;
out_2203357074039413582[64] = 0;
out_2203357074039413582[65] = 0;
out_2203357074039413582[66] = 0;
out_2203357074039413582[67] = 0;
out_2203357074039413582[68] = 0;
}
void h_19(double *state, double *unused, double *out_5874493945137936551) {
out_5874493945137936551[0] = state[20];
out_5874493945137936551[1] = state[21];
out_5874493945137936551[2] = state[22];
}
void H_19(double *state, double *unused, double *out_6160069650627068086) {
out_6160069650627068086[0] = 0;
out_6160069650627068086[1] = 0;
out_6160069650627068086[2] = 0;
out_6160069650627068086[3] = 0;
out_6160069650627068086[4] = 0;
out_6160069650627068086[5] = 0;
out_6160069650627068086[6] = 0;
out_6160069650627068086[7] = 0;
out_6160069650627068086[8] = 0;
out_6160069650627068086[9] = 0;
out_6160069650627068086[10] = 0;
out_6160069650627068086[11] = 0;
out_6160069650627068086[12] = 0;
out_6160069650627068086[13] = 0;
out_6160069650627068086[14] = 0;
out_6160069650627068086[15] = 0;
out_6160069650627068086[16] = 0;
out_6160069650627068086[17] = 0;
out_6160069650627068086[18] = 0;
out_6160069650627068086[19] = 0;
out_6160069650627068086[20] = 1;
out_6160069650627068086[21] = 0;
out_6160069650627068086[22] = 0;
out_6160069650627068086[23] = 0;
out_6160069650627068086[24] = 0;
out_6160069650627068086[25] = 0;
out_6160069650627068086[26] = 0;
out_6160069650627068086[27] = 0;
out_6160069650627068086[28] = 0;
out_6160069650627068086[29] = 0;
out_6160069650627068086[30] = 0;
out_6160069650627068086[31] = 0;
out_6160069650627068086[32] = 0;
out_6160069650627068086[33] = 0;
out_6160069650627068086[34] = 0;
out_6160069650627068086[35] = 0;
out_6160069650627068086[36] = 0;
out_6160069650627068086[37] = 0;
out_6160069650627068086[38] = 0;
out_6160069650627068086[39] = 0;
out_6160069650627068086[40] = 0;
out_6160069650627068086[41] = 0;
out_6160069650627068086[42] = 0;
out_6160069650627068086[43] = 0;
out_6160069650627068086[44] = 1;
out_6160069650627068086[45] = 0;
out_6160069650627068086[46] = 0;
out_6160069650627068086[47] = 0;
out_6160069650627068086[48] = 0;
out_6160069650627068086[49] = 0;
out_6160069650627068086[50] = 0;
out_6160069650627068086[51] = 0;
out_6160069650627068086[52] = 0;
out_6160069650627068086[53] = 0;
out_6160069650627068086[54] = 0;
out_6160069650627068086[55] = 0;
out_6160069650627068086[56] = 0;
out_6160069650627068086[57] = 0;
out_6160069650627068086[58] = 0;
out_6160069650627068086[59] = 0;
out_6160069650627068086[60] = 0;
out_6160069650627068086[61] = 0;
out_6160069650627068086[62] = 0;
out_6160069650627068086[63] = 0;
out_6160069650627068086[64] = 0;
out_6160069650627068086[65] = 0;
out_6160069650627068086[66] = 0;
out_6160069650627068086[67] = 0;
out_6160069650627068086[68] = 1;
}
}
extern "C"{
#define DIM 23
#define EDIM 22
#define MEDIM 22
typedef void (*Hfun)(double *, double *, double *);
void predict(double *x, double *P, double *Q, double dt);
const static double MAHA_THRESH_3 = 3.841459;
void update_3(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_4 = 7.814728;
void update_4(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_9 = 7.814728;
void update_9(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_10 = 7.814728;
void update_10(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_12 = 7.814728;
void update_12(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_31 = 7.814728;
void update_31(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_32 = 9.487729;
void update_32(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_13 = 7.814728;
void update_13(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_14 = 7.814728;
void update_14(double *, double *, double *, double *, double *);
const static double MAHA_THRESH_19 = 7.814728;
void update_19(double *, double *, double *, double *, double *);
}
#include <eigen3/Eigen/Dense>
#include <iostream>
typedef Eigen::Matrix<double, DIM, DIM, Eigen::RowMajor> DDM;
typedef Eigen::Matrix<double, EDIM, EDIM, Eigen::RowMajor> EEM;
typedef Eigen::Matrix<double, DIM, EDIM, Eigen::RowMajor> DEM;
void predict(double *in_x, double *in_P, double *in_Q, double dt) {
typedef Eigen::Matrix<double, MEDIM, MEDIM, Eigen::RowMajor> RRM;
double nx[DIM] = {0};
double in_F[EDIM*EDIM] = {0};
// functions from sympy
f_fun(in_x, dt, nx);
F_fun(in_x, dt, in_F);
EEM F(in_F);
EEM P(in_P);
EEM Q(in_Q);
RRM F_main = F.topLeftCorner(MEDIM, MEDIM);
P.topLeftCorner(MEDIM, MEDIM) = (F_main * P.topLeftCorner(MEDIM, MEDIM)) * F_main.transpose();
P.topRightCorner(MEDIM, EDIM - MEDIM) = F_main * P.topRightCorner(MEDIM, EDIM - MEDIM);
P.bottomLeftCorner(EDIM - MEDIM, MEDIM) = P.bottomLeftCorner(EDIM - MEDIM, MEDIM) * F_main.transpose();
P = P + dt*Q;
// copy out state
memcpy(in_x, nx, DIM * sizeof(double));
memcpy(in_P, P.data(), EDIM * EDIM * sizeof(double));
}
// note: extra_args dim only correct when null space projecting
// otherwise 1
template <int ZDIM, int EADIM, bool MAHA_TEST>
void update(double *in_x, double *in_P, Hfun h_fun, Hfun H_fun, Hfun Hea_fun, double *in_z, double *in_R, double *in_ea, double MAHA_THRESHOLD) {
typedef Eigen::Matrix<double, ZDIM, ZDIM, Eigen::RowMajor> ZZM;
typedef Eigen::Matrix<double, ZDIM, DIM, Eigen::RowMajor> ZDM;
typedef Eigen::Matrix<double, Eigen::Dynamic, EDIM, Eigen::RowMajor> XEM;
//typedef Eigen::Matrix<double, EDIM, ZDIM, Eigen::RowMajor> EZM;
typedef Eigen::Matrix<double, Eigen::Dynamic, 1> X1M;
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> XXM;
double in_hx[ZDIM] = {0};
double in_H[ZDIM * DIM] = {0};
double in_H_mod[EDIM * DIM] = {0};
double delta_x[EDIM] = {0};
double x_new[DIM] = {0};
// state x, P
Eigen::Matrix<double, ZDIM, 1> z(in_z);
EEM P(in_P);
ZZM pre_R(in_R);
// functions from sympy
h_fun(in_x, in_ea, in_hx);
H_fun(in_x, in_ea, in_H);
ZDM pre_H(in_H);
// get y (y = z - hx)
Eigen::Matrix<double, ZDIM, 1> pre_y(in_hx); pre_y = z - pre_y;
X1M y; XXM H; XXM R;
if (Hea_fun){
typedef Eigen::Matrix<double, ZDIM, EADIM, Eigen::RowMajor> ZAM;
double in_Hea[ZDIM * EADIM] = {0};
Hea_fun(in_x, in_ea, in_Hea);
ZAM Hea(in_Hea);
XXM A = Hea.transpose().fullPivLu().kernel();
y = A.transpose() * pre_y;
H = A.transpose() * pre_H;
R = A.transpose() * pre_R * A;
} else {
y = pre_y;
H = pre_H;
R = pre_R;
}
// get modified H
H_mod_fun(in_x, in_H_mod);
DEM H_mod(in_H_mod);
XEM H_err = H * H_mod;
// Do mahalobis distance test
if (MAHA_TEST){
XXM a = (H_err * P * H_err.transpose() + R).inverse();
double maha_dist = y.transpose() * a * y;
if (maha_dist > MAHA_THRESHOLD){
R = 1.0e16 * R;
}
}
// Outlier resilient weighting
double weight = 1;//(1.5)/(1 + y.squaredNorm()/R.sum());
// kalman gains and I_KH
XXM S = ((H_err * P) * H_err.transpose()) + R/weight;
XEM KT = S.fullPivLu().solve(H_err * P.transpose());
//EZM K = KT.transpose(); TODO: WHY DOES THIS NOT COMPILE?
//EZM K = S.fullPivLu().solve(H_err * P.transpose()).transpose();
//std::cout << "Here is the matrix rot:\n" << K << std::endl;
EEM I_KH = Eigen::Matrix<double, EDIM, EDIM>::Identity() - (KT.transpose() * H_err);
// update state by injecting dx
Eigen::Matrix<double, EDIM, 1> dx(delta_x);
dx = (KT.transpose() * y);
memcpy(delta_x, dx.data(), EDIM * sizeof(double));
err_fun(in_x, delta_x, x_new);
Eigen::Matrix<double, DIM, 1> x(x_new);
// update cov
P = ((I_KH * P) * I_KH.transpose()) + ((KT.transpose() * R) * KT);
// copy out state
memcpy(in_x, x.data(), DIM * sizeof(double));
memcpy(in_P, P.data(), EDIM * EDIM * sizeof(double));
memcpy(in_z, y.data(), y.rows() * sizeof(double));
}
extern "C"{
void update_3(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<1,3,0>(in_x, in_P, h_3, H_3, NULL, in_z, in_R, in_ea, MAHA_THRESH_3);
}
void update_4(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_4, H_4, NULL, in_z, in_R, in_ea, MAHA_THRESH_4);
}
void update_9(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_9, H_9, NULL, in_z, in_R, in_ea, MAHA_THRESH_9);
}
void update_10(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_10, H_10, NULL, in_z, in_R, in_ea, MAHA_THRESH_10);
}
void update_12(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_12, H_12, NULL, in_z, in_R, in_ea, MAHA_THRESH_12);
}
void update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_31, H_31, NULL, in_z, in_R, in_ea, MAHA_THRESH_31);
}
void update_32(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<4,3,0>(in_x, in_P, h_32, H_32, NULL, in_z, in_R, in_ea, MAHA_THRESH_32);
}
void update_13(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_13, H_13, NULL, in_z, in_R, in_ea, MAHA_THRESH_13);
}
void update_14(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_14, H_14, NULL, in_z, in_R, in_ea, MAHA_THRESH_14);
}
void update_19(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<3,3,0>(in_x, in_P, h_19, H_19, NULL, in_z, in_R, in_ea, MAHA_THRESH_19);
}
}
| 46.582505 | 673 | 0.686761 | lth1436 |
4039979957516c4bc1245e7b61baf93ccd66128f | 964 | cpp | C++ | Interviewbit/TwoPointers/intersection_of_sorted_arrays.cpp | nullpointxr/HackerRankSolutions | 052c9ab66bfd66268b81d8e7888c3d7504ab988f | [
"Apache-2.0"
] | 1 | 2020-10-25T16:12:09.000Z | 2020-10-25T16:12:09.000Z | Interviewbit/TwoPointers/intersection_of_sorted_arrays.cpp | abhishek-sankar/Competitive-Coding-Solutions | 052c9ab66bfd66268b81d8e7888c3d7504ab988f | [
"Apache-2.0"
] | 3 | 2020-11-12T05:44:24.000Z | 2021-04-05T08:09:01.000Z | Interviewbit/TwoPointers/intersection_of_sorted_arrays.cpp | nullpointxr/HackerRankSolutions | 052c9ab66bfd66268b81d8e7888c3d7504ab988f | [
"Apache-2.0"
] | null | null | null | /*
https://www.interviewbit.com/problems/intersection-of-sorted-arrays/
Intersection Of Sorted Arrays
Asked in: Facebook, Google
Find the intersection of two sorted arrays.
OR in other words,
Given 2 sorted arrays, find all the elements which occur in both the arrays.
Example :
Input :
A : [1 2 3 3 4 5 6]
B : [3 3 5]
Output : [3 3 5]
Input :
A : [1 2 3 3 4 5 6]
B : [3 5]
Output : [3 5]
NOTE : For the purpose of this problem ( as also conveyed by the sample case ), assume that elements that appear more than once in both arrays should be included multiple times in the final output.
*/
vector<int> Solution::intersect(const vector<int> &A, const vector<int> &B) {
vector<int>res;
for(int i=0, j=0;i<A.size() && j<B.size();){
if(A[i]==B[j]){
res.push_back(A[i]);
i++;
j++;
}else if(A[i]<B[j]){
i++;
}else{
j++;
}
}
return res;
}
| 26.054054 | 199 | 0.5861 | nullpointxr |
403b0985825ec36e65acb9daa3cf989bcbea581a | 8,779 | hpp | C++ | applications/ConstitutiveModelsApplication/custom_models/plasticity_models/v2_gens_nova_model.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/ConstitutiveModelsApplication/custom_models/plasticity_models/v2_gens_nova_model.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/ConstitutiveModelsApplication/custom_models/plasticity_models/v2_gens_nova_model.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | //
// Project Name: KratosConstitutiveModelsApplication $
// Created by: $Author: LMonforte $
// Last modified by: $Co-Author: MCiantia $
// Date: $Date: July 2018 $
// Revision: $Revision: 0.0 $
//
//
#if !defined(KRATOS_V2_GENS_NOVA_MODEL_H_INCLUDED )
#define KRATOS_V2_GENS_NOVA_MODEL_H_INCLUDED
// System includes
// External includes
#include <iostream>
#include <fstream>
// Project includes
#include "custom_models/plasticity_models/structured_soil_model.hpp"
#include "custom_models/plasticity_models/hardening_rules/gens_nova_hardening_rule.hpp"
#include "custom_models/plasticity_models/yield_surfaces/gens_nova_yield_surface.hpp"
#include "custom_models/elasticity_models/borja_model.hpp"
#include "custom_models/elasticity_models/tamagnini_model.hpp"
//***** the hardening law associated to this Model has ... variables
// 0. Plastic multiplier
// 1. Plastic Volumetric deformation
// 2. Plastic Deviatoric deformation
// 3. ps (mechanical)
// 4. pt (ageing)
// 5. pcSTAR = ps + (1+k) p_t
// 6. Plastic Volumetric deformation Absolut Value
// 7. NonLocal Plastic Vol Def
// 8. NonLocal Plastic Dev Def
// 9. NonLocal Plastic Vol Def ABS
// ... (the number now is then..., xD)
namespace Kratos
{
///@addtogroup ConstitutiveModelsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/** Detail class definition.
*/
class KRATOS_API(CONSTITUTIVE_MODELS_APPLICATION) V2GensNovaModel : public StructuredSoilModel<TamagniniModel, GensNovaYieldSurface<GensNovaHardeningRule> >
{
public:
///@name Type Definitions
///@{
//elasticity model
//typedef BorjaModel ElasticityModelType;
typedef TamagniniModel ElasticityModelType;
typedef ElasticityModelType::Pointer ElasticityModelPointer;
//yield surface
typedef GensNovaHardeningRule HardeningRuleType;
typedef GensNovaYieldSurface<HardeningRuleType> YieldSurfaceType;
typedef YieldSurfaceType::Pointer YieldSurfacePointer;
//base type
typedef StructuredSoilModel<ElasticityModelType,YieldSurfaceType> BaseType;
//common types
typedef BaseType::Pointer BaseTypePointer;
typedef BaseType::SizeType SizeType;
typedef BaseType::VoigtIndexType VoigtIndexType;
typedef BaseType::MatrixType MatrixType;
typedef BaseType::ModelDataType ModelDataType;
typedef BaseType::MaterialDataType MaterialDataType;
typedef BaseType::PlasticDataType PlasticDataType;
typedef BaseType::InternalVariablesType InternalVariablesType;
/// Pointer definition of V2GensNovaModel
KRATOS_CLASS_POINTER_DEFINITION( V2GensNovaModel );
///@}
///@name Life Cycle
///@{
/// Default constructor.
V2GensNovaModel() : BaseType() { mInitialized = false; }
/// Copy constructor.
V2GensNovaModel(V2GensNovaModel const& rOther) : BaseType(rOther) {}
/// Assignment operator.
V2GensNovaModel& operator=(V2GensNovaModel const& rOther)
{
BaseType::operator=(rOther);
return *this;
}
/// Clone.
ConstitutiveModel::Pointer Clone() const override
{
return ( V2GensNovaModel::Pointer(new V2GensNovaModel(*this)) );
}
/// Destructor.
virtual ~V2GensNovaModel() {}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
virtual std::string Info() const override
{
std::stringstream buffer;
buffer << "V2GensNovaModel" ;
return buffer.str();
}
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const override
{
rOStream << "V2GensNovaModel";
}
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const override
{
rOStream << "V2GensNovaModel Data";
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
// Calculate Stress and constitutive tensor
void CalculateStressAndConstitutiveTensors(ModelDataType& rValues, MatrixType& rStressMatrix, Matrix& rConstitutiveMatrix) override
{
KRATOS_TRY
// integrate "analytically" ps and pt from plastic variables. Then update the internal variables.
PlasticDataType Variables;
this->InitializeVariables( rValues, Variables);
const ModelDataType & rModelData = Variables.GetModelData();
const Properties & rMaterialProperties = rModelData.GetProperties();
const double & rPs0 = rMaterialProperties[PS];
const double & rPt0 = rMaterialProperties[PT];
const double & rChis = rMaterialProperties[CHIS];
const double & rChit = rMaterialProperties[CHIT];
const double & rhos = rMaterialProperties[RHOS];
const double & rhot = rMaterialProperties[RHOT];
const double & k = rMaterialProperties[KSIM];
const double & rPlasticVolDef = Variables.Internal.Variables[1];
const double & rPlasticDevDef = Variables.Internal.Variables[2];
const double & rPlasticVolDefAbs = Variables.Internal.Variables[6];
double sq2_3 = sqrt(2.0/3.0);
double ps;
ps = rPlasticVolDef + sq2_3 * rChis * rPlasticDevDef;
ps = (-rPs0) * std::exp( -rhos*ps);
double pt;
pt = rPlasticVolDefAbs + sq2_3 * rChit * rPlasticDevDef;
pt = (-rPt0) * std::exp( rhot*pt);
double pm;
pm = ps + (1.0+k)*pt;
mInternal.Variables[3] = ps;
mInternal.Variables[4] = pt;
mInternal.Variables[5] = pm;
StructuredSoilModel::CalculateStressAndConstitutiveTensors( rValues, rStressMatrix, rConstitutiveMatrix);
KRATOS_CATCH("")
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Serialization
///@{
friend class Serializer;
virtual void save(Serializer& rSerializer) const override
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, BaseType )
}
virtual void load(Serializer& rSerializer) override
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, BaseType )
}
///@}
///@name Un accessible methods
///@{
///@}
}; // Class V2GensNovaModel
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
///@name Input and output
///@{
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_V2_GENS_NOVA_MODEL_H_INCLUDED defined
| 25.594752 | 159 | 0.536166 | lkusch |
403ff2e3015c718a5d5239b0c203464b263dea44 | 1,550 | cpp | C++ | vkconfig_core/layer_state.cpp | dorian-apanel-intel/VulkanTools | ff6d769f160def2176d6325d8bbee78215ea3c09 | [
"Apache-2.0"
] | 579 | 2016-02-16T14:24:33.000Z | 2022-03-30T01:15:29.000Z | vkconfig_core/layer_state.cpp | dorian-apanel-intel/VulkanTools | ff6d769f160def2176d6325d8bbee78215ea3c09 | [
"Apache-2.0"
] | 1,064 | 2016-02-18T00:27:10.000Z | 2022-03-31T18:17:08.000Z | vkconfig_core/layer_state.cpp | dorian-apanel-intel/VulkanTools | ff6d769f160def2176d6325d8bbee78215ea3c09 | [
"Apache-2.0"
] | 200 | 2016-02-16T19:57:40.000Z | 2022-03-10T22:30:59.000Z | /*
* Copyright (c) 2020-2021 Valve Corporation
* Copyright (c) 2020-2021 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors:
* - Christophe Riccio <christophe@lunarg.com>
*/
#include "layer_state.h"
#include "util.h"
#include <cstring>
#include <cassert>
const char* GetToken(LayerState state) {
static const char* table[] = {
"APPLICATION_CONTROLLED", // LAYER_STATE_APPLICATION_CONTROLLED
"OVERRIDDEN", // LAYER_STATE_OVERRIDDEN
"EXCLUDED" // LAYER_STATE_EXCLUDED
};
static_assert(countof(table) == LAYER_STATE_COUNT, "The tranlation table size doesn't match the enum number of elements");
return table[state];
}
LayerState GetLayerState(const char* token) {
for (std::size_t i = 0, n = LAYER_STATE_COUNT; i < n; ++i) {
const LayerState layer_state = static_cast<LayerState>(i);
if (std::strcmp(GetToken(layer_state), token) == 0) return layer_state;
}
assert(0);
return static_cast<LayerState>(-1);
}
| 32.291667 | 126 | 0.689032 | dorian-apanel-intel |
4043aa0a05715467a56bc3de351a54e62952f628 | 3,855 | cpp | C++ | WaveletTree/WaveletTree/WaveletNode.cpp | Vaan5/Bioinformatics---Construction-of-a-binary-wavelet-tree-using-RRR-structure | 12b8c0a293d521204c97580a6b0ab2654bffac8b | [
"MIT"
] | null | null | null | WaveletTree/WaveletTree/WaveletNode.cpp | Vaan5/Bioinformatics---Construction-of-a-binary-wavelet-tree-using-RRR-structure | 12b8c0a293d521204c97580a6b0ab2654bffac8b | [
"MIT"
] | null | null | null | WaveletTree/WaveletTree/WaveletNode.cpp | Vaan5/Bioinformatics---Construction-of-a-binary-wavelet-tree-using-RRR-structure | 12b8c0a293d521204c97580a6b0ab2654bffac8b | [
"MIT"
] | 4 | 2016-07-24T18:23:06.000Z | 2019-04-11T12:37:22.000Z | #include "WaveletNode.h"
// Returns left child node
WaveletNode* WaveletNode::getLeftChild() const {
return this->leftChild;
}
// Returns right child node
WaveletNode* WaveletNode::getRightChild() const {
return this->rightChild;
}
// Returns parent node
WaveletNode* WaveletNode::getParent() const {
return this->parent;
}
// Creates a new wavelet tree node
// content_ content to be stored in the node
// parent_ parent node in the wavelet tree
// start_ first index of the alphabet subset stored in the node
// end_ last index of the alphabet subset stored in the node
// alphabetIndices_ symbol -> index alphabet mapping calculated when constructing the wavelet tree
// isLeftChild_ flag to know if the current node is a left child
// visualOutput file handler used to generate graphviz data
WaveletNode::WaveletNode(string content_, WaveletNode *parent_, uint8_t start_, uint8_t end_, alphabet &alphabetIndices_, bool isLeftChild_, FILE* visualOutput) : parent(parent_), start(start_), end(end_), isLeftChild(isLeftChild_) {
this->id = idGenerator++;
if (visualOutput != NULL) {
if (this->parent != NULL) {
fprintf(visualOutput, "\t%d -> %d;\n", this->parent->id, this->id);
}
fprintf(visualOutput, "\t%d [ label = \"%s\\n", this->id, content_.c_str());
}
// Alphabet subrange division
// start and end are inclusive indices
// Current node children will get alphabet intervals [start, threshold] and [threshold + 1, end]
this->threshold = (uint8_t)(start / 2. + end / 2.);
uint64_t zeroIndex = 0;
uint64_t oneIndex = 0;
uint64_t contentSize = content_.length();
// Substring from original string that contains only the 0 encoded content part
char* contentZeroes = (char*)malloc(sizeof(char) * (contentSize + 1));
// Substring from original string that contains only the 1 encoded content part
char* contentOnes = (char*)malloc(sizeof(char) * (contentSize + 1));
// Create binary string for RRR input
for (uint64_t i = 0; i < contentSize; i++) {
char c = content_[i];
if (alphabetIndices_[c] <= threshold) {
contentZeroes[zeroIndex] = c;
zeroIndex++;
content_[i] = '0';
}
else {
contentOnes[oneIndex] = c;
oneIndex++;
content_[i] = '1';
}
}
if (visualOutput != NULL) {
fprintf(visualOutput, "%s\"];\n", content_.c_str());
}
// Create RRR
this->content = new RRR(content_);
// Denote the end of substrings
contentOnes[oneIndex] = '\0';
contentZeroes[zeroIndex] = '\0';
// Create children only if content has more than two characters
if ((this->end - this->start) > 1) {
this->leftChild = new WaveletNode((string)contentZeroes, this, this->start, this->threshold, alphabetIndices_, true, visualOutput);
free(contentZeroes);
if (this->threshold + 1 != this->end) this->rightChild = new WaveletNode((string)contentOnes, this, this->threshold + 1, this->end, alphabetIndices_, false, visualOutput);
free(contentOnes);
} else {
// Free aliocated memory
free(contentOnes);
free(contentZeroes);
}
}
// Free memory
WaveletNode::~WaveletNode() {
delete this->leftChild;
delete this->rightChild;
delete this->content;
}
// Returns RRR in which the content is stored
RRR* WaveletNode::getContent() const {
return content;
}
// Returns threshold used to define left and right child alhpabet subsets
uint8_t WaveletNode::getThreshold() {
return this->threshold;
}
// Returns true if the current child is it's parent's left child,
// false otherwise
bool WaveletNode::getIsLeftChild() {
return this->isLeftChild;
}
// Returns first index of the node's alphabet subset
uint8_t WaveletNode::getStart() {
return this->start;
}
// Returns last index of the node's alphabet subset
uint8_t WaveletNode::getEnd() {
return this->end;
}
// Identifier counter used for naming nodes when creating graphviz data
int WaveletNode::idGenerator = 0;
| 31.341463 | 233 | 0.71284 | Vaan5 |
404410bd6dc6abf63b3b42e414528648ce06d498 | 7,157 | cpp | C++ | Source/ChilliSource/Rendering/Particles/ParticleComponent.cpp | mclaughlinhugh4/ChilliSource | bfd86242b28125371804ef35ee512a3908763795 | [
"MIT"
] | 1 | 2015-05-08T14:29:03.000Z | 2015-05-08T14:29:03.000Z | Source/ChilliSource/Rendering/Particles/ParticleComponent.cpp | mclaughlinhugh4/ChilliSource | bfd86242b28125371804ef35ee512a3908763795 | [
"MIT"
] | null | null | null | Source/ChilliSource/Rendering/Particles/ParticleComponent.cpp | mclaughlinhugh4/ChilliSource | bfd86242b28125371804ef35ee512a3908763795 | [
"MIT"
] | null | null | null | //
// ParticleComponent.cpp
// Chilli Source
// Created by Scott Downie on 07/01/2011.
//
// The MIT License (MIT)
//
// Copyright (c) 2011 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <ChilliSource/Rendering/Particles/ParticleComponent.h>
#include <ChilliSource/Rendering/Particles/ParticleSystem.h>
#include <ChilliSource/Rendering/Particles/Affectors/ParticleAffector.h>
namespace ChilliSource
{
namespace Rendering
{
CS_DEFINE_NAMEDTYPE(ParticleComponent);
//=====================================================
/// Particle Component
///
/// Entire particle system
//=====================================================
//-----------------------------------------------------
/// Constructor
//-----------------------------------------------------
ParticleComponent::ParticleComponent(): mpOwningSystem(nullptr), mfUpdateScaleFactor(1.0f), mbEmittersFinished(false)
{
SetCullingEnabled(false);
}
//----------------------------------------------------------
/// Is A
//----------------------------------------------------------
bool ParticleComponent::IsA(CSCore::InterfaceIDType inInterfaceID) const
{
return (inInterfaceID == ParticleComponent::InterfaceID) ||
(inInterfaceID == RenderComponent::InterfaceID);
}
//-------------------------------------------------
/// Set Owning System
//-------------------------------------------------
void ParticleComponent::SetOwningSystem(ParticleSystem* inpSystem)
{
mpOwningSystem = inpSystem;
}
//-------------------------------------------------
/// Remove From World System
//-------------------------------------------------
void ParticleComponent::RemoveFromWorldSystem()
{
mpOwningSystem->RemoveParticleComponent(this);
}
//---------------------------------------------------
/// Add Emitter
//---------------------------------------------------
void ParticleComponent::AddEmitter(ParticleEmitterUPtr inpEmitter)
{
if(inpEmitter)
{
mEmitters.push_back(std::move(inpEmitter));
}
}
//---------------------------------------------------
/// Get number of emitters in this system
//---------------------------------------------------
u32 ParticleComponent::GetNumEmitters() const
{
return mEmitters.size();
}
//---------------------------------------------------
/// Returns the emitter at the given index or nullptr
//---------------------------------------------------
ParticleEmitter* ParticleComponent::GetEmitter(u32 inudwIndex)
{
if (inudwIndex < mEmitters.size())
return mEmitters[inudwIndex].get();
return nullptr;
}
//---------------------------------------------------
/// Add Affector
//---------------------------------------------------
void ParticleComponent::AddAffector(ParticleAffectorUPtr inpAffector)
{
if(!inpAffector)
{
return;
}
for(std::vector<ParticleEmitterUPtr>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it)
{
(*it)->AddAffector(inpAffector.get());
}
mAffectors.push_back(std::move(inpAffector));
}
//-------------------------------------------------
/// Update
//-------------------------------------------------
void ParticleComponent::Update(f32 infDt)
{
bool bEmittingFinished = true;
for(std::vector<ParticleEmitterUPtr>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it)
{
(*it)->Update(infDt * mfUpdateScaleFactor);
if((*it)->GetIsEmittingFinished() == false)
{
bEmittingFinished = false;
}
}
if(bEmittingFinished)
{
mbEmittersFinished = true;
}
}
//-------------------------------------------------
/// Render
//-------------------------------------------------
void ParticleComponent::Render(RenderSystem* inpRenderSystem, CameraComponent* inpCam, ShaderPass ineShaderPass)
{
if (ineShaderPass == ShaderPass::k_ambient)
{
for(std::vector<ParticleEmitterUPtr>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it)
{
(*it)->Render(inpRenderSystem, inpCam);
}
}
}
//---------------------------------------------------
/// Start Emitting
//---------------------------------------------------
void ParticleComponent::StartEmitting()
{
for(std::vector<ParticleEmitterUPtr>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it)
{
(*it)->StartEmitting();
}
}
//---------------------------------------------------
/// Emit Once
//---------------------------------------------------
void ParticleComponent::EmitBurst()
{
for(std::vector<ParticleEmitterUPtr>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it)
{
(*it)->EmitBurst();
}
}
//---------------------------------------------------
/// Stop Emitting
//---------------------------------------------------
void ParticleComponent::StopEmitting()
{
for(std::vector<ParticleEmitterUPtr>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it)
{
(*it)->StopEmitting();
}
}
//---------------------------------------------------
/// Set Update Scale Factor
//---------------------------------------------------
void ParticleComponent::SetUpdateScaleFactor(f32 infScale)
{
mfUpdateScaleFactor = infScale;
}
//-----------------------------------------------------
/// Destructor
//-----------------------------------------------------
ParticleComponent::~ParticleComponent()
{
RemoveFromWorldSystem();
}
}
} | 36.329949 | 120 | 0.467235 | mclaughlinhugh4 |
4048c247364a45f2e4e348bdb1c93cac1b919d6b | 12,497 | cpp | C++ | src/tdme/tools/shared/controller/EntityBaseSubScreenController.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/tools/shared/controller/EntityBaseSubScreenController.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/tools/shared/controller/EntityBaseSubScreenController.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | #include <tdme/tools/shared/controller/EntityBaseSubScreenController.h>
#include <map>
#include <string>
#include <vector>
#include <tdme/gui/GUIParser.h>
#include <tdme/gui/events/Action.h>
#include <tdme/gui/events/GUIActionListener_Type.h>
#include <tdme/gui/nodes/GUIElementNode.h>
#include <tdme/gui/nodes/GUINode.h>
#include <tdme/gui/nodes/GUINodeController.h>
#include <tdme/gui/nodes/GUIParentNode.h>
#include <tdme/gui/nodes/GUIScreenNode.h>
#include <tdme/tools/shared/controller/InfoDialogScreenController.h>
#include <tdme/tools/shared/model/LevelEditorEntity.h>
#include <tdme/tools/shared/model/LevelPropertyPresets.h>
#include <tdme/tools/shared/model/PropertyModelClass.h>
#include <tdme/tools/shared/views/EntityBaseView.h>
#include <tdme/tools/shared/views/PopUps.h>
#include <tdme/utils/Console.h>
#include <tdme/utils/Exception.h>
#include <tdme/utils/MutableString.h>
using std::map;
using std::vector;
using std::string;
using tdme::tools::shared::controller::EntityBaseSubScreenController;
using tdme::gui::GUIParser;
using tdme::gui::events::Action;
using tdme::gui::events::GUIActionListener_Type;
using tdme::gui::nodes::GUIElementNode;
using tdme::gui::nodes::GUINode;
using tdme::gui::nodes::GUINodeController;
using tdme::gui::nodes::GUIParentNode;
using tdme::gui::nodes::GUIScreenNode;
using tdme::tools::shared::controller::InfoDialogScreenController;
using tdme::tools::shared::model::LevelEditorEntity;
using tdme::tools::shared::model::LevelPropertyPresets;
using tdme::tools::shared::model::PropertyModelClass;
using tdme::tools::shared::views::EntityBaseView;
using tdme::tools::shared::views::PopUps;
using tdme::utils::MutableString;
using tdme::utils::Console;
using tdme::utils::Exception;
MutableString EntityBaseSubScreenController::TEXT_EMPTY = MutableString("");
EntityBaseSubScreenController::EntityBaseSubScreenController(PopUps* popUps, Action* onSetEntityDataAction)
{
this->view = new EntityBaseView(this);
this->popUps = popUps;
this->onSetEntityDataAction = onSetEntityDataAction;
value = new MutableString();
}
EntityBaseSubScreenController::~EntityBaseSubScreenController() {
delete view;
delete onSetEntityDataAction;
}
void EntityBaseSubScreenController::initialize(GUIScreenNode* screenNode)
{
try {
entityName = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("entity_name"));
entityDescription = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("entity_description"));
entityApply = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("button_entity_apply"));
entityPropertyName = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("entity_property_name"));
entityPropertyValue = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("entity_property_value"));
entityPropertySave = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("button_entity_properties_save"));
entityPropertyAdd = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("button_entity_properties_add"));
entityPropertyRemove = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("button_entity_properties_remove"));
entityPropertiesList = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("entity_properties_listbox"));
entityPropertyPresetApply = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("button_entity_properties_presetapply"));
entityPropertiesPresets = dynamic_cast< GUIElementNode* >(screenNode->getNodeById("entity_properties_presets"));
} catch (Exception& exception) {
Console::print(string("EntityBaseSubScreenController::initialize(): An error occurred: "));
Console::println(string(exception.what()));
}
setEntityPresetIds(LevelPropertyPresets::getInstance()->getObjectPropertiesPresets());
}
void EntityBaseSubScreenController::setEntityData(const string& name, const string& description)
{
entityName->getController()->setDisabled(false);
entityName->getController()->setValue(name);
entityDescription->getController()->setDisabled(false);
entityDescription->getController()->setValue(description);
entityApply->getController()->setDisabled(false);
}
void EntityBaseSubScreenController::unsetEntityData()
{
entityName->getController()->setValue(TEXT_EMPTY);
entityName->getController()->setDisabled(true);
entityDescription->getController()->setValue(TEXT_EMPTY);
entityDescription->getController()->setDisabled(true);
entityApply->getController()->setDisabled(true);
}
void EntityBaseSubScreenController::onEntityDataApply(LevelEditorEntity* model)
{
if (model == nullptr)
return;
view->setEntityData(model, entityName->getController()->getValue().getString(), entityDescription->getController()->getValue().getString());
onSetEntityDataAction->performAction();
}
void EntityBaseSubScreenController::setEntityPresetIds(const map<string, vector<PropertyModelClass*>>& entityPresetIds)
{
auto entityPropertiesPresetsInnerNode = dynamic_cast< GUIParentNode* >((entityPropertiesPresets->getScreenNode()->getNodeById(entityPropertiesPresets->getId() + "_inner")));
auto idx = 0;
string entityPropertiesPresetsInnerNodeSubNodesXML = "";
entityPropertiesPresetsInnerNodeSubNodesXML =
entityPropertiesPresetsInnerNodeSubNodesXML +
"<scrollarea-vertical id=\"" +
entityPropertiesPresets->getId() +
"_inner_scrollarea\" width=\"100%\" height=\"100\">\n";
for (auto it: entityPresetIds) {
auto entityPresetId = it.first;
entityPropertiesPresetsInnerNodeSubNodesXML =
entityPropertiesPresetsInnerNodeSubNodesXML + "<dropdown-option text=\"" +
GUIParser::escapeQuotes(entityPresetId) +
"\" value=\"" +
GUIParser::escapeQuotes(entityPresetId) +
"\" " +
(idx == 0 ? "selected=\"true\" " : "") +
" />\n";
idx++;
}
entityPropertiesPresetsInnerNodeSubNodesXML = entityPropertiesPresetsInnerNodeSubNodesXML + "</scrollarea-vertical>";
try {
entityPropertiesPresetsInnerNode->replaceSubNodes(entityPropertiesPresetsInnerNodeSubNodesXML, true);
} catch (Exception& exception) {
Console::print(string("EntityBaseSubScreenController::setEntityPresetIds(): An error occurred: "));
Console::println(string(exception.what()));
}
}
void EntityBaseSubScreenController::setEntityProperties(LevelEditorEntity* entity, const string& presetId, const string& selectedName)
{
entityPropertiesPresets->getController()->setDisabled(false);
entityPropertyPresetApply->getController()->setDisabled(false);
entityPropertiesList->getController()->setDisabled(false);
entityPropertyAdd->getController()->setDisabled(false);
entityPropertyRemove->getController()->setDisabled(false);
entityPropertySave->getController()->setDisabled(true);
entityPropertyName->getController()->setDisabled(true);
entityPropertyValue->getController()->setDisabled(true);
entityPropertiesPresets->getController()->setValue(presetId.length() > 0 ? value->set(presetId) : value->set("none"));
auto entityPropertiesListBoxInnerNode = dynamic_cast< GUIParentNode* >((entityPropertiesList->getScreenNode()->getNodeById(entityPropertiesList->getId() + "_inner")));
auto idx = 1;
string entityPropertiesListBoxSubNodesXML = "";
entityPropertiesListBoxSubNodesXML =
entityPropertiesListBoxSubNodesXML +
"<scrollarea-vertical id=\"" +
entityPropertiesList->getId() +
"_inner_scrollarea\" width=\"100%\" height=\"100%\">\n";
for (auto i = 0; i < entity->getPropertyCount(); i++) {
PropertyModelClass* entityProperty = entity->getPropertyByIndex(i);
entityPropertiesListBoxSubNodesXML =
entityPropertiesListBoxSubNodesXML +
"<selectbox-option text=\"" +
GUIParser::escapeQuotes(entityProperty->getName()) +
": " +
GUIParser::escapeQuotes(entityProperty->getValue()) +
"\" value=\"" +
GUIParser::escapeQuotes(entityProperty->getName()) +
"\" " +
(selectedName.length() > 0 && entityProperty->getName() == selectedName ? "selected=\"true\" " : "") +
"/>\n";
}
entityPropertiesListBoxSubNodesXML = entityPropertiesListBoxSubNodesXML + "</scrollarea-vertical>\n";
try {
entityPropertiesListBoxInnerNode->replaceSubNodes(entityPropertiesListBoxSubNodesXML, false);
} catch (Exception& exception) {
Console::print(string("EntityBaseSubScreenController::setEntityProperties(): An error occurred: "));
Console::println(string(exception.what()));
}
onEntityPropertiesSelectionChanged(entity);
}
void EntityBaseSubScreenController::unsetEntityProperties()
{
auto modelPropertiesListBoxInnerNode = dynamic_cast< GUIParentNode* >((entityPropertiesList->getScreenNode()->getNodeById(entityPropertiesList->getId() + "_inner")));
modelPropertiesListBoxInnerNode->clearSubNodes();
entityPropertiesPresets->getController()->setValue(value->set("none"));
entityPropertiesPresets->getController()->setDisabled(true);
entityPropertyPresetApply->getController()->setDisabled(true);
entityPropertiesList->getController()->setDisabled(true);
entityPropertyAdd->getController()->setDisabled(true);
entityPropertyRemove->getController()->setDisabled(true);
entityPropertySave->getController()->setDisabled(true);
entityPropertyName->getController()->setValue(TEXT_EMPTY);
entityPropertyName->getController()->setDisabled(true);
entityPropertyValue->getController()->setValue(TEXT_EMPTY);
entityPropertyValue->getController()->setDisabled(true);
}
void EntityBaseSubScreenController::onEntityPropertySave(LevelEditorEntity* entity)
{
if (view->entityPropertySave(
entity,
entityPropertiesList->getController()->getValue().getString(),
entityPropertyName->getController()->getValue().getString(),
entityPropertyValue->getController()->getValue().getString()) == false) {
showErrorPopUp("Warning", "Saving entity property failed");
}
}
void EntityBaseSubScreenController::onEntityPropertyAdd(LevelEditorEntity* entity)
{
if (view->entityPropertyAdd(entity) == false) {
showErrorPopUp("Warning", "Adding new entity property failed");
}
}
void EntityBaseSubScreenController::onEntityPropertyRemove(LevelEditorEntity* entity)
{
if (view->entityPropertyRemove(entity, entityPropertiesList->getController()->getValue().getString()) == false) {
showErrorPopUp("Warning", "Removing entity property failed");
}
}
void EntityBaseSubScreenController::showErrorPopUp(const string& caption, const string& message)
{
popUps->getInfoDialogScreenController()->show(caption, message);
}
void EntityBaseSubScreenController::onEntityPropertyPresetApply(LevelEditorEntity* model)
{
view->entityPropertiesPreset(model, entityPropertiesPresets->getController()->getValue().getString());
}
void EntityBaseSubScreenController::onEntityPropertiesSelectionChanged(LevelEditorEntity* entity)
{
entityPropertyName->getController()->setDisabled(true);
entityPropertyName->getController()->setValue(TEXT_EMPTY);
entityPropertyValue->getController()->setDisabled(true);
entityPropertyValue->getController()->setValue(TEXT_EMPTY);
entityPropertySave->getController()->setDisabled(true);
entityPropertyRemove->getController()->setDisabled(true);
auto entityProperty = entity->getProperty(entityPropertiesList->getController()->getValue().getString());
if (entityProperty != nullptr) {
entityPropertyName->getController()->setValue(value->set(entityProperty->getName()));
entityPropertyValue->getController()->setValue(value->set(entityProperty->getValue()));
entityPropertyName->getController()->setDisabled(false);
entityPropertyValue->getController()->setDisabled(false);
entityPropertySave->getController()->setDisabled(false);
entityPropertyRemove->getController()->setDisabled(false);
}
}
void EntityBaseSubScreenController::onValueChanged(GUIElementNode* node, LevelEditorEntity* model)
{
if (node == entityPropertiesList) {
onEntityPropertiesSelectionChanged(model);
} else {
}
}
void EntityBaseSubScreenController::onActionPerformed(GUIActionListener_Type* type, GUIElementNode* node, LevelEditorEntity* entity)
{
{
auto v = type;
if (v == GUIActionListener_Type::PERFORMED)
{
if (node->getId().compare("button_entity_apply") == 0) {
onEntityDataApply(entity);
} else
if (node->getId().compare("button_entity_properties_presetapply") == 0) {
onEntityPropertyPresetApply(entity);
} else
if (node->getId().compare("button_entity_properties_add") == 0) {
onEntityPropertyAdd(entity);
} else
if (node->getId().compare("button_entity_properties_remove") == 0) {
onEntityPropertyRemove(entity);
} else
if (node->getId().compare("button_entity_properties_save") == 0) {
onEntityPropertySave(entity);
}
}
}
}
| 43.242215 | 174 | 0.780427 | mahula |
404edbd4d2e23e6b8928d59b59bff36c9954a535 | 39,012 | cpp | C++ | base/Windows/mkasm/mkasm.cpp | sphinxlogic/Singularity-RDK-2.0 | 2968c3b920a5383f7360e3e489aa772f964a7c42 | [
"MIT"
] | null | null | null | base/Windows/mkasm/mkasm.cpp | sphinxlogic/Singularity-RDK-2.0 | 2968c3b920a5383f7360e3e489aa772f964a7c42 | [
"MIT"
] | null | null | null | base/Windows/mkasm/mkasm.cpp | sphinxlogic/Singularity-RDK-2.0 | 2968c3b920a5383f7360e3e489aa772f964a7c42 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// Microsoft Research
// Copyright (C) Microsoft Corporation
//
// File: mkasm.cpp
//
// Contents: Converts binary files into .asm or .cs files.
//
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <winlean.h>
#include <assert.h>
//////////////////////////////////////////////////////////////////////////////
//
enum {
TARGET_BASE = 0x60000,
TARGET_RANGE = 0x10000,
};
BOOL fAsm = TRUE;
BOOL fCpp = FALSE;
BOOL fManaged = FALSE;
BOOL fCompress = FALSE;
BOOL fList = FALSE;
BOOL fAllow64 = FALSE;
CHAR szByteByteVTable[] = "?_vtable@ClassVector_ClassVector_uint8@@2UClass_System_VTable@@A";
// struct Class_System_VTable ClassVector_ClassVector_uint8::_vtable
CHAR szByteByteSuffix[] = "@@2PAUClassVector_ClassVector_uint8@@A";
// ?c_Content@Class_Microsoft_Singularity_Shell_Slides@@2PAUClassVector_ClassVector_uint8@@A
// struct ClassVector_ClassVector_uint8 * Class_Microsoft_Singularity_Shell_Slides::c_Content
CHAR szByteVTable[] = "?_vtable@ClassVector_uint8@@2UClass_System_VTable@@A";
// struct Class_System_VTable ClassVector_uint8::_vtable
CHAR szByteSuffix[] = "@@2PAUClassVector_uint8@@A";
// ?c_Content@Class_Microsoft_Singularity_Shell_Slides@@2PAUClassVector_ClassVector_uint8@@A
// struct ClassVector_ClassVector_uint8 * Class_Microsoft_Singularity_Shell_Slides::c_Content
//////////////////////////////////////////////////////////////////////////////
class CFileInfo
{
public:
CFileInfo()
{
m_pszFile = NULL;
m_pNext = NULL;
m_cbInput = 0;
m_cbOutput = 0;
}
BOOL SetFileName(PCSTR pszFile)
{
m_pszFile = pszFile;
return TRUE;
}
BOOL SetFileAndSize()
{
HANDLE hFile = CreateFile(m_pszFile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return FALSE;
}
m_cbInput = GetFileSize(hFile, NULL);
CloseHandle(hFile);
if (m_cbInput == 0xffffffff) {
m_cbInput = 0;
return FALSE;
}
m_cbOutput = m_cbInput;
return TRUE;
}
BOOL SetOutputSize(UINT32 cbOutput)
{
m_cbOutput = cbOutput;
return TRUE;
}
CFileInfo * m_pNext;
PCSTR m_pszFile;
UINT32 m_cbInput;
UINT32 m_cbOutput;
};
//////////////////////////////////////////////////////////////////// CFileMap.
//
class CFileMap
{
public:
CFileMap();
~CFileMap();
public:
BOOL Load(PCSTR pszFile);
PBYTE Seek(UINT32 cbPos);
UINT32 Size();
VOID Close();
protected:
PBYTE m_pbData;
UINT32 m_cbData;
};
CFileMap::CFileMap()
{
m_pbData = NULL;
m_cbData = 0;
}
CFileMap::~CFileMap()
{
Close();
}
VOID CFileMap::Close()
{
if (m_pbData) {
UnmapViewOfFile(m_pbData);
m_pbData = NULL;
}
m_cbData = 0;
}
UINT32 CFileMap::Size()
{
return m_cbData;
}
PBYTE CFileMap::Seek(UINT32 cbPos)
{
if (m_pbData && cbPos <= m_cbData) {
return m_pbData + cbPos;
}
return NULL;
}
BOOL CFileMap::Load(PCSTR pszFile)
{
Close();
HANDLE hFile = CreateFile(pszFile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return FALSE;
}
ULONG cbInFileData = GetFileSize(hFile, NULL);
if (cbInFileData == 0xffffffff) {
CloseHandle(hFile);
return FALSE;
}
HANDLE hInFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
CloseHandle(hFile);
if (hInFileMap == NULL) {
return FALSE;
}
m_pbData = (PBYTE)MapViewOfFile(hInFileMap, FILE_MAP_COPY, 0, 0, 0);
CloseHandle(hInFileMap);
if (m_pbData == NULL) {
return FALSE;
}
m_cbData = cbInFileData;
return TRUE;
}
//////////////////////////////////////////////////////////////////// CFileOut.
//
class CFileOut
{
public:
CFileOut();
~CFileOut();
public:
BOOL Create(PCSTR pszFile);
BOOL IsOpen();
BOOL Write(PBYTE pbData, UINT32 cbData);
BOOL Print(PCSTR pszMsg, ...);
BOOL VPrint(PCSTR pszMsg, va_list args);
BOOL Delete();
VOID Close();
protected:
HANDLE m_hFile;
CHAR m_szFile[MAX_PATH];
CHAR m_szBuffer[4096];
INT m_cbBuffer;
};
CFileOut::CFileOut()
{
m_hFile = INVALID_HANDLE_VALUE;
m_szFile[0] = '\0';
m_cbBuffer = 0;
}
CFileOut::~CFileOut()
{
Close();
}
VOID CFileOut::Close()
{
if (m_hFile != INVALID_HANDLE_VALUE) {
if (m_cbBuffer) {
Write((PBYTE)m_szBuffer, m_cbBuffer);
m_cbBuffer = 0;
}
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
}
}
BOOL CFileOut::IsOpen()
{
return (m_hFile != INVALID_HANDLE_VALUE);
}
BOOL CFileOut::Write(PBYTE pbData, UINT32 cbData)
{
if (m_hFile == INVALID_HANDLE_VALUE) {
return FALSE;
}
DWORD dwWrote = 0;
if (!WriteFile(m_hFile, pbData, cbData, &dwWrote, NULL) || dwWrote != cbData) {
return FALSE;
}
return TRUE;
}
BOOL CFileOut::VPrint(PCSTR pszMsg, va_list args)
{
if (m_hFile == INVALID_HANDLE_VALUE) {
return FALSE;
}
INT cbUsed = m_cbBuffer;
INT cbData;
cbData = _vsnprintf(m_szBuffer + cbUsed, sizeof(m_szBuffer)-cbUsed-1, pszMsg, args);
m_cbBuffer += cbData;
if (m_szBuffer[m_cbBuffer - 1] == '\n' ||
m_szBuffer[m_cbBuffer - 1] == '\r') {
cbData = m_cbBuffer;
m_cbBuffer = 0;
return Write((PBYTE)m_szBuffer, cbData);
}
return TRUE;
}
BOOL CFileOut::Print(PCSTR pszMsg, ...)
{
BOOL f;
va_list args;
va_start(args, pszMsg);
f = VPrint(pszMsg, args);
va_end(args);
return f;
}
BOOL CFileOut::Delete()
{
if (m_hFile != INVALID_HANDLE_VALUE) {
Close();
return DeleteFile(m_szFile);
}
return FALSE;
}
BOOL CFileOut::Create(PCSTR pszFile)
{
Close();
m_szFile[0] = '\0';
m_hFile = CreateFile(pszFile,
GENERIC_WRITE,
0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (m_hFile == INVALID_HANDLE_VALUE) {
return FALSE;
}
strcpy(m_szFile, pszFile);
m_cbBuffer = 0;
return TRUE;
}
//
//////////////////////////////////////////////////////////////////////////////
class COutput
{
protected:
UINT m_nOffset;
CFileOut *m_pfOutput;
public:
COutput(CFileOut *pfOutput)
{
m_pfOutput = pfOutput;
m_nOffset = 0;
}
BOOL VPrint(PCSTR pszMsg, va_list args)
{
return m_pfOutput->VPrint(pszMsg, args);
}
BOOL Print(PCSTR pszMsg, ...)
{
BOOL f;
va_list args;
va_start(args, pszMsg);
f = m_pfOutput->VPrint(pszMsg, args);
va_end(args);
return f;
}
virtual void Dump(PBYTE pbData, UINT cbData) = 0;
virtual void Finish()
{
if ((m_nOffset % 16) != 0) {
m_pfOutput->Print("\n");
}
m_nOffset = 0;
}
UINT Size()
{
return m_nOffset;
}
};
class CAsmOutput : public COutput
{
public:
CAsmOutput(CFileOut *pfOutput)
: COutput(pfOutput)
{
}
void Dump(PBYTE pbData, UINT cbData)
{
PBYTE pbEnd = pbData + cbData;
for (; pbData < pbEnd; pbData++, m_nOffset++) {
switch (m_nOffset % 16) {
case 0:
Print(" uint8 %03xh", *pbData);
break;
default:
Print(",%03xh", *pbData);
break;
case 15:
Print(",%03xh\n", *pbData);
break;
}
}
}
};
class CSharpOutput : public COutput
{
public:
CSharpOutput(CFileOut *pfOutput)
: COutput(pfOutput)
{
}
void Dump(PBYTE pbData, UINT cbData)
{
PBYTE pbEnd = pbData + cbData;
for (; pbData < pbEnd; pbData++, m_nOffset++) {
switch (m_nOffset % 16) {
case 0:
Print(" 0x%02x,", *pbData);
break;
default:
Print("0x%02x,", *pbData);
break;
case 15:
Print("0x%02x,\n", *pbData);
break;
}
}
}
};
//////////////////////////////////////////////////////////////////////////////
//
UINT DumpBmp(const char *pszFile, COutput *output, PBYTE pbData, UINT cbData)
{
#pragma pack(2)
struct BITMAPFILEHEADER {
UINT16 bfType;
UINT32 bfSize;
UINT16 bfReserved1;
UINT16 bfReserved2;
UINT32 bfOffBits;
};
struct BITMAPINFOHEADER {
UINT32 biSize;
UINT32 biWidth;
UINT32 biHeight;
UINT16 biPlanes;
UINT16 biBitCount;
UINT32 biCompression;
UINT32 biSizeImage;
UINT32 biXPelsPerMeter;
UINT32 biYPelsPerMeter;
UINT32 biClrUsed;
UINT32 biClrImportant;
};
#pragma pack()
BITMAPFILEHEADER *pbmf = (BITMAPFILEHEADER *)pbData;
BITMAPINFOHEADER *pbmi = (BITMAPINFOHEADER *)(pbmf + 1);
if (pbmf->bfType != 'MB') {
fprintf(stderr, "Can't convert non-BMP files to BMP compression.\n");
return 0;
}
UINT cbDumped = 0;
INT16 nValue;
UINT cbScanLine = (((pbmi->biWidth * pbmi->biBitCount) + 31) & ~31) / 8;
PBYTE pbLine = pbData + pbmf->bfOffBits;
//PBYTE pbOut = pbData + pbmf->bfOffBits;
pbmi->biCompression |= 0xff000000;
if (output != NULL) {
output->Dump(pbData, pbmf->bfOffBits);
}
cbDumped += pbmf->bfOffBits;
for (UINT i = 0; i < pbmi->biHeight; i++) {
PBYTE pbIn = pbLine;
PBYTE pbRaw = pbIn;
PBYTE pbEnd = pbLine + cbScanLine;
while (pbIn < pbEnd) {
if (pbIn + 6 < pbEnd &&
pbIn[3] == pbIn[0] &&
pbIn[4] == pbIn[1] &&
pbIn[5] == pbIn[2]) {
PBYTE pbBase = pbIn;
pbIn += 3;
while (pbIn + 3 <= pbEnd &&
pbIn[0] == pbBase[0] &&
pbIn[1] == pbBase[1] &&
pbIn[2] == pbBase[2]) {
pbIn += 3;
}
if (pbBase > pbRaw) {
nValue = (INT16)(pbBase - pbRaw);
if (output != NULL) {
output->Dump((PBYTE)&nValue, sizeof(nValue));
output->Dump(pbRaw, pbBase - pbRaw);
}
cbDumped += sizeof(nValue);
cbDumped += pbBase - pbRaw;
}
nValue = (INT16)(-((pbIn - pbBase) / 3));
if (output != NULL) {
output->Dump((PBYTE)&nValue, sizeof(nValue));
output->Dump(pbBase, 3);
}
cbDumped += sizeof(nValue);
cbDumped += 3;
pbRaw = pbIn;
}
else {
pbIn++;
}
}
if (pbEnd > pbRaw) {
nValue = (INT16)(pbEnd - pbRaw);
if (output != NULL) {
output->Dump((PBYTE)&nValue, sizeof(nValue));
output->Dump(pbRaw, pbEnd - pbRaw);
}
cbDumped += sizeof(nValue);
cbDumped += pbEnd - pbRaw;
}
pbLine += cbScanLine;
}
if (output != NULL) {
printf(" %s from %8d to %8d bytes\n", pszFile, cbData, cbDumped);
if (output->Size() != cbDumped) {
fprintf(stderr, "Failure in compression: %d reported, %d written\n",
cbDumped, output->Size());
}
output->Finish();
}
return cbDumped;
}
char *find_contents64(CFileMap *pfFile,
PIMAGE_NT_HEADERS64 ppe,
UINT32 *pcbEntry,
UINT32 *pcbBase,
UINT32 *pcbSize,
PBYTE *ppbData)
{
PIMAGE_SECTION_HEADER psec;
fprintf(stderr,"Processing a 64-bit image.\n");
psec = IMAGE_FIRST_SECTION(ppe);
if (ppe->FileHeader.NumberOfSections != 1) {
fprintf(stderr, "Warning: More than one section (.pdata)\n");
}
if (ppe->OptionalHeader.SizeOfInitializedData != 0) {
fprintf(stderr, "Image has initialized data outside of text section.\n");
}
if (ppe->OptionalHeader.SizeOfUninitializedData != 0) {
return "Image has uninitialized data outside of text section.";
}
if (psec->PointerToRawData == 0) {
return "Image has no text content.";
}
if (pfFile->Seek(psec->PointerToRawData) == NULL) {
return "Image text section is invalid.";
}
*pcbEntry =(UINT32) ppe->OptionalHeader.ImageBase + ppe->OptionalHeader.AddressOfEntryPoint;
*pcbBase = (UINT32) ppe->OptionalHeader.ImageBase;
*pcbSize = ppe->OptionalHeader.SizeOfImage;
*ppbData = pfFile->Seek(0);
return NULL;
}
char *find_contents32(CFileMap *pfFile,
PIMAGE_NT_HEADERS ppe,
UINT32 *pcbEntry,
UINT32 *pcbBase,
UINT32 *pcbSize,
PBYTE *ppbData)
{
PIMAGE_SECTION_HEADER psec;
psec = IMAGE_FIRST_SECTION(ppe);
if (ppe->FileHeader.NumberOfSections != 1) {
return "Image has more than one sections.";
}
if (ppe->OptionalHeader.SizeOfInitializedData != 0) {
return "Image has initialized data outside of text section.";
}
if (ppe->OptionalHeader.SizeOfUninitializedData != 0) {
return "Image has uninitialized data outside of text section.";
}
if (psec->PointerToRawData == 0) {
return "Image has no text content.";
}
if (pfFile->Seek(psec->PointerToRawData) == NULL) {
return "Image text section is invalid.";
}
*pcbEntry = ppe->OptionalHeader.ImageBase + ppe->OptionalHeader.AddressOfEntryPoint;
*pcbBase = ppe->OptionalHeader.ImageBase;
*pcbSize = ppe->OptionalHeader.SizeOfImage;
*ppbData = pfFile->Seek(0);
return NULL;
}
char *find_contents(CFileMap *pfFile,
UINT32 *pcbEntry,
UINT32 *pcbBase,
UINT32 *pcbSize,
PBYTE *ppbData)
{
PIMAGE_DOS_HEADER pdos;
PIMAGE_NT_HEADERS ppe;
//PIMAGE_NT_HEADERS64 ppe64;
*pcbEntry = 0;
*pcbBase = 0;
*pcbSize = 0;
*ppbData = NULL;
// Read in the PE image header
//
pdos = (PIMAGE_DOS_HEADER)pfFile->Seek(0);
if (pdos == NULL || pdos->e_magic != IMAGE_DOS_SIGNATURE) {
return "Image doesn't have MZ signature.";
}
ppe = (PIMAGE_NT_HEADERS)pfFile->Seek(pdos->e_lfanew);
if (ppe == NULL || ppe->Signature != IMAGE_NT_SIGNATURE) {
return "Image doesn't have PE signature.";
}
if (ppe->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) {
if (fAllow64) {
return find_contents64(pfFile, (PIMAGE_NT_HEADERS64) ppe, pcbEntry, pcbBase, pcbSize, ppbData);
}
else {
return "Image is 64-bit. Use /64 option";
}
}
else return find_contents32(pfFile, ppe, pcbEntry, pcbBase, pcbSize, ppbData);
}
BOOL dump_pe(COutput *pOutput, CFileMap *pInput, PCSTR pszRoot)
{
UINT32 cbEntry = 0;
UINT32 cbBase = 0;
UINT32 cbSize = 0;
PBYTE pbData = NULL;
char *error = find_contents(pInput, &cbEntry, &cbBase, &cbSize, &pbData);
if (error != NULL) {
fprintf(stderr, "Failed: %s\n", error);
return FALSE;
}
if (cbEntry < cbBase || cbEntry >= cbBase + cbSize) {
fprintf(stderr, "Failed: Image entry point is not in text section.");
return FALSE;
}
if (cbBase < TARGET_BASE || cbBase > TARGET_BASE + TARGET_RANGE) {
fprintf(stderr, "Failed: Image is not based at 0x%x.\n", TARGET_BASE);
return FALSE;
}
printf("Total text section: %d bytes\n", cbSize);
// Write .asm data.
//
pOutput->Print("%s_ent EQU 0%08xh\n", pszRoot, cbEntry);
pOutput->Print("%s_dst EQU 0%08xh\n", pszRoot, cbBase);
pOutput->Print("%s_siz EQU 0%08xh\n", pszRoot, cbSize);
pOutput->Print("%s_dat ", pszRoot);
pOutput->Dump(pbData, cbSize);
pOutput->Finish();
pOutput->Print("\n");
return TRUE;
}
BOOL blob_to_asm(COutput *pOutput, CFileMap *pInput)
{
// Copy the rest of the image.
//
pOutput->Dump(pInput->Seek(0), pInput->Size());
pOutput->Finish();
return TRUE;
}
int CompareName(PCSTR psz1, PCSTR psz2)
{
for (;;) {
CHAR c1 = *psz1;
CHAR c2 = *psz2;
if (c1 >= 'A' && c1 <= 'Z') {
c1 = c1 - 'A' + 'a';
}
if (c2 >= 'A' && c2 <= 'Z') {
c2 = c2 - 'A' + 'a';
}
if ((c1 >= '0' && c1 <= '9') && (c2 >= '0' && c2 <= '9')) {
for (c1 = 0; *psz1 >= '0' && *psz1 <= '9'; psz1++) {
c1 = c1 * 10 + (*psz1 - '0');
}
psz1--;
for (c2 = 0; *psz2 >= '0' && *psz2 <= '9'; psz2++) {
c2 = c2 * 10 + (*psz2 - '0');
}
psz2--;
}
if (c1 != c2) {
return c1 - c2;
}
if (c1 == 0 && c2 == 0) {
return 0;
}
psz1++;
psz2++;
}
}
PCHAR AppendToName(PCHAR pszDst, PCSTR pszSrc)
{
while (*pszSrc) {
if (*pszSrc == '.') {
*pszDst++ = '_';
pszSrc++;
}
else {
*pszDst++ = *pszSrc++;
}
}
return pszDst;
}
void AsmName(PCHAR pszAsmName, PCSTR pszNamespace, PCSTR pszClass, PCSTR pszField)
{
pszAsmName = AppendToName(pszAsmName, "?c_");
pszAsmName = AppendToName(pszAsmName, pszField);
pszAsmName = AppendToName(pszAsmName, "@Class_");
pszAsmName = AppendToName(pszAsmName, pszNamespace);
pszAsmName = AppendToName(pszAsmName, "_");
pszAsmName = AppendToName(pszAsmName, pszClass);
*pszAsmName = '\0';
}
void CppClassName(PCHAR pszCppClassName, PCSTR pszNamespace, PCSTR pszClass)
{
pszCppClassName = AppendToName(pszCppClassName, "Class_");
pszCppClassName = AppendToName(pszCppClassName, pszNamespace);
pszCppClassName = AppendToName(pszCppClassName, "_");
pszCppClassName = AppendToName(pszCppClassName, pszClass);
*pszCppClassName = '\0';
}
int __cdecl main(int argc, char **argv)
{
BOOL fNeedHelp = FALSE;
BOOL fFlattenPE = TRUE;
PCSTR pszRoot = "asm";
CFileOut cfOutput;
CFileInfo rFiles[512];
CFileInfo *pFiles = NULL;
UINT cFiles = 0;
CHAR szField[256] = "";
CHAR szClass[512] = "";
CHAR szNamespace[512] = "";
CHAR szAsmName[1024];
CHAR szCppClassName[1024];
for (int arg = 1; arg < argc; arg++) {
if (argv[arg][0] == '-' || argv[arg][0] == '/') {
char *argn = argv[arg]+1; // Argument name
char *argp = argn; // Argument parameter
while (*argp && *argp != ':')
argp++;
if (*argp == ':')
*argp++ = '\0';
switch (argn[0]) {
case 'a': // ASM Format
case 'A':
fAsm = TRUE;
break;
case 'b': // Binary Blob
case 'B':
fFlattenPE = FALSE;
fManaged = TRUE;
break;
case 'c': // C# Class
case 'C':
strcpy(szClass, argp);
fManaged = TRUE;
break;
case 'f': // C# Field
case 'F':
strcpy(szField, argp);
fManaged = TRUE;
break;
case 'l': // List of files
case 'L':
fManaged = TRUE;
fList = TRUE;
break;
case 'm': // C# Format
case 'M':
fAsm = FALSE;
break;
case 'n': // C# Namespace
case 'N':
strcpy(szNamespace, argp);
fManaged = TRUE;
break;
case 'o': // Output file.
case 'O':
if (!cfOutput.Create(argp)) {
fprintf(stderr, "Could not open output file: %s\n", argp);
}
break;
case 'p': // Cpp Format
case 'P':
fCpp = TRUE;
fAsm = FALSE;
break;
case 'r': // Set Label Root
case 'R':
pszRoot = argp;
break;
case 'x': // Compress BMP
case 'X': //
fCompress = TRUE;
fManaged = TRUE;
break;
case '6': // 64-bit PE
fAllow64 = TRUE;
break;
case 'h': // Help
case 'H':
case '?':
fNeedHelp = TRUE;
break;
default:
printf("Unknown argument: %s\n", argv[arg]);
fNeedHelp = TRUE;
break;
}
}
else {
// Save the input files away in sorted linked list.
CFileInfo *pNew = &rFiles[cFiles++];
CFileInfo **ppHead = &pFiles;
pNew->SetFileName(argv[arg]);
while (*ppHead != NULL && CompareName(pNew->m_pszFile, (*ppHead)->m_pszFile) > 0) {
ppHead = &(*ppHead)->m_pNext;
}
pNew->m_pNext = *ppHead;
*ppHead = pNew;
}
}
if (argc == 1) {
fNeedHelp = TRUE;
}
if (!fNeedHelp && !cfOutput.IsOpen()) {
fprintf(stderr, "No output file specified.\n");
fNeedHelp = TRUE;
}
if (!fNeedHelp && pFiles == NULL) {
fprintf(stderr, "No output file specified.\n");
fNeedHelp = TRUE;
}
if (!fNeedHelp && fManaged &&
(szField[0] == '\0' || szClass[0] == '\0')) {
fprintf(stderr, "No field or class name specified for target.\n");
fNeedHelp = TRUE;
}
if (fNeedHelp) {
printf(
"Usage:\n"
" mkasm /o:output [options] inputs\n"
"Options:\n"
" /o:output -- Specify output file.\n"
" /r:root -- Set root label [defaults to `asm'].\n"
" /b -- Treat file as binary blob (not PE file).\n"
" /a -- Output ASM format (default for PE).\n"
" /m -- Output C# format (default for blob).\n"
" /c:class -- Set C# class.\n"
" /n:namespace -- Set C# namespace.\n"
" /f:field -- Set C# field.\n"
" /x -- Use bizarre compression for BMP files.\n"
" /l -- Output contents in an array (list).\n"
" /64 -- manipulate 64-bit PE files."
" /h or /? -- Display this help screen.\n"
"Summary:\n"
" Copies the contents of the input files into the output file\n"
" in .asm format. Specific conversions exists for PE and BMP files.\n"
);
return 2;
}
//////////////////////////////////////////////////////////////////////////
//
// At this point, we have input file(s), output file, and set of desired
// conversions. Time to process the output.
//
BOOL fAbort = false;
COutput *pOutput = NULL;
CAsmOutput asmOutput(&cfOutput);
CSharpOutput sharpOutput(&cfOutput);
AsmName(szAsmName, szNamespace, szClass, szField);
CppClassName(szCppClassName, szNamespace, szClass);
if (fAsm) {
pOutput = &asmOutput;
}
else {
pOutput = &sharpOutput;
}
ULONG cbFiles = 0;
UINT cFile = 0;
for (CFileInfo *pFile = pFiles; pFile != NULL; pFile = pFile->m_pNext) {
if (!pFile->SetFileAndSize()) {
fprintf(stderr, "Unable to open %s, error = %d\n",
pFile->m_pszFile,
GetLastError());
goto abort;
}
if (fCompress) {
CFileMap cfInput;
printf(".");
if (!cfInput.Load(pFile->m_pszFile)) {
fprintf(stderr, "Could not open input file: %s\n", pFile->m_pszFile);
goto abort;
}
pFile->SetOutputSize(DumpBmp(pFile->m_pszFile, NULL, cfInput.Seek(0), cfInput.Size()));
cfInput.Close();
}
cFile++;
cbFiles += pFile->m_cbOutput;
}
//public: static struct ClassVector_ClassVector_uint8 *
// Class_Microsoft_Singularity_Shell_Slides::c_Content;
//" (?c_Content@Class_Microsoft_Singularity_Shell_Slides@@2PAUClassVector_ClassVector_uint8@@A
if (!fFlattenPE) {
if (fAsm) {
cfOutput.Print("externdef %s:NEAR\n", szByteVTable);
if (fList) {
cfOutput.Print("externdef %s:NEAR\n", szByteByteVTable);
}
else {
cfOutput.Print("align 4\n");
cfOutput.Print(" BARTOK_OBJECT_HEADER {} \n");
cfOutput.Print("%s%s_0 UINT32 %s\n",
szAsmName, szByteSuffix, szByteVTable);
cfOutput.Print(" UINT32 %d\n", cbFiles);
}
}
else if (fCpp) {
if (fList) {
cFile = 0;
for (CFileInfo *pFile = pFiles; pFile != NULL; pFile = pFile->m_pNext) {
cfOutput.Print("struct Vector_%s_%s_0_%d {\n",
szCppClassName, szField, cFile);
cfOutput.Print(" uintptr headerwords[HDRWORDCOUNT];\n");
cfOutput.Print(" union {\n");
cfOutput.Print(" struct {\n");
cfOutput.Print(" Class_System_VTable * vtable;\n");
cfOutput.Print(" uint32 length;\n");
cfOutput.Print(" uint8 data[%d];\n",
pFile->m_cbOutput);
cfOutput.Print(" };\n");
cfOutput.Print(" ClassVector_uint8 object;\n");
cfOutput.Print(" };\n");
cfOutput.Print("};\n");
cFile++;
}
cfOutput.Print("struct Vector_%s_%s_0 {\n",
szCppClassName, szField);
cfOutput.Print(" uintptr headerwords[HDRWORDCOUNT];\n");
cfOutput.Print(" union {\n");
cfOutput.Print(" struct {\n");
cfOutput.Print(" Class_System_VTable * vtable;\n");
cfOutput.Print(" uint32 length;\n");
cfOutput.Print(" ClassVector_uint8 * data[%d];\n", cFiles);
cfOutput.Print(" };\n");
cfOutput.Print(" ClassVector_ClassVector_uint8 object;\n");
cfOutput.Print(" };\n");
cfOutput.Print("};\n");
cfOutput.Print("struct %s {\n", szCppClassName);
cfOutput.Print(" private:\n");
for (UINT i = 0; i < cFiles; i++) {
cfOutput.Print(" static Vector_%s_%s_0_%d c_%s_0_%d;\n",
szCppClassName, szField, i,
szField, i);
}
cfOutput.Print(" static Vector_%s_%s_0 c_%s_0;\n",
szCppClassName, szField, szField);
cfOutput.Print(" public:\n");
cfOutput.Print(" static ClassVector_ClassVector_uint8 * c_%s;\n", szField);
cfOutput.Print("};\n");
cfOutput.Print("\n");
cfOutput.Print("ClassVector_ClassVector_uint8 * %s::c_%s = &%s::c_%s_0.object;\n",
szCppClassName, szField,
szCppClassName, szField);
cfOutput.Print("\n");
cfOutput.Print("Vector_%s_%s_0 %s::c_%s_0 = {\n",
szCppClassName, szField,
szCppClassName, szField);
cfOutput.Print(" {},\n");
cfOutput.Print(" (Class_System_VTable *)&ClassVector_ClassVector_uint8::_vtable,\n");
cfOutput.Print(" %d,\n", cFiles);
cfOutput.Print(" {\n");
for (UINT i = 0; i < cFiles; i++) {
cfOutput.Print(" &%s::c_%s_0_%d.object,\n",
szCppClassName, szField, i);
}
cfOutput.Print(" },\n");
cfOutput.Print("};\n");
cfOutput.Print("\n");
}
else {
cfOutput.Print("struct Vector_%s_%s_0 {\n",
szCppClassName, szField);
cfOutput.Print(" uintptr headerwords[HDRWORDCOUNT];\n");
cfOutput.Print(" union { \n");
cfOutput.Print(" struct {\n");
cfOutput.Print(" Class_System_VTable * vtable;\n");
cfOutput.Print(" uint32 length;\n");
cfOutput.Print(" uint8 data[%d];\n",
cbFiles);
cfOutput.Print(" };\n");
cfOutput.Print(" ClassVector_uint8 object;\n");
cfOutput.Print(" };\n");
cfOutput.Print("};\n");
cfOutput.Print("struct %s {\n", szCppClassName);
cfOutput.Print(" private:\n");
cfOutput.Print(" static Vector_%s_%s_0 c_%s_0;\n",
szCppClassName, szField, szField);
cfOutput.Print(" public:\n");
cfOutput.Print(" static ClassVector_uint8 * c_%s;\n", szField);
cfOutput.Print("};\n");
cfOutput.Print("\n");
cfOutput.Print("ClassVector_uint8 * %s::c_%s = &%s::c_%s_0.object;\n",
szCppClassName, szField,
szCppClassName, szField);
cfOutput.Print("\n");
cfOutput.Print("Vector_%s_%s_0 %s::c_%s_0 = {\n",
szCppClassName, szField,
szCppClassName, szField);
cfOutput.Print(" {},\n");
cfOutput.Print(" (Class_System_VTable *)&ClassVector_uint8::_vtable,\n");
cfOutput.Print(" %d,\n", cbFiles);
cfOutput.Print(" {\n");
}
}
else {
if (szNamespace) {
cfOutput.Print("namespace %s {\n", szNamespace);
}
cfOutput.Print(" public class %s {\n", szClass);
if (fList) {
cfOutput.Print(" public static readonly byte[][] %s = {\n", szField);
}
else {
cfOutput.Print(" public static readonly byte[] %s = {\n", szField);
}
}
}
cFile = 0;
for (CFileInfo *pFile = pFiles; pFile != NULL; pFile = pFile->m_pNext) {
CFileMap cfInput;
printf(".");
if (!cfInput.Load(pFile->m_pszFile)) {
fprintf(stderr, "Could not open input file: %s\n", pFile->m_pszFile);
goto abort;
}
if (fFlattenPE) {
// Flatten PE file
if (!dump_pe(pOutput, &cfInput, pszRoot)) {
goto abort;
}
}
else {
if (fAsm) {
if (fList) {
cfOutput.Print("\n");
cfOutput.Print("align 4\n");
cfOutput.Print(" BARTOK_OBJECT_HEADER {} \n");
cfOutput.Print("%s%s_0_%d UINT32 %s\n",
szAsmName,
szByteSuffix,
cFile,
szByteVTable);
cfOutput.Print(" UINT32 %d\n", cfInput.Size());
}
}
else if (fCpp) {
if (fList) {
cfOutput.Print("Vector_%s_%s_0_%d %s::c_%s_0_%d = {\n",
szCppClassName, szField, cFile,
szCppClassName, szField, cFile);
cfOutput.Print(" {},\n");
cfOutput.Print(" (Class_System_VTable *)&ClassVector_uint8::_vtable,\n");
cfOutput.Print(" %d,\n", cfInput.Size());
cfOutput.Print(" {\n");
}
}
else {
if (fList) {
cfOutput.Print(" new byte[] {\n");
}
}
if (fCompress) {
if (!DumpBmp(pFile->m_pszFile, pOutput, cfInput.Seek(0), cfInput.Size())) {
goto abort;
}
}
else {
pOutput->Dump(cfInput.Seek(0), cfInput.Size());
pOutput->Finish();
}
if (fAsm) {
}
else if (fCpp) {
if (fList) {
cfOutput.Print(" },\n");
cfOutput.Print("};\n");
cfOutput.Print("\n");
}
}
else {
if (fList) {
cfOutput.Print(" },\n");
}
}
}
cfInput.Close();
cFile++;
}
if (!fFlattenPE) {
if (fAsm) {
if (fList) {
// create list array at end.
cfOutput.Print("\n");
cfOutput.Print("align 4\n");
cfOutput.Print(" BARTOK_OBJECT_HEADER {} \n");
cfOutput.Print("public %s%s\n",
szAsmName,
szByteByteSuffix);
cfOutput.Print("%s%s_0 UINT32 %s\n",
szAsmName,
szByteByteSuffix,
szByteByteVTable);
cfOutput.Print(" UINT32 %d\n", cFiles);
for (UINT i = 0; i < cFiles; i++) {
cfOutput.Print(" UINT32 %s%s_0_%d\n",
szAsmName,
szByteSuffix,
i);
}
cfOutput.Print("\n");
cfOutput.Print("align 4\n");
cfOutput.Print("public %s%s\n",
szAsmName,
szByteByteSuffix);
cfOutput.Print("%s%s UINT32 %s%s_0\n",
szAsmName,
szByteByteSuffix,
szAsmName,
szByteByteSuffix);
}
else {
cfOutput.Print("\n");
cfOutput.Print("align 4\n");
cfOutput.Print("public %s%s\n",
szAsmName,
szByteSuffix);
cfOutput.Print("%s%s UINT32 %s%s_0\n",
szAsmName,
szByteSuffix,
szAsmName,
szByteSuffix);
}
}
else if (fCpp) {
if (!fList) {
cfOutput.Print(" },\n");
cfOutput.Print("};\n");
cfOutput.Print("\n");
}
}
else
{
cfOutput.Print(" };\n");
cfOutput.Print(" }\n");
cfOutput.Print("}\n");
}
}
if (fAbort) {
abort:
cfOutput.Delete();
return 1;
}
cfOutput.Close();
return 0;
}
//
///////////////////////////////////////////////////////////////// End of File.
| 30.839526 | 108 | 0.442069 | sphinxlogic |
40512a04b2c36385e8cac51dd37f45aaccd077f2 | 7,659 | cpp | C++ | source/tools/Utils/attachLauncher_unix.cpp | NVSL/CSE141pp-Tool-Moneta-Pin | d1f7a1e2aa5ac724cc64fa65f30b1e424a4ad839 | [
"Intel"
] | 17 | 2021-07-10T13:22:26.000Z | 2022-02-09T20:11:39.000Z | source/tools/Utils/attachLauncher_unix.cpp | NVSL/CSE141pp-Tool-Moneta-Pin | d1f7a1e2aa5ac724cc64fa65f30b1e424a4ad839 | [
"Intel"
] | 4 | 2021-08-18T14:07:24.000Z | 2022-01-24T16:38:06.000Z | source/tools/Utils/attachLauncher_unix.cpp | NVSL/CSE141pp-Tool-Moneta-Pin | d1f7a1e2aa5ac724cc64fa65f30b1e424a4ad839 | [
"Intel"
] | 2 | 2021-08-03T10:56:16.000Z | 2022-01-31T12:10:56.000Z | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2015 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
using std::string;
using std::stringstream;
static void ParseArguments(const int argc, const char* argv[], vector<string>& pinCmd, vector<string>& appCmd)
{
if (argc < 4)
{
cerr << "LAUNCHER ERROR: Too few arguments to the launcher. Expected at least the following:" << endl
<< " <launcher> <pin> -- <app>" << endl;
exit(1);
}
const string pin(argv[1]);
if (string::npos == pin.find("pin"))
{
cerr << "LAUNCHER ERROR: Expected to find Pin as the first argument but found '" << pin << "' instead." << endl;
exit(1);
}
pinCmd.push_back(pin);
unsigned int i = 2;
for (; i < argc; ++i)
{
const string token(argv[i]);
if ("--" == token) break;
pinCmd.push_back(token);
}
if (argc == i)
{
cerr << "LAUNCHER ERROR: Could not find the application delimiter '--'." << endl;
exit(1);
}
for (++i; i < argc; ++i)
{
const string token(argv[i]);
appCmd.push_back(token);
}
}
static pid_t LaunchApp(const vector<string>& appCmd)
{
// Prepare the argument list.
const unsigned int appArgc = appCmd.size();
char** appArgv = new char*[appArgc + 1]; // additional slot for the NULL terminator
for (unsigned int i = 0; i < appArgc; ++i)
{
appArgv[i] = strdup(appCmd[i].c_str());
}
appArgv[appArgc] = NULL; // add the NULL terminator
// Launch the application.
const pid_t child = fork();
if (-1 == child)
{
perror("LAUNCHER ERROR: Failed to fork the application process");
exit(1);
}
else if (0 == child)
{
// In the child process.
cout << endl << "LAUNCHER: Running the application with pid [" << getpid() << "]:" << endl << appArgv[0];
for (unsigned int i = 1; NULL != appArgv[i]; ++i)
{
cout << " " << appArgv[i];
}
cout << endl;
const int res = execvp(appArgv[0], appArgv); // does not return on success
perror("LAUNCHER ERROR: In the child process. Failed to execute the application");
exit(1);
}
// In the parent process.
return child;
}
static pid_t LaunchPin(const vector<string>& pinCmd, const pid_t appPid)
{
// Prepare the argument list.
const unsigned int pinArgc = pinCmd.size();
char** pinArgv = new char*[pinArgc + 3]; // two additional slots: "-pid <appPid>" and one for the NULL terminator
pinArgv[0] = strdup(pinCmd[0].c_str());
// Add the attach arguments.
pinArgv[1] = "-pid";
stringstream appPidStrm; // prepare the application's pid as a string
appPidStrm << appPid;
pinArgv[2] = strdup(appPidStrm.str().c_str());
// Add the rest of the arguments for Pin (if they exist).
for (unsigned int origArgs = 1, newArgs = 3; origArgs < pinArgc; ++origArgs, ++newArgs)
{
pinArgv[newArgs] = strdup(pinCmd[origArgs].c_str());
}
pinArgv[pinArgc + 2] = NULL; // add the NULL terminator
// Launch Pin.
const pid_t child = fork();
if (-1 == child)
{
perror("LAUNCHER ERROR: Failed to fork the Pin process");
exit(1);
}
else if (0 == child)
{
// In the child process.
cout << endl << "LAUNCHER: Running Pin:" << endl << pinArgv[0];
for (unsigned int i = 1; NULL != pinArgv[i]; ++i)
{
cout << " " << pinArgv[i];
}
cout << endl << endl;
const int res = execvp(pinArgv[0], pinArgv); // does not return on success
perror("LAUNCHER ERROR: In the child process. Failed to execute Pin");
exit(1);
}
// In the parent process.
return child;
}
static void WaitForPin(const pid_t pinPid, const pid_t appPid)
{
int pinStatus = 0;
if (pinPid != waitpid(pinPid, &pinStatus, 0))
{
perror("LAUNCHER ERROR: Encountered an error while waiting for Pin to exit");
kill(pinPid, SIGKILL);
kill(appPid, SIGKILL);
exit(1);
}
if (!WIFEXITED(pinStatus))
{
cerr << "LAUNCHER ERROR: The Pin process sent a notification to the launcher without exiting." << endl;
kill(pinPid, SIGKILL);
kill(appPid, SIGKILL);
exit(1);
}
else
{
int pinCode = WEXITSTATUS(pinStatus);
if (0 != pinCode)
{
cerr << "LAUNCHER ERROR: Pin exited with an abnormal return value: " << pinCode << endl;
kill(appPid, SIGKILL);
exit(pinCode);
}
}
}
static void WaitForApp(const pid_t appPid)
{
int appStatus = 0;
if (appPid != waitpid(appPid, &appStatus, 0))
{
perror("LAUNCHER ERROR: Encountered an error while waiting for the application to exit");
kill(appPid, SIGKILL);
exit(1);
}
if (!WIFEXITED(appStatus))
{
cerr << "LAUNCHER ERROR: The application sent a notification to the launcher without exiting." << endl;
kill(appPid, SIGKILL);
exit(1);
}
else
{
int appCode = WEXITSTATUS(appStatus);
if (0 != appCode)
{
cerr << "LAUNCHER ERROR: The application exited with an abnormal return value: " << appCode << endl;
exit(appCode);
}
}
}
int main(const int argc, const char* argv[])
{
// Parse the given command line and break it down to Pin and application command lines.
vector<string> pinCmd;
vector<string> appCmd;
ParseArguments(argc, argv, pinCmd, appCmd);
// Launch the application.
const pid_t appPid = LaunchApp(appCmd);
// Launch Pin and attach to the application.
const pid_t pinPid = LaunchPin(pinCmd, appPid);
// Wait for Pin to return.
WaitForPin(pinPid, appPid);
// Wait for the application to return.
WaitForApp(appPid);
// Done.
return 0;
}
| 30.883065 | 120 | 0.629456 | NVSL |
405396e66314ec1ed90f2cb15bc897c67975492d | 149 | cpp | C++ | src/rigidbody_contact.cpp | robdan7/Impact | 75dfce522b569bbd2f4dfb549aa78d2196c8e793 | [
"MIT"
] | null | null | null | src/rigidbody_contact.cpp | robdan7/Impact | 75dfce522b569bbd2f4dfb549aa78d2196c8e793 | [
"MIT"
] | null | null | null | src/rigidbody_contact.cpp | robdan7/Impact | 75dfce522b569bbd2f4dfb549aa78d2196c8e793 | [
"MIT"
] | null | null | null | //
// Created by Robin on 2021-05-31.
//
#include "rigidbody_contact.h"
namespace Impact {
void Rigidbody_contact::resolve_impulse() {
}
}
| 13.545455 | 47 | 0.671141 | robdan7 |
4053dab3cc966705393d1a380ea57d96ef730e04 | 10,505 | cpp | C++ | Core/Src/usb/usb.cpp | shima-529/BareMetalUSB_STM32F042 | 887b2bc9d377bf17ce7585efd0c954f5d285fbef | [
"MIT"
] | 1 | 2021-05-21T02:53:37.000Z | 2021-05-21T02:53:37.000Z | Core/Src/usb/usb.cpp | shima-529/BareMetalUSB_STM32F042 | 887b2bc9d377bf17ce7585efd0c954f5d285fbef | [
"MIT"
] | null | null | null | Core/Src/usb/usb.cpp | shima-529/BareMetalUSB_STM32F042 | 887b2bc9d377bf17ce7585efd0c954f5d285fbef | [
"MIT"
] | 1 | 2021-09-20T02:43:15.000Z | 2021-09-20T02:43:15.000Z | #include <usb/usb.hpp>
#include "stm32f0xx.h"
#include <algorithm>
#include <cstdio>
#include <usb/utils.hpp>
#include <usb_desc/usb_desc_struct.h>
#include <usb_desc/usb_desc.h>
#include <usb/usb_struct.h>
#define printf(...)
/* Pointer Notation
* - type = uintptr_t : This is an pointer for PMA.
* Local offset of PMA is stored.
* - type = void * or others
* : This is an pointer for main memory.
*/
// External Descriptors {{{
// }}}
alignas(2) static uint8_t line_coding_info[7];
// Some macros {{{
enum USBSetupPacketRequest {
GET_STATUS = 0, CLEAR_FEATURE = 1, SET_FEATURE = 3,
SET_ADDRESS = 5, GET_DESCRIPTOR = 6, SET_DESCRIPTOR = 7,
GET_CONFIGURATION = 8, SET_CONFIGURATION = 9,
GET_INTERFACE = 10, SET_INTERFACE = 11, SYNCH_FRAME = 12,
CDC_SET_LINECODING = 0x20,
CDC_GET_LINECODING = 0x21,
CDC_SET_CONTROLLINESTATE = 0x22,
CDC_SEND_BREAK = 0x23,
CDC_SERIALSTATE = 0xA1
};
enum USBDescriptorType {
DEVICE = 1, CONFIGURATION = 2, STRING = 3, INTERFACE = 4,
ENDPOINT = 5, DEVICE_QUALIFIER = 6,
OTHER_SPEED_CONFIGURATION = 7, INTERFACE_POWER = 8,
};
enum USBHIDDescriptorType {
HID_REPORT = 0x22,
};
// }}}
PMAInfo pma_allocation_info;
USBEndpointInfo ep_info[4];
static USB_EP0Info ep0_data;
static USB_InitType init;
// Init global Funcs {{{
void usb_init(USB_InitType init) {
RCC->APB1ENR |= RCC_APB1ENR_USBEN;
USB->CNTR &= ~USB_CNTR_PDWN;
for(volatile int i=0; i<100; i++); // wait for voltage to be stable
USB->CNTR &= ~USB_CNTR_FRES;
USB->BCDR |= USB_BCDR_DPPU; // pull-up DP so as to notify the connection to the host
USB->CNTR = USB_CNTR_RESETM; // enable reset interrupt
NVIC_SetPriority(USB_IRQn, 0); // Highest Priority
NVIC_EnableIRQ(USB_IRQn);
::init = init;
}
// }}}
// Fundamental xfer/recv Funcs {{{
static void usb_ep_set_status(int endp, uint16_t status, uint16_t mask) {
const auto reg = USB_EPnR(endp);
USB_EPnR(endp) = (reg & (USB_EPREG_MASK | mask)) ^ status;
}
void usb_ep_send(int ep_num, uint16_t addr, uint16_t size) {
ep_info[ep_num].pb_ptr->addr_tx = addr;
ep_info[ep_num].pb_ptr->count_tx = size;
usb_ep_set_status(ep_num, USB_EP_TX_VALID, USB_EPTX_STAT);
}
void usb_ep_receive(int ep_num, uint16_t addr, uint16_t size) {
if( ep_info[ep_num].pb_ptr->addr_rx == 0 ) {
ep_info[ep_num].pb_ptr->addr_rx = addr;
if( size > 62 ) {
ep_info[ep_num].pb_ptr->count_rx = ((size / 32) - 1) << 10;
ep_info[ep_num].pb_ptr->count_rx |= 1 << 15;
}else{
ep_info[ep_num].pb_ptr->count_rx = size << 10;
}
}
usb_ep_set_status(ep_num, USB_EP_RX_VALID, USB_EPRX_STAT);
}
// }}}
static void search_and_set_descriptor(uint16_t wValue) { // {{{
const auto desc_type = (wValue >> 8) & 0xFF;
auto& xfer_info = ep_info[0].xfer_info;
auto& offsets = pma_allocation_info.offsets;
switch( desc_type ) {
case DEVICE:
{
const auto len = init.dep.dev_desc->bLength;
if( offsets.device_desc == 0 ) {
offsets.device_desc = Utils::alloc(len);
Utils::pma_in(offsets.device_desc, init.dep.dev_desc, len);
}
xfer_info.ptr = offsets.device_desc;
xfer_info.whole_length = len;
break;
}
case CONFIGURATION:
{
const auto len = init.dep.conf_desc[2] | (init.dep.conf_desc[3] << 8);
if( offsets.config_desc == 0 ) {
offsets.config_desc = Utils::alloc(len);
Utils::pma_in(offsets.config_desc, init.dep.conf_desc, len);
}
xfer_info.ptr = offsets.config_desc;
xfer_info.whole_length = len;
break;
}
case STRING:
{
const auto desc_no = wValue & 0xFF;
const auto len = string_desc[desc_no].bLength;
if( offsets.string_desc[desc_no] == 0 ) {
offsets.string_desc[desc_no] = Utils::alloc(len);
Utils::pma_in(offsets.string_desc[desc_no], &string_desc[desc_no], len);
}
xfer_info.ptr = offsets.string_desc[desc_no];
xfer_info.whole_length = len;
break;
}
case HID_REPORT:
{
const auto index = ep0_data.last_setup.wIndex;
const auto len = init.dep.hid_report_desc_length[index];
if( offsets.report_desc[index] == 0 ) {
offsets.report_desc[index] = Utils::alloc(len);
Utils::pma_in(offsets.report_desc[index], init.dep.hid_report_desc[index], len);
}
xfer_info.ptr = offsets.report_desc[index];
xfer_info.whole_length = len;
break;
}
default:
break;
}
xfer_info.completed_length = 0;
} // }}}
static uint16_t linecoding_adddr;
// EP0 Handler/Preparer {{{
static void usb_ep0_handle_setup() {
static uint16_t device_state = 0;
static uint16_t state_addr = 0;
static uint8_t controllin_state = 0;
const auto& ep = ep_info[0];
auto& xfer_info = const_cast<decltype(ep_info[0])&>(ep).xfer_info;
const auto& last_setup = ep0_data.last_setup;
if( last_setup.bRequest == GET_DESCRIPTOR ) {
search_and_set_descriptor(last_setup.wValue);
usb_ep_send(0, xfer_info.ptr, std::min({last_setup.wLength, ep.packet_size, xfer_info.whole_length}));
}
if( last_setup.bRequest == GET_CONFIGURATION ) {
if( state_addr == 0 ) {
state_addr = Utils::alloc(1);
}
Utils::pma_in(state_addr, &device_state, 1);
xfer_info.ptr = state_addr;
xfer_info.whole_length = 1;
usb_ep_send(0, xfer_info.ptr, xfer_info.whole_length);
}
if( last_setup.bRequest == SET_CONFIGURATION ) {
device_state = last_setup.wValue;
}
if( last_setup.bRequest == CDC_SET_CONTROLLINESTATE ) {
controllin_state = last_setup.wValue;
(void)controllin_state;
}
if( last_setup.bRequest == CDC_SET_LINECODING ) {
if( linecoding_adddr == 0 ) {
linecoding_adddr = Utils::alloc(7);
}
usb_ep_receive(0, linecoding_adddr, 7);
}
}
static void usb_ep0_handle_status() {
if( ep0_data.last_setup.bRequest == SET_ADDRESS ) {
USB->DADDR = USB_DADDR_EF | (ep0_data.last_setup.wValue & 0x7F);
}
if( ep0_data.last_setup.bRequest == CDC_SET_LINECODING ) {
Utils::pma_out(line_coding_info, linecoding_adddr, 7);
printf("BaudRate: %d\n", line_coding_info[0] + (line_coding_info[1] << 8) + (line_coding_info[2] << 16) + (line_coding_info[3] << 24));
printf("bCharFormat: %d\n", line_coding_info[4]);
printf("bParityType: %d\n", line_coding_info[5]);
printf("bDataBits: %d\n", line_coding_info[6]);
}
}
static void usb_ep0_prepare_for_setup() {
if( pma_allocation_info.offsets.setup_packet == 0 ) {
pma_allocation_info.offsets.setup_packet = Utils::alloc(64);
}
usb_ep_receive(0, pma_allocation_info.offsets.setup_packet, sizeof(USBSetupPacket));
}
static void usb_ep0_prepare_for_next_in() {
// Now data is left to be xferred.
// This means the last IN transaction is completed but the data length is not enough.
auto& xfer_info = ep_info[0].xfer_info;
xfer_info.completed_length += ep_info[0].pb_ptr->count_tx;
const auto next_pos = xfer_info.completed_length + xfer_info.ptr;
usb_ep_send(0, next_pos, xfer_info.whole_length - ep_info[0].packet_size);
}
static void usb_ep0_prepare_for_status() {
if( ep0_data.fsm == EP_fsm::STATUS_OUT ) {
usb_ep_receive(0, ep_info[0].recv_info.ptr, 0);
}
if( ep0_data.fsm == EP_fsm::STATUS_IN ) {
usb_ep_send(0, ep_info[0].xfer_info.ptr, 0);
}
}
static void usb_ep0_handle_current_transaction() {
const auto now_state = ep0_data.fsm;
switch(now_state) {
case EP_fsm::SETUP:
usb_ep0_handle_setup();
break;
case EP_fsm::STATUS_IN:
case EP_fsm::STATUS_OUT:
usb_ep0_handle_status();
break;
default:
break;
}
}
static void usb_ep0_prepare_for_next_transaction() {
const auto next_state = ep0_data.fsm;
switch(next_state) {
case EP_fsm::REPETITIVE_IN:
usb_ep0_prepare_for_next_in();
break;
case EP_fsm::STATUS_IN:
case EP_fsm::STATUS_OUT:
usb_ep0_prepare_for_status();
break;
case EP_fsm::SETUP:
usb_ep0_prepare_for_setup();
break;
default:
break;
}
}
// }}}
static EP_fsm next_state_ep0() { // {{{
const auto& ep = ep_info[0];
const auto& last_setup = ep0_data.last_setup;
switch(ep0_data.fsm) {
case EP_fsm::SETUP:
if( last_setup.bmRequestType & 0x80 ) {
return (last_setup.wLength != 0) ? EP_fsm::IN : EP_fsm::STATUS_IN;
}else{
return (last_setup.wLength != 0) ? EP_fsm::OUT : EP_fsm::STATUS_IN;
}
break;
case EP_fsm::IN:
case EP_fsm::REPETITIVE_IN:
{
const auto& xfer_info = ep.xfer_info;
const bool cond = (ep_info[0].pb_ptr->count_tx == ep_info[0].packet_size);
const auto length_to_be_xferred = cond ? xfer_info.whole_length - xfer_info.completed_length : 0;
if( length_to_be_xferred > ep.packet_size ) {
return EP_fsm::REPETITIVE_IN;
}
return EP_fsm::STATUS_OUT;
break;
}
case EP_fsm::OUT:
return EP_fsm::STATUS_IN;
break;
default:
break;
}
return EP_fsm::SETUP;
} // }}}
extern "C" void USB_IRQHandler() {
auto flag = USB->ISTR;
if( flag & USB_ISTR_RESET ) {
printf("\nRESET\n");
USB->ISTR &= ~USB_ISTR_RESET;
USB->CNTR |= USB_CNTR_CTRM | USB_CNTR_RESETM;
pma_allocation_info = {};
USB->BTABLE = Utils::alloc(sizeof(PacketBuffer) * (init.nEndpoints + 1));
USB->DADDR = USB_DADDR_EF; // enable the functionality
// initialize EP0
ep0_data.fsm = EP_fsm::RESET;
ep_info[0].packet_size = 64;
ep_info[0].pb_ptr = reinterpret_cast<PacketBuffer *>(static_cast<uintptr_t>(USB->BTABLE) + USB_PMAADDR);
ep_info[0].pb_ptr->addr_rx = 0;
USB->EP0R = USB_EP_CONTROL;
usb_ep0_prepare_for_setup();
// Other EPs
for(int i = 0; i < init.nEndpoints; i++) {
const int ep_num = i + 1;
init.ep[i].init(ep_num);
}
}
while( (flag = USB->ISTR) & USB_ISTR_CTR ) {
const auto ep_num = flag & USB_ISTR_EP_ID;
const auto epreg = USB_EPnR(ep_num);
if( ep_num == 0 ) {
if( epreg & USB_EP_CTR_RX ) {
// DIR == 1 : IRQ by SETUP transaction. CTR_RX is set.
USB->EP0R = epreg & ~USB_EP_CTR_RX & USB_EPREG_MASK;
if( epreg & USB_EP_SETUP ) {
ep0_data.fsm = EP_fsm::SETUP;
Utils::pma_out(&ep0_data.last_setup, pma_allocation_info.offsets.setup_packet, sizeof(USBSetupPacket));
Utils::Dump::setup_packet();
}
Utils::Dump::fsm();
usb_ep0_handle_current_transaction();
}
if( epreg & USB_EP_CTR_TX ) {
// DIR = 0 : IRQ by IN direction. CTR_TX is set.
USB->EP0R = epreg & ~USB_EP_CTR_TX & USB_EPREG_MASK;
Utils::Dump::fsm();
usb_ep0_handle_current_transaction();
}
ep0_data.fsm = next_state_ep0();
usb_ep0_prepare_for_next_transaction();
}else{
if( epreg & USB_EP_CTR_TX ) {
USB_EPnR(ep_num) = epreg & ~USB_EP_CTR_TX & USB_EPREG_MASK;
init.ep[ep_num - 1].tx_handler(ep_num);
}
if( epreg & USB_EP_CTR_RX ) {
USB_EPnR(ep_num) = epreg & ~USB_EP_CTR_RX & USB_EPREG_MASK;
init.ep[ep_num - 1].rx_handler(ep_num);
}
}
}
}
| 29.928775 | 137 | 0.698239 | shima-529 |
405494e075dbe462812254669e3c19340ed25e4e | 8,368 | cpp | C++ | main/source/textrep/TRFactory.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 27 | 2015-01-05T19:25:14.000Z | 2022-03-20T00:34:34.000Z | main/source/textrep/TRFactory.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 9 | 2015-01-14T06:51:46.000Z | 2021-03-19T12:07:18.000Z | main/source/textrep/TRFactory.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 5 | 2015-01-11T10:31:24.000Z | 2021-01-06T01:32:58.000Z | //======== (C) Copyright 2002 Charles G. Cleveland All rights reserved. =========
//
// The copyright to the contents herein is the property of Charles G. Cleveland.
// The contents may be used and/or copied only with the written permission of
// Charles G. Cleveland, or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: TRFactory.cpp $
// $Date: 2002/08/16 02:28:25 $
//
//-------------------------------------------------------------------------------
// $Log: TRFactory.cpp,v $
// Revision 1.6 2002/08/16 02:28:25 Flayra
// - Added document headers
//
//===============================================================================
#include "TRTag.h"
#include "TRTagValuePair.h"
#include "TRDescription.h"
#include "TRFactory.h"
#include "../util/STLUtil.h"
const int maxLineLength = 256;
bool TRFactory::ReadDescriptions(const string& inRelativePathFilename, TRDescriptionList& outDescriptionList)
{
bool theSuccess = false;
bool theDescriptionRead = false;
// Open file specified by relative path name
fstream infile;
infile.open(inRelativePathFilename.c_str(), ios::in);
if(infile.is_open())
{
do
{
// Try to read the next description in
TRDescription theNextDescription;
theDescriptionRead = ReadDescription(infile, theNextDescription);
// add it to the description list
if(theDescriptionRead)
{
// Function is successful if at least one description was found
outDescriptionList.push_back(theNextDescription);
theSuccess = true;
}
} while(theDescriptionRead);
infile.close();
}
return theSuccess;
}
bool TRFactory::WriteDescriptions(const string& inRelativePathFilename, const TRDescriptionList& inDescriptionList, const string& inHeader)
{
bool theSuccess = false;
// Open the file for output
fstream theOutfile;
theOutfile.open(inRelativePathFilename.c_str(), ios::out);
if(theOutfile.is_open())
{
// Optional: write header
theOutfile << inHeader << std::endl;
//theOutfile << "; Generated by Half-life. Do not edit unless you know what you are doing! " << std::endl;
//theOutfile << std::endl;
// For each description
TRDescriptionList::const_iterator theIter;
for(theIter = inDescriptionList.begin(); theIter != inDescriptionList.end(); theIter++)
{
// Write out that description
const TRDescription& theDesc = *theIter;
TRFactory::WriteDescription(theOutfile, theDesc);
// Write out a blank line to make them look nice and separated
theOutfile << std::endl;
}
theOutfile.close();
theSuccess = true;
}
return theSuccess;
}
// TODO: Add case-insensitivity
bool TRFactory::ReadDescription(fstream& infile, TRDescription& outDescription)
{
bool theSuccess = false;
string currentLine;
bool blockStarted = false;
// for every line in the file
while(!infile.eof())
{
if(readAndTrimNextLine(infile, currentLine))
{
// If line isn't a comment
if(!lineIsAComment(currentLine))
{
// If we haven't started, is line of format: start <type> <name>? If so, set started and set those tags.
if(!blockStarted)
{
blockStarted = readStartBlockLine(currentLine, outDescription);
}
// If we have started
else
{
// Is line an end? If so, this function is over
if(readEndBlockLine(currentLine))
{
break;
}
// else is line of tag = property format? If so, add it as pair
else
{
// If not, print error and proceed
if(readTagAndValueLine(currentLine, outDescription))
{
// Once we have read at least one tag-value pair, considered this a success
theSuccess = true;
}
else
{
//printf("Error reading line of length %d: %s\n", currentLine.length(), currentLine.c_str());
}
}
}
}
}
}
return theSuccess;
}
bool TRFactory::WriteDescription(fstream& outfile, const TRDescription& inDescription)
{
bool theSuccess = true;
// Write out the start block
outfile << "start" << " " << inDescription.GetType() << " " << inDescription.GetName() << std::endl;
// Write out the property tags
TRDescription::const_iterator theIter;
for(theIter = inDescription.begin(); theIter != inDescription.end(); theIter++)
{
outfile << " " << theIter->first << " = " << theIter->second << std:: endl;
}
// Write out the end block.
outfile << "end" << std::endl;
return theSuccess;
}
bool TRFactory::readAndTrimNextLine(istream& inStream, string& outString)
{
char theLine[maxLineLength];
bool theSuccess = false;
inStream.getline(theLine, maxLineLength);
outString = string(theLine);
trimWhitespace(outString);
// Return false if the line is empty when we're done
if(outString.length() > 1)
{
theSuccess = true;
}
return theSuccess;
}
// Trim whitespace from string
void TRFactory::trimWhitespace(string& inString)
{
// find first character that isn't a tab or space and save that offset
//int firstNonWSChar = 0;
//int i= 0;
//int stringLength = inString.length();
//while(i != (stringLength - 1) && ())
//{
//}
// find last character that isn't a tab or space and save that offset
// Build a new string representing string without whitespace
// Set new string equal to inString
}
bool TRFactory::charIsWhiteSpace(char inChar)
{
bool theSuccess = false;
if((inChar == ' ') || (inChar == '\t'))
{
theSuccess = true;
}
return theSuccess;
}
// Is the string a comment?
bool TRFactory::lineIsAComment(const string& inString)
{
bool theLineIsAComment = false;
//replaced loop with actual string functions... KGP
size_t index = inString.find_first_not_of(" \t");
if( index != string::npos && (inString.at(index) == '\'' || inString.at(index) == ';') )
{ theLineIsAComment = true; }
return theLineIsAComment;
}
// Read start block
// Set the name and type of the description
// Returns false if invalid format
bool TRFactory::readStartBlockLine(const string& inString, TRDescription& outDescription)
{
bool theSuccess = false;
char theType[maxLineLength];
char theName[maxLineLength];
memset(theType, ' ', maxLineLength);
memset(theName, ' ', maxLineLength);
// Read three tokens. There should be "start" <type> <name>
if(sscanf(inString.c_str(), "start %s %s", theType, theName) == 2)
{
outDescription.SetName(theName);
outDescription.SetType(theType);
theSuccess = true;
}
return theSuccess;
}
// Read end block
bool TRFactory::readEndBlockLine(const string& inString)
{
bool theSuccess = false;
// There are some CRLF issues on Linux, hence this bit
if(inString.length() >= 3)
{
string theString = inString.substr(0,3);
if(theString == "end")
{
theSuccess = true;
}
else
{
//printf("TRFactory::readEndBlockLine() failed, found (%s)\n", theString.c_str());
}
}
return theSuccess;
}
bool TRFactory::readTagAndValueLine(const string& inString, TRDescription& outDescription)
{
bool theSuccess = false;
char theTag[maxLineLength];
char theValue[maxLineLength];
// Zero them out
memset(theTag, ' ', maxLineLength);
memset(theValue, ' ', maxLineLength);
if((sscanf(inString.c_str(), "%s = %s", theTag, theValue)) == 2)
{
// Add it
TRTagValuePair thePair(theTag, theValue);
outDescription.AddPair(thePair);
theSuccess = true;
}
return theSuccess;
}
| 28.462585 | 140 | 0.593212 | fmoraw |
405967b06203a9c73de4ac3c33509ac132e7f39e | 23,970 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "cpppointerdeclarationformatter.h"
#include "cpptoolsplugin.h"
#include "cpptoolstestcase.h"
#include <coreplugin/coreconstants.h>
#include <texteditor/texteditor.h>
#include <texteditor/textdocument.h>
#include <texteditor/plaintexteditorfactory.h>
#include <utils/fileutils.h>
#include <cplusplus/Overview.h>
#include <cplusplus/pp.h>
#include <QDebug>
#include <QDir>
#include <QTextCursor>
#include <QTextDocument>
#include <QtTest>
using namespace CPlusPlus;
using namespace CppTools;
using namespace CppTools::Internal;
Q_DECLARE_METATYPE(Overview)
namespace {
QString stripCursor(const QString &source)
{
QString copy(source);
const int pos = copy.indexOf(QLatin1Char('@'));
if (pos != -1)
copy.remove(pos, 1);
else
qDebug() << Q_FUNC_INFO << "Warning: No cursor marker to strip.";
return copy;
}
class PointerDeclarationFormatterTestCase : public Tests::TestCase
{
public:
PointerDeclarationFormatterTestCase(const QByteArray &source,
const QString &expectedSource,
Document::ParseMode parseMode,
PointerDeclarationFormatter::CursorHandling cursorHandling)
{
QVERIFY(succeededSoFar());
// Find cursor position and remove cursor marker '@'
int cursorPosition = 0;
QString sourceWithoutCursorMarker = QLatin1String(source);
const int pos = sourceWithoutCursorMarker.indexOf(QLatin1Char('@'));
if (pos != -1) {
sourceWithoutCursorMarker.remove(pos, 1);
cursorPosition = pos;
}
// Write source to temprorary file
Tests::TemporaryDir temporaryDir;
QVERIFY(temporaryDir.isValid());
const QString filePath = temporaryDir.createFile("file.h",
sourceWithoutCursorMarker.toUtf8());
QVERIFY(!filePath.isEmpty());
// Preprocess source
Environment env;
Preprocessor preprocess(0, &env);
const QByteArray preprocessedSource = preprocess.run(filePath, sourceWithoutCursorMarker);
Document::Ptr document = Document::create(filePath);
document->setUtf8Source(preprocessedSource);
document->parse(parseMode);
document->check();
QVERIFY(document->diagnosticMessages().isEmpty());
AST *ast = document->translationUnit()->ast();
QVERIFY(ast);
// Open file
QScopedPointer<TextEditor::BaseTextEditor> editor(
TextEditor::PlainTextEditorFactory::createPlainTextEditor());
QString error;
editor->document()->open(&error, document->fileName(), document->fileName());
QVERIFY(error.isEmpty());
// Set cursor position
QTextCursor cursor = editor->textCursor();
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, cursorPosition);
editor->setTextCursor(cursor);
QTextDocument *qtextDocument = editor->textDocument()->document();
CppRefactoringFilePtr cppRefactoringFile
= CppRefactoringChanges::file(editor->editorWidget(), document);
// Prepare for formatting
Overview overview;
overview.showReturnTypes = true;
overview.showArgumentNames = true;
overview.starBindFlags = Overview::StarBindFlags(0);
// Run the formatter
PointerDeclarationFormatter formatter(cppRefactoringFile, overview, cursorHandling);
Utils::ChangeSet change = formatter.format(ast); // ChangeSet may be empty.
// Apply change
QTextCursor changeCursor(qtextDocument);
change.apply(&changeCursor);
// Compare
QCOMPARE(qtextDocument->toPlainText(), expectedSource);
}
};
} // anonymous namespace
void CppToolsPlugin::test_format_pointerdeclaration_in_simpledeclarations()
{
QFETCH(QString, source);
QFETCH(QString, reformattedSource);
PointerDeclarationFormatterTestCase(source.toUtf8(),
reformattedSource,
Document::ParseDeclaration,
PointerDeclarationFormatter::RespectCursor);
}
void CppToolsPlugin::test_format_pointerdeclaration_in_simpledeclarations_data()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QString>("reformattedSource");
QString source;
//
// Naming scheme for the test cases: <description>_(in|out)-(start|middle|end)
// in/out:
// Denotes whether the cursor is in or out of the quickfix activation range
// start/middle/end:
// Denotes whether is cursor is near to the range start, middle or end
//
QTest::newRow("basic_in-start")
<< "@char *s;"
<< "char * s;";
source = QLatin1String("char *s;@");
QTest::newRow("basic_out-end")
<< source << stripCursor(source);
QTest::newRow("basic_in-end")
<< "char *s@;"
<< "char * s;";
QTest::newRow("basic-with-ws_in-start")
<< "\n @char *s; " // Add some whitespace to check position detection.
<< "\n char * s; ";
source = QLatin1String("\n @ char *s; ");
QTest::newRow("basic-with-ws_out-start")
<< source << stripCursor(source);
QTest::newRow("basic-with-const_in-start")
<< "@const char *s;"
<< "const char * s;";
QTest::newRow("basic-with-const-and-init-value_in-end")
<< "const char *s@ = 0;"
<< "const char * s = 0;";
source = QLatin1String("const char *s @= 0;");
QTest::newRow("basic-with-const-and-init-value_out-end")
<< source << stripCursor(source);
QTest::newRow("first-declarator_in-start")
<< "@const char *s, *t;"
<< "const char * s, *t;";
QTest::newRow("first-declarator_in-end")
<< "const char *s@, *t;"
<< "const char * s, *t;";
source = QLatin1String("const char *s,@ *t;");
QTest::newRow("first-declarator_out-end")
<< source << stripCursor(source);
QTest::newRow("function-declaration-param_in-start")
<< "int f(@char *s);"
<< "int f(char * s);";
QTest::newRow("function-declaration-param_in-end")
<< "int f(char *s@);"
<< "int f(char * s);";
QTest::newRow("function-declaration-param_in-end")
<< "int f(char *s@ = 0);"
<< "int f(char * s = 0);";
QTest::newRow("function-declaration-param-multiple-params_in-end")
<< "int f(char *s@, int);"
<< "int f(char * s, int);";
source = QLatin1String("int f(char *s)@;");
QTest::newRow("function-declaration-param_out-end")
<< source << stripCursor(source);
source = QLatin1String("int f@(char *s);");
QTest::newRow("function-declaration-param_out-start")
<< source << stripCursor(source);
source = QLatin1String("int f(char *s =@ 0);");
QTest::newRow("function-declaration-param_out-end")
<< source << stripCursor(source);
// Function definitions are handled by the same code as function
// declarations, so just check a minimal example.
QTest::newRow("function-definition-param_in-middle")
<< "int f(char @*s) {}"
<< "int f(char * s) {}";
QTest::newRow("function-declaration-returntype_in-start")
<< "@char *f();"
<< "char * f();";
QTest::newRow("function-declaration-returntype_in-end")
<< "char *f@();"
<< "char * f();";
source = QLatin1String("char *f(@);");
QTest::newRow("function-declaration-returntype_out-end")
<< source << stripCursor(source);
QTest::newRow("function-definition-returntype_in-end")
<< "char *f@() {}"
<< "char * f() {}";
QTest::newRow("function-definition-returntype_in-start")
<< "@char *f() {}"
<< "char * f() {}";
source = QLatin1String("char *f(@) {}");
QTest::newRow("function-definition-returntype_out-end")
<< source << stripCursor(source);
source = QLatin1String("inline@ char *f() {}");
QTest::newRow("function-definition-returntype-inline_out-start")
<< source << stripCursor(source);
// Same code is also used for for other specifiers like virtual, inline, friend, ...
QTest::newRow("function-definition-returntype-static-inline_in-start")
<< "static inline @char *f() {}"
<< "static inline char * f() {}";
QTest::newRow("function-declaration-returntype-static-inline_in-start")
<< "static inline @char *f();"
<< "static inline char * f();";
source = QLatin1String("static inline@ char *f() {}");
QTest::newRow("function-definition-returntype-static-inline_out-start")
<< source << stripCursor(source);
QTest::newRow("function-declaration-returntype-static-custom-type_in-start")
<< "static @CustomType *f();"
<< "static CustomType * f();";
source = QLatin1String("static@ CustomType *f();");
QTest::newRow("function-declaration-returntype-static-custom-type_out-start")
<< source << stripCursor(source);
QTest::newRow("function-declaration-returntype-symbolvisibilityattributes_in-start")
<< "__attribute__((visibility(\"default\"))) @char *f();"
<< "__attribute__((visibility(\"default\"))) char * f();";
source = QLatin1String("@__attribute__((visibility(\"default\"))) char *f();");
QTest::newRow("function-declaration-returntype-symbolvisibilityattributes_out-start")
<< source << stripCursor(source);
// The following two are not supported at the moment.
source = QLatin1String("@char * __attribute__((visibility(\"default\"))) f();");
QTest::newRow("function-declaration-returntype-symbolvisibilityattributes_out-start")
<< source << stripCursor(source);
source = QLatin1String("@char * __attribute__((visibility(\"default\"))) f() {}");
QTest::newRow("function-definition-returntype-symbolvisibilityattributes_out-start")
<< source << stripCursor(source);
// NOTE: Since __declspec() is not parsed (but defined to nothing),
// we can't detect it properly. Therefore, we fail on code with
// FOO_EXPORT macros with __declspec() for pointer return types;
QTest::newRow("typedef_in-start")
<< "typedef @char *s;"
<< "typedef char * s;";
source = QLatin1String("@typedef char *s;");
QTest::newRow("typedef_out-start")
<< source << stripCursor(source);
QTest::newRow("static_in-start")
<< "static @char *s;"
<< "static char * s;";
QTest::newRow("pointerToFunction_in-start")
<< "int (*bar)(@char *s);"
<< "int (*bar)(char * s);";
source = QLatin1String("int (@*bar)();");
QTest::newRow("pointerToFunction_in-start")
<< source << stripCursor(source);
source = QLatin1String("int (@*bar)[] = 0;");
QTest::newRow("pointerToArray_in-start")
<< source << stripCursor(source);
//
// Additional test cases that does not fit into the naming scheme
//
// The following case is a side effect of the reformatting. Though
// the pointer type is according to the overview, the double space
// before 'char' gets corrected.
QTest::newRow("remove-extra-whitespace")
<< "@const char * s = 0;"
<< "const char * s = 0;";
// Nothing to pretty print since no pointer or references are involved.
source = QLatin1String("@char bla;"); // Two spaces to get sure nothing is reformatted.
QTest::newRow("precondition-fail-no-pointer")
<< source << stripCursor(source);
// Respect white space within operator names
QTest::newRow("operators1")
<< "class C { C@&operator = (const C &); };"
<< "class C { C & operator = (const C &); };";
QTest::newRow("operators2")
<< "C &C::operator = (const C &) {}"
<< "C & C::operator = (const C &) {}";
}
void CppToolsPlugin::test_format_pointerdeclaration_in_controlflowstatements()
{
QFETCH(QString, source);
QFETCH(QString, reformattedSource);
PointerDeclarationFormatterTestCase(source.toUtf8(),
reformattedSource,
Document::ParseStatement,
PointerDeclarationFormatter::RespectCursor);
}
void CppToolsPlugin::test_format_pointerdeclaration_in_controlflowstatements_data()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QString>("reformattedSource");
QString source;
//
// Same naming scheme as in test_format_pointerdeclaration_in_simpledeclarations_data()
//
QTest::newRow("if_in-start")
<< "if (@char *s = 0);"
<< "if (char * s = 0);";
source = QLatin1String("if @(char *s = 0);");
QTest::newRow("if_out-start")
<< source << stripCursor(source);
QTest::newRow("if_in-end")
<< "if (char *s@ = 0);"
<< "if (char * s = 0);";
source = QLatin1String("if (char *s @= 0);");
QTest::newRow("if_out-end")
<< source << stripCursor(source);
// if and for statements are handled by the same code, so just
// check minimal examples for these
QTest::newRow("while")
<< "while (@char *s = 0);"
<< "while (char * s = 0);";
QTest::newRow("for")
<< "for (;@char *s = 0;);"
<< "for (;char * s = 0;);";
// Should also work since it's a simple declaration
// for (char *s = 0; true;);
QTest::newRow("foreach_in-start")
<< "foreach (@char *s, list);"
<< "foreach (char * s, list);";
source = QLatin1String("foreach @(char *s, list);");
QTest::newRow("foreach-out-start")
<< source << stripCursor(source);
QTest::newRow("foreach_in_end")
<< "foreach (const char *s@, list);"
<< "foreach (const char * s, list);";
source = QLatin1String("foreach (const char *s,@ list);");
QTest::newRow("foreach_out_end")
<< source << stripCursor(source);
//
// Additional test cases that does not fit into the naming scheme
//
source = QLatin1String("@if (char s = 0);"); // Two spaces to get sure nothing is reformatted.
QTest::newRow("precondition-fail-no-pointer") << source << stripCursor(source);
}
void CppToolsPlugin::test_format_pointerdeclaration_multiple_declarators()
{
QFETCH(QString, source);
QFETCH(QString, reformattedSource);
PointerDeclarationFormatterTestCase(source.toUtf8(),
reformattedSource,
Document::ParseDeclaration,
PointerDeclarationFormatter::RespectCursor);
}
void CppToolsPlugin::test_format_pointerdeclaration_multiple_declarators_data()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QString>("reformattedSource");
QString source;
QTest::newRow("function-declaration_in-start")
<< "char *s = 0, @*f(int i) = 0;"
<< "char *s = 0, * f(int i) = 0;";
QTest::newRow("non-pointer-before_in-start")
<< "char c, @*t;"
<< "char c, * t;";
QTest::newRow("pointer-before_in-start")
<< "char *s, @*t;"
<< "char *s, * t;";
QTest::newRow("pointer-before_in-end")
<< "char *s, *t@;"
<< "char *s, * t;";
source = QLatin1String("char *s,@ *t;");
QTest::newRow("md1-out_start")
<< source << stripCursor(source);
source = QLatin1String("char *s, *t;@");
QTest::newRow("md1-out_end")
<< source << stripCursor(source);
QTest::newRow("non-pointer-after_in-start")
<< "char c, @*t, d;"
<< "char c, * t, d;";
QTest::newRow("pointer-after_in-start")
<< "char c, @*t, *d;"
<< "char c, * t, *d;";
QTest::newRow("function-pointer_in-start")
<< "char *s, @*(*foo)(char *s) = 0;"
<< "char *s, *(*foo)(char * s) = 0;";
}
void CppToolsPlugin::test_format_pointerdeclaration_multiple_matches()
{
QFETCH(QString, source);
QFETCH(QString, reformattedSource);
PointerDeclarationFormatterTestCase(source.toUtf8(),
reformattedSource,
Document::ParseTranlationUnit,
PointerDeclarationFormatter::IgnoreCursor);
}
void CppToolsPlugin::test_format_pointerdeclaration_multiple_matches_data()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QString>("reformattedSource");
QTest::newRow("rvalue-reference")
<< "int g(Bar&&c) {}"
<< "int g(Bar && c) {}";
QTest::newRow("if2")
<< "int g() { if (char *s = 0) { char *t = 0; } }"
<< "int g() { if (char * s = 0) { char * t = 0; } }";
QTest::newRow("if1")
<< "int g() { if (int i = 0) { char *t = 0; } }"
<< "int g() { if (int i = 0) { char * t = 0; } }";
QTest::newRow("for1")
<< "int g() { for (char *s = 0; char *t = 0; s++); }"
<< "int g() { for (char * s = 0; char * t = 0; s++); }";
QTest::newRow("for2")
<< "int g() { for (char *s = 0; char *t = 0; s++) { char *u = 0; } }"
<< "int g() { for (char * s = 0; char * t = 0; s++) { char * u = 0; } }";
QTest::newRow("for3")
<< "int g() { for (char *s; char *t = 0; s++) { char *u = 0; } }"
<< "int g() { for (char * s; char * t = 0; s++) { char * u = 0; } }";
QTest::newRow("multiple-declarators")
<< "const char c, *s, *(*foo)(char *s) = 0;"
<< "const char c, * s, *(*foo)(char * s) = 0;";
QTest::newRow("complex")
<<
"int *foo(const int &b, int*, int *&rpi)\n"
"{\n"
" int*pi = 0;\n"
" int*const*const cpcpi = π\n"
" int*const*pcpi = π\n"
" int**const cppi = π\n"
"\n"
" void (*foo)(char *s) = 0;\n"
" int (*bar)[] = 0;\n"
"\n"
" char *s = 0, *f(int i) = 0;\n"
" const char c, *s, *(*foo)(char *s) = 0;"
"\n"
" for (char *s; char *t = 0; s++) { char *u = 0; }"
"\n"
" return 0;\n"
"}\n"
<<
"int * foo(const int & b, int *, int *& rpi)\n"
"{\n"
" int * pi = 0;\n"
" int * const * const cpcpi = π\n"
" int * const * pcpi = π\n"
" int ** const cppi = π\n"
"\n"
" void (*foo)(char * s) = 0;\n"
" int (*bar)[] = 0;\n"
"\n"
" char * s = 0, * f(int i) = 0;\n"
" const char c, * s, *(*foo)(char * s) = 0;"
"\n"
" for (char * s; char * t = 0; s++) { char * u = 0; }"
"\n"
" return 0;\n"
"}\n";
}
void CppToolsPlugin::test_format_pointerdeclaration_macros()
{
QFETCH(QString, source);
QFETCH(QString, reformattedSource);
PointerDeclarationFormatterTestCase(source.toUtf8(),
reformattedSource,
Document::ParseTranlationUnit,
PointerDeclarationFormatter::RespectCursor);
}
void CppToolsPlugin::test_format_pointerdeclaration_macros_data()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QString>("reformattedSource");
QString source;
source = QLatin1String(
"#define FOO int*\n"
"FOO @bla;\n");
QTest::newRow("macro-in-simple-declaration")
<< source << stripCursor(source);
source = QLatin1String(
"#define FOO int*\n"
"FOO @f();\n");
QTest::newRow("macro-in-function-declaration-returntype")
<< source << stripCursor(source);
source = QLatin1String(
"#define FOO int*\n"
"int f(@FOO a);\n");
QTest::newRow("macro-in-function-declaration-param")
<< source << stripCursor(source);
source = QLatin1String(
"#define FOO int*\n"
"FOO @f() {}\n");
QTest::newRow("macro-in-function-definition-returntype")
<< source << stripCursor(source);
source = QLatin1String(
"#define FOO int*\n"
"int f(FOO @a) {}\n");
QTest::newRow("macro-in-function-definition-param")
<< source << stripCursor(source);
source = QLatin1String(
"#define FOO int*\n"
"void f() { while (FOO @s = 0) {} }\n");
QTest::newRow("macro-in-if-while-for")
<< source << stripCursor(source);
source = QLatin1String(
"#define FOO int*\n"
"void f() { foreach (FOO @s, list) {} }\n");
QTest::newRow("macro-in-foreach")
<< source << stripCursor(source);
// The bug was that we got "Reformat to 'QMetaObject staticMetaObject'"
// at the cursor position below, which was completelty wrong.
QTest::newRow("wrong-reformat-suggestion")
<<
"#define Q_OBJECT \\\n"
"public: \\\n"
" template <typename T> inline void qt_check_for_QOBJECT_macro(T &_q_argument) \\\n"
" { int i = qYouForgotTheQ_OBJECT_Macro(this, &_q_argument); i = i; } \\\n"
" QMetaObject staticMetaObject; \\\n"
" void *qt_metacast(const char *); \\\n"
" static inline QString tr(const char *s, const char *f = 0); \\\n"
" \n"
"class KitInformation\n"
"{\n"
" Q_OBJECT\n"
"public:\n"
" typedef QPair<QString, QString> Item;\n"
" \n"
" Core::Id dataId(); // the higher the closer to top.\n"
" \n"
" unsigned int priority() = 0;\n"
" \n"
" QVariant defaultValue(Kit@*) = 0;\n"
"};\n"
<<
"#define Q_OBJECT \\\n"
"public: \\\n"
" template <typename T> inline void qt_check_for_QOBJECT_macro(T &_q_argument) \\\n"
" { int i = qYouForgotTheQ_OBJECT_Macro(this, &_q_argument); i = i; } \\\n"
" QMetaObject staticMetaObject; \\\n"
" void *qt_metacast(const char *); \\\n"
" static inline QString tr(const char *s, const char *f = 0); \\\n"
" \n"
"class KitInformation\n"
"{\n"
" Q_OBJECT\n"
"public:\n"
" typedef QPair<QString, QString> Item;\n"
" \n"
" Core::Id dataId(); // the higher the closer to top.\n"
" \n"
" unsigned int priority() = 0;\n"
" \n"
" QVariant defaultValue(Kit *) = 0;\n"
"};\n";
}
| 34.992701 | 99 | 0.566083 | kevinlq |
405f147bc84b989e1287d8938de4ba8c380de392 | 10,954 | cc | C++ | src/CBLDatabase.cc | stcleezy/couchbase-lite-C | 6e04658b023b48908ff1e0d89197e830df22c178 | [
"Apache-2.0"
] | null | null | null | src/CBLDatabase.cc | stcleezy/couchbase-lite-C | 6e04658b023b48908ff1e0d89197e830df22c178 | [
"Apache-2.0"
] | null | null | null | src/CBLDatabase.cc | stcleezy/couchbase-lite-C | 6e04658b023b48908ff1e0d89197e830df22c178 | [
"Apache-2.0"
] | null | null | null | //
// CBLDatabase.cc
//
// Copyright © 2018 Couchbase. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "CBLDatabase_Internal.hh"
#include "CBLPrivate.h"
#include "Internal.hh"
#include "Util.hh"
#include "PlatformCompat.hh"
#include <sys/stat.h>
#ifndef CMAKE
#include <unistd.h>
#endif
using namespace std;
using namespace fleece;
using namespace cbl_internal;
static constexpr CBLDatabaseFlags kDefaultFlags = kC4DB_Create;
// Default location for databases: the current directory
static const char* defaultDbDir() {
static const string kDir = cbl_getcwd(nullptr, 0);
return kDir.c_str();
}
static slice effectiveDir(const char *inDirectory) {
return slice(inDirectory ? inDirectory : defaultDbDir());
}
static C4DatabaseConfig2 asC4Config(const CBLDatabaseConfiguration *config) {
C4DatabaseConfig2 c4Config = {};
if (config) {
c4Config.parentDirectory = effectiveDir(config->directory);
if (config->flags & kCBLDatabase_Create)
c4Config.flags |= kC4DB_Create;
if (config->flags & kCBLDatabase_ReadOnly)
c4Config.flags |= kC4DB_ReadOnly;
if (config->flags & kCBLDatabase_NoUpgrade)
c4Config.flags |= kC4DB_NoUpgrade;
c4Config.encryptionKey.algorithm = static_cast<C4EncryptionAlgorithm>(
config->encryptionKey.algorithm);
static_assert(sizeof(CBLEncryptionKey::bytes) == sizeof(C4EncryptionKey::bytes),
"C4EncryptionKey and CBLEncryptionKey size do not match");
memcpy(c4Config.encryptionKey.bytes, config->encryptionKey.bytes,
sizeof(CBLEncryptionKey::bytes));
} else {
c4Config.parentDirectory = effectiveDir(nullptr);
c4Config.flags = kDefaultFlags;
}
return c4Config;
}
// For use only by CBLLocalEndpoint
C4Database* CBLDatabase::_getC4Database() const {
return use<C4Database*>([](C4Database *c4db) {
return c4db;
});
}
#pragma mark - STATIC "METHODS":
bool CBL_DatabaseExists(const char *name, const char *inDirectory) CBLAPI {
return c4db_exists(slice(name), effectiveDir(inDirectory));
}
bool CBL_CopyDatabase(const char* fromPath,
const char* toName,
const CBLDatabaseConfiguration *config,
CBLError* outError) CBLAPI
{
C4DatabaseConfig2 c4config = asC4Config(config);
return c4db_copyNamed(slice(fromPath), slice(toName), &c4config, internal(outError));
}
bool CBL_DeleteDatabase(const char *name,
const char *inDirectory,
CBLError* outError) CBLAPI
{
return c4db_deleteNamed(slice(name), effectiveDir(inDirectory), internal(outError));
}
#pragma mark - LIFECYCLE & OPERATIONS:
CBLDatabase* CBLDatabase_Open(const char *name,
const CBLDatabaseConfiguration *config,
CBLError *outError) CBLAPI
{
C4DatabaseConfig2 c4config = asC4Config(config);
C4Database *c4db = c4db_openNamed(slice(name), &c4config, internal(outError));
if (!c4db)
return nullptr;
c4db_startHousekeeping(c4db);
return retain(new CBLDatabase(c4db, name,
c4config.parentDirectory,
(config ? config->flags : kDefaultFlags)));
}
bool CBLDatabase_Close(CBLDatabase* db, CBLError* outError) CBLAPI {
if (!db)
return true;
return db->use<bool>([=](C4Database *c4db) {
return c4db_close(c4db, internal(outError));
});
}
bool CBLDatabase_BeginBatch(CBLDatabase* db, CBLError* outError) CBLAPI {
return db->use<bool>([=](C4Database *c4db) {
return c4db_beginTransaction(c4db, internal(outError));
});
}
bool CBLDatabase_EndBatch(CBLDatabase* db, CBLError* outError) CBLAPI {
return db->use<bool>([=](C4Database *c4db) {
return c4db_endTransaction(c4db, true, internal(outError));
});
}
bool CBLDatabase_Compact(CBLDatabase* db, CBLError* outError) CBLAPI {
return db->use<bool>([=](C4Database *c4db) {
return c4db_compact(c4db, internal(outError));
});
}
bool CBLDatabase_Delete(CBLDatabase* db, CBLError* outError) CBLAPI {
return db->use<bool>([=](C4Database *c4db) {
return c4db_delete(c4db, internal(outError));
});
}
CBLTimestamp CBLDatabase_NextDocExpiration(CBLDatabase* db) CBLAPI {
return db->use<bool>([=](C4Database *c4db) {
return c4db_nextDocExpiration(c4db);
});
}
int64_t CBLDatabase_PurgeExpiredDocuments(CBLDatabase* db, CBLError* outError) CBLAPI {
return db->use<bool>([=](C4Database *c4db) {
return c4db_purgeExpiredDocs(c4db, internal(outError));
});
}
#pragma mark - ACCESSORS:
const char* CBLDatabase_Name(const CBLDatabase* db) CBLAPI {
return db->name.c_str();
}
const char* CBLDatabase_Path(const CBLDatabase* db) CBLAPI {
return db->path.c_str();
}
const CBLDatabaseConfiguration CBLDatabase_Config(const CBLDatabase* db) CBLAPI {
const char *dir = db->dir.empty() ? nullptr : db->dir.c_str();
return {dir, db->flags};
}
uint64_t CBLDatabase_Count(const CBLDatabase* db) CBLAPI {
return db->use<uint64_t>([](C4Database *c4db) {
return c4db_getDocumentCount(c4db);
});
}
uint64_t CBLDatabase_LastSequence(const CBLDatabase* db) CBLAPI {
return db->use<uint64_t>([](C4Database *c4db) {
return c4db_getLastSequence(c4db);
});
}
#pragma mark - NOTIFICATIONS:
void CBLDatabase_BufferNotifications(CBLDatabase *db,
CBLNotificationsReadyCallback callback,
void *context) CBLAPI
{
db->bufferNotifications(callback, context);
}
void CBLDatabase_SendNotifications(CBLDatabase *db) CBLAPI {
db->sendNotifications();
}
#pragma mark - DATABASE CHANGE LISTENERS:
CBLListenerToken* CBLDatabase::addListener(CBLDatabaseChangeListener listener, void *context) {
return use<CBLListenerToken*>([=](C4Database *c4db) {
auto token = _listeners.add(listener, context);
if (!_observer) {
_observer = c4dbobs_create(c4db,
[](C4DatabaseObserver* observer, void *context) {
((CBLDatabase*)context)->databaseChanged();
},
this);
}
return token;
});
}
void CBLDatabase::databaseChanged() {
notify(bind(&CBLDatabase::callDBListeners, this));
}
void CBLDatabase::callDBListeners() {
static const uint32_t kMaxChanges = 100;
while (true) {
C4DatabaseChange c4changes[kMaxChanges];
bool external;
uint32_t nChanges = c4dbobs_getChanges(_observer, c4changes, kMaxChanges, &external);
if (nChanges == 0)
break;
// Convert docID slices to C strings:
const char* docIDs[kMaxChanges];
size_t bufSize = 0;
for (uint32_t i = 0; i < nChanges; ++i)
bufSize += c4changes[i].docID.size + 1;
char *buf = new char[bufSize], *next = buf;
for (uint32_t i = 0; i < nChanges; ++i) {
docIDs[i] = next;
memcpy(next, (const char*)c4changes[i].docID.buf, c4changes[i].docID.size);
next += c4changes[i].docID.size;
*(next++) = '\0';
}
assert(next - buf == bufSize);
// Call the listener(s):
_listeners.call(this, nChanges, docIDs);
delete [] buf;
}
}
CBLListenerToken* CBLDatabase_AddChangeListener(const CBLDatabase* constdb _cbl_nonnull,
CBLDatabaseChangeListener listener _cbl_nonnull,
void *context) CBLAPI
{
return const_cast<CBLDatabase*>(constdb)->addListener(listener, context);
}
#pragma mark - DOCUMENT LISTENERS:
namespace cbl_internal {
// Custom subclass of CBLListenerToken for document listeners.
// (It implements the ListenerToken<> template so that it will work with Listeners<>.)
template<>
class ListenerToken<CBLDocumentChangeListener> : public CBLListenerToken {
public:
ListenerToken(CBLDatabase *db, const char *docID, CBLDocumentChangeListener callback, void *context)
:CBLListenerToken((const void*)callback, context)
,_db(db)
,_docID(docID)
{
db->use([&](C4Database *c4db) {
_c4obs = c4docobs_create(c4db,
slice(docID),
[](C4DocumentObserver* observer, C4String docID,
C4SequenceNumber sequence, void *context)
{
((ListenerToken*)context)->docChanged();
},
this);
});
}
~ListenerToken() {
_db->use([&](C4Database *c4db) {
c4docobs_free(_c4obs);
});
}
CBLDocumentChangeListener callback() const {
return (CBLDocumentChangeListener)_callback.load();
}
// this is called indirectly by CBLDatabase::sendNotifications
void call(const CBLDatabase*, const char*) {
auto cb = callback();
if (cb)
cb(_context, _db, _docID.c_str());
}
private:
void docChanged() {
_db->notify(this, nullptr, nullptr);
}
CBLDatabase* _db;
string _docID;
C4DocumentObserver* _c4obs {nullptr};
};
}
CBLListenerToken* CBLDatabase::addDocListener(const char* docID _cbl_nonnull,
CBLDocumentChangeListener listener, void *context)
{
auto token = new ListenerToken<CBLDocumentChangeListener>(this, docID, listener, context);
_docListeners.add(token);
return token;
}
CBLListenerToken* CBLDatabase_AddDocumentChangeListener(const CBLDatabase* db _cbl_nonnull,
const char* docID _cbl_nonnull,
CBLDocumentChangeListener listener _cbl_nonnull,
void *context) CBLAPI
{
return const_cast<CBLDatabase*>(db)->addDocListener(docID, listener, context);
}
| 31.750725 | 108 | 0.619682 | stcleezy |
406130ac2ca4d5508ff7001c1e25b488fdaae54c | 387 | cpp | C++ | snippets/control_flow/sequential.cpp | raakasf/moderncpp | 2f8495c90e717e73303191e6f6aef37212448a46 | [
"MIT"
] | 334 | 2020-08-29T16:41:02.000Z | 2022-03-28T06:26:28.000Z | snippets/control_flow/sequential.cpp | raakasf/moderncpp | 2f8495c90e717e73303191e6f6aef37212448a46 | [
"MIT"
] | 4 | 2021-02-06T21:18:20.000Z | 2022-03-16T17:10:44.000Z | snippets/control_flow/sequential.cpp | raakasf/moderncpp | 2f8495c90e717e73303191e6f6aef37212448a46 | [
"MIT"
] | 33 | 2020-08-31T11:36:44.000Z | 2022-03-31T07:07:20.000Z | #include <iostream>
int main() {
using namespace std;
double l = 4;
double area = l * l;
cout << "Area: " << area << endl;
double height = 1.90;
double weight = 90;
cout << "BMI: " << weight / (height * height) << endl;
int a = 4;
int b = 7;
int fx = (b * b * b + a * b) - 2 * b + a % b;
cout << "f(x) = " << fx << endl;
return 0;
}
| 17.590909 | 58 | 0.45478 | raakasf |
406132820a828ab682116a0cdf4caa22570a6602 | 23,688 | cc | C++ | selfdrive/can/dbc_out/toyota_prius_2010_pt.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | 1 | 2021-03-05T18:09:52.000Z | 2021-03-05T18:09:52.000Z | selfdrive/can/dbc_out/toyota_prius_2010_pt.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | null | null | null | selfdrive/can/dbc_out/toyota_prius_2010_pt.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | null | null | null | #include <cstdint>
#include "common.h"
namespace {
const Signal sigs_36[] = {
{
.name = "YAW_RATE",
.b1 = 6,
.b2 = 10,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = -512.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STEERING_TORQUE",
.b1 = 22,
.b2 = 10,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = -512.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ACCEL_Y",
.b1 = 38,
.b2 = 10,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = -512.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_37[] = {
{
.name = "STEER_ANGLE",
.b1 = 4,
.b2 = 12,
.bo = 48,
.is_signed = true,
.factor = 1.5,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STEER_RATE",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STEER_FRACTION",
.b1 = 32,
.b2 = 4,
.bo = 28,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_166[] = {
{
.name = "BRAKE_AMOUNT",
.b1 = 0,
.b2 = 8,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "BRAKE_PEDAL",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_170[] = {
{
.name = "WHEEL_SPEED_FR",
.b1 = 0,
.b2 = 16,
.bo = 48,
.is_signed = false,
.factor = 0.0062,
.offset = -67.67,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "WHEEL_SPEED_FL",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 0.0062,
.offset = -67.67,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "WHEEL_SPEED_RR",
.b1 = 32,
.b2 = 16,
.bo = 16,
.is_signed = false,
.factor = 0.0062,
.offset = -67.67,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "WHEEL_SPEED_RL",
.b1 = 48,
.b2 = 16,
.bo = 0,
.is_signed = false,
.factor = 0.0062,
.offset = -67.67,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_180[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "ENCODER",
.b1 = 32,
.b2 = 8,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SPEED",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = false,
.factor = 0.0062,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_295[] = {
{
.name = "COUNTER",
.b1 = 48,
.b2 = 8,
.bo = 8,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "CAR_MOVEMENT",
.b1 = 32,
.b2 = 8,
.bo = 24,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "GEAR",
.b1 = 40,
.b2 = 4,
.bo = 20,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_452[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "ENGINE_RPM",
.b1 = 0,
.b2 = 16,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_466[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "GAS_RELEASED",
.b1 = 3,
.b2 = 1,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ACCEL_NET",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = true,
.factor = 0.001,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "CRUISE_STATE",
.b1 = 48,
.b2 = 4,
.bo = 12,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_467[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "LOW_SPEED_LOCKOUT",
.b1 = 9,
.b2 = 2,
.bo = 53,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "MAIN_ON",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SET_SPEED",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_550[] = {
{
.name = "BRAKE_PRESSURE",
.b1 = 7,
.b2 = 9,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "BRAKE_POSITION",
.b1 = 23,
.b2 = 9,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "BRAKE_PRESSED",
.b1 = 34,
.b2 = 1,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_552[] = {
{
.name = "ACCEL_X",
.b1 = 1,
.b2 = 15,
.bo = 48,
.is_signed = true,
.factor = 0.001,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ACCEL_Z",
.b1 = 17,
.b2 = 15,
.bo = 32,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_560[] = {
{
.name = "BRAKE_LIGHTS",
.b1 = 29,
.b2 = 1,
.bo = 34,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_581[] = {
{
.name = "GAS_PEDAL",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = false,
.factor = 0.005,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_608[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "STEER_OVERRIDE",
.b1 = 7,
.b2 = 1,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STEER_TORQUE_DRIVER",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STEER_TORQUE_EPS",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = true,
.factor = 0.66,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_610[] = {
{
.name = "CHECKSUM",
.b1 = 32,
.b2 = 8,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "STATE",
.b1 = 4,
.b2 = 4,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKA_STATE",
.b1 = 24,
.b2 = 8,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_614[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "ANGLE",
.b1 = 4,
.b2 = 12,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STATE",
.b1 = 0,
.b2 = 4,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SET_ME_X10",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "DIRECTION_CMD",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SET_ME_X00",
.b1 = 48,
.b2 = 8,
.bo = 8,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_740[] = {
{
.name = "COUNTER",
.b1 = 1,
.b2 = 6,
.bo = 57,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "CHECKSUM",
.b1 = 32,
.b2 = 8,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "STEER_REQUEST",
.b1 = 7,
.b2 = 1,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SET_ME_1",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "STEER_TORQUE_CMD",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKA_STATE",
.b1 = 24,
.b2 = 8,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_742[] = {
{
.name = "CHECKSUM",
.b1 = 56,
.b2 = 8,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::TOYOTA_CHECKSUM,
},
{
.name = "LEAD_LONG_DIST",
.b1 = 0,
.b2 = 13,
.bo = 51,
.is_signed = false,
.factor = 0.05,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LEAD_REL_SPEED",
.b1 = 16,
.b2 = 12,
.bo = 36,
.is_signed = true,
.factor = 0.025,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_835[] = {
{
.name = "ACCEL_CMD",
.b1 = 0,
.b2 = 16,
.bo = 48,
.is_signed = true,
.factor = 0.001,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_921[] = {
{
.name = "MAIN_ON",
.b1 = 3,
.b2 = 1,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "CRUISE_CONTROL_STATE",
.b1 = 12,
.b2 = 4,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "UI_SET_SPEED",
.b1 = 24,
.b2 = 8,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_951[] = {
{
.name = "TC_DISABLED",
.b1 = 10,
.b2 = 1,
.bo = 53,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1042[] = {
{
.name = "BARRIERS",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RIGHT_LINE",
.b1 = 4,
.b2 = 2,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LEFT_LINE",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SET_ME_1",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LDA_ALERT",
.b1 = 14,
.b2 = 2,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TWO_BEEPS",
.b1 = 11,
.b2 = 1,
.bo = 52,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ADJUSTING_CAMERA",
.b1 = 10,
.b2 = 1,
.bo = 53,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LDA_MALFUNCTION",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1553[] = {
{
.name = "UNITS",
.b1 = 29,
.b2 = 2,
.bo = 33,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1556[] = {
{
.name = "TURN_SIGNALS",
.b1 = 26,
.b2 = 2,
.bo = 36,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1568[] = {
{
.name = "DOOR_OPEN_RL",
.b1 = 45,
.b2 = 1,
.bo = 18,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "DOOR_OPEN_RR",
.b1 = 44,
.b2 = 1,
.bo = 19,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "DOOR_OPEN_FR",
.b1 = 43,
.b2 = 1,
.bo = 20,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "DOOR_OPEN_FL",
.b1 = 42,
.b2 = 1,
.bo = 21,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SEATBELT_DRIVER_UNLATCHED",
.b1 = 57,
.b2 = 1,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Msg msgs[] = {
{
.name = "KINEMATICS",
.address = 0x24,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_36),
.sigs = sigs_36,
},
{
.name = "STEER_ANGLE_SENSOR",
.address = 0x25,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_37),
.sigs = sigs_37,
},
{
.name = "BRAKE",
.address = 0xA6,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_166),
.sigs = sigs_166,
},
{
.name = "WHEEL_SPEEDS",
.address = 0xAA,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_170),
.sigs = sigs_170,
},
{
.name = "SPEED",
.address = 0xB4,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_180),
.sigs = sigs_180,
},
{
.name = "GEAR_PACKET",
.address = 0x127,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_295),
.sigs = sigs_295,
},
{
.name = "POWERTRAIN",
.address = 0x1C4,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_452),
.sigs = sigs_452,
},
{
.name = "PCM_CRUISE",
.address = 0x1D2,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_466),
.sigs = sigs_466,
},
{
.name = "PCM_CRUISE_2",
.address = 0x1D3,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_467),
.sigs = sigs_467,
},
{
.name = "BRAKE_MODULE",
.address = 0x226,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_550),
.sigs = sigs_550,
},
{
.name = "ACCELEROMETER",
.address = 0x228,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_552),
.sigs = sigs_552,
},
{
.name = "BRAKE_MODULE2",
.address = 0x230,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_560),
.sigs = sigs_560,
},
{
.name = "GAS_PEDAL",
.address = 0x245,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_581),
.sigs = sigs_581,
},
{
.name = "STEER_TORQUE_SENSOR",
.address = 0x260,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_608),
.sigs = sigs_608,
},
{
.name = "EPS_STATUS",
.address = 0x262,
.size = 5,
.num_sigs = ARRAYSIZE(sigs_610),
.sigs = sigs_610,
},
{
.name = "STEERING_IPAS",
.address = 0x266,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_614),
.sigs = sigs_614,
},
{
.name = "STEERING_LKA",
.address = 0x2E4,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_740),
.sigs = sigs_740,
},
{
.name = "LEAD_INFO",
.address = 0x2E6,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_742),
.sigs = sigs_742,
},
{
.name = "ACC_CONTROL",
.address = 0x343,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_835),
.sigs = sigs_835,
},
{
.name = "PCM_CRUISE_SM",
.address = 0x399,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_921),
.sigs = sigs_921,
},
{
.name = "ESP_CONTROL",
.address = 0x3B7,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_951),
.sigs = sigs_951,
},
{
.name = "LKAS_HUD",
.address = 0x412,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1042),
.sigs = sigs_1042,
},
{
.name = "UI_SEETING",
.address = 0x611,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1553),
.sigs = sigs_1553,
},
{
.name = "STEERING_LEVERS",
.address = 0x614,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1556),
.sigs = sigs_1556,
},
{
.name = "SEATS_DOORS",
.address = 0x620,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1568),
.sigs = sigs_1568,
},
};
const Val vals[] = {
{
.name = "GEAR",
.address = 0x127,
.def_val = "0 P 1 R 2 N 3 D 4 B",
.sigs = sigs_295,
},
{
.name = "CRUISE_STATE",
.address = 0x1D2,
.def_val = "8 ACTIVE 7 STANDSTILL 1 OFF",
.sigs = sigs_466,
},
{
.name = "LOW_SPEED_LOCKOUT",
.address = 0x1D3,
.def_val = "2 LOW_SPEED_LOCKED 1 OK",
.sigs = sigs_467,
},
{
.name = "STATE",
.address = 0x262,
.def_val = "5 OVERRIDE 3 ENABLED 1 DISABLED",
.sigs = sigs_610,
},
{
.name = "LKA_STATE",
.address = 0x262,
.def_val = "50 TEMPORARY_FAULT",
.sigs = sigs_610,
},
{
.name = "STATE",
.address = 0x266,
.def_val = "3 ENABLED 1 DISABLED",
.sigs = sigs_614,
},
{
.name = "DIRECTION_CMD",
.address = 0x266,
.def_val = "3 RIGHT 2 CENTER 1 LEFT",
.sigs = sigs_614,
},
{
.name = "CRUISE_CONTROL_STATE",
.address = 0x399,
.def_val = "2 DISABLED 11 HOLD 10 HOLD_WAITING_USER_CMD 6 ENABLED 5 FAULTED",
.sigs = sigs_921,
},
{
.name = "LDA_ALERT",
.address = 0x412,
.def_val = "3 HOLD_WITH_CONTINUOUS_BEEP 2 LDA_UNAVAILABLE 1 HOLD 0 NONE",
.sigs = sigs_1042,
},
{
.name = "LEFT_LINE",
.address = 0x412,
.def_val = "3 ORANGE 2 DOUBLE 1 SOLID 0 NONE",
.sigs = sigs_1042,
},
{
.name = "BARRIERS",
.address = 0x412,
.def_val = "3 BOTH 2 RIGHT 1 LEFT 0 NONE",
.sigs = sigs_1042,
},
{
.name = "RIGHT_LINE",
.address = 0x412,
.def_val = "3 ORANGE 2 DOUBLE 1 SOLID 0 NONE",
.sigs = sigs_1042,
},
{
.name = "UNITS",
.address = 0x611,
.def_val = "1 KM 2 MILES",
.sigs = sigs_1553,
},
{
.name = "TURN_SIGNALS",
.address = 0x614,
.def_val = "3 NONE 2 RIGHT 1 LEFT",
.sigs = sigs_1556,
},
};
}
const DBC toyota_prius_2010_pt = {
.name = "toyota_prius_2010_pt",
.num_msgs = ARRAYSIZE(msgs),
.msgs = msgs,
.vals = vals,
.num_vals = ARRAYSIZE(vals),
};
dbc_init(toyota_prius_2010_pt) | 19.889169 | 83 | 0.461964 | ziggysnorkel |
4065f9f510ff5bbb5952a42f437f1e1cb3ed9ada | 1,938 | cpp | C++ | src/dropbox/sharing/SharingAclUpdatePolicy.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 17 | 2016-12-03T09:12:29.000Z | 2020-06-20T22:08:44.000Z | src/dropbox/sharing/SharingAclUpdatePolicy.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 8 | 2017-01-05T17:50:16.000Z | 2021-08-06T18:56:29.000Z | src/dropbox/sharing/SharingAclUpdatePolicy.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 8 | 2017-09-13T17:28:40.000Z | 2020-07-27T00:41:44.000Z | /**********************************************************
DO NOT EDIT
This file was generated from stone specification "sharing"
Part of "Ardi - the organizer" project.
osoft4ardi@gmail.com
www.prokarpaty.net
***********************************************************/
#include "dropbox/sharing/SharingAclUpdatePolicy.h"
namespace dropboxQt{
namespace sharing{
///AclUpdatePolicy
AclUpdatePolicy::operator QJsonObject()const{
QJsonObject js;
this->toJson(js, "");
return js;
}
void AclUpdatePolicy::toJson(QJsonObject& js, QString name)const{
switch(m_tag){
case AclUpdatePolicy_OWNER:{
if(!name.isEmpty())
js[name] = QString("owner");
}break;
case AclUpdatePolicy_EDITORS:{
if(!name.isEmpty())
js[name] = QString("editors");
}break;
case AclUpdatePolicy_OTHER:{
if(!name.isEmpty())
js[name] = QString("other");
}break;
}//switch
}
void AclUpdatePolicy::fromJson(const QJsonObject& js){
QString s = js[".tag"].toString();
if(s.compare("owner") == 0){
m_tag = AclUpdatePolicy_OWNER;
}
else if(s.compare("editors") == 0){
m_tag = AclUpdatePolicy_EDITORS;
}
else if(s.compare("other") == 0){
m_tag = AclUpdatePolicy_OTHER;
}
}
QString AclUpdatePolicy::toString(bool multiline)const
{
QJsonObject js;
toJson(js, "AclUpdatePolicy");
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<AclUpdatePolicy> AclUpdatePolicy::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
std::unique_ptr<AclUpdatePolicy> rv = std::unique_ptr<AclUpdatePolicy>(new AclUpdatePolicy);
rv->fromJson(js);
return rv;
}
}//sharing
}//dropboxQt
| 24.846154 | 96 | 0.605779 | slashdotted |
406a5a0392853c2b2296555451431376e56e7824 | 499 | cpp | C++ | @DOC by DIPTA/dipta007_final/Number Theory/modular_inverse.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | @DOC by DIPTA/dipta007_final/Number Theory/modular_inverse.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | null | null | null | @DOC by DIPTA/dipta007_final/Number Theory/modular_inverse.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | /** Fermats Theorem **/
( A / B ) % m = ( ( A % m ) * ( B^( m - 2 ) % m ) ) % m , if m is prime
/**
Procedure:
1. Call modInv(x, mod)
**/
typedef pair <ll, ll> pll
pll extendedEuclid(ll a, ll b) // returns x, y jekhane, ax + by = gcd(a,b)
{
if(b == 0)
return pll(1, 0);
else
{
pll d = extendedEuclid(b, a % b);
return pll(d.ss, d.ff - d.ss * (a / b));
}
}
ll modularInverse(ll a, ll M) {
pll ret = extendedEuclid(a, M);
return ((ret.ff % M) + M) % M;
}
| 21.695652 | 76 | 0.48497 | dipta007 |
406bab3d3a7444fed20e33b4f4cb0bb410f999ae | 923 | cpp | C++ | test/unit/math/prim/scal/meta/scalar_seq_view_test.cpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | test/unit/math/prim/scal/meta/scalar_seq_view_test.cpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | archive/math/test/unit/math/prim/scal/meta/scalar_seq_view_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <vector>
TEST(MetaTraits, ScalarSeqViewDouble) {
using stan::scalar_seq_view;
double d = 10;
scalar_seq_view<double> sv(d);
EXPECT_FLOAT_EQ(d, sv[0]);
EXPECT_FLOAT_EQ(d, sv[12]);
const double d_const = 10;
scalar_seq_view<const double> sv_const(d_const);
EXPECT_FLOAT_EQ(d_const, sv_const[0]);
EXPECT_FLOAT_EQ(d_const, sv_const[12]);
const double& d_const_ref = 10;
scalar_seq_view<const double&> sv_const_ref(d_const);
EXPECT_FLOAT_EQ(d_const_ref, sv_const_ref[0]);
EXPECT_FLOAT_EQ(d_const_ref, sv_const_ref[12]);
EXPECT_EQ(1, sv.size());
double* d_point;
d_point = static_cast<double*>(malloc(sizeof(double) * 2));
d_point[0] = 69.0;
d_point[1] = 420.0;
scalar_seq_view<decltype(d_point)> d_point_v(d_point);
EXPECT_FLOAT_EQ(69.0, d_point_v[0]);
EXPECT_FLOAT_EQ(420.0, d_point_v[1]);
free(d_point);
}
| 26.371429 | 61 | 0.722644 | PhilClemson |
406cd461b7e7b316544d849aa2ae1d3a30cc688d | 580 | cpp | C++ | Core/src/latest/entry/main.cpp | CJBuchel/CJ-Vision | 60fad66b807c6082fdcf01df9972b42dfc5c5ecc | [
"MIT"
] | 1 | 2020-09-07T09:15:15.000Z | 2020-09-07T09:15:15.000Z | Core/src/latest/entry/main.cpp | CJBuchel/CJ-Vision | 60fad66b807c6082fdcf01df9972b42dfc5c5ecc | [
"MIT"
] | null | null | null | Core/src/latest/entry/main.cpp | CJBuchel/CJ-Vision | 60fad66b807c6082fdcf01df9972b42dfc5c5ecc | [
"MIT"
] | 1 | 2020-09-02T02:02:11.000Z | 2020-09-02T02:02:11.000Z | #include "CJ_Vision.h"
extern CJ::Application *CJ::createApplication();
int main(int argc, char **argv) {
std::cout << "Test" << std::endl;
/**
* @TODO:
* Create startup procedures + loggers and handlers
*/
CJ::Log::init("[CJ-Vision Client Startup]");
/**
* Create Application, supports only one
*/
auto app = CJ::createApplication();
CJ::Log::setClientName("[Runtime - " + app->getName() + "]");
/**
* Super loop runner
*/
app->run();
CJ::Log::setClientName("[Killtime - " + app->getName() + "]");
/**
* App cleanup
*/
delete app;
return 0;
} | 18.125 | 63 | 0.596552 | CJBuchel |
406dd3dafc850c3200b3fae6450422b7a48b9522 | 3,987 | cc | C++ | src/Modules/Legacy/Converters/ConvertBundleToField.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 92 | 2015-02-09T22:42:11.000Z | 2022-03-25T09:14:50.000Z | src/Modules/Legacy/Converters/ConvertBundleToField.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 1,618 | 2015-01-05T19:39:13.000Z | 2022-03-27T20:28:45.000Z | src/Modules/Legacy/Converters/ConvertBundleToField.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 64 | 2015-02-20T17:51:23.000Z | 2021-11-19T07:08:08.000Z | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// File: ConvertBundleToField.cc
// Author: Fangxiang Jiao
// Date: March 25 2010
#include <Core/Datatypes/Bundle.h>
#include <Core/Datatypes/Field.h>
#include <Core/Datatypes/FieldInformation.h>
#include <Core/Algorithms/Converter/ConvertBundleToField.h>
#include <Core/Algorithms/Fields/ConvertMeshType/ConvertMeshToPointCloudMesh.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/Ports/BundlePort.h>
#include <Dataflow/Network/Ports/FieldPort.h>
using namespace SCIRun;
class ConvertBundleToField : public Module {
public:
ConvertBundleToField(GuiContext*);
virtual ~ConvertBundleToField() {}
virtual void execute();
private:
GuiInt guiclear_;
GuiDouble guitolerance_;
GuiInt guimergenodes_;
GuiInt guiforcepointcloud_;
GuiInt guimatchval_;
GuiInt guimeshonly_;
SCIRunAlgo::ConvertBundleToFieldAlgo algo_;
SCIRunAlgo::ConvertMeshToPointCloudMeshAlgo calgo_;
};
DECLARE_MAKER(ConvertBundleToField)
ConvertBundleToField::ConvertBundleToField(GuiContext* ctx)
: Module("ConvertBundleToField", ctx, Source, "Converters", "SCIRun"),
guiclear_(get_ctx()->subVar("clear", false), 0),
guitolerance_(get_ctx()->subVar("tolerance"), 0.0001),
guimergenodes_(get_ctx()->subVar("force-nodemerge"), 1),
guiforcepointcloud_(get_ctx()->subVar("force-pointcloud"), 0),
guimatchval_(get_ctx()->subVar("matchval"), 0),
guimeshonly_(get_ctx()->subVar("meshonly"), 0)
{
algo_.set_progress_reporter(this);
calgo_.set_progress_reporter(this);
}
void ConvertBundleToField::execute()
{
// Define input handle:
BundleHandle handle;
// Get data from input port:
if (!(get_input_handle("bundle", handle, true)))
{
return;
}
if (inputs_changed_ || !oport_cached("Output") )
{
update_state(Executing);
// Some stuff for old power apps
if (guiclear_.get())
{
guiclear_.set(0);
// Sending 0 does not clear caches.
FieldInformation fi("PointCloudMesh", 0, "double");
FieldHandle fhandle = CreateField(fi);
send_output_handle("Output", fhandle);
return;
}
FieldHandle output;
algo_.set_scalar("tolerance", guitolerance_.get());
algo_.set_bool("merge_nodes", guimergenodes_.get());
algo_.set_bool("match_node_values", guimatchval_.get());
algo_.set_bool("make_no_data", guimeshonly_.get());
if (! ( algo_.run(handle, output) ))
return;
// This option is here to be compatible with the old GatherFields module:
// This is a separate algorithm now
if (guiforcepointcloud_.get())
{
if(! ( calgo_.run(output, output) ))
return;
}
// send new output if there is any:
send_output_handle("Output", output);
}
}
| 30.906977 | 79 | 0.722097 | Haydelj |
40725f5f3de94a17cf68ecfde61e0b369377a5b7 | 3,807 | cpp | C++ | Reflection/Utilities/DefaultRegistration.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | Reflection/Utilities/DefaultRegistration.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | Reflection/Utilities/DefaultRegistration.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 DNV AS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include "DefaultRegistration.h"
#include "Reflection/Classes/Class.h"
#include <sstream>
#include <float.h>
#include "Reflection/TypeLibraries/TypeNotCaseSensitive.h"
#include "Reflection/TypeLibraries/TypeWithGlobalMemberRegistration.h"
#include "Reflection/TypeLibraries/Type.h"
#include "Reflection/Attributes/ParserAttribute.h"
#include "Formatting/ToString.h"
#include "ConstructibleItem.h"
#include "MemberItem.h"
#include "boost\lexical_cast.hpp"
#include "boost\optional.hpp"
namespace DNVS {namespace MoFa {namespace Reflection {namespace Utilities {
template<typename T>
struct FundamentalParser {
public:
boost::optional<T> operator()(const std::string& text, const Formatting::FormattingService& service) const
{
return boost::lexical_cast<T>(text);
}
};
template<>
struct FundamentalParser<double> {
public:
boost::optional<double> operator()(const std::string& text, const Formatting::FormattingService& service) const
{
if (text == "NaN")
{
return std::numeric_limits<double>::quiet_NaN();
}
else if (text == "+Infinity")
{
return std::numeric_limits<double>::infinity();
}
else if (text == "-Infinity")
{
return -std::numeric_limits<double>::infinity();
}
else {
return boost::lexical_cast<double>(text);
}
}
};
template<>
struct FundamentalParser<bool> {
public:
boost::optional<bool> operator()(const std::string& text, const Formatting::FormattingService& service) const
{
if (text == "true")
return true;
else
return false;
}
};
template<typename T>
void ReflectFundamental(TypeLibraries::TypeLibraryPointer typeLibrary)
{
using namespace Classes;
Class<T> cls(typeLibrary, "");
cls.AddAttribute<ParserAttribute>(FundamentalParser<T>());
cls.Operator(This.Const == This.Const);
cls.Operator(This.Const != This.Const);
cls.Operator(This.Const < This.Const);
cls.Operator(This.Const > This.Const);
cls.Operator(This.Const <= This.Const);
cls.Operator(This.Const >= This.Const);
RegisterToStringFunction(cls);
}
void DefaultRegistration::Reflect(TypeLibraries::TypeLibraryPointer typeLibrary)
{
ReflectFundamental<unsigned char>(typeLibrary);
ReflectFundamental<signed char>(typeLibrary);
ReflectFundamental<unsigned short>(typeLibrary);
ReflectFundamental<signed short>(typeLibrary);
ReflectFundamental<unsigned int>(typeLibrary);
ReflectFundamental<signed int>(typeLibrary);
ReflectFundamental<unsigned long>(typeLibrary);
ReflectFundamental<signed long>(typeLibrary);
ReflectFundamental<unsigned __int64>(typeLibrary);
ReflectFundamental<signed __int64>(typeLibrary);
ReflectFundamental<char>(typeLibrary);
ReflectFundamental<bool>(typeLibrary);
ReflectFundamental<float>(typeLibrary);
ReflectFundamental<double>(typeLibrary);
Reflection::Reflect<TypeLibraries::Type>(typeLibrary);
Reflection::Reflect<TypeLibraries::TypeWithGlobalMemberRegistration>(typeLibrary);
Reflection::Reflect<TypeLibraries::TypeNotCaseSensitive>(typeLibrary);
Reflection::Reflect<ConstructibleItem>(typeLibrary);
Reflection::Reflect<MemberItem>(typeLibrary);
}
}}}}
| 35.25 | 119 | 0.653533 | dnv-opensource |
4072b0d7454a535a65f813f01c31f2bc1c6a4ffa | 3,734 | cpp | C++ | src/conv/step/g-step/Shape_Representation.cpp | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 35 | 2015-03-11T11:51:48.000Z | 2021-07-25T16:04:49.000Z | src/conv/step/g-step/Shape_Representation.cpp | CloudComputer/brlcad | 05952aafa27ee9df17cd900f5d8f8217ed2194af | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/conv/step/g-step/Shape_Representation.cpp | CloudComputer/brlcad | 05952aafa27ee9df17cd900f5d8f8217ed2194af | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 19 | 2016-05-04T08:39:37.000Z | 2021-12-07T12:45:54.000Z | /* S H A P E _ R E P R E S E N T A T I O N . C P P
* BRL-CAD
*
* Copyright (c) 2013-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file Shape_Representation.cpp
*
*/
#include "AP_Common.h"
#include "Shape_Representation.h"
SdaiRepresentation *
Add_Shape_Representation(AP203_Contents *sc, SdaiRepresentation_context *context)
{
SdaiShape_representation *shape_rep = (SdaiShape_representation *)sc->registry->ObjCreate("SHAPE_REPRESENTATION");
sc->instance_list->Append((STEPentity *)shape_rep, completeSE);
shape_rep->name_("''");
shape_rep->context_of_items_(context);
EntityAggregate *axis_items = shape_rep->items_();
/* create an axis */
SdaiAxis2_placement_3d *axis3d = (SdaiAxis2_placement_3d *)sc->registry->ObjCreate("AXIS2_PLACEMENT_3D");
sc->instance_list->Append((STEPentity *)axis3d, completeSE);
axis3d->name_("''");
/* set the axis origin */
SdaiCartesian_point *origin= (SdaiCartesian_point *)sc->registry->ObjCreate("CARTESIAN_POINT");
sc->instance_list->Append((STEPentity *)origin, completeSE);
RealNode *xnode = new RealNode();
xnode->value = 0.0;
RealNode *ynode= new RealNode();
ynode->value = 0.0;
RealNode *znode= new RealNode();
znode->value = 0.0;
origin->coordinates_()->AddNode(xnode);
origin->coordinates_()->AddNode(ynode);
origin->coordinates_()->AddNode(znode);
origin->name_("''");
axis3d->location_(origin);
/* set the axis up direction (i-vector) */
SdaiDirection *axis = (SdaiDirection *)sc->registry->ObjCreate("DIRECTION");
sc->instance_list->Append((STEPentity *)axis, completeSE);
RealNode *axis_xnode = new RealNode();
axis_xnode->value = 0.0;
RealNode *axis_ynode= new RealNode();
axis_ynode->value = 0.0;
RealNode *axis_znode= new RealNode();
axis_znode->value = 1.0;
axis->direction_ratios_()->AddNode(axis_xnode);
axis->direction_ratios_()->AddNode(axis_ynode);
axis->direction_ratios_()->AddNode(axis_znode);
axis->name_("''");
axis3d->axis_(axis);
/* add the axis front direction (j-vector) */
SdaiDirection *ref_dir = (SdaiDirection *)sc->registry->ObjCreate("DIRECTION");
sc->instance_list->Append((STEPentity *)ref_dir, completeSE);
RealNode *ref_dir_xnode = new RealNode();
ref_dir_xnode->value = 1.0;
RealNode *ref_dir_ynode= new RealNode();
ref_dir_ynode->value = 0.0;
RealNode *ref_dir_znode= new RealNode();
ref_dir_znode->value = 0.0;
ref_dir->direction_ratios_()->AddNode(ref_dir_xnode);
ref_dir->direction_ratios_()->AddNode(ref_dir_ynode);
ref_dir->direction_ratios_()->AddNode(ref_dir_znode);
ref_dir->name_("''");
axis3d->ref_direction_(ref_dir);
/* add the axis to the shape definition */
axis_items->AddNode(new EntityNode((SDAI_Application_instance *)axis3d));
return (SdaiRepresentation *)shape_rep;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 33.945455 | 118 | 0.696036 | behollis |
40741c24bfc26e731e5b37cfb759f625b35e499f | 6,748 | cc | C++ | ash/window_manager_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ash/window_manager_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ash/window_manager_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 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 <map>
#include <memory>
#include <vector>
#include "ash/public/cpp/window_properties.h"
#include "ash/public/interfaces/constants.mojom.h"
#include "ash/public/interfaces/window_properties.mojom.h"
#include "ash/session/test_session_controller_client.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/ash_test_helper.h"
#include "ash/window_manager.h"
#include "ash/window_manager_service.h"
#include "base/bind.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "components/session_manager/session_manager_types.h"
#include "services/service_manager/public/cpp/service_test.h"
#include "services/ui/public/cpp/property_type_converters.h"
#include "services/ui/public/interfaces/window_manager_constants.mojom.h"
#include "services/ui/public/interfaces/window_tree.mojom.h"
#include "ui/aura/env.h"
#include "ui/aura/mus/property_converter.h"
#include "ui/aura/mus/window_tree_client.h"
#include "ui/aura/mus/window_tree_client_delegate.h"
#include "ui/aura/mus/window_tree_host_mus.h"
#include "ui/aura/mus/window_tree_host_mus_init_params.h"
#include "ui/aura/test/env_test_helper.h"
#include "ui/aura/window.h"
#include "ui/display/display.h"
#include "ui/display/display_list.h"
#include "ui/display/screen_base.h"
#include "ui/wm/core/capture_controller.h"
#include "ui/wm/core/wm_state.h"
namespace ash {
class WindowTreeClientDelegate : public aura::WindowTreeClientDelegate {
public:
WindowTreeClientDelegate() = default;
~WindowTreeClientDelegate() override = default;
void WaitForEmbed() { run_loop_.Run(); }
void DestroyWindowTreeHost() { window_tree_host_.reset(); }
private:
// aura::WindowTreeClientDelegate:
void OnEmbed(
std::unique_ptr<aura::WindowTreeHostMus> window_tree_host) override {
window_tree_host_ = std::move(window_tree_host);
run_loop_.Quit();
}
void OnEmbedRootDestroyed(
aura::WindowTreeHostMus* window_tree_host) override {}
void OnLostConnection(aura::WindowTreeClient* client) override {}
void OnPointerEventObserved(const ui::PointerEvent& event,
int64_t display_id,
aura::Window* target) override {}
aura::PropertyConverter* GetPropertyConverter() override {
return &property_converter_;
}
base::RunLoop run_loop_;
::wm::WMState wm_state_;
aura::PropertyConverter property_converter_;
std::unique_ptr<aura::WindowTreeHostMus> window_tree_host_;
DISALLOW_COPY_AND_ASSIGN(WindowTreeClientDelegate);
};
class WindowManagerServiceTest : public service_manager::test::ServiceTest {
public:
WindowManagerServiceTest()
: service_manager::test::ServiceTest("mash_unittests") {}
~WindowManagerServiceTest() override = default;
void TearDown() override {
// Unset the screen installed by the test.
display::Screen::SetScreenInstance(nullptr);
service_manager::test::ServiceTest::TearDown();
}
private:
DISALLOW_COPY_AND_ASSIGN(WindowManagerServiceTest);
};
void OnEmbed(bool success) {
ASSERT_TRUE(success);
}
#if defined(ADDRESS_SANITIZER)
#define MAYBE_OpenWindow DISABLED_OpenWindow
#else
#define MAYBE_OpenWindow OpenWindow
#endif
TEST_F(WindowManagerServiceTest, MAYBE_OpenWindow) {
display::ScreenBase screen;
screen.display_list().AddDisplay(
display::Display(1, gfx::Rect(0, 0, 200, 200)),
display::DisplayList::Type::PRIMARY);
display::Screen::SetScreenInstance(&screen);
WindowTreeClientDelegate window_tree_delegate;
connector()->StartService(mojom::kServiceName);
// Connect to mus and create a new top level window. The request goes to
// |ash|, but is async.
std::unique_ptr<aura::WindowTreeClient> client =
aura::WindowTreeClient::CreateForWindowTreeFactory(
connector(), &window_tree_delegate, false);
aura::test::EnvWindowTreeClientSetter env_window_tree_client_setter(
client.get());
std::map<std::string, std::vector<uint8_t>> properties;
properties[ui::mojom::WindowManager::kWindowType_InitProperty] =
mojo::ConvertTo<std::vector<uint8_t>>(
static_cast<int32_t>(ui::mojom::WindowType::WINDOW));
aura::WindowTreeHostMus window_tree_host_mus(
aura::CreateInitParamsForTopLevel(client.get(), std::move(properties)));
window_tree_host_mus.InitHost();
aura::Window* child_window = new aura::Window(nullptr);
child_window->Init(ui::LAYER_NOT_DRAWN);
window_tree_host_mus.window()->AddChild(child_window);
// Create another WindowTreeClient by way of embedding in
// |child_window|. This blocks until it succeeds.
ui::mojom::WindowTreeClientPtr tree_client;
auto tree_client_request = MakeRequest(&tree_client);
client->Embed(child_window, std::move(tree_client), 0u, base::Bind(&OnEmbed));
std::unique_ptr<aura::WindowTreeClient> child_client =
aura::WindowTreeClient::CreateForEmbedding(
connector(), &window_tree_delegate, std::move(tree_client_request),
false);
window_tree_delegate.WaitForEmbed();
ASSERT_TRUE(!child_client->GetRoots().empty());
window_tree_delegate.DestroyWindowTreeHost();
}
using WindowManagerTest = AshTestBase;
TEST_F(WindowManagerTest, SystemModalLockIsntReparented) {
ash_test_helper()->test_session_controller_client()->SetSessionState(
session_manager::SessionState::LOCKED);
std::unique_ptr<aura::Window> window = CreateTestWindow();
aura::Window* system_modal_container = Shell::GetContainer(
Shell::GetPrimaryRootWindow(), kShellWindowId_LockSystemModalContainer);
system_modal_container->AddChild(window.get());
aura::WindowManagerDelegate* window_manager_delegate =
ash_test_helper()->window_manager_service()->window_manager();
window_manager_delegate->OnWmSetModalType(window.get(),
ui::MODAL_TYPE_SYSTEM);
ASSERT_TRUE(window->parent());
// Setting to system modal should not reparent.
EXPECT_EQ(kShellWindowId_LockSystemModalContainer, window->parent()->id());
}
TEST_F(WindowManagerTest, CanConsumeSystemKeysFromContentBrowser) {
std::map<std::string, std::vector<uint8_t>> properties;
properties[ash::mojom::kCanConsumeSystemKeys_Property] =
mojo::ConvertTo<std::vector<uint8_t>>(static_cast<int64_t>(true));
aura::WindowManagerDelegate* window_manager_delegate =
ash_test_helper()->window_manager_service()->window_manager();
aura::Window* window = window_manager_delegate->OnWmCreateTopLevelWindow(
ui::mojom::WindowType::WINDOW, &properties);
EXPECT_EQ(true, window->GetProperty(kCanConsumeSystemKeysKey));
}
} // namespace ash
| 38.340909 | 80 | 0.756076 | zipated |
40745804ff968472e9dfd25ce7167fe36acc6855 | 52 | hpp | C++ | src/boost_function_types_parameter_types.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_function_types_parameter_types.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_function_types_parameter_types.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/function_types/parameter_types.hpp>
| 26 | 51 | 0.846154 | miathedev |
40796cedda6f3533ccca96115cfe18a10f5d1b02 | 153 | cpp | C++ | lib/src/block.cpp | caseymcc/client | 0db6e9b6a66828d2c6faf8ce9db173f541221f70 | [
"MIT"
] | 1 | 2021-06-08T14:56:47.000Z | 2021-06-08T14:56:47.000Z | lib/src/block.cpp | caseymcc/client | 0db6e9b6a66828d2c6faf8ce9db173f541221f70 | [
"MIT"
] | null | null | null | lib/src/block.cpp | caseymcc/client | 0db6e9b6a66828d2c6faf8ce9db173f541221f70 | [
"MIT"
] | null | null | null | #include "block.h"
namespace konstructs {
Block::Block(const Vector3i position, const BlockData data):
position(position), data(data) {}
};
| 21.857143 | 64 | 0.686275 | caseymcc |
40798ac56ef00f3eea109ba54670750e4318300a | 127 | hpp | C++ | NWNXLib/API/Mac/API/unknown_std__vectorTemplatedvoidPtrstd__allocatorTemplatedvoidPtr.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | NWNXLib/API/Mac/API/unknown_std__vectorTemplatedvoidPtrstd__allocatorTemplatedvoidPtr.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | NWNXLib/API/Mac/API/unknown_std__vectorTemplatedvoidPtrstd__allocatorTemplatedvoidPtr.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | #pragma once
namespace NWNXLib {
namespace API {
class std__vectorTemplatedvoidPtrstd__allocatorTemplatedvoidPtr { };
}
}
| 10.583333 | 68 | 0.787402 | Qowyn |
407b3d4bdc100f16c790cc3ac0e301cc9b728f0e | 2,484 | cpp | C++ | tianhe/schedule_restricts_test.cpp | VastRock-Huang/GraphPi | a780bd73743c8535b1e36da210558b0dc81ff0d4 | [
"MIT"
] | 22 | 2020-10-07T06:53:49.000Z | 2022-03-18T14:00:55.000Z | tianhe/schedule_restricts_test.cpp | VastRock-Huang/GraphPi | a780bd73743c8535b1e36da210558b0dc81ff0d4 | [
"MIT"
] | null | null | null | tianhe/schedule_restricts_test.cpp | VastRock-Huang/GraphPi | a780bd73743c8535b1e36da210558b0dc81ff0d4 | [
"MIT"
] | 5 | 2020-11-19T20:53:28.000Z | 2021-11-28T17:42:29.000Z | #include <../include/graph.h>
#include <../include/dataloader.h>
#include "../include/pattern.h"
#include "../include/schedule.h"
#include "../include/common.h"
#include "../include/motif_generator.h"
#include <assert.h>
#include <iostream>
#include <string>
#include <algorithm>
void test_pattern(Graph* g, const Pattern &pattern, int performance_modeling_type, int restricts_type, bool use_in_exclusion_optimize = false) {
long long tri_cnt = 7515023;
int thread_num = 24;
double t1,t2;
bool is_pattern_valid;
Schedule schedule(pattern, is_pattern_valid, performance_modeling_type, restricts_type, use_in_exclusion_optimize, g->v_cnt, g->e_cnt, tri_cnt);
assert(is_pattern_valid);
if(schedule.get_multiplicity() == 1) return;
t1 = get_wall_time();
long long ans = g->pattern_matching(schedule, thread_num);
t2 = get_wall_time();
printf("ans %lld,%.6lf\n", ans, t2 - t1);
schedule.print_schedule();
const auto& pairs = schedule.restrict_pair;
printf("%d ",pairs.size());
for(auto& p : pairs)
printf("(%d,%d)",p.first,p.second);
puts("");
fflush(stdout);
}
int main(int argc,char *argv[]) {
Graph *g;
DataLoader D;
std::string type = "Patents";
std::string path = "/home/zms/patents_input";
DataType my_type;
if(type == "Patents") my_type = DataType::Patents;
else {
printf("invalid DataType!\n");
}
assert(D.load_data(g,my_type,path.c_str())==true);
printf("Load data success!\n");
fflush(stdout);
Pattern p(atoi(argv[1]), argv[2]);
test_pattern(g, p, 1, 1, true);
test_pattern(g, p, 1, 1);
test_pattern(g, p, 1, 2);
test_pattern(g, p, 2, 1);
test_pattern(g, p, 2, 2);
/*
int rank = atoi(argv[1]);
for(int size = 3; size < 7; ++size) {
MotifGenerator mg(size);
std::vector<Pattern> patterns = mg.generate();
int len = patterns.size();
for(int i = rank; i < patterns.size(); i += 20) {
Pattern& p = patterns[i];
test_pattern(g, p, 1, 1);
test_pattern(g, p, 1, 2);
test_pattern(g, p, 2, 1);
test_pattern(g, p, 2, 2);
}
}
*/
/*
Pattern p(6);
p.add_edge(0, 1);
p.add_edge(0, 2);
p.add_edge(0, 3);
p.add_edge(1, 4);
p.add_edge(1, 5);
test_pattern(g, p, 1, 1);
test_pattern(g, p, 1, 2);
test_pattern(g, p, 2, 1);
test_pattern(g, p, 2, 2);
*/
delete g;
}
| 26.709677 | 148 | 0.596216 | VastRock-Huang |
407c16ad4c6eb7e3167dcb07c28fc45d6c0559d5 | 13,337 | cc | C++ | v4l2/v4l2camera.cc | rwaldron/node-audiovideo | 89c9da8ce9d63342d335e948246d68cecdfe6578 | [
"MIT"
] | 19 | 2015-05-09T02:49:26.000Z | 2021-11-29T21:53:41.000Z | v4l2/v4l2camera.cc | tcr/node-audiovideo | 61756bfd1e5adead0abbadbf17225d07c3fbfbfa | [
"MIT"
] | 11 | 2016-02-02T18:22:00.000Z | 2016-09-03T16:52:37.000Z | v4l2/v4l2camera.cc | tcr/node-audiovideo | 61756bfd1e5adead0abbadbf17225d07c3fbfbfa | [
"MIT"
] | 4 | 2016-02-03T21:42:26.000Z | 2016-05-02T20:29:40.000Z | #include "capture.h"
#include <nan.h>
#include <node.h>
#include <v8.h>
#include <uv.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <sstream>
using v8::Function;
using v8::FunctionTemplate;
using v8::ObjectTemplate;
using v8::Handle;
using v8::Object;
using v8::String;
using v8::Number;
using v8::Boolean;
using v8::Local;
using v8::Value;
using v8::Array;
using v8::Persistent;
struct CallbackData {
Persistent<Object> thisObj;
Nan::Callback* callback;
};
class Camera : public Nan::ObjectWrap {
public:
static void Init(Handle<Object> exports);
private:
static NAN_METHOD(New);
static NAN_METHOD(Start);
static NAN_METHOD(Stop);
static NAN_METHOD(Capture);
static NAN_METHOD(ToYUYV);
static NAN_METHOD(ToRGB);
static NAN_METHOD(ConfigGet);
static NAN_METHOD(ConfigSet);
static NAN_METHOD(ControlGet);
static NAN_METHOD(ControlSet);
static Local<Object> Controls(camera_t* camera);
static Local<Object> Formats(camera_t* camera);
static void StopCB(uv_poll_t* handle, int status, int events);
static void CaptureCB(uv_poll_t* handle, int status, int events);
static void
WatchCB(uv_poll_t* handle, void (*callbackCall)(CallbackData* data));
static void Watch(Handle<Object> thisObj, Nan::Callback* cb1, uv_poll_cb cb);
Camera();
~Camera();
camera_t* camera;
};
//[error message handling]
struct LogContext {
std::string msg;
};
static void logRecord(camera_log_t type, const char* msg, void* pointer) {
std::stringstream ss;
switch (type) {
case CAMERA_ERROR:
ss << "CAMERA ERROR [" << msg << "] " << errno << " " << strerror(errno);
break;
case CAMERA_FAIL:
ss << "CAMERA FAIL [" << msg << "]";
break;
case CAMERA_INFO:
ss << "CAMERA INFO [" << msg << "]";
break;
}
static_cast<LogContext*>(pointer)->msg = ss.str();
}
//[helpers]
static inline Local<Value>
getValue(const Local<Object>& self, const char* name) {
return Nan::Get(self, Nan::New<String>(name).ToLocalChecked()).ToLocalChecked();
}
static inline int32_t
getInt(const Local<Object>& self, const char* name) {
return getValue(self, name)->Int32Value();
}
static inline uint32_t
getUint(const Local<Object>& self, const char* name) {
return getValue(self, name)->Uint32Value();
}
static inline void
setValue(const Local<Object>& self, const char* name,
const Handle<Value>& value) {
Nan::Set(self, Nan::New<String>(name).ToLocalChecked(), value);
}
static inline void
setInt(const Local<Object>& self, const char* name, int32_t value) {
setValue(self, name, Nan::New<Number>(value));
}
static inline void
setUint(const Local<Object>& self, const char* name,
uint32_t value) {
setValue(self, name, Nan::New<Number>(value));
}
static inline void
setString(const Local<Object>& self, const char* name,
const char* value) {
setValue(self, name, Nan::New<String>(value).ToLocalChecked());
}
static inline void
setBool(const Local<Object>& self, const char* name, bool value) {
setValue(self, name, Nan::New<Boolean>(value));
}
//[callback helpers]
void Camera::WatchCB(uv_poll_t* handle,
void (*callbackCall)(CallbackData* data)) {
auto data = static_cast<CallbackData*>(handle->data);
uv_poll_stop(handle);
uv_close(reinterpret_cast<uv_handle_t*>(handle),
[](uv_handle_t* handle) -> void {delete handle;});
callbackCall(data);
data->thisObj.Reset();
delete data->callback;
delete data;
}
void Camera::Watch(Local<Object> thisObj, Nan::Callback* cb1, uv_poll_cb cb) {
auto data = new CallbackData;
data->thisObj.Reset(v8::Isolate::GetCurrent(), thisObj);
data->callback = cb1;
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
uv_poll_t* handle = new uv_poll_t;
handle->data = data;
uv_poll_init(uv_default_loop(), handle, camera->fd);
uv_poll_start(handle, UV_READABLE, cb);
}
//[methods]
static const char* control_type_names[] = {
"invalid",
"int",
"bool",
"menu",
"int64",
"class"
"string",
"bitmask",
"int_menu",
};
Local<Object> Camera::Controls (camera_t* camera) {
auto ccontrols = camera_controls_new(camera);
auto controls = Nan::New<Array>(ccontrols->length);
for (size_t i = 0; i < ccontrols->length; i++) {
auto ccontrol = &ccontrols->head[i];
auto control = Nan::New<Object>();
auto name = Nan::New<String>(reinterpret_cast<char*>(ccontrol->name)).ToLocalChecked();
Nan::Set(controls, i, control);
Nan::Set(controls, name, control);
setUint(control, "id", ccontrol->id);
setValue(control, "name", name);
setString(control, "type", control_type_names[ccontrol->type]);
setInt(control, "min", ccontrol->min);
setInt(control, "max", ccontrol->max);
setInt(control, "step", ccontrol->step);
setInt(control, "default", ccontrol->default_value);
auto flags = Nan::New<Object>();
setValue(control, "flags", flags);
setBool(flags, "disabled", ccontrol->flags.disabled);
setBool(flags, "grabbed", ccontrol->flags.grabbed);
setBool(flags, "readOnly", ccontrol->flags.read_only);
setBool(flags, "update", ccontrol->flags.update);
setBool(flags, "inactive", ccontrol->flags.inactive);
setBool(flags, "slider", ccontrol->flags.slider);
setBool(flags, "writeOnly", ccontrol->flags.write_only);
setBool(flags, "volatile", ccontrol->flags.volatile_value);
auto menu = Nan::New<Array>(ccontrol->menus.length);
setValue(control, "menu", menu);
switch (ccontrol->type) {
case CAMERA_CTRL_MENU:
for (size_t j = 0; j < ccontrol->menus.length; j++) {
auto value = reinterpret_cast<char*>(ccontrol->menus.head[j].name);
menu->Set(j, Nan::New<String>(value).ToLocalChecked());
}
break;
#ifndef CAMERA_OLD_VIDEODEV2_H
case CAMERA_CTRL_INTEGER_MENU:
for (size_t j = 0; j < ccontrol->menus.length; j++) {
auto value = static_cast<int32_t>(ccontrol->menus.head[j].value);
menu->Set(j, Nan::New<Number>(value));
}
break;
#endif
default: break;
}
}
camera_controls_delete(ccontrols);
return controls;
}
Local<Object> convertFormat(camera_format_t* cformat) {
char name[5];
camera_format_name(cformat->format, name);
auto format = Nan::New<Object>();
setString(format, "formatName", name);
setUint(format, "format", cformat->format);
setUint(format, "width", cformat->width);
setUint(format, "height", cformat->height);
auto interval = Nan::New<Object>();
setValue(format, "interval", interval);
setUint(interval, "numerator", cformat->interval.numerator);
setUint(interval, "denominator", cformat->interval.denominator);
return format;
}
Local<Object> Camera::Formats(camera_t* camera) {
auto cformats = camera_formats_new(camera);
auto formats = Nan::New<Array>(cformats->length);
for (size_t i = 0; i < cformats->length; i++) {
auto cformat = &cformats->head[i];
auto format = convertFormat(cformat);
formats->Set(i, format);
}
return formats;
}
NAN_METHOD(Camera::New) {
if (info.Length() < 1) {
Nan::ThrowTypeError("argument required: device");
}
String::Utf8Value device(info[0]->ToString());
auto camera = camera_open(*device);
if (!camera) {
Nan::ThrowError(strerror(errno));
}
camera->context.pointer = new LogContext;
camera->context.log = &logRecord;
auto thisObj = info.This();
auto self = new Camera();
self->camera = camera;
self->Wrap(thisObj);
setValue(thisObj, "device", info[0]);
setValue(thisObj, "formats", Formats(camera));
setValue(thisObj, "controls", Controls(camera));
info.GetReturnValue().Set(thisObj);
}
NAN_METHOD(Camera::Start) {
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
if (!camera_start(camera)) {
Nan::ThrowError("Camera cannot start");
}
setUint(thisObj, "width", camera->width);
setUint(thisObj, "height", camera->height);
info.GetReturnValue().Set(thisObj);
}
void Camera::StopCB(uv_poll_t* handle, int /*status*/, int /*events*/) {
auto callCallback = [](CallbackData* data) -> void {
Local<Object> thisObj = Nan::New(data->thisObj);
data->callback->Call(thisObj, 0, nullptr);
};
WatchCB(handle, callCallback);
}
NAN_METHOD(Camera::Stop) {
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
if (!camera_stop(camera)) {
Nan::ThrowError("Camera cannot stop");
}
Watch(info.This(), new Nan::Callback(info[0].As<Function>()), StopCB);
info.GetReturnValue().Set(Nan::Undefined());
}
void Camera::CaptureCB(uv_poll_t* handle, int /*status*/, int /*events*/) {
auto callCallback = [](CallbackData* data) -> void {
Local<Object> thisObj = Nan::New(data->thisObj);
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
bool captured = camera_capture(camera);
Local<Value> argv[] = {
Nan::New<Boolean>(captured),
};
data->callback->Call(thisObj, 1, argv);
};
WatchCB(handle, callCallback);
}
NAN_METHOD(Camera::Capture) {
Watch(info.This(), new Nan::Callback(info[0].As<Function>()), CaptureCB);
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(Camera::ToYUYV) {
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
int size = camera->width * camera->height * 2;
Local<Object> ret = Nan::CopyBuffer((const char*) camera->head.start, size).ToLocalChecked();
info.GetReturnValue().Set(ret);
}
NAN_METHOD(Camera::ToRGB) {
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
auto rgb = yuyv2rgb(camera->head.start, camera->width, camera->height);
int size = camera->width * camera->height * 3;
Local<Object> ret = Nan::NewBuffer((char*) rgb, size).ToLocalChecked();
info.GetReturnValue().Set(ret);
}
NAN_METHOD(Camera::ConfigGet) {
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
camera_format_t cformat;
if (!camera_config_get(camera, &cformat)) {
Nan::ThrowError("Cannot get configuration");
}
auto format = convertFormat(&cformat);
info.GetReturnValue().Set(format);
}
NAN_METHOD(Camera::ConfigSet) {
if (info.Length() < 1) {
Nan::ThrowTypeError("argument required: config");
}
auto format = info[0]->ToObject();
uint32_t width = getUint(format, "width");
uint32_t height = getUint(format, "height");
uint32_t numerator = 0;
uint32_t denominator = 0;
auto finterval = getValue(format, "interval");
if (finterval->IsObject()) {
auto interval = finterval->ToObject();
numerator = getUint(interval, "numerator");
denominator = getUint(interval, "denominator");
}
camera_format_t cformat = {0, width, height, {numerator, denominator}};
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
if (!camera_config_set(camera, &cformat)) {
Nan::ThrowError("Cannot set configuration");
}
setUint(thisObj, "width", camera->width);
setUint(thisObj, "height", camera->height);
info.GetReturnValue().Set(thisObj);
}
NAN_METHOD(Camera::ControlGet) {
if (info.Length() < 1) {
return Nan::ThrowTypeError("an argument required: id");
}
uint32_t id = info[0]->Uint32Value();
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
int32_t value = 0;
bool success = camera_control_get(camera, id, &value);
if (!success) {
Nan::ThrowError("Cannot get camera control.");
}
info.GetReturnValue().Set(Nan::New<Number>(value));
}
NAN_METHOD(Camera::ControlSet) {
if (info.Length() < 2) {
Nan::ThrowTypeError("arguments required: id, value");
}
uint32_t id = info[0]->Uint32Value();
int32_t value = info[1]->Int32Value();
auto thisObj = info.This();
auto camera = Nan::ObjectWrap::Unwrap<Camera>(thisObj)->camera;
bool success = camera_control_set(camera, id, value);
if (!success) {
Nan::ThrowError("Cannot set camera control.");
}
info.GetReturnValue().Set(thisObj);
}
Camera::Camera() : camera(nullptr) {}
Camera::~Camera() {
if (camera) {
auto ctx = static_cast<LogContext*>(camera->context.pointer);
camera_close(camera);
delete ctx;
}
}
//[module init]
static inline void
setMethod(const Local<ObjectTemplate>& proto, const char* name,
NAN_METHOD(func)) {
auto funcValue = Nan::New<FunctionTemplate>(func)->GetFunction();
proto->Set(Nan::New<String>(name).ToLocalChecked(), funcValue);
}
void Camera::Init(Handle<Object> exports) {
auto name = Nan::New<String>("Camera");
auto clazz = Nan::New<FunctionTemplate>(New);
clazz->SetClassName(name.ToLocalChecked());
clazz->InstanceTemplate()->SetInternalFieldCount(1);
auto proto = clazz->PrototypeTemplate();
setMethod(proto, "start", Start);
setMethod(proto, "stop", Stop);
setMethod(proto, "capture", Capture);
setMethod(proto, "toYUYV", ToYUYV);
setMethod(proto, "toRGB", ToRGB);
setMethod(proto, "configGet", ConfigGet);
setMethod(proto, "configSet", ConfigSet);
setMethod(proto, "controlGet", ControlGet);
setMethod(proto, "controlSet", ControlSet);
Local<Function> ctor = clazz->GetFunction();
Nan::Set(exports, name.ToLocalChecked(), ctor);
}
NODE_MODULE(v4l2camera, Camera::Init)
| 31.161215 | 95 | 0.677139 | rwaldron |
40806fc33a38823694383f625d001b7955769a7c | 1,747 | hh | C++ | maxutils/maxsql/include/maxsql/mariadb.hh | nephtyws/MaxScale | 312469dca2721666d9fff310b6c3166b0d05d2a3 | [
"MIT"
] | null | null | null | maxutils/maxsql/include/maxsql/mariadb.hh | nephtyws/MaxScale | 312469dca2721666d9fff310b6c3166b0d05d2a3 | [
"MIT"
] | null | null | null | maxutils/maxsql/include/maxsql/mariadb.hh | nephtyws/MaxScale | 312469dca2721666d9fff310b6c3166b0d05d2a3 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxsql/ccdefs.hh>
#include <time.h>
#include <string>
#include <mysql.h>
namespace maxsql
{
/**
* Execute a query, manually defining retry limits.
*
* @param conn MySQL connection
* @param query Query to execute
* @param query_retries Maximum number of retries
* @param query_retry_timeout Maximum time to spend retrying, in seconds
* @return return value of mysql_query
*/
int mysql_query_ex(MYSQL* conn, const std::string& query, int query_retries, time_t query_retry_timeout);
/**
* Check if the MYSQL error number is a connection error.
*
* @param Error code
* @return True if the MYSQL error number is a connection error
*/
bool mysql_is_net_error(unsigned int errcode);
/**
* Enable/disable the logging of all SQL statements MaxScale sends to
* the servers.
*
* @param enable If true, enable, if false, disable.
*/
void mysql_set_log_statements(bool enable);
/**
* Returns whether SQL statements sent to the servers are logged or not.
*
* @return True, if statements are logged, false otherwise.
*/
bool mysql_get_log_statements();
/** Length-encoded integers */
size_t leint_bytes(const uint8_t* ptr);
uint64_t leint_value(const uint8_t* c);
uint64_t leint_consume(uint8_t** c);
/** Length-encoded strings */
char* lestr_consume_dup(uint8_t** c);
char* lestr_consume(uint8_t** c, size_t* size);
}
| 26.469697 | 105 | 0.735547 | nephtyws |
408238d04fe8683e3500c9fc1001102d086fec87 | 1,966 | cpp | C++ | Tests/UnitTests/DFNs/FeaturesDescription2D/OrbDescriptor.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 7 | 2019-02-26T15:09:50.000Z | 2021-09-30T07:39:01.000Z | Tests/UnitTests/DFNs/FeaturesDescription2D/OrbDescriptor.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | null | null | null | Tests/UnitTests/DFNs/FeaturesDescription2D/OrbDescriptor.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 1 | 2020-12-06T12:09:05.000Z | 2020-12-06T12:09:05.000Z | /* --------------------------------------------------------------------------
*
* (C) Copyright …
*
* ---------------------------------------------------------------------------
*/
/*!
* @file OrbDescriptor.cpp
* @date 21/02/2018
* @author Alessandro Bianco
*/
/*!
* @addtogroup DFNsTest
*
* Testing application for the DFN OrbDescriptor.
*
*
* @{
*/
/* --------------------------------------------------------------------------
*
* Includes
*
* --------------------------------------------------------------------------
*/
#include <catch.hpp>
#include <FeaturesDescription2D/OrbDescriptor.hpp>
#include <Converters/MatToFrameConverter.hpp>
using namespace CDFF::DFN::FeaturesDescription2D;
using namespace Converters;
using namespace FrameWrapper;
using namespace VisualPointFeatureVector2DWrapper;
/* --------------------------------------------------------------------------
*
* Test Cases
*
* --------------------------------------------------------------------------
*/
TEST_CASE( "Call to process (ORB descriptor)", "[process]" )
{
// Prepare input data
cv::Mat inputImage(500, 500, CV_8UC3, cv::Scalar(100, 100, 100));
FrameConstPtr inputFrame = MatToFrameConverter().Convert(inputImage);
VisualPointFeatureVector2DConstPtr inputFeatures = NewVisualPointFeatureVector2D();
// Instantiate DFN
OrbDescriptor* orb = new OrbDescriptor;
// Send input data to DFN
orb->frameInput(*inputFrame);
orb->featuresInput(*inputFeatures);
// Run DFN
orb->process();
// Query output data from DFN
const VisualPointFeatureVector2D& output = orb->featuresOutput();
// Cleanup
delete inputFeatures;
delete orb;
}
TEST_CASE( "Call to configure (ORB descriptor)", "[configure]" )
{
// Instantiate DFN
OrbDescriptor* orb = new OrbDescriptor;
// Setup DFN
orb->setConfigurationFile("../tests/ConfigurationFiles/DFNs/FeaturesDescription2D/OrbDescriptor_Conf1.yaml");
orb->configure();
// Cleanup
delete orb;
}
/** @} */
| 23.686747 | 110 | 0.54883 | H2020-InFuse |
4085eccdaf120d1a66b2af366ba4b999347f78c8 | 124 | hxx | C++ | src/Providers/UNIXProviders/CompositeExtent/UNIX_CompositeExtent_ZOS.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/CompositeExtent/UNIX_CompositeExtent_ZOS.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/CompositeExtent/UNIX_CompositeExtent_ZOS.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_ZOS
#ifndef __UNIX_COMPOSITEEXTENT_PRIVATE_H
#define __UNIX_COMPOSITEEXTENT_PRIVATE_H
#endif
#endif
| 10.333333 | 40 | 0.846774 | brunolauze |
408878463094c8bea9d4f8db70ba10373a2e7de6 | 12,839 | cxx | C++ | STEER/ESD/AliESDVZERO.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | STEER/ESD/AliESDVZERO.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | STEER/ESD/AliESDVZERO.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Container class for ESD VZERO data
// Author: Brigitte Cheynis & Cvetan Cheshkov
//-------------------------------------------------------------------------
#include "AliESDVZERO.h"
#include "AliLog.h"
ClassImp(AliESDVZERO)
//__________________________________________________________________________
AliESDVZERO::AliESDVZERO()
:AliVVZERO(),
fBBtriggerV0A(0),
fBGtriggerV0A(0),
fBBtriggerV0C(0),
fBGtriggerV0C(0),
fV0ATime(-1024),
fV0CTime(-1024),
fV0ATimeError(0),
fV0CTimeError(0),
fV0ADecision(kV0Invalid),
fV0CDecision(kV0Invalid),
fTriggerChargeA(0),
fTriggerChargeC(0),
fTriggerBits(0)
{
// Default constructor
for(Int_t j=0; j<64; j++){
fMultiplicity[j] = 0.0;
fAdc[j] = 0.0;
fTime[j] = 0.0;
fWidth[j] = 0.0;
fBBFlag[j]= kFALSE;
fBGFlag[j]= kFALSE;
for(Int_t k = 0; k < 21; ++k) fIsBB[j][k] = fIsBG[j][k] = kFALSE;
}
}
//__________________________________________________________________________
AliESDVZERO::AliESDVZERO(const AliESDVZERO &o)
:AliVVZERO(o),
fBBtriggerV0A(o.fBBtriggerV0A),
fBGtriggerV0A(o.fBGtriggerV0A),
fBBtriggerV0C(o.fBBtriggerV0C),
fBGtriggerV0C(o.fBGtriggerV0C),
fV0ATime(o.fV0ATime),
fV0CTime(o.fV0CTime),
fV0ATimeError(o.fV0ATimeError),
fV0CTimeError(o.fV0CTimeError),
fV0ADecision(o.fV0ADecision),
fV0CDecision(o.fV0CDecision),
fTriggerChargeA(o.fTriggerChargeA),
fTriggerChargeC(o.fTriggerChargeC),
fTriggerBits(o.fTriggerBits)
{
// Default constructor
for(Int_t j=0; j<64; j++) {
fMultiplicity[j] = o.fMultiplicity[j];
fAdc[j] = o.fAdc[j];
fTime[j] = o.fTime[j];
fWidth[j] = o.fWidth[j];
fBBFlag[j] = o.fBBFlag[j];
fBGFlag[j] = o.fBGFlag[j];
for(Int_t k = 0; k < 21; ++k) {
fIsBB[j][k] = o.fIsBB[j][k];
fIsBG[j][k] = o.fIsBG[j][k];
}
}
}
//__________________________________________________________________________
AliESDVZERO::AliESDVZERO(UInt_t BBtriggerV0A, UInt_t BGtriggerV0A,
UInt_t BBtriggerV0C, UInt_t BGtriggerV0C,
Float_t *Multiplicity, Float_t *Adc,
Float_t *Time, Float_t *Width, Bool_t *BBFlag, Bool_t *BGFlag)
:AliVVZERO(),
fBBtriggerV0A(BBtriggerV0A),
fBGtriggerV0A(BGtriggerV0A),
fBBtriggerV0C(BBtriggerV0C),
fBGtriggerV0C(BGtriggerV0C),
fV0ATime(-1024),
fV0CTime(-1024),
fV0ATimeError(0),
fV0CTimeError(0),
fV0ADecision(kV0Invalid),
fV0CDecision(kV0Invalid),
fTriggerChargeA(0),
fTriggerChargeC(0),
fTriggerBits(0)
{
// Constructor
for(Int_t j=0; j<64; j++) {
fMultiplicity[j] = Multiplicity[j];
fAdc[j] = Adc[j];
fTime[j] = Time[j];
fWidth[j] = Width[j];
fBBFlag[j] = BBFlag[j];
fBGFlag[j] = BGFlag[j];
for(Int_t k = 0; k < 21; ++k) fIsBB[j][k] = fIsBG[j][k] = kFALSE;
}
}
//__________________________________________________________________________
AliESDVZERO& AliESDVZERO::operator=(const AliESDVZERO& o)
{
if(this==&o) return *this;
AliVVZERO::operator=(o);
// Assignment operator
fBBtriggerV0A=o.fBBtriggerV0A;
fBGtriggerV0A=o.fBGtriggerV0A;
fBBtriggerV0C=o.fBBtriggerV0C;
fBGtriggerV0C=o.fBGtriggerV0C;
fV0ATime = o.fV0ATime;
fV0CTime = o.fV0CTime;
fV0ATimeError = o.fV0ATimeError;
fV0CTimeError = o.fV0CTimeError;
fV0ADecision = o.fV0ADecision;
fV0CDecision = o.fV0CDecision;
fTriggerChargeA = o.fTriggerChargeA;
fTriggerChargeC = o.fTriggerChargeC;
fTriggerBits = o.fTriggerBits;
for(Int_t j=0; j<64; j++) {
fMultiplicity[j] = o.fMultiplicity[j];
fAdc[j] = o.fAdc[j];
fTime[j] = o.fTime[j];
fWidth[j] = o.fWidth[j];
fBBFlag[j] = o.fBBFlag[j];
fBGFlag[j] = o.fBGFlag[j];
for(Int_t k = 0; k < 21; ++k) {
fIsBB[j][k] = o.fIsBB[j][k];
fIsBG[j][k] = o.fIsBG[j][k];
}
}
return *this;
}
//______________________________________________________________________________
void AliESDVZERO::Copy(TObject &obj) const {
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliESDVZERO *robj = dynamic_cast<AliESDVZERO*>(&obj);
if(!robj)return; // not an AliESDVZERO
*robj = *this;
}
//__________________________________________________________________________
Short_t AliESDVZERO::GetNbPMV0A() const
{
// Returns the number of
// fired PM in V0A
Short_t n=0;
for(Int_t i=32;i<64;i++)
if (fMultiplicity[i]>0) n++;
return n;
}
//__________________________________________________________________________
Short_t AliESDVZERO::GetNbPMV0C() const
{
// Returns the number of
// fired PM in V0C
Short_t n=0;
for(Int_t i=0;i<32;i++)
if (fMultiplicity[i]>0) n++;
return n;
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMTotV0A() const
{
// returns total multiplicity
// in V0A
Float_t mul=0.0;
for(Int_t i=32;i<64;i++)
mul+= fMultiplicity[i];
return mul;
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMTotV0C() const
{
// returns total multiplicity
// in V0C
Float_t mul=0.0;
for(Int_t i=0;i<32;i++)
mul+= fMultiplicity[i];
return mul;
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMRingV0A(Int_t ring) const
{
// returns multiplicity in a
// given ring of V0A
if (OutOfRange(ring, "AliESDVZERO:::GetMRingV0A",4)) return -1;
Float_t mul =0.0;
if (ring == 0) for(Int_t i=32;i<40;i++) mul += fMultiplicity[i];
if (ring == 1) for(Int_t i=40;i<48;i++) mul += fMultiplicity[i];
if (ring == 2) for(Int_t i=48;i<56;i++) mul += fMultiplicity[i];
if (ring == 3) for(Int_t i=56;i<64;i++) mul += fMultiplicity[i];
return mul ;
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMRingV0C(Int_t ring) const
{
// returns multiplicity in a
// given ring of V0C
if (OutOfRange(ring, "AliESDVZERO:::GetMRingV0C",4)) return -1;
Float_t mul =0.0;
if (ring == 0) for(Int_t i=0;i<8;i++) mul += fMultiplicity[i];
if (ring == 1) for(Int_t i=8;i<16;i++) mul += fMultiplicity[i];
if (ring == 2) for(Int_t i=16;i<24;i++) mul += fMultiplicity[i];
if (ring == 3) for(Int_t i=24;i<32;i++) mul += fMultiplicity[i];
return mul ;
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMultiplicity(Int_t i) const
{
// returns multiplicity in a
// given cell of V0
if (OutOfRange(i, "AliESDVZERO::GetMultiplicity:",64)) return -1;
return fMultiplicity[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMultiplicityV0A(Int_t i) const
{
// returns multiplicity in a
// given cell of V0A
if (OutOfRange(i, "AliESDVZERO::GetMultiplicityV0A:",32)) return -1;
return fMultiplicity[32+i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetMultiplicityV0C(Int_t i) const
{
// returns multiplicity in a
// given cell of V0C
if (OutOfRange(i, "AliESDVZERO::GetMultiplicityV0C:",32)) return -1;
return fMultiplicity[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetAdc(Int_t i) const
{
// returns ADC charge in a
// given cell of V0
if (OutOfRange(i, "AliESDVZERO::GetAdc:",64)) return -1;
return fAdc[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetAdcV0A(Int_t i) const
{
// returns ADC charge in a
// given cell of V0A
if (OutOfRange(i, "AliESDVZERO::GetAdcV0A:",32)) return -1;
return fAdc[32+i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetAdcV0C(Int_t i) const
{
// returns ADC charge in a
// given cell of V0C
if (OutOfRange(i, "AliESDVZERO::GetAdcV0C:",32)) return -1;
return fAdc[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetTime(Int_t i) const
{
// returns leading time measured by TDC
// in a given cell of V0
if (OutOfRange(i, "AliESDVZERO::GetTime:",64)) return -1;
return fTime[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetTimeV0A(Int_t i) const
{
// returns leading time measured by TDC
// in a given cell of V0A
if (OutOfRange(i, "AliESDVZERO::GetTimeV0A:",32)) return -1;
return fTime[32+i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetTimeV0C(Int_t i) const
{
// returns leading time measured by TDC
// in a given cell of V0C
if (OutOfRange(i, "AliESDVZERO::GetTimeV0C:",32)) return -1;
return fTime[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetWidth(Int_t i) const
{
// returns time signal width
// in a given cell of V0
if (OutOfRange(i, "AliESDVZERO::GetWidth:",64)) return -1;
return fWidth[i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetWidthV0A(Int_t i) const
{
// returns time signal width
// in a given cell of V0A
if (OutOfRange(i, "AliESDVZERO::GetWidthV0A:",32)) return -1;
return fWidth[32+i];
}
//__________________________________________________________________________
Float_t AliESDVZERO::GetWidthV0C(Int_t i) const
{
// returns time signal width
// in a given cell of V0C
if (OutOfRange(i, "AliESDVZERO::GetWidthV0C:",32)) return -1;
return fWidth[i];
}
//__________________________________________________________________________
Bool_t AliESDVZERO::BBTriggerV0A(Int_t i) const
{
// returns offline beam-beam flags in V0A
// one bit per cell
if (OutOfRange(i, "AliESDVZERO:::BBTriggerV0A",32)) return kFALSE;
UInt_t test = 1;
return ( fBBtriggerV0A & (test << i) ? kTRUE : kFALSE );
}
//__________________________________________________________________________
Bool_t AliESDVZERO::BGTriggerV0A(Int_t i) const
{
// returns offline beam-gas flags in V0A
// one bit per cell
if (OutOfRange(i, "AliESDVZERO:::BGTriggerV0A",32)) return kFALSE;
UInt_t test = 1;
return ( fBGtriggerV0A & (test << i) ? kTRUE : kFALSE );
}
//__________________________________________________________________________
Bool_t AliESDVZERO::BBTriggerV0C(Int_t i) const
{
// returns offline beam-beam flags in V0C
// one bit per cell
if (OutOfRange(i, "AliESDVZERO:::BBTriggerV0C",32)) return kFALSE;
UInt_t test = 1;
return ( fBBtriggerV0C & (test << i) ? kTRUE : kFALSE );
}
//__________________________________________________________________________
Bool_t AliESDVZERO::BGTriggerV0C(Int_t i) const
{
// returns offline beam-gasflags in V0C
// one bit per cell
if (OutOfRange(i, "AliESDVZERO:::BGTriggerV0C",32)) return kFALSE;
UInt_t test = 1;
return ( fBGtriggerV0C & (test << i) ? kTRUE : kFALSE );
}
//__________________________________________________________________________
Bool_t AliESDVZERO::GetBBFlag(Int_t i) const
{
// returns online beam-beam flag in V0
// one boolean per cell
if (OutOfRange(i, "AliESDVZERO::GetBBFlag:",64)) return kFALSE;
return fBBFlag[i];
}
//__________________________________________________________________________
Bool_t AliESDVZERO::GetBGFlag(Int_t i) const
{
// returns online beam-gas flag in V0
// one boolean per cell
if (OutOfRange(i, "AliESDVZERO::GetBGFlag:",64)) return kFALSE;
return fBGFlag[i];
}
| 30.352246 | 80 | 0.684789 | AllaMaevskaya |
40898156dac49bb300c78244296291376d978c1e | 4,093 | cpp | C++ | raytracer/catch/arealights.cpp | tobiasmarciszko/qt_raytracer_challenge | 188bf38211e30cb0655577a101c82f6ee8ae2ab8 | [
"MIT"
] | 24 | 2019-06-29T07:44:24.000Z | 2021-05-27T11:11:49.000Z | raytracer/catch/arealights.cpp | tobiasmarciszko/qt_raytracer_challenge | 188bf38211e30cb0655577a101c82f6ee8ae2ab8 | [
"MIT"
] | 1 | 2020-12-02T22:54:02.000Z | 2021-01-29T08:47:32.000Z | raytracer/catch/arealights.cpp | tobiasmarciszko/qt_raytracer_challenge | 188bf38211e30cb0655577a101c82f6ee8ae2ab8 | [
"MIT"
] | 7 | 2020-01-29T15:01:19.000Z | 2021-05-28T02:34:34.000Z | #include "catch.hpp"
#include "worlds.h"
#include "point.h"
#include "engine.h"
#include "equal.h"
using namespace Raytracer::Engine;
TEST_CASE("is_shadow tests for occlusion between two points")
{
const World w = Worlds::default_world();
const Point light_position{-10, -10, -10};
const std::vector<std::tuple<Point, bool>> data{
{Point{-10, -10, 10}, false},
{Point{10, 10, 10}, true},
{Point{-20, -20, -20}, false},
{Point{-5, -5, -5}, false}
};
for (const auto& [point, result]: data) {
const auto r = is_shadowed(w, light_position, point);
REQUIRE(r == result);
}
}
TEST_CASE("Point lights evaluate the light intensity at a given point")
{
const World w = Worlds::default_world();
const PointLight *light = dynamic_cast<PointLight *>(w.lights.front().get());
const std::vector<std::tuple<Point, float>> data{
{Point{0, 1.0001, 0}, 1.0},
{Point{-1.0001, 0, 0}, 1.0},
{Point{0, 0, -1.0001}, 1.0},
{Point{0, 0, 1.0001}, 0.0},
{Point{1.0001, 0, 0}, 0.0},
{Point{0, -1.0001, 0}, 0.0},
{Point{0, 0, 0}, 0.0}
};
for (const auto& [point, result]: data) {
const float intensity = intensity_at(*light, point, w);
REQUIRE(intensity == result);
}
}
TEST_CASE("lighting() uses light intensity to attenuate color")
{
World w = Worlds::default_world();
w.lights.front() = std::make_unique<PointLight>(PointLight(Point{0, 0, -10}, Color{1, 1, 1}));
w.shapes.front()->material.ambient = 0.1;
w.shapes.front()->material.diffuse = 0.9;
w.shapes.front()->material.specular = 0;
w.shapes.front()->material.color = Color{1, 1, 1};
const Point pt{0, 0, -1};
const Vector eyev{0, 0, -1};
const Vector normalv{0, 0, -1};
auto res = lighting(w.shapes.front()->material, w.shapes.front().get(), *w.lights.front().get(), pt, eyev, normalv, 1.0);
REQUIRE(res == Color{1.0, 1.0, 1.0});
res = lighting(w.shapes.front()->material, w.shapes.front().get(), *w.lights.front().get(), pt, eyev, normalv, 0.5);
REQUIRE(res == Color{0.55, 0.55, 0.55});
res = lighting(w.shapes.front()->material, w.shapes.front().get(), *w.lights.front().get(), pt, eyev, normalv, 0.0);
REQUIRE(res == Color{0.1, 0.1, 0.1});
}
TEST_CASE("Creating an area light")
{
const Point corner{0, 0, 0};
const Vector v1{2, 0, 0};
const Vector v2{0, 0, 1};
const AreaLight light = AreaLight(corner, v1, 4, v2, 2, Color{1, 1, 1});
REQUIRE(light.corner == corner);
REQUIRE(light.uvec == Vector{0.5, 0, 0});
REQUIRE(light.usteps == 4);
REQUIRE(light.vvec == Vector{0, 0, 0.5});
REQUIRE(light.vsteps == 2);
REQUIRE(light.samples == 8);
// REQUIRE(light.position == Point{1, 0, 0.5});
}
TEST_CASE("Finding a single point on an area light")
{
const Point corner{0, 0, 0};
const Vector v1{2, 0, 0};
const Vector v2{0, 0, 1};
const AreaLight light = AreaLight{corner, v1, 4, v2, 2, Color{1, 1, 1}};
const std::vector<std::tuple<float, float, Point>> data{
{0, 0, Point{0.25, 0, 0.25}},
{1, 0, Point{0.75, 0, 0.25}},
{0, 1, Point{0.25, 0, 0.75}},
{2, 0, Point{1.25, 0, 0.25}},
{3, 1, Point{1.75, 0, 0.75}}
};
for (const auto& [u, v, result]: data) {
const auto pt = point_on_light(light, u, v);
REQUIRE(pt == result);
}
}
TEST_CASE("The area light intensity function")
{
const World w = Worlds::default_world();
const Point corner{-0.5, -0.5, -5};
const Vector v1{1, 0, 0};
const Vector v2{0, 1, 0};
const AreaLight light = AreaLight{corner, v1, 2, v2, 2, Color{1, 1, 1}};
const std::vector<std::tuple<Point, float>> data{
{Point{0, 0, 2}, 0.0},
{Point{1, -1, 2}, 0.25},
{Point{1.5, 0, 2}, 0.5},
{Point{1.25, 1.25, 3}, 0.75},
{Point{0, 0, -2}, 1.0}
};
for (const auto& [point, result]: data) {
const auto intensity = intensity_at(light, point, w);
REQUIRE(equal(intensity, result));
}
} | 30.544776 | 125 | 0.569753 | tobiasmarciszko |
408aa3a9ff4085098c60438365f02f64ef55bd27 | 657 | cpp | C++ | November/Homeworks/Homework 3/4/4/4.cpp | MrMirhan/Algorithm-Class-221-HomeWorks | 3198fce11a0fd4ea10b576b418cec3a35ffcff2e | [
"MIT"
] | 1 | 2020-11-19T09:15:09.000Z | 2020-11-19T09:15:09.000Z | November/Homeworks/Homework 3/4/4/4.cpp | MrMirhan/Algorithm-Class-221-HomeWorks | 3198fce11a0fd4ea10b576b418cec3a35ffcff2e | [
"MIT"
] | null | null | null | November/Homeworks/Homework 3/4/4/4.cpp | MrMirhan/Algorithm-Class-221-HomeWorks | 3198fce11a0fd4ea10b576b418cec3a35ffcff2e | [
"MIT"
] | 2 | 2020-11-12T17:37:28.000Z | 2020-11-21T14:48:49.000Z | #include <iostream>
using namespace std;
int main()
{
int arr[12] = { 4, 11, 16, -2, 65, -5, 12, 1, 123, 54, 10, 0 };
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
int min = arr[i];
int minAll = i;
for (int n = i; n < size; n++) {
if (arr[n] < min) {
min = arr[n];
minAll = n;
}
}
int x = arr[minAll];
arr[minAll] = arr[i] ;
arr[i] = x;
}
for (int x = 0; x < size; x++) {
if(x == (size - 1)) {
cout << arr[x];
} else cout << arr[x] << ", ";
}
}
| 19.323529 | 67 | 0.360731 | MrMirhan |
408b1ad8105f458557101496977e83e033158085 | 3,905 | cc | C++ | chrome/common/extensions/api/extension_action/script_badge_handler.cc | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | chrome/common/extensions/api/extension_action/script_badge_handler.cc | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/common/extensions/api/extension_action/script_badge_handler.cc | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/api/extension_action/script_badge_handler.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/manifest.h"
#include "chrome/common/extensions/manifest_handlers/icons_handler.h"
#include "extensions/common/install_warning.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
namespace extensions {
ScriptBadgeHandler::ScriptBadgeHandler() {
}
ScriptBadgeHandler::~ScriptBadgeHandler() {
}
const std::vector<std::string> ScriptBadgeHandler::PrerequisiteKeys() const {
return SingleKey(keys::kIcons);
}
bool ScriptBadgeHandler::Parse(Extension* extension, string16* error) {
scoped_ptr<ActionInfo> action_info(new ActionInfo);
// Provide a default script badge if one isn't declared in the manifest.
if (!extension->manifest()->HasKey(keys::kScriptBadge)) {
SetActionInfoDefaults(extension, action_info.get());
ActionInfo::SetScriptBadgeInfo(extension, action_info.release());
return true;
}
// So as to not confuse developers if they specify a script badge section
// in the manifest, show a warning if the script badge declaration isn't
// going to have any effect.
if (!FeatureSwitch::script_badges()->IsEnabled()) {
extension->AddInstallWarning(
InstallWarning(InstallWarning::FORMAT_TEXT,
errors::kScriptBadgeRequiresFlag));
}
const DictionaryValue* dict = NULL;
if (!extension->manifest()->GetDictionary(keys::kScriptBadge, &dict)) {
*error = ASCIIToUTF16(errors::kInvalidScriptBadge);
return false;
}
action_info = ActionInfo::Load(extension, dict, error);
if (!action_info.get())
return false; // Failed to parse script badge definition.
// Script badges always use their extension's title and icon so users can rely
// on the visual appearance to know which extension is running. This isn't
// bulletproof since an malicious extension could use a different 16x16 icon
// that matches the icon of a trusted extension, and users wouldn't be warned
// during installation.
if (!action_info->default_title.empty()) {
extension->AddInstallWarning(
InstallWarning(InstallWarning::FORMAT_TEXT,
errors::kScriptBadgeTitleIgnored));
}
if (!action_info->default_icon.empty()) {
extension->AddInstallWarning(
InstallWarning(InstallWarning::FORMAT_TEXT,
errors::kScriptBadgeIconIgnored));
}
SetActionInfoDefaults(extension, action_info.get());
ActionInfo::SetScriptBadgeInfo(extension, action_info.release());
return true;
}
bool ScriptBadgeHandler::AlwaysParseForType(Manifest::Type type) const {
return type == Manifest::TYPE_EXTENSION;
}
void ScriptBadgeHandler::SetActionInfoDefaults(const Extension* extension,
ActionInfo* info) {
info->default_title = extension->name();
info->default_icon.Clear();
for (size_t i = 0; i < extension_misc::kNumScriptBadgeIconSizes; ++i) {
std::string path = IconsInfo::GetIcons(extension).Get(
extension_misc::kScriptBadgeIconSizes[i],
ExtensionIconSet::MATCH_BIGGER);
if (!path.empty()) {
info->default_icon.Add(
extension_misc::kScriptBadgeIconSizes[i], path);
}
}
}
const std::vector<std::string> ScriptBadgeHandler::Keys() const {
return SingleKey(keys::kScriptBadge);
}
} // namespace extensions
| 35.5 | 80 | 0.728553 | hujiajie |
408c1df277703a403d5ee121e71f990090a2642b | 812 | cc | C++ | dictionary.cc | jkotlinski/htdk | e1a626fce61112c151e9a63cc176bc67a5a92a91 | [
"MIT"
] | 2 | 2016-07-23T18:32:29.000Z | 2017-10-24T06:33:37.000Z | dictionary.cc | jkotlinski/htdk | e1a626fce61112c151e9a63cc176bc67a5a92a91 | [
"MIT"
] | null | null | null | dictionary.cc | jkotlinski/htdk | e1a626fce61112c151e9a63cc176bc67a5a92a91 | [
"MIT"
] | null | null | null | #include "dictionary.h"
#include <cassert>
void Dictionary::addWord(const std::string& word) {
if (addedWords.find(word) != addedWords.end()) {
fprintf(stderr, "Redefining word '%s' is not allowed\n", word.c_str());
exit(1);
}
addedWords.insert(word);
auto missingIt = missingWords.find(word);
if (missingIt != missingWords.end()) {
missingWords.erase(missingIt);
}
}
void Dictionary::markAsUsed(const std::string& word) {
if (addedWords.find(word) == addedWords.end()) {
missingWords.insert(word);
}
}
const char* Dictionary::getMissingWord() const {
if (missingWords.empty()) {
return nullptr;
}
return missingWords.begin()->c_str();
}
void Dictionary::popMissingWord() {
missingWords.erase(missingWords.begin());
}
| 23.882353 | 79 | 0.641626 | jkotlinski |
408c893a4b5af700c9aa9386a9101d51db7bc1eb | 8,019 | cpp | C++ | drowaudio-Utility/plugins/Gate/src/DRowAudioEditorComponent.cpp | 34Audiovisual/Progetti_JUCE | d22d91d342939a8463823d7a7ec528bd2228e5f7 | [
"MIT"
] | 92 | 2015-02-25T12:28:58.000Z | 2022-02-15T17:24:24.000Z | drowaudio-Utility/plugins/Gate/src/DRowAudioEditorComponent.cpp | 34Audiovisual/Progetti_JUCE | d22d91d342939a8463823d7a7ec528bd2228e5f7 | [
"MIT"
] | 8 | 2015-05-03T18:36:49.000Z | 2018-02-06T15:50:32.000Z | drowaudio-Utility/plugins/Gate/src/DRowAudioEditorComponent.cpp | 34Audiovisual/Progetti_JUCE | d22d91d342939a8463823d7a7ec528bd2228e5f7 | [
"MIT"
] | 34 | 2015-01-02T13:34:49.000Z | 2021-05-23T20:37:49.000Z | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-7 by Raw Material Software ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the
GNU General Public License, as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.
JUCE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JUCE; if not, visit www.gnu.org/licenses or write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
------------------------------------------------------------------------------
If you'd like to release a closed-source product which uses JUCE, commercial
licenses are also available: visit www.rawmaterialsoftware.com/juce for
more information.
==============================================================================
*/
#include "DRowAudioEditorComponent.h"
//==============================================================================
DRowAudioEditorComponent::DRowAudioEditorComponent (DRowAudioFilter* const ownerFilter)
: AudioProcessorEditor (ownerFilter),
noButtons(3)
{
customLookAndFeel = new dRowLookAndFeel;
setLookAndFeel(customLookAndFeel);
// customLookAndFeel->setColour(Label::textColourId, (Colours::black).withBrightness(0.9f));
addAndMakeVisible( comboBox = new ComboBox(T("comboBox")) );
for (int i = 0; i < noParams; i++)
{
sliders.add( new Slider(String(T("param")) << String(i)) );
addAndMakeVisible( sliders[i]);
String labelName = ownerFilter->getParameterName(i);
(new Label(String(T("Label")) << String(i), labelName))->attachToComponent(sliders[i], true);
sliders[i]->addListener (this);
sliders[i]->setRange (ownerFilter->getParameterMin(i), ownerFilter->getParameterMax(i), ownerFilter->getParameterStep(i));
sliders[i]->setSkewFactor(ownerFilter->getParameterSkewFactor(i));
sliders[i]->setTextBoxStyle(Slider::TextBoxRight, false, 70, 20);
sliders[i]->setValue (ownerFilter->getScaledParameter(i), false);
ownerFilter->getParameterPointer(i)->setupSlider(*sliders[i]);
}
for ( int i = 0; i < noButtons; i++ )
{
buttons.add(new TextButton(String(T("Button ")) << String(i)));
addAndMakeVisible(buttons[i]);
}
buttons[0]->setButtonText(T("Monitor"));
buttons[0]->setClickingTogglesState(true);
buttons[0]->addButtonListener(this);
buttons[1]->setButtonText(T("Use RMS"));
buttons[1]->setClickingTogglesState(true);
buttons[1]->addButtonListener(this);
buttons[2]->setButtonText(parameterNames[FILTER]);
buttons[2]->setClickingTogglesState(true);
buttons[2]->addButtonListener(this);
// set up the meters
addAndMakeVisible(meterLeft = new MeterComponent(&ownerFilter->RMSLeft, &ownerFilter->peakLeft, &ownerFilter->getCallbackLock()));
addAndMakeVisible(meterRight = new MeterComponent(&ownerFilter->RMSRight, &ownerFilter->peakRight, &ownerFilter->getCallbackLock()));
addAndMakeVisible( ownerFilter->waveformDisplayPre );
addAndMakeVisible( ownerFilter->waveformDisplayPost );
addAndMakeVisible(incLabel = new Label(T("incLabel"), T("0.0")));
addAndMakeVisible(currentLabel = new Label(T("currentLabel"), T("0.0")));
// set our component's initial size to be the last one that was stored in the filter's settings
setSize (400, 500);
// register ourselves with the filter - it will use its ChangeBroadcaster base
// class to tell us when something has changed, and this will call our changeListenerCallback()
// method.
ownerFilter->addChangeListener (this);
// start the timer to update the meters
startTimer(50);
}
DRowAudioEditorComponent::~DRowAudioEditorComponent()
{
getFilter()->removeChangeListener (this);
sliders.clear();
buttons.clear();
deleteAllChildren();
}
//==============================================================================
void DRowAudioEditorComponent::paint (Graphics& g)
{
// just clear the window
g.fillAll (Colour::greyLevel (0.9f));
g.setColour(Colours::red);
g.setFont(30);
g.drawFittedText(T("dRowAudio: Gate"),
getWidth()/2 - (getWidth()/2), 5,
getWidth(), getHeight(),
Justification::centredTop,
1);
}
void DRowAudioEditorComponent::resized()
{
comboBox->setBounds (getWidth()/2 - 100, 40,
200, 20);
for (int i = 0; i < noParams; i++)
sliders[i]->setBounds (70, 70 + (30*i), getWidth()-140, 20);
// meterLeft->setBounds(getWidth()-65, 70, 25, 290);
// meterRight->setBounds(getWidth()-35, 70, 25, 290);
for ( int i = 0; i < noButtons; i++ )
buttons[i]->setBounds( 10 + (i * ((getWidth()-20)/noButtons) + ((noButtons-1)*5)), 370,
((getWidth()-20)/noButtons)-(((noButtons-1)*5)), 20);
getFilter()->waveformDisplayPre->setBounds(10, buttons[0]->getBottom()+10,
getWidth()-20, (getHeight()-buttons[0]->getBottom()-20)*0.5-1);
getFilter()->waveformDisplayPost->setBounds(10, getFilter()->waveformDisplayPre->getBottom()+2,
getWidth()-20, (getHeight()-buttons[0]->getBottom()-20)*0.5-1);
incLabel->setBounds(5, 5, 100, 20);
currentLabel->setBounds(5, 25, 100, 20);
}
//==============================================================================
void DRowAudioEditorComponent::sliderValueChanged (Slider* changedSlider)
{
DRowAudioFilter* currentFilter = getFilter();
for (int i = 0; i < noParams; i++)
if ( changedSlider == sliders[i] )
currentFilter->setScaledParameterNotifyingHost (i, (float) sliders[i]->getValue());
if (changedSlider == sliders[9]) {
currentFilter->waveformDisplayPre->setHorizontalZoom(sliders[9]->getValue());
currentFilter->waveformDisplayPost->setHorizontalZoom(sliders[9]->getValue());
}
}
void DRowAudioEditorComponent::buttonClicked(Button* clickedButton)
{
DRowAudioFilter* currentFilter = getFilter();
if (clickedButton == buttons[0])
{
if(clickedButton->getToggleState())
currentFilter->setScaledParameterNotifyingHost(MONITOR, 1.0);
else
currentFilter->setScaledParameterNotifyingHost(MONITOR, 0.0);
}
if (clickedButton == buttons[2])
{
if(clickedButton->getToggleState())
currentFilter->setScaledParameterNotifyingHost(FILTER, 1.0);
else
currentFilter->setScaledParameterNotifyingHost(FILTER, 0.0);
}
}
void DRowAudioEditorComponent::changeListenerCallback (void* source)
{
// this is the filter telling us that it's changed, so we'll update our
// display of the time, midi message, etc.
updateParametersFromFilter();
}
//==============================================================================
void DRowAudioEditorComponent::updateParametersFromFilter()
{
DRowAudioFilter* const filter = getFilter();
float tempParamVals[noParams];
// we use this lock to make sure the processBlock() method isn't writing to the
// lastMidiMessage variable while we're trying to read it, but be extra-careful to
// only hold the lock for a minimum amount of time..
filter->getCallbackLock().enter();
for(int i = 0; i < noParams; i++)
tempParamVals[i] = filter->getScaledParameter (i);
// ..release the lock ASAP
filter->getCallbackLock().exit();
for(int i = 0; i < noParams; i++)
sliders[i]->setValue (tempParamVals[i], false);
}
void DRowAudioEditorComponent::timerCallback()
{
incLabel->setText(String(getFilter()->RMSLeft), false);
currentLabel->setText(String(getFilter()->RMSRight), false);
currentLabel->setText(String(getFilter()->RMSRight), false);
currentLabel->setColour(Label::backgroundColourId, Colours::black.withBrightness(getFilter()->RMSRight));
} | 35.959641 | 134 | 0.658187 | 34Audiovisual |
408f510d8b8c8139501a7bedd41c3947572ee85c | 2,338 | cpp | C++ | fbmeshd/tests/SocketTest.cpp | yuyanduan/fbmeshd | 56650c4bab7d4ab15d3f1a853d17fa12f83f43f2 | [
"MIT"
] | 36 | 2019-10-03T22:33:51.000Z | 2020-11-04T15:04:29.000Z | fbmeshd/tests/SocketTest.cpp | yuyanduan/fbmeshd | 56650c4bab7d4ab15d3f1a853d17fa12f83f43f2 | [
"MIT"
] | 3 | 2019-10-31T01:27:26.000Z | 2020-10-06T17:35:50.000Z | fbmeshd/tests/SocketTest.cpp | yuyanduan/fbmeshd | 56650c4bab7d4ab15d3f1a853d17fa12f83f43f2 | [
"MIT"
] | 15 | 2019-10-30T15:57:09.000Z | 2020-11-11T06:34:59.000Z | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <fbmeshd/gateway-connectivity-monitor/Socket.h>
#include <folly/Subprocess.h>
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include <sys/types.h>
#include <unistd.h>
using namespace fbmeshd;
class SocketTest : public ::testing::Test {
protected:
static constexpr auto testInterface{"lo"};
static const folly::SocketAddress testAddress;
static constexpr std::chrono::seconds testInterval{1};
};
const folly::SocketAddress SocketTest::testAddress{"127.0.0.1", 1337};
constexpr std::chrono::seconds SocketTest::testInterval;
TEST_F(SocketTest, ConnectFailure) {
Socket socket;
Socket::Result result{
socket.connect(testInterface, testAddress, testInterval)};
EXPECT_FALSE(result.success);
EXPECT_EQ(
getuid() != 0 ? "setsockopt_bindtodevice" : "err_non_zero",
result.errorMsg);
}
void
waitUntilListening(const folly::SocketAddress& key) {
std::string stdOut{};
do {
folly::Subprocess ss{{"/usr/sbin/ss", std::string{"-tanpl"}},
folly::Subprocess::Options().pipeStdout()};
stdOut = ss.communicate().first;
EXPECT_EQ(0, ss.wait().exitStatus());
} while (stdOut.find(key.describe()) == std::string::npos);
}
TEST_F(SocketTest, ConnectSuccess) {
folly::Subprocess proc{{"/bin/nc",
"-l",
testAddress.getAddressStr(),
folly::to<std::string>(testAddress.getPort())}};
waitUntilListening(testAddress);
{
Socket socket;
Socket::Result result{
socket.connect(testInterface, testAddress, testInterval)};
// This test is really only interesting when run as root. But this makes it
// so it will at least pass otherwise.
if (getuid() == 0) {
EXPECT_TRUE(result.success);
EXPECT_EQ("", result.errorMsg);
} else {
proc.terminate();
}
}
auto status = proc.wait();
EXPECT_TRUE(getuid() != 0 || status.exitStatus() == 0);
}
int
main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
::testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);
return RUN_ALL_TESTS();
}
| 28.168675 | 79 | 0.662104 | yuyanduan |
40909a31cee901c3f07b9821d3255251cd1f7042 | 97 | cpp | C++ | src/test/cpp/compare/project/Component.Edge.StaticClass.cpp | nightlark/xlang | a381bac0f32aaef6f0e7a0e81da3c0fc71a7c253 | [
"MIT"
] | null | null | null | src/test/cpp/compare/project/Component.Edge.StaticClass.cpp | nightlark/xlang | a381bac0f32aaef6f0e7a0e81da3c0fc71a7c253 | [
"MIT"
] | null | null | null | src/test/cpp/compare/project/Component.Edge.StaticClass.cpp | nightlark/xlang | a381bac0f32aaef6f0e7a0e81da3c0fc71a7c253 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "StaticClass.h"
namespace winrt::Component::Edge::implementation
{
}
| 13.857143 | 48 | 0.731959 | nightlark |
40913449aeb1c71f99a5625737c71011bd588b06 | 1,038 | cpp | C++ | src/test-libwfp/wfp/layerconditions.cpp | taliesins/libwfp | ac1632d336cfdba106f6f8b8fcc2ccc913b443bb | [
"MIT"
] | null | null | null | src/test-libwfp/wfp/layerconditions.cpp | taliesins/libwfp | ac1632d336cfdba106f6f8b8fcc2ccc913b443bb | [
"MIT"
] | null | null | null | src/test-libwfp/wfp/layerconditions.cpp | taliesins/libwfp | ac1632d336cfdba106f6f8b8fcc2ccc913b443bb | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "gtest/gtest.h"
#include "libwfp/layerconditions.h"
#include <guiddef.h>
#include <fwpmu.h>
TEST(LibWfpLayerConditions, IsCompatibleWithCompatibleCondition)
{
ASSERT_TRUE(wfp::LayerConditions::IsCompatible(FWPM_LAYER_OUTBOUND_TRANSPORT_V6, FWPM_CONDITION_IP_LOCAL_ADDRESS_TYPE));
// Match last item in defined condition array, to ensure no off-by-one issues
ASSERT_TRUE(wfp::LayerConditions::IsCompatible(FWPM_LAYER_OUTBOUND_TRANSPORT_V6, FWPM_CONDITION_CURRENT_PROFILE_ID));
}
TEST(LibWfpLayerConditions, IsNotCompatibleWithIncompatibleCondition)
{
ASSERT_FALSE(wfp::LayerConditions::IsCompatible(FWPM_LAYER_OUTBOUND_TRANSPORT_V6, FWPM_CONDITION_DIRECTION));
}
TEST(LibWfpLayerConditions, IsCompatibleWithInvalidLayerThrows)
{
static const GUID InvalidLayer = {
0xa86fd1bf,
0x21cd,
0x497e,
{ 0xa0, 0xbb, 0x17, 0x42, 0x5c, 0x88, 0x5c, 0x58 }
};
ASSERT_THROW(wfp::LayerConditions::IsCompatible(InvalidLayer, FWPM_CONDITION_DIRECTION), std::runtime_error);
}
| 32.4375 | 122 | 0.790944 | taliesins |
40949e5ca30bd9b376b54abeb3aaf939bafb2add | 1,023 | cpp | C++ | Source/JavascriptEditor/JavascriptCommandlet.cpp | ninemcom/Unreal.js-core | 9b7bf774c570be95f4d9f687557164c872bb2307 | [
"BSD-3-Clause"
] | 1 | 2019-07-24T13:20:45.000Z | 2019-07-24T13:20:45.000Z | Source/JavascriptEditor/JavascriptCommandlet.cpp | ninemcom/Unreal.js-core | 9b7bf774c570be95f4d9f687557164c872bb2307 | [
"BSD-3-Clause"
] | null | null | null | Source/JavascriptEditor/JavascriptCommandlet.cpp | ninemcom/Unreal.js-core | 9b7bf774c570be95f4d9f687557164c872bb2307 | [
"BSD-3-Clause"
] | null | null | null | #include "JavascriptCommandlet.h"
#include "JavascriptIsolate.h"
#include "JavascriptContext.h"
UJavascriptCommandlet::UJavascriptCommandlet(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{}
int32 UJavascriptCommandlet::Main(const FString& Params)
{
bool bSuccess = true;
#if !UE_BUILD_SHIPPING
const TCHAR* ParamStr = *Params;
ParseCommandLine(ParamStr, CmdLineTokens, CmdLineSwitches);
{
auto JavascriptIsolate = NewObject<UJavascriptIsolate>();
JavascriptIsolate->Init(true);
auto JavascriptContext = JavascriptIsolate->CreateContext();
JavascriptContext->Expose(TEXT("Root"), this);
JavascriptContext->AddToRoot();
JavascriptContext->SetContextId(TEXT("Commandlet"));
{
FEditorScriptExecutionGuard ScriptGuard;
if (CmdLineTokens.Num())
{
JavascriptContext->RunFile(CmdLineTokens[0]);
}
}
JavascriptContext->JavascriptContext.Reset();
JavascriptContext->RemoveFromRoot();
}
#else
bSuccess = false;
#endif
return bSuccess ? 0 : 1;
} | 22.23913 | 89 | 0.753666 | ninemcom |
40951a20330f7180bc20457151a94c4f6c9b460c | 289 | cpp | C++ | examples/polar_plots/polarplot/polarplot_6.cpp | solosuper/matplotplusplus | 87ff5728b14ad904bc6acaa2bf010c1a03c6cb4a | [
"MIT"
] | 2,709 | 2020-08-29T01:25:40.000Z | 2022-03-31T18:35:25.000Z | examples/polar_plots/polarplot/polarplot_6.cpp | p-ranav/matplotplusplus | b45015e2be88e3340b400f82637b603d733d45ce | [
"MIT"
] | 124 | 2020-08-29T04:48:17.000Z | 2022-03-25T15:45:59.000Z | examples/polar_plots/polarplot/polarplot_6.cpp | p-ranav/matplotplusplus | b45015e2be88e3340b400f82637b603d733d45ce | [
"MIT"
] | 203 | 2020-08-29T04:16:22.000Z | 2022-03-30T02:08:36.000Z | #include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
std::vector<double> theta = linspace(0, 2 * pi, 25);
std::vector<double> rho = transform(theta, [](double t) { return 2 * t; });
polarplot(theta, rho, "r-o");
show();
return 0;
} | 22.230769 | 79 | 0.598616 | solosuper |
4095c874492d2f1ab71d2d4cfa4786387c97869c | 8,271 | hh | C++ | include/aleph/topology/io/SimplicialComplexReader.hh | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 56 | 2019-04-24T22:11:15.000Z | 2022-03-22T11:37:47.000Z | include/aleph/topology/io/SimplicialComplexReader.hh | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 48 | 2016-11-30T09:37:13.000Z | 2019-01-30T21:43:39.000Z | include/aleph/topology/io/SimplicialComplexReader.hh | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 11 | 2019-05-02T11:54:31.000Z | 2020-12-10T14:05:40.000Z | #ifndef ALEPH_TOPOLOGY_IO_SIMPLICIAL_COMPLEX_READER_HH__
#define ALEPH_TOPOLOGY_IO_SIMPLICIAL_COMPLEX_READER_HH__
#include <algorithm>
#include <fstream>
#include <iterator>
#include <string>
#include <stdexcept>
#include <vector>
#include <aleph/topology/io/EdgeLists.hh>
#include <aleph/topology/io/GML.hh>
#include <aleph/topology/io/HDF5.hh>
#include <aleph/topology/io/Pajek.hh>
#include <aleph/topology/io/PLY.hh>
#include <aleph/topology/io/VTK.hh>
#include <aleph/utilities/Filesystem.hh>
namespace aleph
{
namespace topology
{
namespace io
{
/**
@class SimplicialComplexReader
@brief Generic simplicial complex reader class
The purpose of this class is to provide a unified interface for
reading a simplicial complex from an input file, assign weights
that are consistent, and sort it.
The class offers a rich interface but not every file format has
the proper capabilities to support it.
*/
class SimplicialComplexReader
{
public:
/**
Attempts to read the simplicial complex \p K from the given input
file, while using a default strategy for assigning weights. For a
support file format, weights of higher-dimensional simplices will
be assigned according to the *maximum* of their vertices.
@param filename Input file
@param K Simplicial complex to read
@see SimplicialComplexReader::operator()( const std::string&, SimplicialComplex&, Functor )
*/
template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::ValueType;
using DataType = typename Simplex::DataType;
this->operator()( filename, K, [] ( DataType a, DataType b ) { return std::max(a,b); } );
}
/**
Reads a simplicial complex from a file using a separate functor to
assign weights for higher-dimensional simplices. The functor needs
to support the following interface:
\code{.cpp}
using SimplexType = typename SimplicialComplex::ValueType;
using DataType = typename Simplex::DataType;
DataType Functor::operator()( DataType a, DataType b )
{
// Do something with a and b. Typically, this would be calculating
// either the minimum or the maximum...
return std::max(a, b);
}
\endcode
Typically, if you use `std::max()` in the functor, you obtain
a simplicial complex that is filtrated by its *sublevel* sets,
whereas you obtain a *superlevel* set filtration whenever you
use `std::min()` instead. Other functors need to yield a valid
filtration. This class does *not* check for it!
@see SimplicialComplexReader::operator()( const std::string&, SimplicialComplex& )
*/
template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor functor )
{
std::ifstream in( filename );
if( !in )
throw std::runtime_error( "Unable to read input file" );
auto extension = aleph::utilities::extension( filename );
// The GML parser works more or less on its own and does not make
// use of any stored variables.
if( extension == ".gml" )
{
GMLReader reader;
reader( filename, K );
using VertexType = typename SimplicialComplex::ValueType::VertexType;
_labels = getLabels( reader.getNodeAttribute( _labelAttribute ), reader.id_to_index<VertexType>() );
}
// The HDF5 parser permits the use of a functor that assigns
// a weight to a higher-dimensional simplex.
else if( extension == ".h5" )
{
HDF5SimpleDataSpaceReader reader;
reader( filename, K );
}
// The Pajek parser also works on its own and does not require any
// other configuration options.
else if( extension == ".net" )
{
PajekReader reader;
reader( filename, K );
_labels = getLabels( reader.getLabelMap() );
}
// For PLY files, the parser supports optionally reading a property
// for every vertex to assign as a data property to the vertices of
// the simplicial complex.
else if( extension == ".ply" )
{
PLYReader reader;
if( !_dataAttribute.empty() )
reader.setDataProperty( _dataAttribute );
reader( filename, K );
}
// VTK files permit the use of a functor that assigns a weight to a
// higher-dimensional simplex.
else if( extension == ".vtk" )
{
VTKStructuredGridReader reader;
reader( filename, K, functor );
}
// In all other cases, we fall back to reading a graph from an edge
// list, with optional weights being specified.
//
// TODO: does it make sense to make this reader configurable?
else
{
EdgeListReader reader;
reader.setTrimLines();
reader.setReadWeights();
reader( filename, K );
}
}
/**
Sets the attribute that is used to extract data values from input
files. For PLY files, for example, this means using an attribute
of the vertices of the mesh. Note that the attribute is only used
if non-empty.
*/
void setDataAttribute( const std::string& attribute ) noexcept
{
_dataAttribute = attribute;
}
/**
@returns Current data attribute
@see SimplicialComplexReader::setDataAttribute()
*/
std::string dataAttribute() const noexcept
{
return _dataAttribute;
}
/** Sets current label attribute */
void setLabelAttribute( const std::string& attribute ) noexcept
{
_labelAttribute = attribute;
}
/** @returns Current label attribute */
std::string labelAttribute() const noexcept
{
return _labelAttribute;
}
/**
@returns Node labels (if any). The indexing follows the vertex order
in the simplicial complex and the graph. The label at index `0` thus
corresponds to the vertex `0` in the resulting simplicial complex.
*/
std::vector<std::string> labels() const noexcept
{
return _labels;
}
private:
/**
Specifies an attribute of the input data file that stores the data
property of the corresponding simplicial complex. The usage of the
attribute depends on the file format. For a PLY file, for example,
this means that a certain vertex attribute of the mesh set is used
to obtain weights.
This property is only used if it is not left empty.
@see SimplicialComplexReader::dataAttribute()
@see SimplicialComplexReader::setDataAttribute()
*/
std::string _dataAttribute;
/**
Specifies an attribute of the input data file that stores labels for
the corresponding simplicial complex. Since not all file formats are
capable of storing labels at all, this attribute may not be used.
@see SimplicialComplexReader::labelAttribute()
@see SimplicialComplexReader::setLabelAttribute()
*/
std::string _labelAttribute = "label";
/**
Converts a map of labels, obtained from a subordinate reader class,
to a vector of labels. The order is guaranteed to follow the vertex
order in the graph and in the simplicial complex.
*/
template <class Map> std::vector<std::string> getLabels( const Map& map )
{
if( map.empty() )
return {};
std::vector<std::string> labels;
labels.reserve( map.size() );
for( auto&& pair : map )
{
if( !pair.second.empty() )
labels.push_back( pair.second );
}
return labels;
}
/**
Unrolls all stored labels (if any) of the simplicial complex into
a vector, following the lexicographical ordering inside a map for
mapping node IDs to their labels.
*/
template <class Map1, class Map2> std::vector<std::string> getLabels( const Map1& labelMap, const Map2& idMap )
{
if( labelMap.empty() || idMap.empty() )
return {};
std::vector<std::string> labels;
labels.resize( labelMap.size() );
for( auto&& pair : labelMap )
{
if( !pair.second.empty() )
labels.at( idMap.at( pair.first ) ) = pair.second;
}
return labels;
}
/**
Optionally stores labels that have been extracted when reading an
input file.
Use SimplicialComplexReader::labels() to access them.
*/
std::vector<std::string> _labels;
};
} // namespace io
} // namespace topology
} // namespace aleph
#endif
| 27.57 | 137 | 0.683351 | eudoxos |
409774ca7d7a8642ff69436f7a1ee94894892d47 | 3,978 | cpp | C++ | src/vk_helpers.cpp | AdlanSADOU/Vulkan_Renderer | f57fcfbd7d97c42690188724d3b82d02c902072b | [
"Unlicense"
] | 1 | 2020-06-10T07:38:05.000Z | 2020-06-10T07:38:05.000Z | src/vk_helpers.cpp | AdlanSADOU/Vulkan_Renderer | f57fcfbd7d97c42690188724d3b82d02c902072b | [
"Unlicense"
] | 3 | 2021-03-17T14:31:12.000Z | 2021-03-17T14:31:45.000Z | src/vk_helpers.cpp | AdlanSADOU/Vulkan_Renderer | f57fcfbd7d97c42690188724d3b82d02c902072b | [
"Unlicense"
] | null | null | null | #include <vulkan/vulkan.h>
#include "vk_types.h"
uint32_t FindProperties(
const VkPhysicalDeviceMemoryProperties *pMemoryProperties,
uint32_t memoryTypeBitsRequirement,
VkMemoryPropertyFlags requiredProperties)
{
const uint32_t memoryCount = pMemoryProperties->memoryTypeCount;
for (uint32_t memoryIndex = 0; memoryIndex < memoryCount; ++memoryIndex) {
const uint32_t memoryTypeBits = (1 << memoryIndex);
const bool isRequiredMemoryType = memoryTypeBitsRequirement & memoryTypeBits;
const VkMemoryPropertyFlags properties = pMemoryProperties->memoryTypes[memoryIndex].propertyFlags;
const bool hasRequiredProperties = (properties & requiredProperties) == requiredProperties;
if (isRequiredMemoryType && hasRequiredProperties)
return memoryIndex;
}
// failed to find memory type
return -1;
}
bool AllocateBufferMemory(
VkDevice device,
VkPhysicalDevice gpu,
VkBuffer buffer,
VkDeviceMemory *memory)
{
VkMemoryPropertyFlags flags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
VkMemoryRequirements buffer_memory_requirements;
vkGetBufferMemoryRequirements(device, buffer, &buffer_memory_requirements);
VkPhysicalDeviceMemoryProperties gpu_memory_properties;
vkGetPhysicalDeviceMemoryProperties(gpu, &gpu_memory_properties);
uint32_t memory_type = FindProperties(&gpu_memory_properties, buffer_memory_requirements.memoryTypeBits, flags);
VkMemoryAllocateInfo memory_allocate_info = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, // VkStructureType sType
nullptr, // const void *pNext
buffer_memory_requirements.size, // VkDeviceSize allocationSize
memory_type // uint32_t memoryTypeIndex
};
if (vkAllocateMemory(device, &memory_allocate_info, nullptr, memory) == VK_SUCCESS)
return true;
return false;
}
void GetDescriptorSetLayoutBinding(
uint32_t binding,
VkDescriptorType descriptorType,
uint32_t descriptorCount,
VkShaderStageFlags stageFlags,
const VkSampler *pImmutableSamplers)
{
// desc_set_layout_bindings.push_back(desc_set_layout_binding_storage_buffer);
}
VkResult CreateDescriptorSetLayout(
VkDevice device,
const VkAllocationCallbacks *allocator,
VkDescriptorSetLayout *set_layout,
const VkDescriptorSetLayoutBinding *bindings,
uint32_t binding_count)
{
VkDescriptorSetLayoutCreateInfo create_info_desc_set_layout = {};
create_info_desc_set_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
create_info_desc_set_layout.pNext = NULL;
create_info_desc_set_layout.flags = 0;
create_info_desc_set_layout.pBindings = bindings;
create_info_desc_set_layout.bindingCount = binding_count;
return vkCreateDescriptorSetLayout(device, &create_info_desc_set_layout, NULL, set_layout);
}
VkResult AllocateDescriptorSets(
VkDevice device,
VkDescriptorPool descriptor_pool,
uint32_t descriptor_set_count,
const VkDescriptorSetLayout *set_layouts,
VkDescriptorSet *descriptor_set)
{
VkDescriptorSetAllocateInfo allocInfo = {};
allocInfo.pNext = NULL;
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptor_pool;
allocInfo.descriptorSetCount = descriptor_set_count;
allocInfo.pSetLayouts = set_layouts;
return vkAllocateDescriptorSets(device, &allocInfo, descriptor_set);
} | 32.876033 | 118 | 0.682755 | AdlanSADOU |
4097767cb9f5f40b3d26a9c45b6ca2987265e33c | 2,271 | hpp | C++ | stan/math/prim/scal/prob/student_t_log.hpp | peterwicksstringfield/math | 5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/scal/prob/student_t_log.hpp | peterwicksstringfield/math | 5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/scal/prob/student_t_log.hpp | peterwicksstringfield/math | 5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_LOG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_LOG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/prob/student_t_lpdf.hpp>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The log of the Student-t density for the given y, nu, mean, and
* scale parameter. The scale parameter must be greater
* than 0.
*
* \f{eqnarray*}{
y &\sim& t_{\nu} (\mu, \sigma^2) \\
\log (p (y \, |\, \nu, \mu, \sigma) ) &=& \log \left( \frac{\Gamma((\nu + 1)
/2)}
{\Gamma(\nu/2)\sqrt{\nu \pi} \sigma} \left( 1 + \frac{1}{\nu} (\frac{y -
\mu}{\sigma})^2 \right)^{-(\nu + 1)/2} \right) \\
&=& \log( \Gamma( (\nu+1)/2 )) - \log (\Gamma (\nu/2) - \frac{1}{2} \log(\nu
\pi) - \log(\sigma)
-\frac{\nu + 1}{2} \log (1 + \frac{1}{\nu} (\frac{y - \mu}{\sigma})^2)
\f}
*
* @deprecated use <code>student_t_lpdf</code>
*
* @param y A scalar variable.
* @param nu Degrees of freedom.
* @param mu The mean of the Student-t distribution.
* @param sigma The scale parameter of the Student-t distribution.
* @return The log of the Student-t density at y.
* @throw std::domain_error if sigma is not greater than 0.
* @throw std::domain_error if nu is not greater than 0.
* @tparam T_y Type of scalar.
* @tparam T_dof Type of degrees of freedom.
* @tparam T_loc Type of location.
* @tparam T_scale Type of scale.
*/
template <bool propto, typename T_y, typename T_dof, typename T_loc,
typename T_scale>
return_type_t<T_y, T_dof, T_loc, T_scale> student_t_log(const T_y& y,
const T_dof& nu,
const T_loc& mu,
const T_scale& sigma) {
return student_t_lpdf<propto, T_y, T_dof, T_loc, T_scale>(y, nu, mu, sigma);
}
/** \ingroup prob_dists
* @deprecated use <code>student_t_lpdf</code>
*/
template <typename T_y, typename T_dof, typename T_loc, typename T_scale>
inline return_type_t<T_y, T_dof, T_loc, T_scale> student_t_log(
const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma) {
return student_t_lpdf<T_y, T_dof, T_loc, T_scale>(y, nu, mu, sigma);
}
} // namespace math
} // namespace stan
#endif
| 37.229508 | 79 | 0.621312 | peterwicksstringfield |
409b96050ff311b99e2a59dd6532ddc4768b927e | 3,937 | cpp | C++ | tests/simple_worker.cpp | SiddiqSoft/basic-worker | 30ece197c9f5605d2e81f921e466ad8ccfcdcf25 | [
"BSD-3-Clause"
] | null | null | null | tests/simple_worker.cpp | SiddiqSoft/basic-worker | 30ece197c9f5605d2e81f921e466ad8ccfcdcf25 | [
"BSD-3-Clause"
] | 3 | 2021-09-18T15:29:01.000Z | 2021-10-06T05:25:13.000Z | tests/simple_worker.cpp | SiddiqSoft/basic-worker | 30ece197c9f5605d2e81f921e466ad8ccfcdcf25 | [
"BSD-3-Clause"
] | 1 | 2021-10-05T22:30:34.000Z | 2021-10-05T22:30:34.000Z | /*
asynchrony-lib
Add asynchrony to your apps
BSD 3-Clause License
Copyright (c) 2021, Siddiq Software LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest/gtest.h"
#include <iostream>
#include <format>
#include <string>
#include <thread>
#include "nlohmann/json.hpp"
#include "../src/simple_worker.hpp"
TEST(simple_worker, test1)
{
bool passTest {false};
siddiqsoft::simple_worker<nlohmann::json> worker {[&](auto&& item) {
std::cerr << std::format("Got object: {}\n", item.dump());
passTest = true;
}};
worker.queue({{"hello", "world"}});
// This is important otherwise the destructor will kill the thread before it has a chance to process anything!
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(passTest);
std::cerr << nlohmann::json(worker).dump() << std::endl;
}
TEST(simple_worker, test2)
{
bool passTest {false};
siddiqsoft::simple_worker<std::shared_ptr<nlohmann::json>> worker {[&](auto&& item) {
std::cerr << std::format("Got object: {}\n", item->dump());
passTest = true;
}};
worker.queue(std::make_shared<nlohmann::json>(nlohmann::json {{"hello", "world"}}));
// This is important otherwise the destructor will kill the thread before it has a chance to process anything!
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(passTest);
}
TEST(simple_worker, test3)
{
bool passTest {false};
struct nonCopyableObject
{
std::string Data {};
nonCopyableObject(const std::string& s)
: Data(s)
{
}
nonCopyableObject(nonCopyableObject&) = delete;
nonCopyableObject& operator=(nonCopyableObject&) = delete;
// Move constructors
nonCopyableObject(nonCopyableObject&&) = default;
nonCopyableObject& operator=(nonCopyableObject&&) = default;
};
siddiqsoft::simple_worker<nonCopyableObject> worker {[&](auto&& item) {
std::cerr << std::format("Got object: {}\n", item.Data);
passTest = true;
}};
worker.queue(nonCopyableObject {"Hello world!"});
// This is important otherwise the destructor will kill the thread before it has a chance to process anything!
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(passTest);
}
| 34.234783 | 114 | 0.679705 | SiddiqSoft |
409c6fc47b25f7f8d9ea799cc925d017f66ca751 | 4,360 | cpp | C++ | src/AST/StmtNode.cpp | linvs/test | 9d9390e94ecebd1e3098167c553c86a2cddca289 | [
"MIT"
] | 428 | 2020-06-12T06:48:38.000Z | 2022-02-15T00:43:19.000Z | src/AST/StmtNode.cpp | linvs/test | 9d9390e94ecebd1e3098167c553c86a2cddca289 | [
"MIT"
] | null | null | null | src/AST/StmtNode.cpp | linvs/test | 9d9390e94ecebd1e3098167c553c86a2cddca289 | [
"MIT"
] | 18 | 2020-06-15T02:49:30.000Z | 2021-09-08T04:39:13.000Z | #include "AST/StmtNode.h"
#include "AST/DeclNode.h"
#include "Sema/ASTVisitor.h"
ExprStmtNode::ExprStmtNode(const SharedPtr<ExprNode> &expr) : expr(expr) {}
void ExprStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<ExprStmtNode>(shared_from_this()));
}
void ExprStmtNode::bindChildrenInversely() {
expr->parent = shared_from_this();
}
CompoundStmtNode::CompoundStmtNode(const SharedPtrVector<StmtNode> &childStmts) : childStmts(childStmts) {}
bool CompoundStmtNode::isEmpty() const {
return childStmts.empty();
}
void CompoundStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<CompoundStmtNode>(shared_from_this()));
}
void CompoundStmtNode::bindChildrenInversely() {
auto self = shared_from_this();
for (const SharedPtr<StmtNode> &stmt: childStmts) {
stmt->parent = self;
}
}
void VarDeclStmtNode::pushVarDecl(const SharedPtr<VarDeclNode> &varDecl) {
childVarDecls.push_back(varDecl);
}
void VarDeclStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<VarDeclStmtNode>(shared_from_this()));
}
void VarDeclStmtNode::bindChildrenInversely() {
auto self = shared_from_this();
for (const SharedPtr<VarDeclNode> &varDecl: childVarDecls) {
varDecl->parent = self;
}
}
FunctionDeclStmtNode::FunctionDeclStmtNode(
const SharedPtr<FunctionDeclNode> &childFunctionDecl
) : childFunctionDecl(childFunctionDecl) {}
void FunctionDeclStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<FunctionDeclStmtNode>(shared_from_this()));
}
void FunctionDeclStmtNode::bindChildrenInversely() {
childFunctionDecl->parent = shared_from_this();
}
IfStmtNode::IfStmtNode(
const SharedPtr<ExprNode> &condition,
const SharedPtr<StmtNode> &thenStmt,
const SharedPtr<StmtNode> &elseStmt
) : condition(condition), thenBody(thenStmt), elseBody(elseStmt) {}
void IfStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<IfStmtNode>(shared_from_this()));
}
void IfStmtNode::bindChildrenInversely() {
auto self = shared_from_this();
condition->parent = thenBody->parent = self;
if (elseBody) {
elseBody->parent = self;
}
}
WhileStmtNode::WhileStmtNode(
const SharedPtr<ExprNode> &condition,
const SharedPtr<StmtNode> &body
) : condition(condition), body(body) {}
void WhileStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<WhileStmtNode>(shared_from_this()));
}
void WhileStmtNode::bindChildrenInversely() {
condition->parent = body->parent = shared_from_this();
}
ForStmtNode::ForStmtNode(
const SharedPtr<VarDeclStmtNode> &forInitVarDecls,
const SharedPtrVector<ExprNode> &forInitExprList,
const SharedPtr<ExprNode> &forCondition,
const SharedPtrVector<ExprNode> &forUpdate,
const SharedPtr<StmtNode> &body
) : initVarStmt(forInitVarDecls),
initExprs(forInitExprList),
condition(forCondition),
updates(forUpdate), body(body) {}
void ForStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<ForStmtNode>(shared_from_this()));
}
void ForStmtNode::bindChildrenInversely() {
auto self = shared_from_this();
if (initVarStmt) {
initVarStmt->parent = self;
}
for (const SharedPtr<ExprNode> &forInitExpr: initExprs) {
forInitExpr->parent = self;
}
if (condition) {
condition->parent = self;
}
for (const SharedPtr<ExprNode> &forUpdateItem: updates) {
forUpdateItem->parent = self;
}
body->parent = self;
}
void ContinueStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<ContinueStmtNode>(shared_from_this()));
}
void BreakStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<BreakStmtNode>(shared_from_this()));
}
ReturnStmtNode::ReturnStmtNode(const SharedPtr<ExprNode> &argument) : returnExpr(argument) {}
void ReturnStmtNode::accept(const SharedPtr<ASTVisitor> &visitor) {
visitor->visit(staticPtrCast<ReturnStmtNode>(shared_from_this()));
}
void ReturnStmtNode::bindChildrenInversely() {
if (returnExpr) {
returnExpr->parent = shared_from_this();
}
}
| 30.704225 | 107 | 0.726606 | linvs |
409cd717968fd714dfded5deeac8e7f119262425 | 29,110 | cpp | C++ | tests/unit_tests/blockchain_db.cpp | OIEIEIO/ombre-working-old-chain-before-for-test | 4069cc254c3a142b2d40a665185e58130e3ded8d | [
"BSD-3-Clause"
] | 107 | 2018-07-03T19:35:21.000Z | 2022-01-12T09:05:44.000Z | tests/unit_tests/blockchain_db.cpp | OIEIEIO/ombre-working-old-chain-before-for-test | 4069cc254c3a142b2d40a665185e58130e3ded8d | [
"BSD-3-Clause"
] | 87 | 2018-06-25T14:04:20.000Z | 2021-05-31T08:15:47.000Z | tests/unit_tests/blockchain_db.cpp | OIEIEIO/ombre-working-old-chain-before-for-test | 4069cc254c3a142b2d40a665185e58130e3ded8d | [
"BSD-3-Clause"
] | 69 | 2018-06-25T05:41:34.000Z | 2022-03-09T08:57:37.000Z | // Copyright (c) 2014-2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <chrono>
#include <cstdio>
#include <iostream>
#include <thread>
#include "gtest/gtest.h"
#include "blockchain_db/blockchain_db.h"
#include "blockchain_db/lmdb/db_lmdb.h"
#include "string_tools.h"
#ifdef BERKELEY_DB
#include "blockchain_db/berkeleydb/db_bdb.h"
#endif
#include "cryptonote_basic/cryptonote_format_utils.h"
using namespace cryptonote;
using epee::string_tools::pod_to_hex;
#define ASSERT_HASH_EQ(a, b) ASSERT_EQ(pod_to_hex(a), pod_to_hex(b))
namespace
{ // anonymous namespace
const std::vector<std::string> t_blocks = {
std::string("\x08\x08\xec\xea\xab\xe0\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x71\xfe\x19\x54\x03\x9a\x97\x0a\x01\xff\xde\x96\x0a\x01\x80\xc1\xed\xac\x9c\x01\x02\x52\x71\xcb\x3c"
"\xca\x35\xf2\x26\x08\x5c\x93\x59\x5e\x7f\x05\xfc\xdc\x3d\x96\x8a\x70\x07\x2e\x75\xb0\x45\x55\x31\x93\x30\x3a\xdd\x21\x01\xd1\xff"
"\x9d\x58\x25\x53\xf4\x4f\x6f\x20\xe1\x62\x11\x00\x73\xab\xbe\x38\x23\x67\xfe\x4e\x6e\x8f\x65\x9b\x97\x70\x43\x1d\x2b\xaf\x00\x01"
"\x35\x79\x96\xf3\xc7\x12\xe9\xf6\xab\x2f\x6b\xee\x7c\xc7\xba\xc4\x84\xb8\xaf\x83\x95\x79\x58\x37\x59\x85\xfa\x10\x98\x4a\x31\x51", 160),
std::string("\x08\x08\xb4\xf1\xab\xe0\x05\xe5\x88\xd4\x7f\xc1\xee\x21\x3f\xd0\x6a\xed\xeb\xcf\x5d\xa7\x71\x00\xaf\x4f\x7c\xfe\x96\xef\xd3\x28"
"\x2f\x51\xcf\x20\x7a\x47\x89\xb6\xfe\x5b\x73\x03\x9b\x97\x0a\x01\xff\xdf\x96\x0a\x01\x80\xc1\xed\xac\x9c\x01\x02\xe3\x26\x67\xf8"
"\x7c\x63\xba\x08\x6b\xcc\x68\x04\xab\xf3\xec\xc8\xe7\x4b\xfd\x86\x22\x3a\x94\x91\x00\x3c\xa7\x0f\x3d\x9d\x87\xd8\x21\x01\x3c\x33"
"\x0f\x80\x81\x85\x12\xcd\x85\xf4\x78\x1d\x47\xba\x60\x7f\x7e\xb2\x7f\x82\x8e\xb3\xe3\x52\xcd\x8e\x07\xd6\x1c\xc1\xfe\x4e\x00\x00", 128)
};
const std::vector<size_t> t_sizes =
{
1122, 347};
const std::vector<difficulty_type> t_diffs =
{
4003674, 4051757};
const std::vector<uint64_t> t_coins =
{
1952630229575370, 1970220553446486};
const std::vector<std::vector<std::string>> t_transactions ={ {
std::string("\x03\x00\x02\x02\x00\x19\x80\x87\x06\xd9\x02\xf0\x19\x9f\x07\x98\x29\xbb\x60\xc0\x0b\x9b\x13\xa1\x21\xd4\x22\xb8\x11\xef\x14\xa7"
"\x0c\xf8\x2c\xf4\x23\xc5\x23\x92\x1e\xda\x03\x9b\x06\xfd\x21\x0b\x39\x08\x1f\x11\xca\x77\xfe\x17\x8e\x05\x12\xe0\xfe\x1c\x43\x3b"
"\x19\x29\xfb\xd0\x4b\xb9\xef\x3c\x35\x83\x34\xf2\xce\xb4\xa2\x60\x7a\x45\x62\x6b\x02\x00\x19\x8f\xdf\x02\x90\x51\xd4\xd2\x03\xaa"
"\x1a\xa6\x29\xd4\x27\xb2\x23\xb5\x05\xbf\x35\x88\x27\xd1\x02\xb3\x25\xf2\x1b\x64\x92\x01\x84\x30\x91\x04\xe3\x18\x02\x13\x99\x01"
"\x1d\x39\x15\x48\x14\xff\x33\xd3\x69\x48\xd6\x87\x0b\x3e\xf0\x6e\xc2\x89\x8e\x76\x33\xb9\x6c\x79\x68\x9d\x38\xd5\xc6\x72\x2b\x09"
"\xf0\xce\x5b\x77\x02\x00\x02\x8a\x61\xb0\x15\x32\x77\x4a\xe2\x99\x0e\x8f\xbc\x45\xe2\xb5\x57\x5b\x3c\xfd\xac\x6b\x8b\x68\xa2\xdc"
"\x0a\xe5\x85\xde\xb5\x2c\xe8\x00\x02\xce\x5b\x8b\x3f\x84\x91\x30\xf5\x06\xa1\x0a\x55\x52\x85\x2f\x4a\xdb\xb4\x8d\x36\xde\x50\xe1"
"\x33\x66\xe1\x43\x66\x63\xe6\x59\xb7\x4a\x01\xf4\xf4\x5c\x42\x47\x99\x59\x47\x01\x1a\xe9\x9f\x03\x18\x18\x54\x17\xd5\x1d\x06\x4a"
"\x80\xd7\x5e\x9e\xa1\xe5\xcc\x75\xcb\x2f\x42\x05\x92\x83\x0f\x06\x12\xb8\xbf\x1a\x14\x45\xba\xfc\x63\x05\x2d\x68\x88\x0f\xe8\xec"
"\x63\xa8\x1a\xff\xd6\x20\x57\xf7\xb7\x49\x0c\x16\x61\x69\x77\xa4\x12\xf3\xb4\xa7\x03\xc0\xc3\x93\x07\x71\xac\xda\x53\xec\x9a\x64"
"\xa2\xdc\xd9\x26\x5a\x1f\xa5\x2c\x75\x5e\x50\x31\xa7\x12\x90\x12\x9d\x12\x25\x8c\x29\x71\x54\xde\x0e\xef\x64\xfa\x9b\x0f\xf6\x93"
"\x0d\x8a\xf4\x31\xe0\x2e\x18\x4b\xff\xcb\xe5\x44\xed\xcf\x9f\xc4\x4e\x59\x0a\xde\x45\x5c\xee\x7e\x0c\x9b\x15\x90\xef\x15\x46\x11"
"\x06\xf1\xd0\x79\x05\x8e\x8c\x9a\xab\xf7\x01\x41\x5b\xbe\xa0\x9b\xc4\x6d\x3a\x00\xb7\xcf\x52\x89\x0d\x82\x1b\xd7\xd6\x81\xaf\x86"
"\x5e\xc2\x97\x46\xdd\x0a\x80\x62\x6e\xc7\x3e\xe4\x5f\x43\x77\xc1\xde\xbe\x28\x9f\x89\x92\xd3\x4c\x08\xb1\x86\x7c\xc0\x71\x22\x1c"
"\x26\x08\x60\x2c\xf6\x85\x69\xa8\xff\x5a\xea\xe4\xda\xd5\x6a\x7b\xac\x10\x5b\x5f\x98\x44\x56\xa6\xc8\x08\x1a\xf6\xd9\x06\xa1\x9c"
"\xf9\xba\xb2\xc9\xb3\x24\x58\xe9\x91\x8a\x35\x35\x9d\x47\xa0\x93\x63\x65\xee\x2f\x2c\x46\x0e\xfa\xe2\x01\x00\x00\x00\xe2\x23\xdf"
"\x74\xc0\x51\xdc\xe6\x1a\xb3\xbf\x61\x6d\xaa\x43\xa4\xc2\x0a\xf0\x2c\x8c\xc5\x0c\xed\x14\x33\x66\x0b\x8d\xf7\x99\x60\x58\x85\x3d"
"\x78\x9a\xaa\xd9\xdd\x34\x2b\x9b\xdb\xa2\x54\x2c\x6f\xb9\x7b\xae\x73\x75\xcd\x55\x52\x17\x51\xe8\xa3\x8d\x04\xa6\x16\xe6\x1a\xd2"
"\x8c\x0f\x34\xe8\x5e\xde\x95\x9a\x71\xfc\x5f\x74\x59\xec\x92\xb6\x60\xec\xae\x4c\x52\x71\x27\x64\x4f\x51\x70\x0e\x5b\xa9\xf2\xed"
"\xa9\xf5\x0d\xac\x96\x12\x23\x4b\x3a\x5e\x54\x4a\x2a\xd1\x20\xfc\xe4\x84\x00\xed\xbd\xc3\xa8\x76\x7b\xfa\x28\xa1\x1e\xaa\x66\x2a"
"\xe1\xe7\xc1\x02\x2a\x87\x81\x8d\xd0\xb5\x2b\xf6\x4e\xec\xd7\x1e\x53\xbf\x34\xa5\xab\x08\xac\x5c\x1a\xa7\x98\x04\x04\x9e\x25\xa4"
"\x65\xe8\xdd\x5a\xb8\x85\x83\xe3\x53\xd5\x66\xec\x46\x32\x91\xc2\xb5\x74\xd7\x9c\x3b\x36\xea\xc3\xfd\x6c\x52\xc9\x0f\x07\xce\x8a"
"\x56\xce\xa7\xfa\xbd\x87\x83\x15\x4b\x5f\xa3\x6d\x8d\x21\x8d\x98\x06\x72\xc6\x3e\x4b\x3d\x54\x82\xf3\x94\x9d\x9a\x59\x6f\xad\x8b"
"\x21\xee\x74\xab\xd8\x62\x3f\x0a\x66\x73\x9c\x16\xcc\x6d\xa5\xf2\x87\x08\x04\x12\x15\x76\x1a\x42\x16\xab\x50\xd0\xc1\xca\x9c\xf2"
"\xfd\x99\xbe\x43\x92\x11\x8d\xcd\x19\x58\x6a\x27\xd1\x24\x16\xf7\xbd\x02\x75\xa0\x23\x71\x73\x96\x7f\x45\x7c\xa1\x29\x6f\x12\x89"
"\x36\x61\x7f\x74\x55\xc4\x75\x0f\xfd\xda\xea\x0b\x11\x59\xdf\x34\x53\xe6\x5c\xfd\xa3\x83\xe7\x8a\xb9\x69\xc0\x08\xc4\x2e\x2d\xad"
"\xa4\xa5\xef\x4d\x27\x7f\x99\xb0\x22\xcc\x3e\x9a\x0a\x6f\xdf\x84\x92\x8a\xa0\x3a\x63\x83\xb9\x01\x99\x5b\x5c\x9a\x48\x60\xfa\x28"
"\xae\xc1\xb1\x24\xc5\x7a\xac\x7e\x78\x3e\x41\xb6\x9a\x41\x21\xd9\xf5\xd1\xea\x71\xf7\x96\xa2\x30\x7f\xd1\x33\x96\xf9\x44\xaf\x82"
"\x65\xb9\xdd\xd0\xc1\x3f\xe1\xf5\xe0\xd0\x45\xf6\x90\x05\xa1\x5c\xa0\x94\xe4\x42\x31\xb5\x02\xd4\x61\xe1\x2e\x48\x7d\x99\x07\x49"
"\x27\x9a\xe4\x00\xf8\x6f\x53\x39\x9d\x99\xc3\xb6\x24\x3a\xd6\x58\xed\xe2\xf1\xa8\xb7\xbb\x70\x8b\x0c\xca\xab\x40\xe0\x16\x93\xc2"
"\x93\x5e\x96\x92\x21\xa8\xb1\x98\x70\x21\x06\xe4\x43\x12\x6b\x38\x69\xb7\x75\x0e\xd6\xff\x6f\x50\xf3\x9d\x9a\x8e\x56\x2b\xa7\x5e"
"\x23\x95\x4d\xc4\x46\xf2\xc8\x6b\xad\x75\x4c\x8e\xbf\x00\x1b\xd7\xd0\x93\x5e\x34\x1d\x4d\xe5\xc0\x25\x79\x26\x79\xab\xf2\xb1\x8a"
"\x41\x2e\xa3\xc2\x29\xa0\x03\xca\x19\xf0\x3e\x19\x76\x51\x87\xe8\x2c\x6f\x46\x97\x64\x22\x9f\xcd\x8a\xa7\x7c\xf7\x5d\x4e\x96\x78"
"\xe6\x72\xb0\x66\xd5\xba\x70\x77\xb0\xad\x38\xbb\x6d\x4c\x37\x99\xca\x94\xfa\x3c\xb0\xe9\x0c\xa1\x3a\x73\xe0\xf8\x04\x64\x17\xc4"
"\x76\x1f\x27\xc6\x1d\x77\x0e\xd6\x5b\x84\x11\x69\xc6\xd2\x93\xc3\x25\x0b\x52\x57\xfa\xef\x7c\xbd\xa2\x93\xbd\xd9\xa9\x76\xdc\x38"
"\xa8\xe3\xfa\x9a\x93\xde\xcf\xd1\xcf\x9f\xf0\x62\x26\xb9\x12\x05\xed\xf6\x4e\x63\x65\x18\x14\x8c\xa4\xaa\x0a\xd5\x79\x4d\x10\x39"
"\x81\x27\x80\xfe\xd1\x01\x60\xe6\x15\x52\x76\x85\x22\xfe\x61\xd6\x96\x9b\xe3\xd4\x0a\xa7\xc5\x8f\xac\xf4\xe9\x3e\xc5\xa1\x0b\xdc"
"\x9d\x86\x6c\xad\x6f\x65\x3d\x3f\xbb\x49\xc2\xa7\x71\x68\x93\xad\xbb\x2b\x80\x44\x5d\xa5\xff\xe5\xb7\xde\x89\xdc\x77\x90\x09\x5a"
"\x77\x46\xeb\x48\xc3\x26\x02\xcf\xb4\x5e\x06\x65\x7f\x93\x51\xb4\x1a\xbf\xa7\xc0\xed\xd0\x05\xde\xdb\x50\xef\xb4\xd1\x02\x04\x67"
"\xc8\xc1\x95\x38\x38\xba\x0c\xc5\x6d\xff\x4d\xd6\x3e\xc2\xb9\xc8\xc2\x22\x8e\x88\xfb\x87\xb6\x05\xc9\xe5\xe9\x99\x37\xc3\x05\xc0"
"\x8f\x29\xd3\x88\xff\x84\x8a\x2a\x74\xa8\x6b\x68\xff\x7b\x44\x2c\x8f\xf7\x73\xed\x13\xf6\x4b\x15\x66\x03\x12\x1f\x06\x2e\x04\xd6"
"\xfe\x60\x0f\x0d\xde\x66\xe2\xb1\xea\x94\xc2\x57\x95\x63\x74\xfa\x24\x20\x48\x79\x0c\x99\xc9\x6b\xd9\xde\xef\x8c\x8c\xf0\x01\xbe"
"\xc5\xb1\x93\xc1\x3d\x0a\xbd\x67\x09\x18\x96\xbe\xb8\x16\x0d\x3e\x58\xa6\x17\x6e\x18\xf7\x9e\x70\x84\xb2\x51\x7d\x34\x7f\x0a\x07"
"\x53\xbd\x58\xe2\xd8\xe6\xda\x62\xfd\x6a\xef\x5a\x16\x82\x06\x42\x0d\xe1\xfb\xc2\x96\xeb\xbe\x60\xd1\x2d\x9c\x61\xa8\xd7\x08\x37"
"\x9d\x90\x89\x68\x47\xa7\x9c\xf1\x50\xdd\x53\x93\x84\xdc\xc4\x45\xec\x8e\x26\xcc\xe4\x49\x7f\x1f\xd6\x6b\x25\xc7\xd7\xdf\x08\xc9"
"\x4f\xf3\xac\x91\x61\x94\x78\xbc\x91\x9f\x7e\xe4\xfe\x7a\x2c\xdf\xe8\xb6\x6f\xa6\x30\xe1\x50\x1e\x71\xe4\xca\xdb\xae\xb3\x03\xd8"
"\x89\x7c\x93\x3d\x68\x11\xbe\xdb\x46\xf9\x54\x33\x0a\x29\x76\xe7\x1c\x42\x76\xb0\x44\xd1\x03\x42\xa2\xfe\x02\x47\x4d\x42\x00\xc8"
"\x14\xb9\xf9\xc5\x52\x28\xf1\x3f\x6a\x9a\x01\x1d\xff\xde\x01\xa8\x8d\x69\x57\x43\xbc\x09\x28\xa5\x33\x41\x22\xca\x51\xfc\x0f\x99"
"\x03\x21\x5e\x82\x12\x04\x6f\x10\xef\x98\x4a\xa1\x8a\x44\x71\xa3\xbd\x2a\x58\xce\x31\x78\x44\xbb\x0e\x15\xd2\x13\x8e\x07\x09\xee"
"\x92\x9c\x8e\x66\xc8\x91\x81\x19\xf3\x87\x4c\xed\x82\x20\xd4\x7b\xd2\x00\x8c\xa3\x36\xba\x0b\xe8\x2c\xb1\x19\x81\xd0\xb8\x00\x6d"
"\x9f\x61\xcb\xb0\x21\xd8\xbe\x1b\x59\xd7\xdd\x5b\xb8\x9c\x45\x9a\x09\xd8\x77\xbc\x20\xc8\x92\x2a\xf4\x61\xfd\xe8\xd4\x1f\x05\xe8"
"\xab\x71\xb7\xe6\x33\xce\x90\xd6\xa2\x03\xa2\x54\x52\x05\x72\xaa\xc9\x69\xc7\x8f\xcc\x65\xd2\x74\x0e\x4e\x2f\xae\x5a\x2b\x0f\xd4"
"\x2d\x0a\xf0\xb8\x0c\x3b\xb3\x91\xb7\xa3\x2d\xc0\xb0\xbf\x94\x5b\xc4\x8e\x0c\xca\xbb\xa9\x53\x73\x71\x5d\x80\x3b\x62\x4e\x0e\x72"
"\xd1\xc1\xc2\x3e\xf2\x8a\x4a\x7e\x83\xff\xb2\xe4\x44\x0b\x30\xbf\x03\x7a\xaf\xc5\xbe\x7f\x49\xcd\x53\xb4\x82\x05\x46\x0e\x02\x71"
"\x89\xbd\x4b\x3e\xc1\xe2\x05\xbf\x17\xbe\xb8\x85\x48\x60\xea\xe4\x07\x5c\x0d\x68\x9a\x31\x38\xd6\x3c\x2d\x06\xb3\x47\x35\x0d\xf2"
"\x08\x35\x20\xda\xde\x26\xe1\x8a\xad\x04\xc9\xce\xfc\x15\xea\x6e\x49\xf3\x92\xe7\xdd\x4b\x8a\xaf\xea\x5a\xd2\xf2\x20\x26\x0f\x72"
"\x78\x4a\x84\x42\x76\x8c\x79\x65\x41\xc3\x51\x18\x25\xa0\x6f\x25\x82\x3a\x8c\x21\x32\xba\xe5\xe8\x51\x2e\x38\x41\x04\x00\x04\xd7"
"\xc2\x91\xfe\x4b\x3b\x4c\x4c\xce\x1a\x69\xa8\xf7\xd0\xb3\xcb\x35\x73\x35\x58\xcb\xa2\xcd\xf6\xeb\xac\x0c\x1d\xe2\x1a\x6e\x0a\x10"
"\xda\x54\x60\x29\x8f\x5b\x4b\x73\x1a\x23\x35\x24\x67\x89\xa1\x59\x30\x71\xfb\x3e\x38\xcc\x2e\xa5\xab\xf3\xa6\x71\x5a\x0e\x05\x88"
"\x2e\x2d\x1b\xc2\xb8\x6e\x64\xe2\xf7\x92\x8f\x42\x63\xee\x61\x72\xab\x80\xd3\x73\x11\x2e\x3b\x8e\xc2\x3f\x2d\xc5\xc1\x75\x0b\xef"
"\x45\xcc\xd6\xa8\x77\x9f\xb1\x58\xaf\x02\xff\x7b\xd4\xfc\x9e\xd8\x0a\xa2\xac\x3c\xfc\x2c\x3d\xa7\xde\x44\x59\x51\x87\xdd\x04\x51"
"\x89\x58\x82\x05\xeb\x7e\xe3\xe3\x99\x0a\xc9\xfb\xc7\xf1\x2a\x05\xd2\x74\xfa\x74\x1c\x2d\xfd\xb1\x2f\xa2\x8f\xbe\x47\x66\x01\x62"
"\x28\x59\xf9\xe2\x76\xdd\x74\xbb\x30\x27\x09\x54\x96\x8d\x27\x70\x67\x37\x47\xd4\x91\x3b\xe4\x05\x0d\x92\x42\xf4\x5e\x94\x0d\x71"
"\x56\x8a\x9f\xdc\x35\x9d\xd7\x09\x3d\xcb\x39\x2b\xe0\xe5\x01\x27\x44\x4e\x46\x18\x6d\xb4\xd0\x3b\x5d\x5f\x88\x7e\xea\x59\x0b\x6f"
"\x48\x66\x70\x45\xec\x6e\x62\x4f\x43\xf4\xeb\x5d\x8f\x59\xf7\x3b\x6a\x66\x95\x0e\xd0\x2d\xe1\x24\xf1\x4a\xa9\x6a\x34\x12\x09\x05"
"\x32\x6f\x75\xb1\x36\xcb\x6b\xa7\x8a\xab\x1f\xaa\xb6\x2b\x0a\x0a\x02\x9b\x57\xaa\x06\x83\x4b\x33\x6e\x1e\xb9\xc0\x5d\x06\x02\x98"
"\xd7\xfe\x00\x5f\x74\x03\xda\xdf\xc7\x96\x45\x35\x94\x1f\xf3\x4d\x4e\xc6\x19\x5b\x25\xc9\x09\x3b\x84\xdc\x79\x06\x1d\x11\x05\xeb"
"\x9f\x53\x3b\xdf\xe5\x40\x45\x3f\x38\xd5\xb2\xae\x2a\xb7\x6d\xdc\x2c\xc6\xb8\x45\x1e\x87\x35\x3f\x87\xb6\x62\xa1\x38\xbb\x09\xc7"
"\x7e\xf7\x3d\xb3\x73\x14\xcb\x6d\xcd\x89\x68\x41\x71\x16\x93\xe1\x9e\xba\xff\xb4\x7d\xb3\x74\xda\x63\x28\x48\xfd\x04\xac\x07\x43"
"\x78\x27\x07\xa9\x62\x48\xfb\xa1\xc1\x06\x9c\x49\xe2\x95\xff\x7f\xb1\xa1\x6e\x5f\xb1\x03\x5b\xe4\xe6\xc4\xe3\xff\xca\x22\x01\x33"
"\x9b\x43\x87\xc8\x4f\x87\xbc\x80\x49\x3d\x11\xe3\x46\xb4\x35\xa5\xd5\x00\xc4\xa6\x1b\x45\x5c\x0e\x1b\x2c\xed\xdd\x47\x4e\x0f\x6b"
"\x31\x68\xfd\x98\x5c\x8e\xc4\xe1\x92\xeb\x1c\x50\x49\x90\x21\x3e\x79\x92\x8d\xc8\x89\xc5\x94\x28\x5d\x71\xdb\xf7\x65\x82\x02\xf4"
"\x55\x45\xd4\x11\x4c\x65\xcd\xc9\xad\x07\x14\x1d\x8c\x03\x2b\x09\xcb\x4d\xbd\xa9\xdf\xb4\x7c\x67\xbc\x05\x71\x90\x94\x02\x0a\x99"
"\xc8\x5c\xee\xfc\xe3\x6e\xee\x35\x66\x3b\xac\x9e\xb9\x3f\x52\xb5\x82\x59\x78\xdf\xc2\x82\x9d\xb4\x0d\xb9\xe5\xea\xa8\x4b\x0d\xff"
"\x19\xe3\x3b\xc4\x32\x1b\xaa\x64\x6f\x29\x59\x83\xff\xa7\x40\xc6\xfc\x9b\x3b\x35\x1d\x4c\xd6\x08\xc3\x20\x3f\x44\xa9\x2d\x01\x91"
"\x8d\xf6\xb0\x8c\x6c\x67\x6e\x20\x0b\xfe\x98\x64\xe8\x5e\x1b\xf9\x21\x13\x58\x30\x70\x0d\xb8\x98\xc6\xe0\x9c\xbb\xa0\x06\x03\xf1"
"\xf4\x56\x51\xd9\x5c\xf7\x14\x4d\xc9\x66\x32\xa1\x6d\x5c\x5b\xcb\x6f\x1e\x22\x35\x52\xae\x4a\xef\xc8\xfd\x39\x4b\xaa\xa3\x0c\xf9"
"\xd7\xcb\x08\x86\xf7\x5c\x90\x09\x51\xf6\x0a\xc3\x39\x99\x03\x4a\xd9\xc7\x0d\x49\xac\xf2\x5f\xcd\x0d\xbe\x34\x11\x9c\xfc\x0a\xfc"
"\x04\x80\xbd\x51\xbc\x9b\xb4\x74\x4a\x1d\x69\x13\x7c\xde\xb7\xb9\x81\x39\x3b\x6e\x24\xfd\x18\xa7\x4f\x4f\x48\x9d\x69\xf8\x07\x99"
"\xd7\xca\xc0\xc7\xdc\x16\x8e\x2d\xd4\xc4\x47\x7e\x1c\xa3\x5f\x04\xf2\xa7\x4d\x33\xb2\x62\x8e\x36\xf2\x44\x02\x75\x96\xfb\x03\x41"
"\x92\xea\x55\x7e\x97\x53\x5b\x1e\xda\x55\x4e\xae\x23\x80\x2c\x6a\x42\x4e\x02\x68\x67\x7a\xd9\xd2\xe5\x68\x32\x9d\xbf\x8e\x05\x3a"
"\x8a\x6e\x7f\x99\xdc\x3c\xc0\xba\xac\x6a\xd0\x09\xf2\x9c\xb8\xe3\xf4\x7b\x9d\xfe\xd7\x64\x2c\xba\x1e\x99\x85\x2c\xfe\xe9\x00\x7b"
"\x57\x25\x7b\xff\x4c\x08\xb5\x6a\xf3\xcd\xa8\x39\x77\xc3\x9b\x7c\xd4\x42\xe1\xea\x8b\x58\x33\xe2\x28\xf9\xe9\xfc\x6d\xde\x01\xc6"
"\xdd\x62\x48\xf9\x92\xad\x66\xfd\xdf\x34\x8a\x46\x5b\x3d\x64\x8e\xce\x42\xd0\xd9\xd8\x01\xb2\xb4\x9b\x0c\x1c\xc1\x27\xf9\x0c\x37"
"\x34\x4a\x98\xec\x03\xcb\xde\x27\xf8\x61\xa0\x9f\x5f\xe0\x63\x8c\x6d\x9a\xb6\x42\x30\x14\x3e\xce\x1f\x15\x6d\x2a\xb7\x05\x0a\x00"
"\x8d\x71\xcb\x0b\xa8\x26\x6f\xfc\xb3\x16\xe1\x96\xaa\xe9\x6f\x34\x77\xa0\xf4\xcc\x6c\x55\x50\xd2\x39\xb6\xe3\x72\x6e\x96\x09\xcc"
"\x02\xfc\xbb\x12\x2e\x82\x25\x84\x79\xa4\xd1\x17\x28\x7c\x46\x16\xc2\x9b\x32\xcc\xcb\xd5\x87\x30\x98\x8b\x08\x04\x7f\x05\x02\xc9"
"\x6e\xb4\x54\x0b\xa8\x33\x21\x20\x62\x55\x4b\x2e\xa1\x5e\x53\x6f\xe4\x13\xf9\xbe\xf2\xcb\xb5\x67\xae\xa3\xaf\x0e\xcc\x52\x07\x21"
"\x87\xfd\x99\x68\xae\x3b\x8d\x86\xe1\x69\xce\x34\x34\x85\x22\x91\xe7\xc9\x52\xfa\xc9\x50\xf9\xde\x3d\x3d\x00\xe7\x04\x47\x0f\x32"
"\x0b\x6f\x07\xc8\xe0\x54\xcc\x22\x13\x41\x17\x95\x85\x31\x67\xeb\x6c\xda\x70\xb1\xfe\x52\x3f\xc1\x5d\xb3\x83\xae\x41\xf9\x05\x11"
"\xf0\x65\xe2\x1c\x43\x05\x21\x29\x3c\x08\x0b\xcc\x67\x5b\xde\xff\x0b\x5f\x7a\x72\x86\x17\x53\x86\xa4\x9e\xef\x8b\xc6\x5f\x0a\xf1"
"\xb2\x86\x51\xc5\x6f\xf1\x36\x57\xbc\x5a\xc1\x91\x7e\x86\xc5\xcb\x48\x01\xc6\x73\xaa\xc9\xde\xe3\x83\xfd\x13\xb3\xb8\xc1\x0a\xfa"
"\xbe\x8d\xa3\x10\xf7\x58\xfb\x4b\x89\x60\xca\xe6\x6d\x3f\x7b\x75\x1f\xf4\xab\xe6\x29\x38\x6d\x1e\x76\x5a\xe8\x41\xb5\xcb\x0d\x28"
"\xf1\x64\x0c\x9c\x4d\xdf\xb8\xb6\xf4\x5d\x31\x07\xcc\x67\xab\x25\x68\x54\x68\x92\x2b\xd1\x81\xe2\x73\x7c\xe2\x56\x59\x30\x08\xd9"
"\xf2\x9a\x9c\xc8\xcb\x85\x1f\x60\x85\x70\x02\xac\xed\x4d\x1b\x9c\xc1\x5b\x17\x07\xff\x3d\x24\x0d\x3f\x5f\x8f\x97\x32\x22\x03\xaa"
"\x4d\x00\xd5\xd5\x90\x9b\x34\x76\x5c\xe4\x74\x2e\xcb\xdc\x96\xf9\x1a\xbd\x52\x66\x81\xd0\x5a\xee\x14\x40\xf3\xa2\xfe\x2a\x0f\x8b"
"\xe1\xb2\xaa\x9a\xf7\x05\x7a\xb4\x92\x56\xea\x03\x9d\xd4\xbf\x32\xa1\x66\xe8\x2e\x2c\x37\x7d\xc8\xdd\x12\x6c\x63\xf1\x70\x0d\xdb"
"\xb1\x43\xae\xf3\x55\x21\xa9\xf0\xe2\xe4\x44\x8e\xc6\xa8\x13\x1b\xc3\x9e\xc8\xca\xc6\xf4\xf1\xe9\x30\x2e\x5e\x89\x10\xef\x0f\xb2"
"\x28\x5d\xcb\xc1\xb0\x53\x87\x22\xa8\xc2\x67\x0b\x5e\x56\x61\xae\x1c\x17\x9f\x2d\x41\xfc\xd4\xa2\xa2\x5a\x82\xbb\xf8\x46\x0a\xa7"
"\xd2\xc0\x0b\x9f\x29\x52\xf0\xce\x88\xe9\x93\xf4\x97\x9f\x39\xa2\x6e\x39\xed\x33\xc8\xfc\x1f\x4d\x44\x2f\x0b\xc2\xe0\x03\x0d\xab"
"\x35\xa6\x79\xc4\xdd\xd1\x42\xa0\xaf\x71\x33\xce\x41\xf7\x96\x95\xdf\xe1\xd5\x8c\x3c\xc0\x66\xce\xe6\x58\x90\x78\x93\x8a\x0e\x03"
"\x2d\x49\xd0\xa7\x3f\x88\x6c\x5c\x09\x03\xa8\xba\xc6\xe9\x43\x7e\xe8\xa9\x25\x07\x68\x3a\xf9\x2c\x21\x10\xa3\x36\x41\xe7\x01\x39"
"\xf8\x19\x8e\x35\xd0\x69\xe2\xdf\x8e\x5c\x25\x73\x75\xdf\xb8\x54\x9e\x55\x37\xbe\x83\xe9\x31\x88\x2d\x80\x95\xf8\xf8\x98\x09\x45"
"\x7b\xf8\x9c\xe7\x72\x95\xb0\x11\xe4\xcf\x67\xf8\x2a\x0f\x62\x9b\xc7\x6c\x34\x1f\xbe\x23\x55\xdc\x03\xa1\xef\xa1\x85\xc7\x02\x10"
"\x8b\xba\x1e\xbb\x7d\x69\x61\x24\x59\xe2\x10\x45\x95\x29\x00\x02\x7d\x73\x82\x2d\x46\x8f\x06\xef\x23\xac\x98\xfb\xc7\x2e\x07\xb8"
"\x92\x7d\x87\x2c\x7c\x40\xad\xd8\xb4\xe8\x62\xcb\x12\x7d\x8f\x24\xe5\xc3\x7c\xb0\xec\x8b\x40\x2f\x9b\x61\xda\x37\x41\xc0\x02\xcf"
"\xfb\x58\xe6\x99\xbc\xac\xdc\xcb\xd8\x5d\xfe\x28\xd6\x01\x17\xce\x40\xe9\xdd\xa9\xfd\x90\xe1\xc4\xa2\x4b\x56\xca\xd6\x2b\x03\xf6"
"\x9b\x08\x43\x83\xe6\x2f\x8a\x76\x51\xf2\x77\xbd\xaf\xfd\xf9\x08\x6c\xbf\xe9\x43\x05\x84\xc1\xcf\x29\x44\x77\xa3\xe8\x2e\x0f\x1a"
"\x8a\x87\xe1\xb7\x7e\x17\xa2\xd1\xd9\xfa\x1c\x3d\x2b\xe8\xda\x97\x7e\x6c\xc3\x87\xeb\xdf\x4b\x44\x95\x92\x88\x6f\xf9\x8c\x0e\xd8"
"\x6f\x2c\x1b\xf8\xed\x07\x69\xa5\xf0\xdd\x13\x0a\x66\xc5\xd7\x60\xe3\xd5\xfb\x2d\x21\xfc\x03\x60\xf7\x98\x1a\x26\xda\xe5\x02\x76"
"\xf2\xe4\xc1\x4a\x76\x49\x5a\xe9\x12\x40\xa5\x0d\x7e\xa3\x47\x07\x55\x80\xf7\x21\x11\xa9\xd3\xb8\x8d\xa4\x25\x93\x6d\x64\x0e\xd7"
"\x21\xfe\xc6\xb6\xe6\x71\x90\xfe\xa5\x40\x58\x90\xad\xfd\xe0\x59\x52\xd8\xde\x96\xdc\x9b\x0e\x82\x00\xc7\x08\xdf\x56\x5a\x0d\x01"
"\xab\x70\xa7\xd2\x01\x46\x4e\x49\x92\x39\x23\xe0\xcb\x56\x35\x08\x1e\x70\x9b\x34\xad\x48\x5b\x6a\xfb\x9d\x85\x35\x8b\x17\x03\xd7"
"\x7d\xa8\x35\xb1\x94\xca\x65\xaf\x33\xd9\xfc\x22\x2a\x67\x1a\x72\x9e\x1a\x44\x46\xbd\xa9\x04\x7c\x31\xee\x87\xed\x88\x43\x0c\x83"
"\x39\xd1\xbe\xa2\x36\x3b\x62\x53\xcc\x5d\x7f\xe0\x91\xe3\x6c\xd2\xa2\x3e\x29\x5b\xf2\x4a\x16\x09\xb7\x61\x02\xa7\x23\x95\x07\xd2"
"\x17\xaa\x26\xa0\x1f\x31\xec\xa3\x59\x89\xe3\xe6\x36\xb0\xd0\x9a\xa8\x10\xd4\xa9\x89\x20\xc3\x5b\x6c\xe8\x1c\x36\x06\x7f\x05\x86"
"\x5d\xb8\x23\x6c\xb9\x67\x0d\x9b\x4a\xcc\xde\x90\x30\xdf\xa0\xae\xd8\x43\xe2\x85\x4e\x84\x31\x48\xea\x24\xf1\xa3\x3a\x4c\x0e\x7d"
"\xb8\x10\x7e\xe5\x7c\x68\x4c\xa5\x24\xf7\x22\x1f\x8d\x86\x39\x68\x36\xa3\xec\x30\xb5\x94\x1c\xb4\x18\xcf\xc1\xa6\x9d\xb9\x07\x58"
"\x4e\xd3\x2f\x5b\x6d\xc5\x1c\xbb\xfd\xdd\x15\xbc\x45\xaa\x6f\x51\x7a\xc8\xf6\xd8\x92\x47\xb0\x40\x09\x78\x64\x3f\x27\x3f\x01\x7c"
"\x76\x6b\x40\xfd\x13\x14\x1a\xa5\x2e\xd7\xc6\x4a\x32\xf5\x3f\xe6\x62\x15\xbb\x20\x09\x94\xff\x58\xb2\x1b\x61\x9c\x13\x09\x0a\xc9"
"\x3f\x15\xbe\xfe\xcf\x04\x4f\x3e\x0b\xe2\x19\xc2\x26\x41\xb9\xfa\x97\xc1\xfc\xe6\xfd\xc2\xf1\x40\x1f\x31\xf1\xb5\xa4\x61\x07\x06"
"\xde\xf5\x67\xe2\x73\x89\x10\x3c\xa1\x49\x06\xc0\xd8\xe1\x6e\x52\x07\xc6\x1f\x51\xdb\x16\xe8\xaa\x94\x7b\x6b\x73\xd7\x1b\x0e\xb1"
"\x47\xfa\xe5\x08\x1a\x07\x40\x03\x58\xab\x43\xa3\xec\x29\xa4\x81\xce\x1c\x8b\xaf\xc9\xce\x6a\x14\x4d\xa9\x0a\x8d\xb4\x4d\x03\x40"
"\xde\x29\xee\xf1\xfa\xac\xeb\x25\x2b\xd8\x3e\xff\xd2\x16\xd0\x70\xb0\x47\x65\x46\x13\xda\xb6\x2e\x23\x78\x33\x41\x77\x5b\x04\x93"
"\x75\x68\xfd\x7d\x2c\x6a\x22\xd0\x94\x23\xa1\x04\x07\x67\xa4\x7b\xd6\xca\x54\x68\x71\x62\x5a\x4d\x2a\xe9\x5b\x94\x13\x46\x00\x78"
"\xa2\xbb\xe8\xb5\x05\x94\xc9\xda\x59\x6a\xc0\x07\x9b\x2a\x2f\x50\x90\x84\x0e\x48\xb4\x91\x4c\x14\x9a\xf2\xa2\x88\xe0\xca\x09\x90"
"\x84\x3c\x3a\xe9\x97\x36\x3d\x14\x0b\xf0\xff\x9a\xdd\xd1\x25\x4c\x7a\x79\xa4\xab\xec\x5b\x84\x4f\xc6\x86\xa3\x1b\x58\x6a\x03\xd3"
"\xc9\x97\x86\x18\x05\xe1\xd9\xfd\xec\x2d\x63\x5a\x7f\x83\x4d\xde\xf5\x21\x2f\x3f\x5f\xe4\x80\x0c\x7b\x46\x8f\x2c\xad\x9f\x0d\x4f"
"\x9b\x9e\xdf\xb7\x34\x64\xd1\x6b\xc3\x55\x21\xd5\xb2\x4b\xf5\xdf\x5a\x78\xa3\x9e\x7c\xfe\x51\xbf\xc2\xc1\x0f\x1a\x4d\xfa\x09\xb8"
"\x91\x35\x79\x43\xda\xff\x75\x20\xce\xbe\x10\x48\xd7\x6b\x22\x73\x1d\xf8\x33\x34\x66\x47\x31\xd7\x99\x58\x3e\x15\x99\x50\x0a\x5e"
"\x24\xc9\xf1\xd9\x6e\x46\x39\x90\x1b\xf2\x88\x64\x13\x64\x36\x52\x8e\x44\x4e\x01\x9c\x12\xd0\x74\x64\x71\xc6\x0c\xf8\xed\x04\xab"
"\xb8\x55\xa7\x0e\x1b\xe7\x9e\x6d\x02\x4b\xb4\x10\x52\xdf\xaa\xe9\x9a\x73\xbc\x39\xd0\xab\x2d\x6b\x11\x53\xb2\xc5\x15\x9f\x00\xf0"
"\x15\xc0\x74\xb2\x35\x87\x02\x37\xa0\x34\x84\x4f\x67\xd2\x4e\xb9\xde\x30\x85\xfa\xac\xb3\x53\xe4\xe9\xdc\xf6\xaf\xd5\xaa\x05\xee"
"\x08\xe9\xdd\xdb\xcc\xaf\x28\x05\x47\x6c\x54\x88\x1b\xf6\x85\xc4\x30\xb3\x56\x54\xa4\xde\x6c\x25\xbf\xd7\xd0\x06\x3d\x10\x01\x9a"
"\xf4\xc0\x35\xb6\xbc\xe0\x29\x01\x72\xc1\xc7\x2f\x2a\x67\x59\x5d\x1f\x91\x2c\xff\xcb\xb0\xc0\x08\x74\x8b\xb6\xe0\xa3\xf4\x0e\x59"
"\x00\xf2\x29\x0a\x3b\x6d\x89\x33\xc4\xf2\x04\xcd\xc8\x00\xf2\x35\xad\x50\xbe\x3a\x4d\x58\xe2\x11\x45\xe4\x60\x5c\xba\x5a\x0a\x71"
"\xb9\xc7\xaa\xb8\x54\xa1\x5f\x55\xac\x1a\xd7\x11\x45\x9b\x84\x2d\xa8\xb2\xfd\x44\x6b\xba\x0f\x50\x0d\x70\xc8\x85\xfb\x0d\x09\xae"
"\x27\xdf\x01\xa3\xd1\x83\xe9\xe4\x06\xba\x18\x8f\xca\xf1\xd4\xef\xad\xe5\x04\x7b\x75\x11\xe1\x88\x44\x07\x58\x38\x3d\x7a\x0d\x4d"
"\x7b\x1a\x2b\x30\x48\x18\x32\x0d\x84\xbe\x83\x6c\x4b\x6f\xc1\xd1\x69\x42\xe6\xfd\x22\xd1\x22\x52\xc4\xbc\x3e\x14\xcb\xe4\x05\x34"
"\xc5\xcc\x30\xed\x8f\xce\x52\xbf\x54\x37\x10\x45\xe0\x6b\x8f\x06\xd6\x2f\xc2\x84\xef\x25\xeb\xf1\xc8\x6d\x0e\x6c\xb3\x82\x0d\xdc"
"\x15\x66\xb7\xa8\x84\xb0\x10\xe7\x2e\x47\x60\xb6\xa1\x14\x32\x6f\x4b\x1c\x66\xab\x30\x37\xb1\x1d\xf1\x69\x7b\xec\x13\x70\x0b\x05"
"\xa3\x2d\x0f\x34\x2c\xc4\x81\x12\xca\xde\x89\x30\x62\x5a\xf1\x25\x1d\xea\x65\x80\x3c\xb0\x00\x1b\xba\xd0\xe2\xcc\x30\xe3\x2b\xd0"
"\x27\x27\x9f\x77\x28\xb0\xd5\x13\x2e\x9b\x25\x8a\x86\x12\xa8\x5b\x3c\x2f\xc4\x14\x1a\x53\x35\x97\xe3\x35\xfe\xc6\xc9\x8f\x63", 4575)},
{}
};
// if the return type (blobdata for now) of block_to_blob ever changes
// from std::string, this might break.
bool compare_blocks(const block &a, const block &b)
{
auto hash_a = pod_to_hex(get_block_hash(a));
auto hash_b = pod_to_hex(get_block_hash(b));
return hash_a == hash_b;
}
/*
void print_block(const block& blk, const std::string& prefix = "")
{
std::cerr << prefix << ": " << std::endl
<< "\thash - " << pod_to_hex(get_block_hash(blk)) << std::endl
<< "\tparent - " << pod_to_hex(blk.prev_id) << std::endl
<< "\ttimestamp - " << blk.timestamp << std::endl
;
}
// if the return type (blobdata for now) of tx_to_blob ever changes
// from std::string, this might break.
bool compare_txs(const transaction& a, const transaction& b)
{
auto ab = tx_to_blob(a);
auto bb = tx_to_blob(b);
return ab == bb;
}
*/
template <typename T>
class BlockchainDBTest : public testing::Test
{
protected:
BlockchainDBTest() : m_db(new T()), m_hardfork(*m_db, 1, 0)
{
for(auto &i : t_blocks)
{
block bl;
parse_and_validate_block_from_blob(i, bl);
m_blocks.push_back(bl);
}
for(auto &i : t_transactions)
{
std::vector<transaction> txs;
for(auto &j : i)
{
transaction tx;
parse_and_validate_tx_from_blob(j, tx);
txs.push_back(tx);
}
m_txs.push_back(txs);
}
}
~BlockchainDBTest()
{
delete m_db;
remove_files();
}
BlockchainDB *m_db;
HardFork m_hardfork;
std::string m_prefix;
std::vector<block> m_blocks;
std::vector<std::vector<transaction>> m_txs;
std::vector<std::string> m_filenames;
void init_hard_fork()
{
m_hardfork.init();
m_db->set_hard_fork(&m_hardfork);
}
void get_filenames()
{
m_filenames = m_db->get_filenames();
for(auto &f : m_filenames)
{
std::cerr << "File created by test: " << f << std::endl;
}
}
void remove_files()
{
// remove each file the db created, making sure it starts with fname.
for(auto &f : m_filenames)
{
if(boost::starts_with(f, m_prefix))
{
boost::filesystem::remove(f);
}
else
{
std::cerr << "File created by test not to be removed (for safety): " << f << std::endl;
}
}
// remove directory if it still exists
boost::filesystem::remove_all(m_prefix);
}
void set_prefix(const std::string &prefix)
{
m_prefix = prefix;
}
};
using testing::Types;
typedef Types<BlockchainLMDB
#ifdef BERKELEY_DB
,
BlockchainBDB
#endif
>
implementations;
TYPED_TEST_CASE(BlockchainDBTest, implementations);
TYPED_TEST(BlockchainDBTest, OpenAndClose)
{
boost::filesystem::path tempPath = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
std::string dirPath = tempPath.string();
this->set_prefix(dirPath);
// make sure open does not throw
ASSERT_NO_THROW(this->m_db->open(dirPath));
this->get_filenames();
// make sure open when already open DOES throw
ASSERT_THROW(this->m_db->open(dirPath), DB_OPEN_FAILURE);
ASSERT_NO_THROW(this->m_db->close());
}
TYPED_TEST(BlockchainDBTest, AddBlock)
{
boost::filesystem::path tempPath = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
std::string dirPath = tempPath.string();
this->set_prefix(dirPath);
// make sure open does not throw
ASSERT_NO_THROW(this->m_db->open(dirPath));
this->get_filenames();
this->init_hard_fork();
// adding a block with no parent in the blockchain should throw.
// note: this shouldn't be possible, but is a good (and cheap) failsafe.
//
// TODO: need at least one more block to make this reasonable, as the
// BlockchainDB implementation should not check for parent if
// no blocks have been added yet (because genesis has no parent).
//ASSERT_THROW(this->m_db->add_block(this->m_blocks[1], t_sizes[1], t_diffs[1], t_coins[1], this->m_txs[1]), BLOCK_PARENT_DNE);
ASSERT_NO_THROW(this->m_db->add_block(this->m_blocks[0], t_sizes[0], t_diffs[0], t_coins[0], this->m_txs[0]));
ASSERT_NO_THROW(this->m_db->add_block(this->m_blocks[1], t_sizes[1], t_diffs[1], t_coins[1], this->m_txs[1]));
block b;
ASSERT_TRUE(this->m_db->block_exists(get_block_hash(this->m_blocks[0])));
ASSERT_NO_THROW(b = this->m_db->get_block(get_block_hash(this->m_blocks[0])));
ASSERT_TRUE(compare_blocks(this->m_blocks[0], b));
ASSERT_NO_THROW(b = this->m_db->get_block_from_height(0));
ASSERT_TRUE(compare_blocks(this->m_blocks[0], b));
// assert that we can't add the same block twice
ASSERT_THROW(this->m_db->add_block(this->m_blocks[0], t_sizes[0], t_diffs[0], t_coins[0], this->m_txs[0]), TX_EXISTS);
for(auto &h : this->m_blocks[0].tx_hashes)
{
transaction tx;
ASSERT_TRUE(this->m_db->tx_exists(h));
ASSERT_NO_THROW(tx = this->m_db->get_tx(h));
ASSERT_HASH_EQ(h, get_transaction_hash(tx));
}
}
TYPED_TEST(BlockchainDBTest, RetrieveBlockData)
{
boost::filesystem::path tempPath = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
std::string dirPath = tempPath.string();
this->set_prefix(dirPath);
// make sure open does not throw
ASSERT_NO_THROW(this->m_db->open(dirPath));
this->get_filenames();
this->init_hard_fork();
ASSERT_NO_THROW(this->m_db->add_block(this->m_blocks[0], t_sizes[0], t_diffs[0], t_coins[0], this->m_txs[0]));
ASSERT_EQ(t_sizes[0], this->m_db->get_block_size(0));
ASSERT_EQ(t_diffs[0], this->m_db->get_block_cumulative_difficulty(0));
ASSERT_EQ(t_diffs[0], this->m_db->get_block_difficulty(0));
ASSERT_EQ(t_coins[0], this->m_db->get_block_already_generated_coins(0));
ASSERT_NO_THROW(this->m_db->add_block(this->m_blocks[1], t_sizes[1], t_diffs[1], t_coins[1], this->m_txs[1]));
ASSERT_EQ(t_diffs[1] - t_diffs[0], this->m_db->get_block_difficulty(1));
ASSERT_HASH_EQ(get_block_hash(this->m_blocks[0]), this->m_db->get_block_hash_from_height(0));
std::vector<block> blks;
ASSERT_NO_THROW(blks = this->m_db->get_blocks_range(0, 1));
ASSERT_EQ(2, blks.size());
ASSERT_HASH_EQ(get_block_hash(this->m_blocks[0]), get_block_hash(blks[0]));
ASSERT_HASH_EQ(get_block_hash(this->m_blocks[1]), get_block_hash(blks[1]));
std::vector<crypto::hash> hashes;
ASSERT_NO_THROW(hashes = this->m_db->get_hashes_range(0, 1));
ASSERT_EQ(2, hashes.size());
ASSERT_HASH_EQ(get_block_hash(this->m_blocks[0]), hashes[0]);
ASSERT_HASH_EQ(get_block_hash(this->m_blocks[1]), hashes[1]);
}
} // anonymous namespace
| 64.402655 | 143 | 0.720818 | OIEIEIO |
40a05189a81660446ad282b9ee0261b8a2c6dd69 | 456 | cpp | C++ | Entrenamiento/A/268.cpp | snat-s/competitiva | a743f323e1bedec4709416ef684a0c6a15e42e00 | [
"MIT"
] | null | null | null | Entrenamiento/A/268.cpp | snat-s/competitiva | a743f323e1bedec4709416ef684a0c6a15e42e00 | [
"MIT"
] | null | null | null | Entrenamiento/A/268.cpp | snat-s/competitiva | a743f323e1bedec4709416ef684a0c6a15e42e00 | [
"MIT"
] | null | null | null | #include <iostream>
#include <utility>
int main(void)
{
int n = 0, answer = 0;
std::cin >> n;
std::pair<int, int> teams[n];
for (int i = 0; i < n; ++i) {
std::cin >> teams[i].first >> teams[i].second;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(teams[i].first == teams[j].second || teams[i].first == teams[j].second && i != j) {
answer++;
}
}
}
std::cout << answer << "\n";
return 0;
}
| 19 | 92 | 0.475877 | snat-s |
40a38fd9b67fbcb9b21519ae4fa5f0b301d1a0df | 12,173 | cc | C++ | libs/daemon/shell.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/daemon/shell.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/daemon/shell.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | //==========================================================================
// ObTools::Daemon: shell.cc
//
// Implementation of daemon shell
//
// Copyright (c) 2009 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-daemon.h"
#include "ot-log.h"
#include "ot-misc.h"
#include "ot-init.h"
#include "ot-file.h"
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <fstream>
#if !defined(PLATFORM_WINDOWS)
#include <execinfo.h>
#include <sys/wait.h>
#include <unistd.h>
#else
#include <dbghelp.h>
typedef __p_sig_fn_t sighandler_t;
#endif
#define DEFAULT_TIMESTAMP "%a %d %b %H:%M:%*S [%*L]: "
#define DEFAULT_HOLD_TIME "1 min"
#define FIRST_WATCHDOG_SLEEP_TIME 1
#define MAX_WATCHDOG_SLEEP_TIME 60
namespace ObTools { namespace Daemon {
//--------------------------------------------------------------------------
// Signal handlers for both processes
static Shell *the_shell = 0;
const sighandler_t sig_ign(SIG_IGN);
const sighandler_t sig_dfl(SIG_DFL);
// Clean shutdown signals
void sigshutdown(int)
{
if (the_shell) the_shell->signal_shutdown();
signal(SIGTERM, sig_ign);
signal(SIGINT, sig_ign);
#if !defined(PLATFORM_WINDOWS)
signal(SIGQUIT, sig_ign);
#endif
}
#if !defined(PLATFORM_WINDOWS)
// SIGHUP: Reload config
void sighup(int)
{
if (the_shell) the_shell->signal_reload();
signal(SIGHUP, sighup);
}
#endif
// Various bad things!
void sigevil(int sig)
{
if (the_shell) the_shell->log_evil(sig);
signal(sig, sig_dfl);
raise(sig);
}
//--------------------------------------------------------------------------
// Main run function
// Delegate entirely to the application
int Shell::run()
{
int result = application.pre_run();
if (result)
return result;
while (!shut_down)
{
result = application.tick();
if (result)
return result;
int wait = application.tick_wait();
if (wait)
this_thread::sleep_for(chrono::microseconds{wait});
if (trigger_shutdown)
{
shutdown();
}
else if (trigger_reload)
{
reload();
trigger_reload = false;
}
}
return 0;
}
//--------------------------------------------------------------------------
// Start process, with arguments
// Returns process exit code
int Shell::start(int argc, char **argv)
{
// Run initialisation sequence (auto-registration of modules etc.)
Init::Sequence::run();
// Grab config filename if specified
string cf = default_config_file;
if (argc > 1) cf = argv[argc-1]; // Last arg, leaves room for options
// Read config
config.add_file(cf);
if (!config.read(config_element))
{
cerr << argv[0] << ": Can't read config file " << cf << endl;
return 2;
}
// Process <include> in config
config.process_includes();
#if defined(DEBUG)
bool go_daemon = config.get_value_bool("background/@daemon", false);
#else
bool go_daemon = config.get_value_bool("background/@daemon", true);
#endif
// Create log stream if daemon
auto chan_out = static_cast<Log::Channel *>(nullptr);
if (go_daemon)
{
#if !defined(PLATFORM_WINDOWS)
if (config.get_value_bool("log/@syslog"))
{
chan_out = new Log::SyslogChannel;
}
else
{
#endif
const auto log_conf = File::Path{config.get_value("log/@file",
default_log_file)};
const auto log_exp = log_conf.expand();
const auto logfile = File::Path{cf}.resolve(log_exp);
const auto log_dir = logfile.dir();
if (!log_dir.ensure(true))
{
cerr << argv[0] << ": Logfile directory can not be created: "
<< log_dir << endl;
return 2;
}
auto sout = new ofstream(logfile.c_str(), ios::app);
if (!*sout)
{
cerr << argv[0] << ": Unable to open logfile " << logfile << endl;
return 2;
}
chan_out = new Log::OwnedStreamChannel{sout};
#if !defined(PLATFORM_WINDOWS)
}
#endif
}
else
{
chan_out = new Log::StreamChannel{&cout};
}
auto log_level = config.get_value_int("log/@level",
static_cast<int>(Log::Level::summary));
auto level_out = static_cast<Log::Level>(log_level);
auto time_format = config.get_value("log/@timestamp", DEFAULT_TIMESTAMP);
auto hold_time = config.get_value("log/@hold-time", DEFAULT_HOLD_TIME);
Log::logger.connect_full(chan_out, level_out, time_format, hold_time);
Log::Streams log;
log.summary << name << " version " << version << " starting\n";
// Tell application to read config settings
application.read_config(config, cf);
// Call preconfigure before we go daemon - e.g. asking for SSL passphrase
int rc = application.preconfigure();
if (rc)
{
log.error << "Preconfigure failed: " << rc << endl;
return rc;
}
#if !defined(PLATFORM_WINDOWS)
// Full background daemon
if (go_daemon)
{
if (daemon(0, 0))
log.error << "Can't become daemon: " << strerror(errno) << endl;
// Create pid file
string pid_file = config.get_value("daemon/pid/@file", default_pid_file);
ofstream pidfile(pid_file.c_str());
pidfile << getpid() << endl;
pidfile.close();
}
#endif
// Register signal handlers - same for both master and slave
the_shell = this;
signal(SIGTERM, sigshutdown);
signal(SIGINT, sigshutdown); // quit from Ctrl-C
#if !defined(PLATFORM_WINDOWS)
signal(SIGQUIT, sigshutdown); // quit from Ctrl-backslash
signal(SIGHUP, sighup);
// Ignore SIGPIPE from closed sockets etc.
signal(SIGPIPE, sig_ign);
#endif
signal(SIGSEGV, sigevil);
signal(SIGILL, sigevil);
signal(SIGFPE, sigevil);
signal(SIGABRT, sigevil);
#if !defined(PLATFORM_WINDOWS)
// Watchdog? Master/slave processes...
bool enable_watchdog = config.get_value_bool("watchdog/@restart", true);
int sleep_time = FIRST_WATCHDOG_SLEEP_TIME;
if (go_daemon && enable_watchdog)
{
// Now loop forever restarting a child process, in case it fails
bool first = true;
while (!shut_down)
{
if (!first)
{
log.detail << "Waiting for " << sleep_time << "s\n";
this_thread::sleep_for(chrono::seconds(sleep_time));
// Exponential backoff, up to a max
sleep_time *= 2;
if (sleep_time > MAX_WATCHDOG_SLEEP_TIME)
sleep_time = MAX_WATCHDOG_SLEEP_TIME;
log.error << "*** RESTARTING SLAVE ***\n";
}
first = false;
log.summary << "Forking slave process\n";
slave_pid = fork();
if (slave_pid < 0)
{
log.error << "Can't fork slave process: " << strerror(errno) << endl;
continue;
}
if (slave_pid)
{
// PARENT PROCESS
log.detail << "Slave process pid " << slave_pid << " forked\n";
// Wait for it to exit
int status;
int died = waitpid(slave_pid, &status, 0);
// Check for fatal failure
if (died && !WIFEXITED(status))
{
log.error << "*** Slave process " << slave_pid << " died ***\n";
}
else
{
int rc = WEXITSTATUS(status);
if (rc)
{
log.error << "*** Slave process " << slave_pid
<< " exited with code " << rc << " ***\n";
}
else
{
log.summary << "Slave process exited OK\n"; // Expected
shut_down = true;
}
}
// However it exited, if shutdown is requested, stop
if (trigger_shutdown) shut_down = true;
}
else
{
// SLAVE PROCESS
// Run subclass prerun before dropping privileges
int rc = application.run_priv();
if (rc) return rc;
rc = drop_privileges();
if (rc) return rc;
// Run subclass full startup
rc = run();
application.cleanup();
return rc;
}
}
log.summary << "Master process exiting\n";
return 0;
}
else
{
#endif
// Just run directly
rc = application.run_priv();
if (rc) return rc;
#if !defined(PLATFORM_WINDOWS)
rc = drop_privileges();
if (rc) return rc;
#endif
rc = run();
application.cleanup();
return rc;
#if !defined(PLATFORM_WINDOWS)
}
#endif
}
//--------------------------------------------------------------------------
// Drop privileges if required
// Returns 0 on success, rc if not
int Shell::drop_privileges()
{
#if defined(PLATFORM_WINDOWS)
return -99;
#else
// Drop privileges if root
if (!getuid())
{
Log::Streams log;
string username = config["security/@user"];
string groupname = config["security/@group"];
// Set group first - needs to still be root
if (!groupname.empty())
{
int gid = File::Path::group_name_to_id(groupname);
if (gid >= 0)
{
log.summary << "Changing to group " << groupname
<< " (" << gid << ")\n";
if (setgid(static_cast<gid_t>(gid)))
{
log.error << "Can't change group: " << strerror(errno) << endl;
return 2;
}
}
else
{
log.error << "Can't find group " << groupname << "\n";
return 2;
}
}
if (!username.empty())
{
int uid = File::Path::user_name_to_id(username);
if (uid >= 0)
{
log.summary << "Changing to user " << username
<< " (" << uid << ")\n";
if (setuid(static_cast<uid_t>(uid)))
{
log.error << "Can't change user: " << strerror(errno) << endl;
return 2;
}
}
else
{
log.error << "Can't find user " << username << "\n";
return 2;
}
}
}
return 0;
#endif
}
//--------------------------------------------------------------------------
// Shut down - indirectly called from SIGTERM handler
void Shell::shutdown()
{
// Stop our restart loop (master) and any loop in the slave
shut_down=true;
}
//--------------------------------------------------------------------------
// Reload config - indirectly called from SIGHUP handler
void Shell::reload()
{
Log::Streams log;
log.summary << "SIGHUP received\n";
if (config.read(config_element))
application.read_config(config);
else
log.error << "Failed to re-read config, using existing" << endl;
application.reconfigure();
}
//--------------------------------------------------------------------------
// Handle a failure signal
void Shell::log_evil(int sig)
{
string what;
switch (sig)
{
case SIGSEGV: what = "segment violation"; break;
case SIGILL: what = "illegal instruction"; break;
case SIGFPE: what = "floating point exception"; break;
case SIGABRT: what = "aborted"; break;
default: what = "unknown";
}
Log::Streams log;
log.error << "*** Signal received in " << (slave_pid?"master":"slave")
<< ": " << what << " (" << sig << ") ***\n";
// Do a backtrace
#define MAXTRACE 100
#define MAXNAMELEN 1024
void *buffer[MAXTRACE];
#if defined(PLATFORM_WINDOWS)
const auto frames = CaptureStackBackTrace(1, MAXTRACE, buffer, nullptr);
if (frames)
{
log.error << "--- backtrace:\n";
for (auto i = 0; i < frames; ++i)
{
auto sumbuff = vector<uint64_t>(sizeof(SYMBOL_INFO) + MAXNAMELEN
+ sizeof(uint64_t) - 1);
auto *info = reinterpret_cast<SYMBOL_INFO *>(&sumbuff[0]);
info->SizeOfStruct = sizeof(SYMBOL_INFO);
info->MaxNameLen = 1024;
auto displacement = uint64_t{};
if (SymFromAddr(GetCurrentProcess(), (DWORD64)buffer[i], &displacement,
info))
{
log.error << "- " << string(info->Name, info->NameLen) << endl;
}
}
log.error << "---\n";
}
#else
int n = backtrace(buffer, MAXTRACE);
char **strings = backtrace_symbols(buffer, n);
if (strings)
{
log.error << "--- backtrace:\n";
for(int i=0; i<n; i++)
log.error << "- " << strings[i] << endl;
log.error << "---\n";
free(strings);
}
#endif
}
}} // namespaces
| 25.955224 | 79 | 0.563707 | sandtreader |
40a549761ea5232f9cd5e39cc36568e04c3e9159 | 10,083 | cpp | C++ | src/midend/mir_rewriter.cpp | ericmei/graphit-exploratory | aa12687a1a0c714653cff0503f4c154488097cfb | [
"MIT"
] | null | null | null | src/midend/mir_rewriter.cpp | ericmei/graphit-exploratory | aa12687a1a0c714653cff0503f4c154488097cfb | [
"MIT"
] | null | null | null | src/midend/mir_rewriter.cpp | ericmei/graphit-exploratory | aa12687a1a0c714653cff0503f4c154488097cfb | [
"MIT"
] | null | null | null | //
// Created by Yunming Zhang on 5/12/17.
//
#include <graphit/midend/mir_rewriter.h>
namespace graphit {
namespace mir {
void MIRRewriter::visit(Expr::Ptr expr) {
node = rewrite<Expr>(expr);
};
void MIRRewriter::visit(ExprStmt::Ptr stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->expr = rewrite<Expr>(stmt->expr);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(AssignStmt::Ptr stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->lhs = rewrite<Expr>(stmt->lhs);
stmt->expr = rewrite<Expr>(stmt->expr);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(CompareAndSwapStmt::Ptr stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->lhs = rewrite<Expr>(stmt->lhs);
stmt->expr = rewrite<Expr>(stmt->expr);
stmt->compare_val_expr = rewrite<Expr>(stmt->expr);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(ReduceStmt::Ptr stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->lhs = rewrite<Expr>(stmt->lhs);
stmt->expr = rewrite<Expr>(stmt->expr);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(PrintStmt::Ptr stmt) {
stmt->expr = rewrite<Expr>(stmt->expr);
node = stmt;
}
void MIRRewriter::visit(StmtBlock::Ptr stmt_block) {
for (auto stmt : *(stmt_block->stmts)) {
stmt = rewrite<Stmt>(stmt);
}
node = stmt_block;
}
void MIRRewriter::visit(FuncDecl::Ptr func_decl) {
if (func_decl->body && func_decl->body->stmts) {
func_decl->body = rewrite<StmtBlock>(func_decl->body);
}
node = func_decl;
}
void MIRRewriter::visit(Call::Ptr expr) {
// need to use & to actually modify the argument (with reference), not a copy of it
for (auto &arg : expr->args) {
arg = rewrite<Expr>(arg);
}
node = expr;
};
void MIRRewriter::visit(MulExpr::Ptr expr) {
visitBinaryExpr(expr);
}
void MIRRewriter::visit(DivExpr::Ptr expr) {
visitBinaryExpr(expr);
}
void MIRRewriter::visit(NegExpr::Ptr expr) {
expr->operand = rewrite<mir::Expr>(expr->operand);
node = expr;
}
void MIRRewriter::visit(EqExpr::Ptr expr) {
visitNaryExpr(expr);
}
void MIRRewriter::visit(AddExpr::Ptr expr) {
visitBinaryExpr(expr);
}
void MIRRewriter::visit(SubExpr::Ptr expr) {
visitBinaryExpr(expr);
}
void MIRRewriter::visit(std::shared_ptr<VarDecl> var_decl) {
if (var_decl->stmt_label != "") {
label_scope_.scope(var_decl->stmt_label);
}
if (var_decl->initVal != nullptr)
var_decl->initVal = rewrite<Expr>(var_decl->initVal);
node = var_decl;
if (var_decl->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(std::shared_ptr<VertexSetAllocExpr> expr) {
expr->size_expr = rewrite<Expr>(expr->size_expr);
expr->element_type = rewrite<ElementType>(expr->element_type);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<ListAllocExpr> expr) {
if (expr->size_expr != nullptr)
expr->size_expr = rewrite<Expr>(expr->size_expr);
expr->element_type = rewrite<Type>(expr->element_type);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<VertexSetApplyExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<EdgeSetApplyExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<PushEdgeSetApplyExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<PullEdgeSetApplyExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<HybridDenseEdgeSetApplyExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<HybridDenseForwardEdgeSetApplyExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<VertexSetWhereExpr> expr) {
//expr->input_func = rewrite<Expr>(expr->input_func);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<TensorReadExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
expr->index = rewrite<Expr>(expr->index);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<TensorStructReadExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
expr->index = rewrite<Expr>(expr->index);
expr->field_target = rewrite<Expr>(expr->field_target);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<TensorArrayReadExpr> expr) {
expr->target = rewrite<Expr>(expr->target);
expr->index = rewrite<Expr>(expr->index);
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<NameNode> stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->body = rewrite<StmtBlock>(stmt->body);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(std::shared_ptr<ForStmt> stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->domain = rewrite<ForDomain>(stmt->domain);
stmt->body = rewrite<StmtBlock>(stmt->body);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(std::shared_ptr<ForDomain> for_domain) {
for_domain->lower = rewrite<Expr>(for_domain->lower);
for_domain->upper = rewrite<Expr>(for_domain->upper);
node = for_domain;
}
void MIRRewriter::visit(std::shared_ptr<StructTypeDecl> struct_type_decl) {
for (auto field : struct_type_decl->fields) {
field = rewrite<VarDecl>(field);
}
node = struct_type_decl;
}
void MIRRewriter::visit(std::shared_ptr<VertexSetType> vertexset_type) {
vertexset_type->element = rewrite<ElementType>(vertexset_type->element);
node = vertexset_type;
}
void MIRRewriter::visit(std::shared_ptr<ListType> list_type) {
list_type->element_type = rewrite<Type>(list_type->element_type);
node = list_type;
}
void MIRRewriter::visit(std::shared_ptr<EdgeSetType> edgeset_type) {
edgeset_type->element = rewrite<ElementType>(edgeset_type->element);
for (auto element_type : *edgeset_type->vertex_element_type_list) {
element_type = rewrite<ElementType>(element_type);
}
node = edgeset_type;
}
void MIRRewriter::visit(std::shared_ptr<VectorType> vector_type) {
vector_type->element_type = rewrite<ElementType>(vector_type->element_type);
vector_type->vector_element_type = rewrite<Type>(vector_type->vector_element_type);
node = vector_type;
}
void MIRRewriter::visitBinaryExpr(BinaryExpr::Ptr expr) {
expr->lhs = rewrite<Expr>(expr->lhs);
expr->rhs = rewrite<Expr>(expr->rhs);
node = expr;
}
void MIRRewriter::visitNaryExpr(NaryExpr::Ptr expr) {
// Here we are modifying the original operand, so need the & before operand
for (auto &operand : expr->operands) {
operand = rewrite<Expr>(operand);
}
node = expr;
}
void MIRRewriter::visit(std::shared_ptr<WhileStmt> stmt) {
if (stmt->stmt_label != "") {
label_scope_.scope(stmt->stmt_label);
}
stmt->body = rewrite<StmtBlock>(stmt->body);
stmt->cond = rewrite<Expr>(stmt->cond);
node = stmt;
if (stmt->stmt_label != "") {
label_scope_.unscope();
}
}
void MIRRewriter::visit(IfStmt::Ptr stmt) {
stmt->cond = rewrite<Expr>(stmt->cond);
stmt->ifBody = rewrite<Stmt>(stmt->ifBody);
if (stmt->elseBody) {
stmt->elseBody = rewrite<Stmt>(stmt->elseBody);
}
node = stmt;
}
void MIRRewriter::visit(EdgeSetLoadExpr::Ptr load_expr) {
load_expr->file_name = rewrite<Expr>(load_expr->file_name);
node = load_expr;
}
}
}
| 33.277228 | 95 | 0.529505 | ericmei |
40a721506ac9c6339abc64023a3026b1dd0e4d18 | 24,194 | cpp | C++ | trunk/src/app/srs_app_forward_rtsp.cpp | breezeewu/media-server | b7f6e7c24a1c849180ba31088250c0174b1112e0 | [
"MIT"
] | null | null | null | trunk/src/app/srs_app_forward_rtsp.cpp | breezeewu/media-server | b7f6e7c24a1c849180ba31088250c0174b1112e0 | [
"MIT"
] | null | null | null | trunk/src/app/srs_app_forward_rtsp.cpp | breezeewu/media-server | b7f6e7c24a1c849180ba31088250c0174b1112e0 | [
"MIT"
] | null | null | null | /****************************************************************************************************************
* filename srs_app_forward_rtsp.cpp
* describe Sunvalley forward rtsp classs define
* author Created by dawson on 2019/04/25
* Copyright ©2007 - 2029 Sunvally. All Rights Reserved.
***************************************************************************************************************/
#include <srs_app_forward_rtsp.hpp>
#include <srs_app_source.hpp>
#include <srs_rtmp_stack.hpp>
#include <srs_rtmp_msg_array.hpp>
#include <srs_kernel_flv.hpp>
#include <srs_kernel_ts.hpp>
#include <sys/stat.h>
ForwardRtspQueue::ForwardRtspQueue()
{
//srs_trace("ForwardRtspQueue begin");
m_nmax_queue_size = 1000;
m_pavccodec = new SrsAvcAacCodec();
LB_ADD_MEM(m_pavccodec, sizeof(SrsAvcAacCodec));
m_pavcsample = new SrsCodecSample();
LB_ADD_MEM(m_pavcsample, sizeof(SrsCodecSample));
m_paaccodec = new SrsAvcAacCodec();
LB_ADD_MEM(m_paaccodec, sizeof(SrsAvcAacCodec));
m_paacsample = new SrsCodecSample();
LB_ADD_MEM(m_paacsample, sizeof(SrsCodecSample));
m_bwait_keyframe = true;
m_bsend_avc_seq_hdr = false;
m_bsend_aac_seq_hdr = false;
//srs_trace("ForwardRtspQueue end");
}
ForwardRtspQueue::~ForwardRtspQueue()
{
//srs_trace("~ForwardRtspQueue begin");
srs_freep(m_pavccodec);
srs_freep(m_pavcsample);
srs_freep(m_paaccodec);
srs_freep(m_paacsample);
/*if(m_pavccodec)
{
delete m_pavccodec;
m_pavccodec = NULL;
}
if(m_pavcsample)
{
delete m_pavcsample;
m_pavcsample = NULL;
}
if(m_paaccodec)
{
delete m_paaccodec;
m_paaccodec = NULL;
}
if(m_paacsample)
{
delete m_paacsample;
m_paacsample = NULL;
}*/
//srs_trace("~ForwardRtspQueue end");
}
int ForwardRtspQueue::enqueue(SrsSharedPtrMessage* pmsg)
{
int ret;
if(NULL == pmsg)
{
srs_trace("Invalid pmsg ptr %p", pmsg);
m_bwait_keyframe = true;
return -1;
}
if((int)m_vFwdMsgList.size() >= m_nmax_queue_size)
{
srs_trace("Forward rtsp queue is full, list size %d < max queue size %d", (int)m_vFwdMsgList.size(), m_nmax_queue_size);
return -1;
}
if(pmsg->is_video())
{
ret = m_pavccodec->video_avc_demux(pmsg->payload, pmsg->size, m_pavcsample);
//srs_trace("avc enqueue(payload:%p, size:%d, pmsg->pts:%"PRId64"), m_pavcsample->frame_type:%d, m_bwait_keyframe:%d\n", pmsg->payload, pmsg->size, pmsg->timestamp, m_pavcsample->frame_type, (int)m_bwait_keyframe);
if(ERROR_SUCCESS != ret)
{
srs_error("ret:%d = m_pavccodec->video_avc_demux(pmsg->payload:%p, pmsg->size:%d, m_pavcsample:%p) failed", ret, pmsg->payload, pmsg->size, m_pavcsample);
srs_err_memory(pmsg->payload, 32);
return ret;
}
/*if(m_pavcsample->nb_sample_units <= 0)
{
return 0;
}*/
if(SrsCodecVideoAVCTypeSequenceHeader == m_pavcsample->avc_packet_type)
{
/*srs_rtsp_debug("avc sequence header, m_pavcsample->nb_sample_units:%d:\n", m_pavcsample->nb_sample_units);
for(int i = 0; i < m_pavcsample->nb_sample_units; i++)
{
srs_trace_memory(m_pavcsample->sample_units[i].bytes, m_pavcsample->sample_units[i].size);
}*/
}
else if(m_bwait_keyframe && m_pavcsample->frame_type != SrsCodecVideoAVCFrameKeyFrame)
{
//srs_trace("wait for keyframe, not keyframe, drop video\n");
m_pavcsample->clear();
return 0;
}
else
{
if(m_bwait_keyframe)
{
srs_trace("key frame come, pts:%"PRId64", m_pavcsample.nb_sample_units:%d", pmsg->timestamp, m_pavcsample->nb_sample_units);
m_bwait_keyframe = false;
}
/*if(SrsCodecVideoAVCFrameKeyFrame == m_pavcsample->frame_type)
{
m_pavcsample->add_prefix_sample_uint(m_pavccodec->pictureParameterSetNALUnit, m_pavccodec->pictureParameterSetLength);
m_pavcsample->add_prefix_sample_uint(m_pavccodec->sequenceParameterSetNALUnit, m_pavccodec->sequenceParameterSetLength);
}*/
ret = enqueue_avc(m_pavccodec, m_pavcsample, pmsg->timestamp);
}
m_pavcsample->clear();
}
else
{
ret = m_paaccodec->audio_aac_demux(pmsg->payload, pmsg->size, m_paacsample);
if(ERROR_SUCCESS != ret)
{
srs_error("ret:%d = m_paaccodec->audio_aac_demux(pmsg->payload:%p, pmsg->size:%d, m_paacsample:%p) failed", ret, pmsg->payload, pmsg->size, m_paacsample);
srs_err_memory(pmsg->payload, 32);
return ret;
}
if(m_bwait_keyframe)
{
//srs_trace("wait for keyframe, not keyframe, drop audio\n");
m_paacsample->clear();
return 0;
}
/*if(m_pavcsample->nb_sample_units <= 0)
{
return 0;
}
if(!m_bsend_aac_seq_hdr)
{
m_bsend_aac_seq_hdr = true;
m_pavcsample->add_prefix_sample_uint(m_paaccodec->aac_extra_data, m_pavccodec->aac_extra_size);
}*/
if(SrsCodecAudioTypeSequenceHeader == m_paacsample->aac_packet_type)
{
//srs_rtsp_debug("aac sequence header, m_pavcsample->nb_sample_units:%d\n", m_paacsample->nb_sample_units);
for(int i = 0; i < m_paacsample->nb_sample_units; i++)
{
srs_trace_memory(m_paacsample->sample_units[i].bytes, m_paacsample->sample_units[i].size);
}
}
else
{
//srs_trace("aac enqueue(payload:%p, size:%d, pmsg->pts:%"PRId64")\n", pmsg->payload, pmsg->size, pmsg->timestamp);
ret = enqueue_aac(m_paaccodec, m_paacsample, pmsg->timestamp);
}
m_paacsample->clear();
}
//srs_trace("enqueue end, ret:%d", ret);
return ret;
}
int ForwardRtspQueue::enqueue_avc(SrsAvcAacCodec* codec, SrsCodecSample* sample, int64_t pts)
{
int ret = ERROR_SUCCESS;
int pt = SRS_RTSP_AVC_PAYLOAD_TYPE;
// Whether aud inserted.
//bool aud_inserted = false;
static u_int8_t fresh_nalu_header[] = { 0x00, 0x00, 0x00, 0x01 };
//srs_trace("codec:%p, sample:%p, pts:"PRId64"", codec, sample, pts);
if(SrsCodecVideoHEVC == codec->video_codec_id)
{
pt = SRS_RTSP_HEVC_PAYLOAD_TYPE;
}
// Insert a default AUD NALU when no AUD in samples.
if (!sample->has_aud)
{
// the aud(access unit delimiter) before each frame.
// 7.3.2.4 Access unit delimiter RBSP syntax
// H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 66.
//
// primary_pic_type u(3), the first 3bits, primary_pic_type indicates that the slice_type values
// for all slices of the primary coded picture are members of the set listed in Table 7-5 for
// the given value of primary_pic_type.
// 0, slice_type 2, 7
// 1, slice_type 0, 2, 5, 7
// 2, slice_type 0, 1, 2, 5, 6, 7
// 3, slice_type 4, 9
// 4, slice_type 3, 4, 8, 9
// 5, slice_type 2, 4, 7, 9
// 6, slice_type 0, 2, 3, 4, 5, 7, 8, 9
// 7, slice_type 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
// 7.4.2.4 Access unit delimiter RBSP semantics
// H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 102.
//
// slice_type specifies the coding type of the slice according to Table 7-6.
// 0, P (P slice)
// 1, B (B slice)
// 2, I (I slice)
// 3, SP (SP slice)
// 4, SI (SI slice)
// 5, P (P slice)
// 6, B (B slice)
// 7, I (I slice)
// 8, SP (SP slice)
// 9, SI (SI slice)
// H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 105.
/*static u_int8_t default_aud_nalu[] = { 0x09, 0xf0};
pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header));
pfwdmsg->payload->append((const char*)default_aud_nalu, 2);*/
}
bool is_sps_pps_appended = false;
// all sample use cont nalu header, except the sps-pps before IDR frame.
for (int i = 0; i < sample->nb_sample_units; i++) {
SrsCodecSampleUnit* sample_unit = &sample->sample_units[i];
int32_t size = sample_unit->size;
//srs_trace("sample_unit:%p, size:%d", sample_unit, size);
if (!sample_unit->bytes || size <= 0) {
ret = ERROR_HLS_AVC_SAMPLE_SIZE;
srs_error("invalid avc sample length=%d, ret=%d", size, ret);
//delete pfwdmsg;
return ret;
}
ForwardRtspSample* pfwdmsg = new ForwardRtspSample();
LB_ADD_MEM(pfwdmsg, sizeof(ForwardRtspSample));
pfwdmsg->payloadtype = pt;
// 5bits, 7.3.1 NAL unit syntax,
// H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 83.
SrsAvcNaluType nal_unit_type = (SrsAvcNaluType)(sample_unit->bytes[0] & 0x1f);
//srs_rtsp_debug("nal_unit_type:%d, sample_unit->size:%d", nal_unit_type, sample_unit->size);
if(9 == nal_unit_type || 10 == nal_unit_type)
{
srs_freep(pfwdmsg);
continue;
}
// Insert sps/pps before IDR when there is no sps/pps in samples.
// The sps/pps is parsed from sequence header(generally the first flv packet).
if (nal_unit_type == SrsAvcNaluTypeIDR && !sample->has_sps_pps && !is_sps_pps_appended) {
if (codec->sequenceParameterSetLength > 0) {
//srs_avc_insert_aud(pfwdmsg->payload, aud_inserted);
/*pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header));
pfwdmsg->payload->append(codec->sequenceParameterSetNALUnit, codec->sequenceParameterSetLength);
srs_trace("codec->sequenceParameterSetNALUnit:%p, codec->sequenceParameterSetLength:%d\n", codec->sequenceParameterSetNALUnit, codec->sequenceParameterSetLength);
srs_trace_memory(codec->sequenceParameterSetNALUnit, codec->sequenceParameterSetLength > 48 ? 48 : codec->sequenceParameterSetLength);*/
}
if (codec->pictureParameterSetLength > 0) {
//srs_avc_insert_aud(pfwdmsg->payload, aud_inserted);
/*pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header));
pfwdmsg->payload->append(codec->pictureParameterSetNALUnit, codec->pictureParameterSetLength);
srs_trace("codec->pictureParameterSetNALUnit:%p, codec->sequenceParameterSetLength:%d\n", codec->pictureParameterSetNALUnit, codec->sequenceParameterSetLength);
srs_trace_memory(codec->pictureParameterSetNALUnit, codec->pictureParameterSetLength > 48 ? 48 : codec->pictureParameterSetLength);*/
}
is_sps_pps_appended = true;
// Insert the NALU to video in annexb.
}
pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header));
//srs_avc_insert_aud(pfwdmsg->payload, aud_inserted);
pfwdmsg->payload->append(sample_unit->bytes, sample_unit->size);
pfwdmsg->pts = pts;
pfwdmsg->dts = pts;
pfwdmsg->mediatype = 0;
m_vFwdMsgList.push(pfwdmsg);
//srs_rtsp_debug("pfwdmsg:%p, length:%d, pt:%d, list size:%ld, pts:%"PRId64"\n", pfwdmsg, pfwdmsg->payload->length(), pfwdmsg->payloadtype, m_vFwdMsgList.size(), pfwdmsg->pts);
}
//srs_trace("pfwdmsg:%p, length:%d, pt:%d, list size:%ld, pts:%"PRId64"\n", pfwdmsg, pfwdmsg->payload->length(), pfwdmsg->payloadtype, m_vFwdMsgList.size(), pfwdmsg->pts);
return ret;
}
int ForwardRtspQueue::enqueue_aac(SrsAvcAacCodec* codec, SrsCodecSample* sample, int64_t pts)
{
int ret = ERROR_SUCCESS;
ForwardRtspSample* pfwdmsg = new ForwardRtspSample();
LB_ADD_MEM(pfwdmsg, sizeof(ForwardRtspSample));
pfwdmsg->payloadtype = SRS_RTSP_AAC_PAYLOAD_TYPE;
//srs_trace("(codec:%p, sample:%p) begin", codec, sample);
for (int i = 0; i < sample->nb_sample_units; i++)
{
SrsCodecSampleUnit* sample_unit = &sample->sample_units[i];
int32_t size = sample_unit->size;
if (!sample_unit->bytes || size <= 0 || size > 0x1fff)
{
ret = ERROR_HLS_AAC_FRAME_LENGTH;
srs_error("invalid aac frame length=%d, ret=%d, pt:%d, audio_codec_id:%d", size, ret, pfwdmsg->payloadtype, codec->audio_codec_id);
//delete pfwdmsg;
srs_freep(pfwdmsg);
return ret;
}
// the frame length is the AAC raw data plus the adts header size.
int32_t frame_length = size + 7;
// AAC-ADTS
// 6.2 Audio Data Transport Stream, ADTS
// in aac-iso-13818-7.pdf, page 26.
// fixed 7bytes header
u_int8_t adts_header[7] = {0xff, 0xf9, 0x00, 0x00, 0x00, 0x0f, 0xfc};
/*
// adts_fixed_header
// 2B, 16bits
int16_t syncword; //12bits, '1111 1111 1111'
int8_t protection_absent; //1bit, can be '1'
// 12bits
int8_t profile; //2bit, 7.1 Profiles, page 40
TSAacSampleFrequency sampling_frequency_index; //4bits, Table 35, page 46
int8_t private_bit; //1bit, can be '0'
int8_t channel_configuration; //3bits, Table 8
int8_t original_or_copy; //1bit, can be '0'
int8_t home; //1bit, can be '0'
// adts_variable_header
// 28bits
int8_t copyright_identification_bit; //1bit, can be '0'
int8_t copyright_identification_start; //1bit, can be '0'
int16_t frame_length; //13bits
int16_t adts_buffer_fullness; //11bits, 7FF signals that the bitstream is a variable rate bitstream.
int8_t number_of_raw_data_blocks_in_frame; //2bits, 0 indicating 1 raw_data_block()
*/
// profile, 2bits
SrsAacProfile aac_profile = srs_codec_aac_rtmp2ts(codec->aac_object);
adts_header[2] = (aac_profile << 6) & 0xc0;
// sampling_frequency_index 4bits
adts_header[2] |= (codec->aac_sample_rate << 2) & 0x3c;
// channel_configuration 3bits
adts_header[2] |= (codec->aac_channels >> 2) & 0x01;
adts_header[3] = (codec->aac_channels << 6) & 0xc0;
// frame_length 13bits
adts_header[3] |= (frame_length >> 11) & 0x03;
adts_header[4] = (frame_length >> 3) & 0xff;
adts_header[5] = ((frame_length << 5) & 0xe0);
// adts_buffer_fullness; //11bits
adts_header[5] |= 0x1f;
//srs_verbose("codec->aac_sample_rate:%d, codec->aac_channels:%d, codec->aac_object:%d", codec->aac_sample_rate, codec->aac_channels, codec->aac_object);
// copy to audio buffer
pfwdmsg->payload->append((const char*)adts_header, sizeof(adts_header));
pfwdmsg->payload->append(sample_unit->bytes, sample_unit->size);
}
pfwdmsg->pts = pts;
pfwdmsg->dts = pts;
pfwdmsg->mediatype = 1;
m_vFwdMsgList.push(pfwdmsg);
//srs_trace("pfwdmsg:%p, length:%d, pfwdmsg->payloadtype:%d, list_size:%ld, pts:%"PRId64"\n", pfwdmsg, pfwdmsg->payload->length(), pfwdmsg->payloadtype, m_vFwdMsgList.size(), pfwdmsg->pts);
return ret;
}
int ForwardRtspQueue::push_back(ForwardRtspSample* psample)
{
if(NULL == psample)
{
lberror("Invalid parameter, psample:%p\n", psample);
return -1;
}
if(m_bwait_keyframe && 0 == psample->mediatype && psample->keyflag)
{
m_bwait_keyframe = false;
}
else if(m_bwait_keyframe)
{
srs_trace("wait for key frame, drop frame, mt:%d, pts:%" PRId64 " keyflag:%d, size:%d\n", psample->mediatype, psample->pts, psample->keyflag, psample->payload->length());
return -1;
}
m_vFwdMsgList.push(psample);
return 0;
}
int ForwardRtspQueue::get_queue_size()
{
return (int)m_vFwdMsgList.size();
}
ForwardRtspSample* ForwardRtspQueue::dump_packet()
{
ForwardRtspSample* pfwdmsg = NULL;
if(m_vFwdMsgList.size() > 0)
{
pfwdmsg = m_vFwdMsgList.front();
m_vFwdMsgList.pop();
}
return pfwdmsg;
}
int ForwardRtspQueue::get_sps_pps(std::string& sps, std::string& pps)
{
if(m_pavccodec && m_pavccodec->sequenceParameterSetLength > 0 && m_pavccodec->pictureParameterSetLength > 0)
{
sps.clear();
pps.clear();
sps.append(m_pavccodec->sequenceParameterSetNALUnit, m_pavccodec->sequenceParameterSetLength);
pps.append(m_pavccodec->pictureParameterSetNALUnit, m_pavccodec->pictureParameterSetLength);
return 0;
}
return -1;
}
int ForwardRtspQueue::get_aac_sequence_hdr(std::string& audio_cfg)
{
if(m_paaccodec && m_paaccodec->aac_extra_size > 0)
{
audio_cfg.clear();
audio_cfg.append(m_paaccodec->aac_extra_data, m_paaccodec->aac_extra_size);
return 0;
}
return -1;
}
bool ForwardRtspQueue::is_codec_ok()
{
if(m_pavccodec) return m_pavccodec->is_avc_codec_ok();
return false;
}
bool SrsForwardRtsp::m_bInit(false);
SrsForwardRtsp::SrsForwardRtsp(SrsRequest* req):rtsp_forward_thread("fwdrtsp", this, SRS_RTSP_FORWARD_SLEEP_US)
{
m_lConnectID = -1;
m_pReq = req->copy();
srs_debug(" m_pReq:%p = req->copy()\n", m_pReq);
m_pvideofile = NULL;
m_paudiofile = NULL;
}
SrsForwardRtsp::~SrsForwardRtsp()
{
srs_trace("~SrsForwardRtsp begin");
stop();
srs_trace("~SrsForwardRtsp after stop");
srs_freep(m_pReq);
/*if(m_pReq)
{
delete m_pReq;
m_pReq = NULL;
}*/
srs_trace("~SrsForwardRtsp after m_pSrsMsgArry");
if(m_pvideofile)
{
fclose(m_pvideofile);
m_pvideofile =NULL;
}
if(m_paudiofile)
{
fclose(m_paudiofile);
m_paudiofile =NULL;
}
srs_trace("~SrsForwardRtsp end");
}
int SrsForwardRtsp::initialize(const char* prtsp_url, const char* prtsp_log_url)
{
srs_trace("initialize(prtsp_url:%s, prtsp_log_url:%s)", prtsp_url, prtsp_log_url);
if(!prtsp_url)
{
srs_error("initialize failed, invalid url prtsp_url:%s", prtsp_url);
return ERROR_FORWARD_RTSP_INVALID_URL;
}
m_sRtspUrl = prtsp_url;
if(!m_bInit)
{
if(prtsp_log_url)
{
m_sFwdRtspLogUrl = prtsp_log_url;
}
int ret = SVRtspPush_API_Initialize();
if(ret < 0)
{
srs_error("ret:%d = SVRtspPush_API_Initialize() faield", ret);
return ret;
}
ret = SVRtspPush_API_Init_log(m_sFwdRtspLogUrl.c_str(), 3, 2);
srs_trace("initialize end, ret:%d", ret);
m_bInit = true;
}
return ERROR_SUCCESS;
}
int SrsForwardRtsp::set_raw_data_path(const char* prawpath)
{
srs_trace("prawpath:%s", prawpath);
if(prawpath)
{
if(access(prawpath, F_OK) != 0)
{
mkdir(prawpath, 0777);
}
m_sFwdRtspRawDataDir = prawpath;
return ERROR_SUCCESS;
}
return -1;
}
int SrsForwardRtsp::publish()
{
int ret = start();
srs_trace("Forward rtsp publish ret:%d", ret);
return ret;
}
int SrsForwardRtsp::unpublish()
{
stop();
srs_trace("Forward rtsp unpublish end");
return ERROR_SUCCESS;
}
int SrsForwardRtsp::start()
{
srs_trace("start begin, m_bInit:%d", (int)m_bInit);
int ret = ERROR_FORWARD_RTSP_NOT_INIT;
if(m_bInit)
{
stop();
ret = rtsp_forward_thread.start();
srs_trace("start end ret:%d, m_bInit:%d", ret, (int)m_bInit);
return ret;
}
return ret;
}
void SrsForwardRtsp::on_thread_start()
{
srs_trace(" begin, m_bInit:%d", (int)m_bInit);
if(m_bInit)
{
m_lConnectID = SVRtspPush_API_Connect(m_sRtspUrl.c_str(), SrsForwardRtsp::RtspCallback);
srs_trace("m_lConnectID:%ld = SVRtspPush_API_Connect(m_sRtspUrl.c_str():%s, SrsForwardRtsp::RtspCallback:%p)", m_lConnectID, m_sRtspUrl.c_str(), SrsForwardRtsp::RtspCallback);
//m_pvideofile = fopen("avc.data", "wb");
//m_paudiofile = fopen("aac.data", "wb");
if(!m_sFwdRtspRawDataDir.empty())
{
char path[256] = {0};
sprintf(path, "%s/rtspfwd.h264", m_sFwdRtspRawDataDir.c_str());
m_pvideofile = fopen(path, "wb");
sprintf(path, "%s/rtspfwd.aac", m_sFwdRtspRawDataDir.c_str());
m_paudiofile = fopen(path, "wb");
}
srs_trace("m_pvideofile:%p, m_paudiofile:%p", m_pvideofile, m_paudiofile);
m_bRuning = true;
}
srs_trace(" end");
}
int SrsForwardRtsp::cycle()
{
int ret = -1;
//srs_trace("Forward rtsp cycle begin, m_vFwdMsgList.size():%d", (int)m_vFwdMsgList.size());
while(m_vFwdMsgList.size() > 0 && m_bRuning)
{
int writed = 0;
ForwardRtspSample* pfrs = dump_packet();
if(pfrs)
{
//srs_trace("Forward rtsp cycle, send packetg, m_lConnectID:%ld, pfrs->mediatype:%d, size:%d, pts:%"PRId64"", m_lConnectID, pfrs->mediatype, pfrs->payload->length());
if(pfrs->mediatype == 0)
{
ret = SVRtspPush_API_Send_VideoPacket(m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts);
if(m_pvideofile && 0 == ret)
{
writed = fwrite(pfrs->payload->bytes(), 1, pfrs->payload->length(), m_pvideofile);
//srs_trace("writed:%d = fwrite(pfrs->payload->bytes():%p, 1, pfrs->payload->length():%d, m_pvideofile:%p)", writed, pfrs->payload->bytes(), pfrs->payload->length(), m_pvideofile);
}
srs_trace("ret:%d = SVRtspPush_API_Send_VideoPacket, writed:%d", ret, writed);
//srs_trace("ret:%d = SVRtspPush_API_Send_VideoPacket(m_lConnectID:%ld, pfrs->payload->bytes():%p, pfrs->payload->length():%d, pfrs->pts:%"PRId64")", ret, m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts);
}
else
{
ret = SVRtspPush_API_Send_AudioPacket(m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts);
if(m_paudiofile && 0 == ret)
{
writed = fwrite(pfrs->payload->bytes(), 1, pfrs->payload->length(), m_paudiofile);
//srs_trace("writed:%d = fwrite(pfrs->payload->bytes():%p, 1, pfrs->payload->length():%d, m_paudiofile:%p)", writed, pfrs->payload->bytes(), pfrs->payload->length(), m_paudiofile);
}
srs_trace("ret:%d = SVRtspPush_API_Send_AudioPacket, writed:%d", ret, writed);
//srs_trace("ret:%d = SVRtspPush_API_Send_AudioPacket(m_lConnectID:%ld, pfrs->payload->bytes():%p, pfrs->payload->length():%d, pfrs->pts:%"PRId64")", ret, m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts);
}
srs_freep(pfrs);
//delete pfrs;
//pfrs = NULL;
srs_trace("after delete pfrs");
}
}
return ret;
}
void SrsForwardRtsp::on_thread_stop()
{
}
void SrsForwardRtsp::stop()
{
srs_trace(" begin");
m_bRuning = false;
rtsp_forward_thread.stop();
if(m_bInit && m_lConnectID >= 0)
{
int ret = SVRtspPush_API_Close(m_lConnectID);
srs_trace("ret:%d = SVRtspPush_API_Close(m_lConnectID:%ld)", ret, m_lConnectID);
}
if(m_pvideofile)
{
fclose(m_pvideofile);
m_pvideofile = NULL;
}
if(m_paudiofile)
{
fclose(m_paudiofile);
m_paudiofile = NULL;
}
}
bool SrsForwardRtsp::is_forward_rtsp_enable()
{
return !m_sForwardRtspUrl.empty();
}
int SrsForwardRtsp::RtspCallback(int nUserID, E_Event_Code eHeaderEventCode)
{
srs_trace("nUserID:%ld, eHeaderEventCode:%d\n", nUserID, eHeaderEventCode);
return ERROR_SUCCESS;
}
| 36.381955 | 245 | 0.607175 | breezeewu |
40a7a0e1adb9efa3bf2788595aaf7399c8a1060b | 164 | cpp | C++ | Week4/FriendFunction/TestFriendFunction.cpp | AvansTi/TMTI-DATC-Voorbeelden | 572d009ad9378228d125e4025bc0f9aa7763d053 | [
"BSD-3-Clause"
] | 2 | 2019-04-26T07:13:05.000Z | 2020-04-24T09:47:20.000Z | Week4/FriendFunction/TestFriendFunction.cpp | AvansTi/TMTI-DATC-Voorbeelden | 572d009ad9378228d125e4025bc0f9aa7763d053 | [
"BSD-3-Clause"
] | null | null | null | Week4/FriendFunction/TestFriendFunction.cpp | AvansTi/TMTI-DATC-Voorbeelden | 572d009ad9378228d125e4025bc0f9aa7763d053 | [
"BSD-3-Clause"
] | 1 | 2020-05-08T12:19:30.000Z | 2020-05-08T12:19:30.000Z | #include <iostream>
#include "Date.h"
void p() {
Date date{ 2010, 5, 9 };
date.year = 2000;
std::cout << date.year << '\n';
}
int main() {
p();
return 0;
} | 10.933333 | 32 | 0.542683 | AvansTi |
40a7a7c216a19ecf469391fdd26677c687cda6e5 | 5,457 | cpp | C++ | Bomberman/GUI.cpp | PratikMandlecha/Bomberman | e62d99880f9856aab2aea393099e3386cedcb3ee | [
"MIT"
] | 26 | 2016-05-18T09:39:22.000Z | 2022-03-25T10:21:26.000Z | Bomberman/GUI.cpp | PratikMandlecha/Bomberman | e62d99880f9856aab2aea393099e3386cedcb3ee | [
"MIT"
] | 4 | 2016-05-22T11:55:22.000Z | 2016-06-09T08:22:36.000Z | Bomberman/GUI.cpp | PratikMandlecha/Bomberman | e62d99880f9856aab2aea393099e3386cedcb3ee | [
"MIT"
] | 21 | 2016-07-20T16:13:01.000Z | 2021-11-28T11:08:24.000Z | #include "GUI.h"
void GUI::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
rect->setFillColor(sf::Color(255, 255, 255, 155));
rect->setSize(sf::Vector2f(m_screenWidth, m_screenHeight));
if (m_endOfGameMenuView)
{
target.draw(*m_frame, states);
target.draw(*rect, states);
target.draw(*m_returnToMenuButton->GetSpritePointer(), states);
target.draw(*m_returnToMenuButton->GetTextPointer(), states);
target.draw(*m_playAgainButton->GetSpritePointer(), states);
target.draw(*m_playAgainButton->GetTextPointer(), states);
target.draw(*m_exitButton->GetSpritePointer(), states);
target.draw(*m_exitButton->GetTextPointer(), states);
target.draw(*m_winnerText);
}
if (m_gameGUIView)
{
target.draw(*m_playerOneLives);
target.draw(*m_playerSecondLives);
}
}
GUI::GUI()
{
}
GUI::~GUI()
{
delete rect;
delete m_returnToMenuButton;
delete m_playAgainButton;
delete m_exitButton;
delete m_frameTexture;
delete m_frame;
delete m_winnerText;
delete m_playerOneLives;
delete m_playerSecondLives;
}
void GUI::Init(sf::Font * font, short textSize, int screenWidth, int screenHeight, bool* playAgain, bool* exit, bool* enterMenu)
{
rect = new sf::RectangleShape();
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;;
m_playerOneLives = new sf::Text();
m_playerOneLives->setFont(*font);
m_playerOneLives->setString("Player 1 Lives: 3");
m_playerOneLives->setPosition(sf::Vector2f(20, 10));
m_playerOneLives->setColor(sf::Color(255, 255, 255));
m_playerOneLives->setScale(1.2f, 1.2f);
m_playerSecondLives = new sf::Text();
m_playerSecondLives->setFont(*font);
m_playerSecondLives->setString("Player 2 Lives: 3");
m_playerSecondLives->setPosition(sf::Vector2f(screenWidth-300, screenHeight-50));
m_playerSecondLives->setColor(sf::Color(255, 255, 255));
m_playerSecondLives->setScale(1.2f, 1.2f);
m_whoWin = -1;
m_enterMenu = enterMenu;
m_exit = exit;
m_playAgain = playAgain;
m_endOfGameMenuView = false;
m_gameGUIView = true;
m_frameTexture = new sf::Texture();
m_frameTexture->loadFromFile("data/frame.png");
m_frame = new sf::Sprite();
m_frame->setTexture(*m_frameTexture);
m_frame->setScale((float)m_frameTexture->getSize().x / (float)(screenWidth * 5), (float)m_frameTexture->getSize().y / (float)(screenHeight * 7));
m_frame->setPosition(screenWidth / 2.f - (m_frameTexture->getSize().x * m_frame->getScale().x)/2.f, screenHeight / 3.3f - 50);
m_returnToMenuButton = new Button(sf::Vector2f(screenWidth / 2 - 150, screenHeight / 2.3f - 50), sf::Vector2i(300, 75.f), "data/pressButton.png", "data/unpressButton.png", "Return to Menu");
m_playAgainButton = new Button(sf::Vector2f(screenWidth / 2 - 150, screenHeight / 1.7f -50), sf::Vector2i(300, 75.f), "data/pressButton.png", "data/unpressButton.png", "Play Again");
m_exitButton = new Button(sf::Vector2f(screenWidth / 2 - 150, screenHeight / 1.7f + screenHeight / 1.7f - screenHeight / 2.3f - 50), sf::Vector2i(300, 75.f), "data/pressButton.png", "data/unpressButton.png", "Exit Game");
m_winnerText = new sf::Text();
m_winnerText->setFont(*font);
m_winnerText->setString("Player 1 Wins!");
sf::FloatRect textRect = m_winnerText->getLocalBounds();
m_winnerText->setOrigin(textRect.left + textRect.width / 2.0f, 0);
m_winnerText->setPosition(sf::Vector2f(screenWidth / 2.f,m_frame->getPosition().y+20));
m_winnerText->setColor(sf::Color(0.f, 107, 139));
m_winnerText->setScale(1.2f, 1.2f);
}
void GUI::UpdateStats(std::vector<Player*>* players, short mouseX, short mouseY)
{
m_endOfGameMenuView = false;
m_gameGUIView = true;
for (short i = 0; i < players->size(); ++i)
{
switch (i)
{
case 0:
m_playerOneLives->setString("Player 1 Lives: " + std::to_string((*players)[i]->GetRespawnsCount()));
case 1:
m_playerSecondLives->setString("Player 2 Lives: " + std::to_string((*players)[i]->GetRespawnsCount()));
}
if ((*players)[i]->GetWin())
{
m_whoWin = i;
m_winnerText->setString("Player "+ std::to_string(m_whoWin+1)+" Wins!");
break;
}
else
{
}
}
}
void GUI::UpdateStats(std::vector<Player*>* players, short mouseX, short mouseY, bool & playAgain, bool & exit, bool & enterMenu)
{
UpdateStats(players, mouseX, mouseY);
m_endOfGameMenuView = true;
m_gameGUIView = false;
}
void GUI::processEvents(sf::Vector2i mousePos, sf::Event* eventPointer)
{
if (m_endOfGameMenuView)
{
if (eventPointer->type == sf::Event::MouseButtonReleased && eventPointer->mouseButton.button == sf::Mouse::Left)
{
m_returnToMenuButton->Update(mousePos, false);
m_playAgainButton->Update(mousePos, false);
m_exitButton->Update(mousePos, false);
if (m_returnToMenuButton->GetSpritePointer()->getGlobalBounds().contains((sf::Vector2f)mousePos))
{
*m_playAgain = false;
*m_enterMenu = true;
*m_exit = true;
}
if (m_playAgainButton->GetSpritePointer()->getGlobalBounds().contains((sf::Vector2f)mousePos))
{
*m_playAgain = true;
*m_enterMenu = false;
*m_exit = false;
}
if (m_exitButton->GetSpritePointer()->getGlobalBounds().contains((sf::Vector2f)mousePos))
{
*m_playAgain = false;
*m_enterMenu = false;
*m_exit = true;
}
}
if (eventPointer->type == sf::Event::MouseButtonPressed && eventPointer->mouseButton.button == sf::Mouse::Left)
{
m_returnToMenuButton->Update(mousePos, true);
m_playAgainButton->Update(mousePos, true);
m_exitButton->Update(mousePos, true);
}
}
}
| 29.983516 | 222 | 0.708814 | PratikMandlecha |