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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c4b686e364cd0d9b86a354df6e64cbbb8ab96071 | 343 | hpp | C++ | src/framework/forms/input/input.hpp | kevinaud/asm-dom-OO-counters | 58ea010941b5e7ab860109b6ebbd6f3ca47fd4c6 | [
"MIT"
] | 9 | 2018-06-07T00:39:45.000Z | 2021-06-28T18:26:51.000Z | src/framework/forms/input/input.hpp | kevinaud/asm-dom-OO-counters | 58ea010941b5e7ab860109b6ebbd6f3ca47fd4c6 | [
"MIT"
] | null | null | null | src/framework/forms/input/input.hpp | kevinaud/asm-dom-OO-counters | 58ea010941b5e7ab860109b6ebbd6f3ca47fd4c6 | [
"MIT"
] | 2 | 2019-05-04T15:35:04.000Z | 2019-09-24T12:11:45.000Z | #ifndef INPUT_H
#define INPUT_H
#include "../../component/component.hpp"
#include "../../view-property/view-property.hpp"
class Input : public Component {
public:
Input(Component* parent);
Input(Component* parent, string initValue);
VNode* render();
private:
ViewProperty<string>* value;
};
#endif
| 18.052632 | 51 | 0.641399 | kevinaud |
c4b86abbd7ac32192638543b82b05e5363f5706b | 4,208 | hpp | C++ | src/CameraControl/EDSDK/EdsdkSourceDeviceImpl.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 16 | 2015-03-26T02:32:43.000Z | 2021-10-18T16:34:31.000Z | src/CameraControl/EDSDK/EdsdkSourceDeviceImpl.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 7 | 2019-02-21T06:07:09.000Z | 2022-01-01T10:00:50.000Z | src/CameraControl/EDSDK/EdsdkSourceDeviceImpl.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 6 | 2019-05-07T09:21:15.000Z | 2021-09-01T06:36:24.000Z | //
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2017 Michael Fink
//
/// \file EdsdkSourceDeviceImpl.hpp EDSDK - SourceDevice impl
//
#pragma once
// includes
#include "SourceDevice.hpp"
#include "EdsdkCameraFileSystemImpl.hpp"
#include "EdsdkRemoteReleaseControlImpl.hpp"
#include "EdsdkShutterCounterReader.hpp"
namespace EDSDK
{
/// source device implementation for EDSDK
class SourceDeviceImpl:
public SourceDevice,
public std::enable_shared_from_this<SourceDeviceImpl>
{
public:
/// ctor
SourceDeviceImpl(const Handle& hCamera, const EdsDeviceInfo& deviceInfo)
:m_hCamera(hCamera),
m_deviceInfo(deviceInfo)
{
}
/// dtor
virtual ~SourceDeviceImpl()
{
// Ugly workaround: EdsCloseSession() may lock up; call EdsGetEvent() to process internal events.
// This should probably go into an Idle handler for the SDK.
for(int i=0; i<100; i++)
EdsGetEvent();
EdsError err = EdsCloseSession(m_hCamera);
LOG_TRACE(_T("EdsCloseSession(ref = %08x) returned %08x\n"), m_hCamera.Get(), err);
// note: don't check error here, as we're in dtor
}
virtual bool GetDeviceCapability(SourceDevice::T_enDeviceCapability enDeviceCapability) const override
{
switch (enDeviceCapability)
{
case SourceDevice::capRemoteReleaseControl:
// supported on all camera models
return true;
case SourceDevice::capRemoteViewfinder:
// supported on all camera models
return true;
case SourceDevice::capCameraFileSystem:
// supported on all camera models
return true;
default:
ATLASSERT(false);
}
return false;
}
virtual CString ModelName() const override
{
PropertyAccess p(m_hCamera);
Variant v = p.Get(kEdsPropID_ProductName);
return v.Get<CString>();
}
virtual CString SerialNumber() const override
{
PropertyAccess p(m_hCamera);
Variant v = p.Get(kEdsPropID_BodyIDEx);
return v.Get<CString>();
}
virtual std::vector<unsigned int> EnumDeviceProperties() const override
{
PropertyAccess p(m_hCamera);
std::vector<unsigned int> vecDeviceIds;
p.EnumDeviceIds(vecDeviceIds);
return vecDeviceIds;
}
virtual DeviceProperty GetDeviceProperty(unsigned int uiPropertyId) const override
{
if (uiPropertyId == kEdsPropID_ShutterCounter)
{
ShutterCounterReader reader;
unsigned int uiShutterCounter = 0;
reader.Read(m_deviceInfo.szPortName, uiShutterCounter);
Variant value;
value.Set(uiShutterCounter);
value.SetType(Variant::typeUInt32);
return DeviceProperty(variantEdsdk, uiPropertyId, value, true);
}
// get value
PropertyAccess p(m_hCamera);
Variant value = p.Get(uiPropertyId);
bool bReadOnly = p.IsReadOnly(uiPropertyId);
DeviceProperty deviceProperty(variantEdsdk, uiPropertyId, value, bReadOnly);
p.Enum(uiPropertyId, deviceProperty.ValidValues(), bReadOnly);
return deviceProperty;
}
virtual std::shared_ptr<CameraFileSystem> GetFileSystem() override
{
std::shared_ptr<SourceDevice> spSourceDevice = shared_from_this();
return std::shared_ptr<CameraFileSystem>(new EDSDK::CameraFileSystemImpl(spSourceDevice, m_hCamera));
}
virtual std::shared_ptr<RemoteReleaseControl> EnterReleaseControl() override
{
if (!GetDeviceCapability(capRemoteReleaseControl))
{
// throw an error code of 7, which means "not supported"
throw CameraException(_T("EDSDK::SourceDevice::EnterReleaseControl"),
_T("Not supported"), EDS_ERR_NOT_SUPPORTED, __FILE__, __LINE__);
}
std::shared_ptr<SourceDevice> spSourceDevice = shared_from_this();
// there's no dedicated function to start "remote release control" mode, just add camera ref
return std::shared_ptr<RemoteReleaseControl>(new RemoteReleaseControlImpl(spSourceDevice, m_hCamera));
}
private:
/// handle to camera object
Handle m_hCamera;
/// camera device info
EdsDeviceInfo m_deviceInfo;
};
} // namespace EDSDK
| 27.86755 | 108 | 0.689401 | vividos |
c4b89cd754ed4e145b5eb1a88a5604a2934d4aac | 37,506 | cpp | C++ | src/method/method_schema_info.cpp | Yechan0815/cubrid | da09d9e60b583d0b7ce5f665429f397976728d99 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/method/method_schema_info.cpp | Yechan0815/cubrid | da09d9e60b583d0b7ce5f665429f397976728d99 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/method/method_schema_info.cpp | Yechan0815/cubrid | da09d9e60b583d0b7ce5f665429f397976728d99 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
*
* Copyright 2016 CUBRID 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.
*
*/
#include "method_schema_info.hpp"
#include <algorithm>
#include <cstring>
#include <string>
#include "dbtype_def.h"
#include "dbi.h"
#include "method_query_handler.hpp"
#include "method_query_util.hpp"
#include "trigger_manager.h"
#include "work_space.h"
#include "schema_manager.h"
#include "language_support.h"
namespace cubmethod
{
schema_info
schema_info_handler::get_schema_info (int schema_type, std::string &arg1, std::string &arg2, int flag)
{
int error = NO_ERROR;
schema_info info;
switch (schema_type)
{
case SCH_CLASS:
error = sch_class_info (info, arg1, flag, 0);
break;
case SCH_VCLASS:
error = sch_class_info (info, arg1, flag, 1);
break;
case SCH_QUERY_SPEC:
error = sch_queryspec (info, arg1);
break;
case SCH_ATTRIBUTE:
error = sch_attr_info (info, arg1, arg2, flag, 0);
break;
case SCH_CLASS_ATTRIBUTE:
error = sch_attr_info (info, arg1, arg2, flag, 1);
break;
case SCH_METHOD:
error = sch_method_info (info, arg1, 0);
break;
case SCH_CLASS_METHOD:
error = sch_method_info (info, arg1, 1);
break;
case SCH_METHOD_FILE:
error = sch_methfile_info (info, arg1);
break;
case SCH_SUPERCLASS:
error = sch_superclass (info, arg1, 1);
break;
case SCH_SUBCLASS:
error = sch_superclass (info, arg1, 0);
break;
case SCH_CONSTRAINT:
error = sch_constraint (info, arg1);
break;
case SCH_TRIGGER:
error = sch_trigger (info, arg1, flag);
break;
case SCH_CLASS_PRIVILEGE:
error = sch_class_priv (info, arg1, flag);
break;
case SCH_ATTR_PRIVILEGE:
error = sch_attr_priv (info, arg1, arg2, flag);
break;
case SCH_DIRECT_SUPER_CLASS:
error = sch_direct_super_class (info, arg1, flag);
break;
case SCH_PRIMARY_KEY:
error = sch_primary_key (info, arg1);
break;
case SCH_IMPORTED_KEYS:
error = sch_imported_keys (info, arg1);
break;
case SCH_EXPORTED_KEYS:
error = sch_exported_keys_or_cross_reference (info, arg1, arg2, false);
break;
case SCH_CROSS_REFERENCE:
error = sch_exported_keys_or_cross_reference (info, arg1, arg2, true);
break;
default:
error = ER_FAILED;
break;
}
if (error == NO_ERROR)
{
// TODO: what should I do here?
info.schema_type = schema_type;
}
else
{
close_and_free_session ();
// TODO: proper error code
m_error_ctx.set_error (METHOD_CALLBACK_ER_SCHEMA_TYPE, NULL, __FILE__, __LINE__);
}
return info;
}
int
schema_info_handler::execute_schema_info_query (std::string &sql_stmt)
{
lang_set_parser_use_client_charset (false);
m_session = db_open_buffer (sql_stmt.c_str());
if (!m_session)
{
lang_set_parser_use_client_charset (true);
m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__);
return ER_FAILED;
}
int stmt_id = db_compile_statement (m_session);
if (stmt_id < 0)
{
close_and_free_session ();
m_error_ctx.set_error (stmt_id, NULL, __FILE__, __LINE__);
return ER_FAILED;
}
DB_QUERY_RESULT *result = NULL;
int stmt_type = db_get_statement_type (m_session, stmt_id);
lang_set_parser_use_client_charset (false);
int num_result = db_execute_statement (m_session, stmt_id, &result);
lang_set_parser_use_client_charset (true);
if (num_result < 0)
{
close_and_free_session ();
m_error_ctx.set_error (stmt_id, NULL, __FILE__, __LINE__);
return ER_FAILED;
}
query_result &q_result = m_q_result;
q_result.stmt_type = stmt_type;
q_result.stmt_id = stmt_id;
q_result.tuple_count = num_result;
q_result.result = result;
q_result.include_oid = false;
// TODO: managing structure for schema info queries
/*
m_q_result.push_back (q_result);
m_max_col_size = -1;
m_current_result_index = 0;
m_current_result = &m_q_result[m_current_result_index];
m_has_result_set = true;
*/
return num_result;
}
int
schema_info_handler::sch_class_info (schema_info &info, std::string &class_name,
int pattern_flag, int v_class_flag)
{
std::string schema_name;
std::string class_name_only;
std::size_t found;
std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower);
class_name_only = class_name;
found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
class_name_only = class_name.substr (found + 1);
}
}
// *INDENT-OFF*
std::string sql = ""
"SELECT "
"CASE "
"WHEN is_system_class = 'NO' THEN LOWER (owner_name) || '.' || class_name "
"ELSE class_name "
"END AS unique_name, "
"CAST ( "
"CASE "
"WHEN is_system_class = 'YES' THEN 0 "
"WHEN class_type = 'CLASS' THEN 2 "
"ELSE 1 "
"END "
"AS SHORT "
"), "
"comment "
"FROM "
"db_class "
"WHERE 1 = 1 ";
// *INDENT-ON*
if (v_class_flag)
{
sql.append ("AND class_type = 'VCLASS' ");
}
if (pattern_flag & CLASS_NAME_PATTERN_MATCH)
{
if (!class_name_only.empty())
{
/* AND class_name LIKE '%s' ESCAPE '%s' */
sql.append ("AND class_name LIKE '");
sql.append (class_name_only);
sql.append ("' ESCAPE '");
sql.append (get_backslash_escape_string ());
sql.append ("' ");
}
}
else
{
/* AND class_name = '%s' */
sql.append ("AND class_name = '");
sql.append (class_name_only);
sql.append ("' ");
}
if (!schema_name.empty())
{
/* AND owner_name = UPPER ('%s') */
sql.append ("AND owner_name = UPPER ('");
sql.append (schema_name);
sql.append ("') ");
}
int num_result = execute_schema_info_query (sql);
if (num_result < 0)
{
return num_result;
}
info.num_result = num_result;
return NO_ERROR;
}
int
schema_info_handler::sch_attr_info (schema_info &info, std::string &class_name,
std::string &attr_name, int pattern_flag,
int class_attr_flag)
{
std::string schema_name;
std::string class_name_only;
std::size_t found;
std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower);
std::transform (attr_name.begin(), attr_name.end(), attr_name.begin(), ::tolower);
class_name_only = class_name;
found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
class_name_only = class_name.substr (found + 1);
}
}
// *INDENT-OFF*
std::string sql = ""
"SELECT "
"CASE "
"WHEN ( "
"SELECT b.is_system_class "
"FROM db_class b "
"WHERE b.class_name = a.class_name AND b.owner_name = a.owner_name "
") = 'NO' THEN LOWER (a.owner_name) || '.' || a.class_name "
"ELSE a.class_name "
"END AS unique_name, "
"a.attr_name "
"FROM "
"db_attribute a "
"WHERE 1 = 1 ";
// *INDENT-ON*
if (class_attr_flag)
{
sql.append ("AND a.attr_type = 'CLASS' ");
}
else
{
sql.append ("AND a.attr_type in {'INSTANCE', 'SHARED'} ");
}
if (pattern_flag & CLASS_NAME_PATTERN_MATCH)
{
if (!class_name_only.empty())
{
/* AND class_name LIKE '%s' ESCAPE '%s' */
sql.append ("AND a.class_name LIKE '");
sql.append (class_name_only);
sql.append ("' ESCAPE '");
sql.append (get_backslash_escape_string ());
sql.append ("' ");
}
}
else
{
/* AND class_name = '%s' */
sql.append ("AND a.class_name = '");
sql.append (class_name_only);
sql.append ("' ");
}
if (pattern_flag & ATTR_NAME_PATTERN_MATCH)
{
if (!attr_name.empty())
{
/* AND a.attr_name LIKE '%s' ESCAPE '%s' */
sql.append ("AND a.attr_name LIKE '");
sql.append (attr_name);
sql.append ("' ESCAPE '");
sql.append (get_backslash_escape_string ());
sql.append ("' ");
}
}
else
{
/* AND a.attr_name = '%s' */
sql.append ("AND a.class_name = '");
sql.append (attr_name);
sql.append ("' ");
}
if (!schema_name.empty())
{
/* AND owner_name = UPPER ('%s') */
sql.append ("AND a.owner_name = UPPER ('");
sql.append (schema_name);
sql.append ("') ");
}
sql.append ("ORDER BY a.class_name, a.def_order ");
int num_result = execute_schema_info_query (sql);
if (num_result < 0)
{
return num_result;
}
info.num_result = num_result;
return NO_ERROR;
}
int
schema_info_handler::sch_queryspec (schema_info &info, std::string &class_name)
{
std::string schema_name;
std::string class_name_only;
std::size_t found;
std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower);
class_name_only = class_name;
found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
class_name_only = class_name.substr (found + 1);
}
}
std::string sql = "SELECT vclass_def FROM db_vclass WHERE unique_name = '";
sql.append (class_name_only);
sql.append ("' ");
if (!schema_name.empty())
{
/* AND owner_name = UPPER ('%s') */
sql.append ("AND owner_name = UPPER ('");
sql.append (schema_name);
sql.append ("') ");
}
int num_result = execute_schema_info_query (sql);
if (num_result < 0)
{
return num_result;
}
info.num_result = num_result;
return NO_ERROR;
}
int
schema_info_handler::sch_method_info (schema_info &info, std::string &class_name, int flag)
{
DB_OBJECT *class_obj = db_find_class (class_name.c_str());
DB_METHOD *method_list;
if (flag)
{
method_list = db_get_class_methods (class_obj);
}
else
{
method_list = db_get_methods (class_obj);
}
int num_method = 0;
for (DB_METHOD *method = method_list; method; method = db_method_next (method))
{
num_method++;
}
info.num_result = num_method;
m_method_list = method_list;
return NO_ERROR;
}
int
schema_info_handler::sch_methfile_info (schema_info &info, std::string &class_name)
{
DB_OBJECT *class_obj = db_find_class (class_name.c_str());
DB_METHFILE *method_files = db_get_method_files (class_obj);
int num_mf= 0;
for (DB_METHFILE *mf = method_files; mf; mf = db_methfile_next (mf))
{
num_mf++;
}
info.num_result = num_mf;
m_method_files = method_files;
return NO_ERROR;
}
int
schema_info_handler::sch_superclass (schema_info &info, std::string &class_name, int flag)
{
int error = NO_ERROR;
DB_OBJECT *class_obj = db_find_class (class_name.c_str());
DB_OBJLIST *obj_list = NULL;
if (flag)
{
obj_list = db_get_superclasses (class_obj);
}
else
{
obj_list = db_get_subclasses (class_obj);
}
class_table ct;
for (DB_OBJLIST *tmp = obj_list; tmp; tmp = tmp->next)
{
char *p = (char *) db_get_class_name (tmp->op);
int cls_type = class_type (tmp->op);
if (cls_type < 0)
{
error = cls_type;
break;
}
ct.class_name.assign (p);
ct.class_type = cls_type;
m_obj_list.push_back (ct);
}
db_objlist_free (obj_list);
info.num_result = m_obj_list.size ();
return error;
}
int
schema_info_handler::sch_constraint (schema_info &info, std::string &class_name)
{
DB_OBJECT *class_obj = db_find_class (class_name.c_str ());
DB_CONSTRAINT *constraint = db_get_constraints (class_obj);
int num_const = 0;
for (DB_CONSTRAINT *tmp_c = constraint; tmp_c; tmp_c = db_constraint_next (tmp_c))
{
int type = db_constraint_type (tmp_c);
switch (type)
{
case DB_CONSTRAINT_UNIQUE:
case DB_CONSTRAINT_INDEX:
case DB_CONSTRAINT_REVERSE_UNIQUE:
case DB_CONSTRAINT_REVERSE_INDEX:
{
DB_ATTRIBUTE **attr = db_constraint_attributes (tmp_c);
for (int i = 0; attr[i]; i++)
{
num_const++;
}
}
default:
break;
}
}
info.num_result = num_const;
m_constraint = constraint;
return NO_ERROR;
}
int
schema_info_handler::sch_trigger (schema_info &info, std::string &class_name, int flag)
{
int error = NO_ERROR;
bool is_pattern_match = (flag & CLASS_NAME_PATTERN_MATCH) ? true : false;
info.num_result = 0;
if (class_name.empty () && !is_pattern_match)
{
return NO_ERROR;
}
DB_OBJLIST *tmp_trigger = NULL;
if (db_find_all_triggers (&tmp_trigger) < 0)
{
return NO_ERROR;
}
int num_trig = 0;
DB_OBJLIST *all_trigger = NULL;
if (class_name.empty ())
{
all_trigger = tmp_trigger;
num_trig = db_list_length ((DB_LIST *) all_trigger);
}
else
{
std::string schema_name;
DB_OBJECT *owner = NULL;
std::string class_name_only = class_name;
std::size_t found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
/* If the user does not exist, compare the entire class_name. */
owner = db_find_user (schema_name.c_str ());
if (owner != NULL)
{
class_name_only = class_name.substr (found + 1);
}
}
}
DB_OBJLIST *tmp = NULL;
for (tmp = tmp_trigger; tmp; tmp = tmp->next)
{
MOP tmp_obj = tmp->op;
assert (tmp_obj != NULL);
TR_TRIGGER *trigger = tr_map_trigger (tmp_obj, 1);
if (trigger == NULL)
{
assert (er_errid () != NO_ERROR);
error = er_errid ();
break;
}
DB_OBJECT *obj_trigger_target = trigger->class_mop;
assert (obj_trigger_target != NULL);
const char *name_trigger_target = sm_get_ch_name (obj_trigger_target);
if (name_trigger_target == NULL)
{
assert (er_errid () != NO_ERROR);
error = er_errid ();
break;
}
const char *only_name_trigger_target = name_trigger_target;
/* If the user does not exist, compare the entire class_name. */
if (owner)
{
only_name_trigger_target = strchr (name_trigger_target, '.');
if (only_name_trigger_target)
{
only_name_trigger_target = only_name_trigger_target + 1;
}
else
{
assert (false);
}
/* If the owner is different from the specified owner, skip it. */
if (db_get_owner (tmp_obj) != owner)
{
continue;
}
}
if (is_pattern_match)
{
if (str_like (std::string (name_trigger_target), class_name_only.c_str (), '\\') == 1)
{
error = ml_ext_add (&all_trigger, tmp_obj, NULL);
if (error != NO_ERROR)
{
break;
}
num_trig++;
}
}
else
{
if (strcmp (class_name_only.c_str (), name_trigger_target) == 0)
{
error = ml_ext_add (&all_trigger, tmp_obj, NULL);
if (error != NO_ERROR)
{
break;
}
num_trig++;
}
}
}
if (tmp_trigger)
{
ml_ext_free (tmp_trigger);
}
if (error != NO_ERROR && all_trigger)
{
ml_ext_free (all_trigger);
all_trigger = NULL;
num_trig = 0;
}
}
info.num_result = num_trig;
m_all_trigger = all_trigger;
return error;
}
int
schema_info_handler::sch_class_priv (schema_info &info, std::string &class_name, int pat_flag)
{
int num_tuple = 0;
unsigned int class_priv;
if ((pat_flag & CLASS_NAME_PATTERN_MATCH) == 0)
{
if (!class_name.empty())
{
DB_OBJECT *class_obj = db_find_class (class_name.c_str ());
if (class_obj != NULL)
{
if (db_get_class_privilege (class_obj, &class_priv) >= 0)
{
num_tuple = set_priv_table (m_priv_tbl, 0, (char *) db_get_class_name (class_obj), class_priv);
}
}
}
}
else
{
std::string schema_name;
DB_OBJECT *owner = NULL;
std::string class_name_only = class_name;
std::size_t found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
/* If the user does not exist, compare the entire class_name. */
owner = db_find_user (schema_name.c_str ());
if (owner != NULL)
{
class_name_only = class_name.substr (found + 1);
}
}
}
DB_OBJLIST *obj_list = db_get_all_classes ();
for (DB_OBJLIST *tmp = obj_list; tmp; tmp = tmp->next)
{
char *p = (char *) db_get_class_name (tmp->op);
char *q = p;
/* If the user does not exist, compare the entire class_name. */
if (owner && db_is_system_class (tmp->op) == FALSE)
{
/* p: unique_name, q: class_name */
q = strchr (p, '.');
if (q)
{
q = q + 1;
}
else
{
assert (false);
}
/* If the owner is different from the specified owner, skip it. */
if (db_get_owner (tmp->op) != owner)
{
continue;
}
}
if (!class_name.empty() && str_like (std::string (q), class_name.c_str(), '\\') < 1)
{
continue;
}
if (db_get_class_privilege (tmp->op, &class_priv) >= 0)
{
num_tuple += set_priv_table (m_priv_tbl, num_tuple, (char *) db_get_class_name (tmp->op), class_priv);
}
}
db_objlist_free (obj_list);
}
info.num_result = num_tuple;
return NO_ERROR;
}
int
schema_info_handler::sch_attr_priv (schema_info &info, std::string &class_name,
std::string &attr_name_pat,
int pat_flag)
{
int num_tuple = 0;
DB_OBJECT *class_obj = db_find_class (class_name.c_str ());
if (class_obj == NULL)
{
info.num_result = num_tuple;
return NO_ERROR;
}
unsigned int class_priv;
if (db_get_class_privilege (class_obj, &class_priv) >= 0)
{
DB_ATTRIBUTE *attributes = db_get_attributes (class_obj);
for (DB_ATTRIBUTE *attr = attributes; attr; attr = db_attribute_next (attr))
{
char *attr_name = (char *) db_attribute_name (attr);
if (pat_flag & ATTR_NAME_PATTERN_MATCH)
{
if (attr_name_pat.empty() == false && str_like (std::string (attr_name), attr_name_pat.c_str (), '\\') < 1)
{
continue;
}
}
else
{
if (attr_name_pat.empty() == true || strcmp (attr_name, attr_name_pat.c_str ()) != 0)
{
continue;
}
}
num_tuple += set_priv_table (m_priv_tbl, num_tuple, (char *) db_get_class_name (class_obj), class_priv);
}
}
info.num_result = num_tuple;
return NO_ERROR;
}
int
schema_info_handler::sch_direct_super_class (schema_info &info, std::string &class_name,
int pattern_flag)
{
std::string schema_name;
std::string class_name_only;
std::size_t found;
std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower);
class_name_only = class_name;
found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
class_name_only = class_name.substr (found + 1);
}
}
// *INDENT-OFF*
std::string sql = ""
"SELECT "
"CASE "
"WHEN ( "
"SELECT b.is_system_class "
"FROM db_class b "
"WHERE b.class_name = a.class_name AND b.owner_name = a.owner_name "
") = 'NO' THEN LOWER (a.owner_name) || '.' || a.class_name "
"ELSE a.class_name "
"END AS unique_name, "
"CASE "
"WHEN ( "
"SELECT b.is_system_class "
"FROM db_class b "
"WHERE b.class_name = a.super_class_name AND b.owner_name = a.super_owner_name "
") = 'NO' THEN LOWER (a.super_owner_name) || '.' || a.super_class_name "
"ELSE a.super_class_name "
"END AS super_unique_name "
"FROM "
"db_direct_super_class a "
"WHERE 1 = 1 ";
// *INDENT-ON*
if (pattern_flag & CLASS_NAME_PATTERN_MATCH)
{
if (!class_name_only.empty())
{
/* AND class_name LIKE '%s' ESCAPE '%s' */
sql.append ("AND class_name LIKE '");
sql.append (class_name_only);
sql.append ("' ESCAPE '");
sql.append (get_backslash_escape_string ());
sql.append ("' ");
}
}
else
{
/* AND class_name = '%s' */
sql.append ("AND class_name = '");
sql.append (class_name_only);
sql.append ("' ");
}
if (!schema_name.empty())
{
/* AND owner_name = UPPER ('%s') */
sql.append ("AND owner_name = UPPER ('");
sql.append (schema_name);
sql.append ("') ");
}
int num_result = execute_schema_info_query (sql);
if (num_result < 0)
{
return num_result;
}
info.num_result = num_result;
return NO_ERROR;
}
int schema_info_handler::sch_primary_key (schema_info &info, std::string &class_name)
{
std::string schema_name;
std::string class_name_only;
std::size_t found;
int num_result = 0;
int i;
std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower);
class_name_only = class_name;
found = class_name.find ('.');
if (found != std::string::npos)
{
/* If the length is not correct, the username is invalid, so compare the entire class_name. */
if (found > 0 && found < DB_MAX_SCHEMA_LENGTH)
{
schema_name = class_name.substr (0, found);
class_name_only = class_name.substr (found + 1);
}
}
DB_OBJECT *class_object = db_find_class (class_name.c_str ());
if (class_object != NULL)
{
// *INDENT-OFF*
std::string sql = ""
"SELECT "
"CASE "
"WHEN ( "
"SELECT c.is_system_class "
"FROM db_class c "
"WHERE c.class_name = a.class_name AND c.owner_name = a.owner_name "
") = 'NO' THEN LOWER (a.owner_name) || '.' || a.class_name "
"ELSE a.class_name "
"END AS unique_name, "
"b.key_attr_name, "
"b.key_order + 1, "
"a.index_name "
"FROM "
"db_index a, "
"db_index_key b "
"WHERE "
"a.index_name = b.index_name "
"AND a.class_name = b.class_name "
"AMD a.owner_name = b.owner_name "
"AND a.is_primary_key = 'YES' "
"AND a.class_name = '";
sql.append (class_name_only);
sql.append ("' ");
// *INDENT-ON*
if (!schema_name.empty())
{
/* AND owner_name = UPPER ('%s') */
sql.append ("AND owner_name = UPPER ('");
sql.append (schema_name);
sql.append ("') ");
}
sql.append ("ORDER BY b.key_attr_name");
num_result = execute_schema_info_query (sql);
if (num_result < 0)
{
return num_result;
}
}
info.num_result = num_result;
return NO_ERROR;
}
int schema_info_handler::sch_imported_keys (schema_info &info, std::string &fktable_name)
{
int error = NO_ERROR;
int num_fk_info = 0, i = 0;
DB_OBJECT *fktable_obj = db_find_class (fktable_name.c_str ());
if (fktable_obj == NULL)
{
/* The followings are possible situations. - A table matching fktable_name does not exist. - User has no
* authorization on the table. - Other error we do not expect. In these cases, we will send an empty result. And
* this rule is also applied to CCI_SCH_EXPORTED_KEYS and CCI_SCH_CROSS_REFERENCE. */
info.num_result = num_fk_info;
return NO_ERROR;
}
for (DB_CONSTRAINT *fk_const = db_get_constraints (fktable_obj); fk_const != NULL;
fk_const = db_constraint_next (fk_const))
{
DB_CONSTRAINT_TYPE type = db_constraint_type (fk_const);
if (type != DB_CONSTRAINT_FOREIGN_KEY)
{
continue;
}
SM_FOREIGN_KEY_INFO *fk_info = fk_const->fk_info;
/* Find referenced table to get table name and columns. */
DB_OBJECT *pktable_obj = db_get_foreign_key_ref_class (fk_const);
if (pktable_obj == NULL)
{
m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__);
return ER_FAILED;
}
const char *pktable_name = db_get_class_name (pktable_obj);
if (pktable_name == NULL)
{
m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__);
return ER_FAILED;
}
DB_CONSTRAINT *pktable_cons = db_get_constraints (pktable_obj);
error = db_error_code ();
if (error != NO_ERROR)
{
m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__);
return ER_FAILED;
}
DB_CONSTRAINT *pk = db_constraint_find_primary_key (pktable_cons);
if (pk == NULL)
{
m_error_ctx.set_error (ER_FK_REF_CLASS_HAS_NOT_PK, "Referenced class has no primary key.", __FILE__, __LINE__);
return ER_FAILED;
}
const char *pk_name = db_constraint_name (pk);
DB_ATTRIBUTE **pk_attr = db_constraint_attributes (pk);
if (pk_attr == NULL)
{
m_error_ctx.set_error (ER_SM_INVALID_CONSTRAINT, "Primary key has no attribute.", __FILE__, __LINE__);
return ER_FAILED;
}
DB_ATTRIBUTE **fk_attr = db_constraint_attributes (fk_const);
if (fk_attr == NULL)
{
m_error_ctx.set_error (ER_SM_INVALID_CONSTRAINT, "Foreign key has no attribute.", __FILE__, __LINE__);
return ER_FAILED;
}
for (i = 0; pk_attr[i] != NULL && fk_attr[i] != NULL; i++)
{
// TODO: not implemented yet
/*
fk_res =
add_fk_info_result (fk_res, pktable_name, db_attribute_name (pk_attr[i]), fktable_name,
db_attribute_name (fk_attr[i]), (short) i + 1, fk_info->update_action,
fk_info->delete_action, fk_info->name, pk_name, FK_INFO_SORT_BY_PKTABLE_NAME);
if (fk_res == NULL)
m_error_ctx.set_error (METHOD_CALLBACK_ER_NO_MORE_MEMORY, NULL, __FILE__, __LINE__);
{
return ER_FAILED;
}
*/
num_fk_info++;
}
/* pk_attr and fk_attr is null-terminated array. So, they should be null at this time. If one of them is not
* null, it means that they have different number of attributes. */
assert (pk_attr[i] == NULL && fk_attr[i] == NULL);
if (pk_attr[i] != NULL || fk_attr[i] != NULL)
{
m_error_ctx.set_error (ER_FK_NOT_MATCH_KEY_COUNT,
"The number of keys of the foreign key is different from that of the primary key.", __FILE__, __LINE__);
return ER_FAILED;
}
}
info.num_result = num_fk_info;
return NO_ERROR;
}
int schema_info_handler::sch_exported_keys_or_cross_reference (schema_info &info,
std::string &pktable_name,
std::string &fktable_name, bool find_cross_ref)
{
// TODO
return NO_ERROR;
}
int
schema_info_handler::class_type (DB_OBJECT *class_obj)
{
int error = db_is_system_class (class_obj);
if (error < 0)
{
m_error_ctx.set_error (error, NULL, __FILE__, __LINE__);
return ER_FAILED;
}
if (error > 0)
{
return 0;
}
error = db_is_vclass (class_obj);
if (error < 0)
{
m_error_ctx.set_error (error, NULL, __FILE__, __LINE__);
return ER_FAILED;
}
if (error > 0)
{
return 1;
}
return 2;
}
int
schema_info_handler::set_priv_table (std::vector<priv_table> &pts, int index, char *name, unsigned int class_priv)
{
int grant_opt = class_priv >> 8;
int priv_type = 1;
int num_tuple = 0;
for (int i = 0; i < 7; i++)
{
if (class_priv & priv_type)
{
priv_table pt;
pt.class_name.assign (name);
pt.priv = priv_type;
if (grant_opt & priv_type)
{
pt.grant = 1;
}
else
{
pt.grant = 0;
}
pts.push_back (pt);
num_tuple++;
}
priv_type <<= 1;
}
return num_tuple;
}
void
schema_info_handler::close_and_free_session ()
{
if (m_session)
{
db_close_session ((DB_SESSION *) (m_session));
}
m_session = NULL;
}
std::vector<column_info>
get_schema_table_meta ()
{
column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME");
column_info type (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "TYPE");
column_info remarks (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_CLASS_COMMENT_LENGTH, lang_charset(), "REMARKS");
return std::vector<column_info> {name, type, remarks};
}
std::vector<column_info>
get_schema_query_spec_meta ()
{
column_info query_spec (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "QUERY_SPEC");
return std::vector<column_info> {query_spec};
}
std::vector<column_info>
get_schema_attr_meta ()
{
column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME");
column_info domain (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "DOMAIN");
column_info scale (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "SCALE");
column_info precision (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "PRECISION");
column_info indexed (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "INDEXED");
column_info non_null (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "NON_NULL");
column_info shared (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "SHARED");
column_info unique (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "UNIQUE");
column_info default_ (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "DEFAULT");
column_info attr_order (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "ATTR_ORDER");
column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME");
column_info source_class (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "SOURCE_CLASS");
column_info is_key (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "IS_KEY");
column_info remarks (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_CLASS_COMMENT_LENGTH, lang_charset(), "REMARKS");
return std::vector<column_info> {attr_name, domain, scale, precision, indexed, non_null, shared, unique, default_, attr_order, class_name, source_class, is_key, remarks};
}
std::vector<column_info>
get_schema_method_meta ()
{
column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME");
column_info ret_domain (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "RET_DOMAIN");
column_info arg_domain (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ARG_DOMAIN");
return std::vector<column_info> {name, ret_domain, arg_domain};
}
std::vector<column_info>
get_schema_methodfile_meta ()
{
column_info met_file (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "METHOD_FILE");
return std::vector<column_info> {met_file};
}
std::vector<column_info>
get_schema_superclasss_meta ()
{
column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME");
column_info type (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "TYPE");
return std::vector<column_info> {class_name, type};
}
std::vector<column_info>
get_schema_constraint_meta ()
{
column_info type (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "TYPE");
column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME");
column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME");
column_info num_pages (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "NUM_PAGES");
column_info num_keys (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "NUM_KEYS");
column_info primary_key (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "PRIMARY_KEY");
column_info key_order (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "KEY_ORDER");
column_info asc_desc (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ASC_DESC");
return std::vector<column_info> {type, name, attr_name, num_pages, num_keys, primary_key, key_order, asc_desc};
}
std::vector<column_info>
get_schema_trigger_meta ()
{
column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME");
column_info status (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "STATUS");
column_info event (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "EVENT");
column_info target_class (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "TARGET_CLASS");
column_info target_attr (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "TARGET_ATTR");
column_info action_time (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ACTION_TIME");
column_info action (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ACTION");
column_info priority (DB_TYPE_FLOAT, DB_TYPE_NULL, 0, 0, lang_charset(), "PRIORITY");
column_info condition_time (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(),
"CONDITION_TIME");
column_info condition (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CONDITION");
column_info remarks (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_CLASS_COMMENT_LENGTH, lang_charset(), "REMARKS");
return std::vector<column_info> {name, status, event, target_class, target_attr, action_time, action, priority, condition_time, condition, remarks};
}
std::vector<column_info>
get_schema_classpriv_meta ()
{
column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME");
column_info privilege (DB_TYPE_STRING, DB_TYPE_NULL, 0, 10, lang_charset(), "PRIVILEGE");
column_info grantable (DB_TYPE_STRING, DB_TYPE_NULL, 0, 5, lang_charset(), "GRANTABLE");
return std::vector<column_info> {class_name, privilege, grantable};
}
std::vector<column_info>
get_schema_attrpriv_meta ()
{
column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME");
column_info privilege (DB_TYPE_STRING, DB_TYPE_NULL, 0, 10, lang_charset(), "PRIVILEGE");
column_info grantable (DB_TYPE_STRING, DB_TYPE_NULL, 0, 5, lang_charset(), "GRANTABLE");
return std::vector<column_info> {attr_name, privilege, grantable};
}
std::vector<column_info>
get_schema_directsuper_meta ()
{
column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME");
column_info super_class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(),
"SUPER_CLASS_NAME");
return std::vector<column_info> {class_name, super_class_name};
}
std::vector<column_info>
get_schema_primarykey_meta ()
{
column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME");
column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME");
column_info num_keys (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "KEY_SEQ");
column_info key_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "KEY_NAME");
return std::vector<column_info> {class_name, attr_name, num_keys, key_name};
}
std::vector<column_info>
get_schema_fk_info_meta ()
{
column_info pktable_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "PKTABLE_NAME");
column_info pkcolumn_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "PKCOLUMN_NAME");
column_info fktable_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "FKTABLE_NAME");
column_info fkcolumn_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "FKCOLUMN_NAME");
column_info key_seq (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "KEY_SEQ");
column_info update_rule (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "UPDATE_RULE");
column_info delete_rule (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "DELETE_RULE");
column_info fk_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "FK_NAME");
column_info pk_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "PK_NAME");
return std::vector<column_info> {pktable_name, pkcolumn_name, fktable_name, fkcolumn_name, key_seq, update_rule, delete_rule, fk_name, pk_name};
}
} | 29.43956 | 174 | 0.661174 | Yechan0815 |
c4ba7b34dc3b3e66b9eec7f770a9565416ea41e9 | 474 | hpp | C++ | aech/src/resource_management/material_library.hpp | markomijolovic/aech | 6e2ea36146596dff6f92e451a598aab535b03d3c | [
"BSD-3-Clause"
] | 4 | 2021-05-25T13:58:30.000Z | 2021-05-26T20:13:15.000Z | aech/src/resource_management/material_library.hpp | markomijolovic/aech | 6e2ea36146596dff6f92e451a598aab535b03d3c | [
"BSD-3-Clause"
] | null | null | null | aech/src/resource_management/material_library.hpp | markomijolovic/aech | 6e2ea36146596dff6f92e451a598aab535b03d3c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "material.hpp"
#include <unordered_map>
namespace aech::graphics {
namespace material_library {
inline std::unordered_map<std::string, material_t> default_materials{};
// creates default material objects
auto generate_default_materials() noexcept -> void;
// create a material from the given template
[[nodiscard]] auto create_material(const std::string &from) noexcept -> material_t;
} // namespace material_library
} // namespace aech::graphics
| 26.333333 | 83 | 0.776371 | markomijolovic |
c4bbda3e53670c898370397ab10975570b59dde3 | 89 | hpp | C++ | openexr-c/abigen/imf_deeptiledoutputpart.hpp | vfx-rs/openexr-bind | ee4fd6010beedb0247737a39ee61ffb87c586448 | [
"BSD-3-Clause"
] | 7 | 2021-06-04T20:59:16.000Z | 2022-02-11T01:00:42.000Z | openexr-c/abigen/imf_deeptiledoutputpart.hpp | vfx-rs/openexr-bind | ee4fd6010beedb0247737a39ee61ffb87c586448 | [
"BSD-3-Clause"
] | 35 | 2021-05-14T04:28:22.000Z | 2021-12-30T12:08:40.000Z | openexr-c/abigen/imf_deeptiledoutputpart.hpp | vfx-rs/openexr-bind | ee4fd6010beedb0247737a39ee61ffb87c586448 | [
"BSD-3-Clause"
] | 5 | 2021-05-15T04:02:56.000Z | 2021-07-02T05:38:01.000Z | #pragma once
#include <ostream>
void abi_gen_imf_deeptiledoutputpart(std::ostream& os);
| 17.8 | 55 | 0.797753 | vfx-rs |
c4bc3d397a4bb39caad3e5a4ec91485b71cad824 | 1,631 | hpp | C++ | source/hougfx/include/hou/gfx/gfx_exceptions.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/hougfx/include/hou/gfx/gfx_exceptions.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/hougfx/include/hou/gfx/gfx_exceptions.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#ifndef HOU_GFX_GFX_EXCEPTIONS_HPP
#define HOU_GFX_GFX_EXCEPTIONS_HPP
#include "hou/cor/exception.hpp"
#include "hou/gfx/gfx_config.hpp"
namespace hou
{
/** Font creation error.
*
* This exception is thrown when creating a font object fails.
* This normally means that the font data is corrupted or in a wrong format.
*/
class HOU_GFX_API font_creation_error : public exception
{
public:
/** Constructor.
*
* \param path the path to the source file where the error happened.
*
* \param line the line where the error happened.
*
* \throws std::bad_alloc.
*/
font_creation_error(const std::string& path, uint line);
};
/** Font destruction error.
*
* This exception is thrown when destructing a font object fails.
*/
class HOU_GFX_API font_destruction_error : public exception
{
public:
/** Constructor.
*
* \param path the path to the source file where the error happened.
*
* \param line the line where the error happened.
*
* \throws std::bad_alloc.
*/
font_destruction_error(const std::string& path, uint line);
};
/** Font operation error.
*
* This exception is thrown when an operation on a font object fails.
*/
class HOU_GFX_API font_operation_error : public exception
{
public:
/** Constructor.
*
* \param path the path to the source file where the error happened.
*
* \param line the line where the error happened.
*
* \throws std::bad_alloc.
*/
font_operation_error(const std::string& path, uint line);
};
} // namespace hou
#endif
| 21.746667 | 76 | 0.702636 | DavideCorradiDev |
c4bce915f809e6a7583322ea1475f8dd37c80c23 | 6,525 | cpp | C++ | src/Text/FontCache.cpp | tido64/rainbow | b54b84860979eca86e7d32ab61f92d9745fecfaa | [
"MIT"
] | 43 | 2019-03-13T16:35:09.000Z | 2021-11-14T20:35:05.000Z | src/Text/FontCache.cpp | tido64/rainbow | b54b84860979eca86e7d32ab61f92d9745fecfaa | [
"MIT"
] | 574 | 2019-02-27T22:21:55.000Z | 2021-09-06T18:46:59.000Z | src/Text/FontCache.cpp | tn0502/rainbow | b54b84860979eca86e7d32ab61f92d9745fecfaa | [
"MIT"
] | 7 | 2015-12-22T20:12:55.000Z | 2018-02-24T10:05:55.000Z | // Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#include "Text/FontCache.h"
#include "Common/Logging.h"
#include "Common/TypeCast.h"
#include "FileSystem/File.h"
#include "Graphics/Image.h"
#include "Text/SystemFonts.h"
using rainbow::Color;
using rainbow::FontCache;
using rainbow::SpriteVertex;
using rainbow::Vec2i;
using rainbow::graphics::TextureProvider;
namespace
{
/// <summary>Horizontal/vertical resolution in dpi.</summary>
constexpr uint32_t kDPI = 96;
constexpr int kGlyphMargin = 1;
/// <summary>26.6 fixed-point pixel coordinates.</summary>
constexpr int kPixelFormat = 64;
constexpr size_t kTextureSizeBytes =
FontCache::kTextureSize * FontCache::kTextureSize * 4;
void blit(const uint8_t* src,
const stbrp_rect& src_rect,
Color* dst,
const Vec2i& dst_sz)
{
for (uint32_t row = 0; row < src_rect.h; ++row) {
auto out = dst + ((src_rect.y + row) * dst_sz.x + src_rect.x);
const auto begin = src + src_rect.w * row;
std::transform(begin, begin + src_rect.w, out, [](uint8_t alpha) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
return Color{0xff, alpha};
});
}
}
} // namespace
FontCache::FontCache()
{
const auto texture_size = ceil_pow2(kTextureSize);
stbrp_init_target(&bin_context_,
texture_size,
texture_size,
bin_nodes_.data(),
narrow_cast<int>(bin_nodes_.size()));
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
bitmap_ = std::make_unique<uint8_t[]>(kTextureSizeBytes);
std::fill_n(bitmap_.get(), kTextureSizeBytes, 0);
FT_Init_FreeType(&library_);
R_ASSERT(library_, "Failed to initialise FreeType");
make_global();
}
FontCache::~FontCache()
{
if (library_ == nullptr)
return;
for (auto&& i : font_cache_)
FT_Done_Face(i.second.face);
FT_Done_FreeType(library_);
}
auto FontCache::get(std::string_view font_name) -> FT_Face
{
auto search = font_cache_.find(font_name);
if (search == font_cache_.end()) {
auto data = font_name.empty()
? text::monospace_font()
: File::read(font_name.data(), FileType::Asset);
FT_Face face;
[[maybe_unused]] FT_Error error =
FT_New_Memory_Face(library_,
data.as<FT_Byte*>(),
narrow_cast<FT_Long>(data.size()),
0,
&face);
R_ASSERT(error == FT_Err_Ok, "Failed to load font face");
R_ASSERT(FT_IS_SCALABLE(face), "Unscalable fonts are not supported");
error = FT_Select_Charmap(face, FT_ENCODING_UNICODE);
R_ASSERT(error == FT_Err_Ok, "Failed to select character map");
font_cache_.emplace(font_name, FontFace{face, std::move(data)});
return face;
}
return search->second.face;
}
auto FontCache::get_glyph(FT_Face face, int32_t font_size, uint32_t glyph_index)
-> std::array<SpriteVertex, 4>
{
const Index cache_index{face, font_size, glyph_index};
auto search = glyph_cache_.find(cache_index);
if (search == glyph_cache_.end()) {
FT_Set_Char_Size(face, 0, font_size * kPixelFormat, 0, kDPI);
FT_Load_Glyph(face, glyph_index, FT_LOAD_RENDER);
FT_GlyphSlot slot = face->glyph;
const FT_Bitmap& bitmap = slot->bitmap;
R_ASSERT(bitmap.num_grays == 256, "");
R_ASSERT(bitmap.pixel_mode == FT_PIXEL_MODE_GRAY, "");
stbrp_rect rect{
0,
static_cast<stbrp_coord>(bitmap.width + kGlyphMargin * 2),
static_cast<stbrp_coord>(bitmap.rows + kGlyphMargin * 2),
0,
0,
0};
stbrp_pack_rects(&bin_context_, &rect, 1);
R_ASSERT(rect.was_packed != 0,
"Failed to pack a glyph, please increase your texture size");
// Adjust coordinates to compensate for margins.
rect.w -= kGlyphMargin * 2;
rect.h -= kGlyphMargin * 2;
rect.x += kGlyphMargin;
rect.y += kGlyphMargin;
blit(bitmap.buffer,
rect,
reinterpret_cast<Color*>(bitmap_.get()),
{kTextureSize, kTextureSize});
state_ = State::NeedsUpdate;
std::array<SpriteVertex, 4> vx;
vx[0].position.x = slot->bitmap_left;
vx[0].position.y = narrow_cast<float>(slot->bitmap_top -
narrow_cast<FT_Int>(bitmap.rows));
vx[1].position.x = narrow_cast<float>(slot->bitmap_left + bitmap.width);
vx[1].position.y = vx[0].position.y;
vx[2].position.x = vx[1].position.x;
vx[2].position.y = narrow_cast<float>(slot->bitmap_top);
vx[3].position.x = vx[0].position.x;
vx[3].position.y = vx[2].position.y;
vx[0].texcoord.x = rect.x / narrow_cast<float>(kTextureSize);
vx[0].texcoord.y = (rect.y + rect.h) / narrow_cast<float>(kTextureSize);
vx[1].texcoord.x = (rect.x + rect.w) / narrow_cast<float>(kTextureSize);
vx[1].texcoord.y = vx[0].texcoord.y;
vx[2].texcoord.x = vx[1].texcoord.x;
vx[2].texcoord.y = rect.y / narrow_cast<float>(kTextureSize);
vx[3].texcoord.x = vx[0].texcoord.x;
vx[3].texcoord.y = vx[2].texcoord.y;
glyph_cache_[cache_index] = {vx};
return vx;
}
return search->second.vertices;
}
void FontCache::update(TextureProvider& texture_provider)
{
if (state_ != State::Ready) {
const auto image = Image{
Image::Format::RGBA,
narrow_cast<uint32_t>(kTextureSize),
narrow_cast<uint32_t>(kTextureSize),
32U,
4U,
kTextureSizeBytes,
bitmap_.get(),
};
if (!texture_)
texture_ = texture_provider.get("rainbow://font-cache", image);
else
texture_provider.update(texture_, image);
state_ = State::Ready;
}
}
#define STB_RECT_PACK_IMPLEMENTATION
// clang-format off
#include "ThirdParty/DisableWarnings.h"
#include <imgui/imstb_rectpack.h> // NOLINT(llvm-include-order)
#include "ThirdParty/ReenableWarnings.h"
// clang-format on
| 32.788945 | 80 | 0.6 | tido64 |
c4bf748586b523ee4d3eaa57641be1668e75e2b0 | 146,403 | cc | C++ | src/mavsdk_server/src/generated/camera_server/camera_server.pb.cc | hamishwillee/MAVSDK | e7f4e27bdd4442b91b623abf6ac86d1cbb188244 | [
"BSD-3-Clause"
] | 115 | 2018-07-11T00:18:12.000Z | 2019-06-05T22:10:23.000Z | src/mavsdk_server/src/generated/camera_server/camera_server.pb.cc | hamishwillee/MAVSDK | e7f4e27bdd4442b91b623abf6ac86d1cbb188244 | [
"BSD-3-Clause"
] | 228 | 2018-07-09T12:03:21.000Z | 2019-06-07T09:51:14.000Z | src/mavsdk_server/src/generated/camera_server/camera_server.pb.cc | hamishwillee/MAVSDK | e7f4e27bdd4442b91b623abf6ac86d1cbb188244 | [
"BSD-3-Clause"
] | 104 | 2018-07-19T09:45:16.000Z | 2019-06-05T18:40:35.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: camera_server/camera_server.proto
#include "camera_server/camera_server.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
PROTOBUF_PRAGMA_INIT_SEG
namespace _pb = ::PROTOBUF_NAMESPACE_ID;
namespace _pbi = _pb::internal;
namespace mavsdk {
namespace rpc {
namespace camera_server {
PROTOBUF_CONSTEXPR SetInformationRequest::SetInformationRequest(
::_pbi::ConstantInitialized)
: information_(nullptr){}
struct SetInformationRequestDefaultTypeInternal {
PROTOBUF_CONSTEXPR SetInformationRequestDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~SetInformationRequestDefaultTypeInternal() {}
union {
SetInformationRequest _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SetInformationRequestDefaultTypeInternal _SetInformationRequest_default_instance_;
PROTOBUF_CONSTEXPR SetInformationResponse::SetInformationResponse(
::_pbi::ConstantInitialized)
: camera_server_result_(nullptr){}
struct SetInformationResponseDefaultTypeInternal {
PROTOBUF_CONSTEXPR SetInformationResponseDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~SetInformationResponseDefaultTypeInternal() {}
union {
SetInformationResponse _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SetInformationResponseDefaultTypeInternal _SetInformationResponse_default_instance_;
PROTOBUF_CONSTEXPR SetInProgressRequest::SetInProgressRequest(
::_pbi::ConstantInitialized)
: in_progress_(false){}
struct SetInProgressRequestDefaultTypeInternal {
PROTOBUF_CONSTEXPR SetInProgressRequestDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~SetInProgressRequestDefaultTypeInternal() {}
union {
SetInProgressRequest _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SetInProgressRequestDefaultTypeInternal _SetInProgressRequest_default_instance_;
PROTOBUF_CONSTEXPR SetInProgressResponse::SetInProgressResponse(
::_pbi::ConstantInitialized)
: camera_server_result_(nullptr){}
struct SetInProgressResponseDefaultTypeInternal {
PROTOBUF_CONSTEXPR SetInProgressResponseDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~SetInProgressResponseDefaultTypeInternal() {}
union {
SetInProgressResponse _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SetInProgressResponseDefaultTypeInternal _SetInProgressResponse_default_instance_;
PROTOBUF_CONSTEXPR SubscribeTakePhotoRequest::SubscribeTakePhotoRequest(
::_pbi::ConstantInitialized){}
struct SubscribeTakePhotoRequestDefaultTypeInternal {
PROTOBUF_CONSTEXPR SubscribeTakePhotoRequestDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~SubscribeTakePhotoRequestDefaultTypeInternal() {}
union {
SubscribeTakePhotoRequest _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SubscribeTakePhotoRequestDefaultTypeInternal _SubscribeTakePhotoRequest_default_instance_;
PROTOBUF_CONSTEXPR TakePhotoResponse::TakePhotoResponse(
::_pbi::ConstantInitialized)
: index_(0){}
struct TakePhotoResponseDefaultTypeInternal {
PROTOBUF_CONSTEXPR TakePhotoResponseDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~TakePhotoResponseDefaultTypeInternal() {}
union {
TakePhotoResponse _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TakePhotoResponseDefaultTypeInternal _TakePhotoResponse_default_instance_;
PROTOBUF_CONSTEXPR RespondTakePhotoRequest::RespondTakePhotoRequest(
::_pbi::ConstantInitialized)
: capture_info_(nullptr)
, take_photo_feedback_(0)
{}
struct RespondTakePhotoRequestDefaultTypeInternal {
PROTOBUF_CONSTEXPR RespondTakePhotoRequestDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~RespondTakePhotoRequestDefaultTypeInternal() {}
union {
RespondTakePhotoRequest _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 RespondTakePhotoRequestDefaultTypeInternal _RespondTakePhotoRequest_default_instance_;
PROTOBUF_CONSTEXPR RespondTakePhotoResponse::RespondTakePhotoResponse(
::_pbi::ConstantInitialized)
: camera_server_result_(nullptr){}
struct RespondTakePhotoResponseDefaultTypeInternal {
PROTOBUF_CONSTEXPR RespondTakePhotoResponseDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~RespondTakePhotoResponseDefaultTypeInternal() {}
union {
RespondTakePhotoResponse _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 RespondTakePhotoResponseDefaultTypeInternal _RespondTakePhotoResponse_default_instance_;
PROTOBUF_CONSTEXPR Information::Information(
::_pbi::ConstantInitialized)
: vendor_name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{})
, model_name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{})
, firmware_version_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{})
, definition_file_uri_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{})
, focal_length_mm_(0)
, horizontal_sensor_size_mm_(0)
, vertical_sensor_size_mm_(0)
, horizontal_resolution_px_(0u)
, vertical_resolution_px_(0u)
, lens_id_(0u)
, definition_file_version_(0u){}
struct InformationDefaultTypeInternal {
PROTOBUF_CONSTEXPR InformationDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~InformationDefaultTypeInternal() {}
union {
Information _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 InformationDefaultTypeInternal _Information_default_instance_;
PROTOBUF_CONSTEXPR Position::Position(
::_pbi::ConstantInitialized)
: latitude_deg_(0)
, longitude_deg_(0)
, absolute_altitude_m_(0)
, relative_altitude_m_(0){}
struct PositionDefaultTypeInternal {
PROTOBUF_CONSTEXPR PositionDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~PositionDefaultTypeInternal() {}
union {
Position _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 PositionDefaultTypeInternal _Position_default_instance_;
PROTOBUF_CONSTEXPR Quaternion::Quaternion(
::_pbi::ConstantInitialized)
: w_(0)
, x_(0)
, y_(0)
, z_(0){}
struct QuaternionDefaultTypeInternal {
PROTOBUF_CONSTEXPR QuaternionDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~QuaternionDefaultTypeInternal() {}
union {
Quaternion _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 QuaternionDefaultTypeInternal _Quaternion_default_instance_;
PROTOBUF_CONSTEXPR CaptureInfo::CaptureInfo(
::_pbi::ConstantInitialized)
: file_url_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{})
, position_(nullptr)
, attitude_quaternion_(nullptr)
, time_utc_us_(uint64_t{0u})
, is_success_(false)
, index_(0){}
struct CaptureInfoDefaultTypeInternal {
PROTOBUF_CONSTEXPR CaptureInfoDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~CaptureInfoDefaultTypeInternal() {}
union {
CaptureInfo _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 CaptureInfoDefaultTypeInternal _CaptureInfo_default_instance_;
PROTOBUF_CONSTEXPR CameraServerResult::CameraServerResult(
::_pbi::ConstantInitialized)
: result_str_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{})
, result_(0)
{}
struct CameraServerResultDefaultTypeInternal {
PROTOBUF_CONSTEXPR CameraServerResultDefaultTypeInternal()
: _instance(::_pbi::ConstantInitialized{}) {}
~CameraServerResultDefaultTypeInternal() {}
union {
CameraServerResult _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 CameraServerResultDefaultTypeInternal _CameraServerResult_default_instance_;
} // namespace camera_server
} // namespace rpc
} // namespace mavsdk
static ::_pb::Metadata file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[13];
static const ::_pb::EnumDescriptor* file_level_enum_descriptors_camera_5fserver_2fcamera_5fserver_2eproto[2];
static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_camera_5fserver_2fcamera_5fserver_2eproto = nullptr;
const uint32_t TableStruct_camera_5fserver_2fcamera_5fserver_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInformationRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInformationRequest, information_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInformationResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInformationResponse, camera_server_result_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInProgressRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInProgressRequest, in_progress_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInProgressResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SetInProgressResponse, camera_server_result_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::SubscribeTakePhotoRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::TakePhotoResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::TakePhotoResponse, index_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::RespondTakePhotoRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::RespondTakePhotoRequest, take_photo_feedback_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::RespondTakePhotoRequest, capture_info_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::RespondTakePhotoResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::RespondTakePhotoResponse, camera_server_result_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, vendor_name_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, model_name_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, firmware_version_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, focal_length_mm_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, horizontal_sensor_size_mm_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, vertical_sensor_size_mm_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, horizontal_resolution_px_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, vertical_resolution_px_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, lens_id_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, definition_file_version_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Information, definition_file_uri_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Position, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Position, latitude_deg_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Position, longitude_deg_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Position, absolute_altitude_m_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Position, relative_altitude_m_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Quaternion, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Quaternion, w_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Quaternion, x_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Quaternion, y_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::Quaternion, z_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, position_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, attitude_quaternion_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, time_utc_us_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, is_success_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, index_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CaptureInfo, file_url_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CameraServerResult, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _inlined_string_donated_
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CameraServerResult, result_),
PROTOBUF_FIELD_OFFSET(::mavsdk::rpc::camera_server::CameraServerResult, result_str_),
};
static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, -1, sizeof(::mavsdk::rpc::camera_server::SetInformationRequest)},
{ 7, -1, -1, sizeof(::mavsdk::rpc::camera_server::SetInformationResponse)},
{ 14, -1, -1, sizeof(::mavsdk::rpc::camera_server::SetInProgressRequest)},
{ 21, -1, -1, sizeof(::mavsdk::rpc::camera_server::SetInProgressResponse)},
{ 28, -1, -1, sizeof(::mavsdk::rpc::camera_server::SubscribeTakePhotoRequest)},
{ 34, -1, -1, sizeof(::mavsdk::rpc::camera_server::TakePhotoResponse)},
{ 41, -1, -1, sizeof(::mavsdk::rpc::camera_server::RespondTakePhotoRequest)},
{ 49, -1, -1, sizeof(::mavsdk::rpc::camera_server::RespondTakePhotoResponse)},
{ 56, -1, -1, sizeof(::mavsdk::rpc::camera_server::Information)},
{ 73, -1, -1, sizeof(::mavsdk::rpc::camera_server::Position)},
{ 83, -1, -1, sizeof(::mavsdk::rpc::camera_server::Quaternion)},
{ 93, -1, -1, sizeof(::mavsdk::rpc::camera_server::CaptureInfo)},
{ 105, -1, -1, sizeof(::mavsdk::rpc::camera_server::CameraServerResult)},
};
static const ::_pb::Message* const file_default_instances[] = {
&::mavsdk::rpc::camera_server::_SetInformationRequest_default_instance_._instance,
&::mavsdk::rpc::camera_server::_SetInformationResponse_default_instance_._instance,
&::mavsdk::rpc::camera_server::_SetInProgressRequest_default_instance_._instance,
&::mavsdk::rpc::camera_server::_SetInProgressResponse_default_instance_._instance,
&::mavsdk::rpc::camera_server::_SubscribeTakePhotoRequest_default_instance_._instance,
&::mavsdk::rpc::camera_server::_TakePhotoResponse_default_instance_._instance,
&::mavsdk::rpc::camera_server::_RespondTakePhotoRequest_default_instance_._instance,
&::mavsdk::rpc::camera_server::_RespondTakePhotoResponse_default_instance_._instance,
&::mavsdk::rpc::camera_server::_Information_default_instance_._instance,
&::mavsdk::rpc::camera_server::_Position_default_instance_._instance,
&::mavsdk::rpc::camera_server::_Quaternion_default_instance_._instance,
&::mavsdk::rpc::camera_server::_CaptureInfo_default_instance_._instance,
&::mavsdk::rpc::camera_server::_CameraServerResult_default_instance_._instance,
};
const char descriptor_table_protodef_camera_5fserver_2fcamera_5fserver_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n!camera_server/camera_server.proto\022\030mav"
"sdk.rpc.camera_server\032\024mavsdk_options.pr"
"oto\"S\n\025SetInformationRequest\022:\n\013informat"
"ion\030\001 \001(\0132%.mavsdk.rpc.camera_server.Inf"
"ormation\"d\n\026SetInformationResponse\022J\n\024ca"
"mera_server_result\030\001 \001(\0132,.mavsdk.rpc.ca"
"mera_server.CameraServerResult\"+\n\024SetInP"
"rogressRequest\022\023\n\013in_progress\030\001 \001(\010\"c\n\025S"
"etInProgressResponse\022J\n\024camera_server_re"
"sult\030\001 \001(\0132,.mavsdk.rpc.camera_server.Ca"
"meraServerResult\"\033\n\031SubscribeTakePhotoRe"
"quest\"\"\n\021TakePhotoResponse\022\r\n\005index\030\001 \001("
"\005\"\240\001\n\027RespondTakePhotoRequest\022H\n\023take_ph"
"oto_feedback\030\001 \001(\0162+.mavsdk.rpc.camera_s"
"erver.TakePhotoFeedback\022;\n\014capture_info\030"
"\002 \001(\0132%.mavsdk.rpc.camera_server.Capture"
"Info\"f\n\030RespondTakePhotoResponse\022J\n\024came"
"ra_server_result\030\001 \001(\0132,.mavsdk.rpc.came"
"ra_server.CameraServerResult\"\276\002\n\013Informa"
"tion\022\023\n\013vendor_name\030\001 \001(\t\022\022\n\nmodel_name\030"
"\002 \001(\t\022\030\n\020firmware_version\030\003 \001(\t\022\027\n\017focal"
"_length_mm\030\004 \001(\002\022!\n\031horizontal_sensor_si"
"ze_mm\030\005 \001(\002\022\037\n\027vertical_sensor_size_mm\030\006"
" \001(\002\022 \n\030horizontal_resolution_px\030\007 \001(\r\022\036"
"\n\026vertical_resolution_px\030\010 \001(\r\022\017\n\007lens_i"
"d\030\t \001(\r\022\037\n\027definition_file_version\030\n \001(\r"
"\022\033\n\023definition_file_uri\030\013 \001(\t\"q\n\010Positio"
"n\022\024\n\014latitude_deg\030\001 \001(\001\022\025\n\rlongitude_deg"
"\030\002 \001(\001\022\033\n\023absolute_altitude_m\030\003 \001(\002\022\033\n\023r"
"elative_altitude_m\030\004 \001(\002\"8\n\nQuaternion\022\t"
"\n\001w\030\001 \001(\002\022\t\n\001x\030\002 \001(\002\022\t\n\001y\030\003 \001(\002\022\t\n\001z\030\004 \001"
"(\002\"\320\001\n\013CaptureInfo\0224\n\010position\030\001 \001(\0132\".m"
"avsdk.rpc.camera_server.Position\022A\n\023atti"
"tude_quaternion\030\002 \001(\0132$.mavsdk.rpc.camer"
"a_server.Quaternion\022\023\n\013time_utc_us\030\003 \001(\004"
"\022\022\n\nis_success\030\004 \001(\010\022\r\n\005index\030\005 \001(\005\022\020\n\010f"
"ile_url\030\006 \001(\t\"\263\002\n\022CameraServerResult\022C\n\006"
"result\030\001 \001(\01623.mavsdk.rpc.camera_server."
"CameraServerResult.Result\022\022\n\nresult_str\030"
"\002 \001(\t\"\303\001\n\006Result\022\022\n\016RESULT_UNKNOWN\020\000\022\022\n\016"
"RESULT_SUCCESS\020\001\022\026\n\022RESULT_IN_PROGRESS\020\002"
"\022\017\n\013RESULT_BUSY\020\003\022\021\n\rRESULT_DENIED\020\004\022\020\n\014"
"RESULT_ERROR\020\005\022\022\n\016RESULT_TIMEOUT\020\006\022\031\n\025RE"
"SULT_WRONG_ARGUMENT\020\007\022\024\n\020RESULT_NO_SYSTE"
"M\020\010*\216\001\n\021TakePhotoFeedback\022\037\n\033TAKE_PHOTO_"
"FEEDBACK_UNKNOWN\020\000\022\032\n\026TAKE_PHOTO_FEEDBAC"
"K_OK\020\001\022\034\n\030TAKE_PHOTO_FEEDBACK_BUSY\020\002\022\036\n\032"
"TAKE_PHOTO_FEEDBACK_FAILED\020\0032\211\004\n\023CameraS"
"erverService\022y\n\016SetInformation\022/.mavsdk."
"rpc.camera_server.SetInformationRequest\032"
"0.mavsdk.rpc.camera_server.SetInformatio"
"nResponse\"\004\200\265\030\001\022v\n\rSetInProgress\022..mavsd"
"k.rpc.camera_server.SetInProgressRequest"
"\032/.mavsdk.rpc.camera_server.SetInProgres"
"sResponse\"\004\200\265\030\001\022~\n\022SubscribeTakePhoto\0223."
"mavsdk.rpc.camera_server.SubscribeTakePh"
"otoRequest\032+.mavsdk.rpc.camera_server.Ta"
"kePhotoResponse\"\004\200\265\030\0000\001\022\177\n\020RespondTakePh"
"oto\0221.mavsdk.rpc.camera_server.RespondTa"
"kePhotoRequest\0322.mavsdk.rpc.camera_serve"
"r.RespondTakePhotoResponse\"\004\200\265\030\001B,\n\027io.m"
"avsdk.camera_serverB\021CameraServerProtob\006"
"proto3"
;
static const ::_pbi::DescriptorTable* const descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_deps[1] = {
&::descriptor_table_mavsdk_5foptions_2eproto,
};
static ::_pbi::once_flag descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once;
const ::_pbi::DescriptorTable descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto = {
false, false, 2486, descriptor_table_protodef_camera_5fserver_2fcamera_5fserver_2eproto,
"camera_server/camera_server.proto",
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once, descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_deps, 1, 13,
schemas, file_default_instances, TableStruct_camera_5fserver_2fcamera_5fserver_2eproto::offsets,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto, file_level_enum_descriptors_camera_5fserver_2fcamera_5fserver_2eproto,
file_level_service_descriptors_camera_5fserver_2fcamera_5fserver_2eproto,
};
PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter() {
return &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto;
}
// Force running AddDescriptors() at dynamic initialization time.
PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_camera_5fserver_2fcamera_5fserver_2eproto(&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto);
namespace mavsdk {
namespace rpc {
namespace camera_server {
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CameraServerResult_Result_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto);
return file_level_enum_descriptors_camera_5fserver_2fcamera_5fserver_2eproto[0];
}
bool CameraServerResult_Result_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
constexpr CameraServerResult_Result CameraServerResult::RESULT_UNKNOWN;
constexpr CameraServerResult_Result CameraServerResult::RESULT_SUCCESS;
constexpr CameraServerResult_Result CameraServerResult::RESULT_IN_PROGRESS;
constexpr CameraServerResult_Result CameraServerResult::RESULT_BUSY;
constexpr CameraServerResult_Result CameraServerResult::RESULT_DENIED;
constexpr CameraServerResult_Result CameraServerResult::RESULT_ERROR;
constexpr CameraServerResult_Result CameraServerResult::RESULT_TIMEOUT;
constexpr CameraServerResult_Result CameraServerResult::RESULT_WRONG_ARGUMENT;
constexpr CameraServerResult_Result CameraServerResult::RESULT_NO_SYSTEM;
constexpr CameraServerResult_Result CameraServerResult::Result_MIN;
constexpr CameraServerResult_Result CameraServerResult::Result_MAX;
constexpr int CameraServerResult::Result_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* TakePhotoFeedback_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto);
return file_level_enum_descriptors_camera_5fserver_2fcamera_5fserver_2eproto[1];
}
bool TakePhotoFeedback_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
// ===================================================================
class SetInformationRequest::_Internal {
public:
static const ::mavsdk::rpc::camera_server::Information& information(const SetInformationRequest* msg);
};
const ::mavsdk::rpc::camera_server::Information&
SetInformationRequest::_Internal::information(const SetInformationRequest* msg) {
return *msg->information_;
}
SetInformationRequest::SetInformationRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.SetInformationRequest)
}
SetInformationRequest::SetInformationRequest(const SetInformationRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_information()) {
information_ = new ::mavsdk::rpc::camera_server::Information(*from.information_);
} else {
information_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.SetInformationRequest)
}
inline void SetInformationRequest::SharedCtor() {
information_ = nullptr;
}
SetInformationRequest::~SetInformationRequest() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.SetInformationRequest)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void SetInformationRequest::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
if (this != internal_default_instance()) delete information_;
}
void SetInformationRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void SetInformationRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.SetInformationRequest)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaForAllocation() == nullptr && information_ != nullptr) {
delete information_;
}
information_ = nullptr;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SetInformationRequest::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.Information information = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_information(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* SetInformationRequest::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.SetInformationRequest)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.Information information = 1;
if (this->_internal_has_information()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, _Internal::information(this),
_Internal::information(this).GetCachedSize(), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.SetInformationRequest)
return target;
}
size_t SetInformationRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.SetInformationRequest)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.Information information = 1;
if (this->_internal_has_information()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*information_);
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SetInformationRequest::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
SetInformationRequest::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SetInformationRequest::GetClassData() const { return &_class_data_; }
void SetInformationRequest::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<SetInformationRequest *>(to)->MergeFrom(
static_cast<const SetInformationRequest &>(from));
}
void SetInformationRequest::MergeFrom(const SetInformationRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.SetInformationRequest)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_has_information()) {
_internal_mutable_information()->::mavsdk::rpc::camera_server::Information::MergeFrom(from._internal_information());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void SetInformationRequest::CopyFrom(const SetInformationRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.SetInformationRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SetInformationRequest::IsInitialized() const {
return true;
}
void SetInformationRequest::InternalSwap(SetInformationRequest* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(information_, other->information_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SetInformationRequest::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[0]);
}
// ===================================================================
class SetInformationResponse::_Internal {
public:
static const ::mavsdk::rpc::camera_server::CameraServerResult& camera_server_result(const SetInformationResponse* msg);
};
const ::mavsdk::rpc::camera_server::CameraServerResult&
SetInformationResponse::_Internal::camera_server_result(const SetInformationResponse* msg) {
return *msg->camera_server_result_;
}
SetInformationResponse::SetInformationResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.SetInformationResponse)
}
SetInformationResponse::SetInformationResponse(const SetInformationResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_camera_server_result()) {
camera_server_result_ = new ::mavsdk::rpc::camera_server::CameraServerResult(*from.camera_server_result_);
} else {
camera_server_result_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.SetInformationResponse)
}
inline void SetInformationResponse::SharedCtor() {
camera_server_result_ = nullptr;
}
SetInformationResponse::~SetInformationResponse() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.SetInformationResponse)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void SetInformationResponse::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
if (this != internal_default_instance()) delete camera_server_result_;
}
void SetInformationResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void SetInformationResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.SetInformationResponse)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaForAllocation() == nullptr && camera_server_result_ != nullptr) {
delete camera_server_result_;
}
camera_server_result_ = nullptr;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SetInformationResponse::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_camera_server_result(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* SetInformationResponse::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.SetInformationResponse)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
if (this->_internal_has_camera_server_result()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, _Internal::camera_server_result(this),
_Internal::camera_server_result(this).GetCachedSize(), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.SetInformationResponse)
return target;
}
size_t SetInformationResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.SetInformationResponse)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
if (this->_internal_has_camera_server_result()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*camera_server_result_);
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SetInformationResponse::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
SetInformationResponse::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SetInformationResponse::GetClassData() const { return &_class_data_; }
void SetInformationResponse::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<SetInformationResponse *>(to)->MergeFrom(
static_cast<const SetInformationResponse &>(from));
}
void SetInformationResponse::MergeFrom(const SetInformationResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.SetInformationResponse)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_has_camera_server_result()) {
_internal_mutable_camera_server_result()->::mavsdk::rpc::camera_server::CameraServerResult::MergeFrom(from._internal_camera_server_result());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void SetInformationResponse::CopyFrom(const SetInformationResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.SetInformationResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SetInformationResponse::IsInitialized() const {
return true;
}
void SetInformationResponse::InternalSwap(SetInformationResponse* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(camera_server_result_, other->camera_server_result_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SetInformationResponse::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[1]);
}
// ===================================================================
class SetInProgressRequest::_Internal {
public:
};
SetInProgressRequest::SetInProgressRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.SetInProgressRequest)
}
SetInProgressRequest::SetInProgressRequest(const SetInProgressRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
in_progress_ = from.in_progress_;
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.SetInProgressRequest)
}
inline void SetInProgressRequest::SharedCtor() {
in_progress_ = false;
}
SetInProgressRequest::~SetInProgressRequest() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.SetInProgressRequest)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void SetInProgressRequest::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
}
void SetInProgressRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void SetInProgressRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.SetInProgressRequest)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
in_progress_ = false;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SetInProgressRequest::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// bool in_progress = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) {
in_progress_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* SetInProgressRequest::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.SetInProgressRequest)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// bool in_progress = 1;
if (this->_internal_in_progress() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteBoolToArray(1, this->_internal_in_progress(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.SetInProgressRequest)
return target;
}
size_t SetInProgressRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.SetInProgressRequest)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// bool in_progress = 1;
if (this->_internal_in_progress() != 0) {
total_size += 1 + 1;
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SetInProgressRequest::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
SetInProgressRequest::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SetInProgressRequest::GetClassData() const { return &_class_data_; }
void SetInProgressRequest::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<SetInProgressRequest *>(to)->MergeFrom(
static_cast<const SetInProgressRequest &>(from));
}
void SetInProgressRequest::MergeFrom(const SetInProgressRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.SetInProgressRequest)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_in_progress() != 0) {
_internal_set_in_progress(from._internal_in_progress());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void SetInProgressRequest::CopyFrom(const SetInProgressRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.SetInProgressRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SetInProgressRequest::IsInitialized() const {
return true;
}
void SetInProgressRequest::InternalSwap(SetInProgressRequest* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(in_progress_, other->in_progress_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SetInProgressRequest::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[2]);
}
// ===================================================================
class SetInProgressResponse::_Internal {
public:
static const ::mavsdk::rpc::camera_server::CameraServerResult& camera_server_result(const SetInProgressResponse* msg);
};
const ::mavsdk::rpc::camera_server::CameraServerResult&
SetInProgressResponse::_Internal::camera_server_result(const SetInProgressResponse* msg) {
return *msg->camera_server_result_;
}
SetInProgressResponse::SetInProgressResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.SetInProgressResponse)
}
SetInProgressResponse::SetInProgressResponse(const SetInProgressResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_camera_server_result()) {
camera_server_result_ = new ::mavsdk::rpc::camera_server::CameraServerResult(*from.camera_server_result_);
} else {
camera_server_result_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.SetInProgressResponse)
}
inline void SetInProgressResponse::SharedCtor() {
camera_server_result_ = nullptr;
}
SetInProgressResponse::~SetInProgressResponse() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.SetInProgressResponse)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void SetInProgressResponse::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
if (this != internal_default_instance()) delete camera_server_result_;
}
void SetInProgressResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void SetInProgressResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.SetInProgressResponse)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaForAllocation() == nullptr && camera_server_result_ != nullptr) {
delete camera_server_result_;
}
camera_server_result_ = nullptr;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SetInProgressResponse::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_camera_server_result(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* SetInProgressResponse::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.SetInProgressResponse)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
if (this->_internal_has_camera_server_result()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, _Internal::camera_server_result(this),
_Internal::camera_server_result(this).GetCachedSize(), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.SetInProgressResponse)
return target;
}
size_t SetInProgressResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.SetInProgressResponse)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
if (this->_internal_has_camera_server_result()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*camera_server_result_);
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SetInProgressResponse::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
SetInProgressResponse::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SetInProgressResponse::GetClassData() const { return &_class_data_; }
void SetInProgressResponse::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<SetInProgressResponse *>(to)->MergeFrom(
static_cast<const SetInProgressResponse &>(from));
}
void SetInProgressResponse::MergeFrom(const SetInProgressResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.SetInProgressResponse)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_has_camera_server_result()) {
_internal_mutable_camera_server_result()->::mavsdk::rpc::camera_server::CameraServerResult::MergeFrom(from._internal_camera_server_result());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void SetInProgressResponse::CopyFrom(const SetInProgressResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.SetInProgressResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SetInProgressResponse::IsInitialized() const {
return true;
}
void SetInProgressResponse::InternalSwap(SetInProgressResponse* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(camera_server_result_, other->camera_server_result_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SetInProgressResponse::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[3]);
}
// ===================================================================
class SubscribeTakePhotoRequest::_Internal {
public:
};
SubscribeTakePhotoRequest::SubscribeTakePhotoRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase(arena, is_message_owned) {
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.SubscribeTakePhotoRequest)
}
SubscribeTakePhotoRequest::SubscribeTakePhotoRequest(const SubscribeTakePhotoRequest& from)
: ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.SubscribeTakePhotoRequest)
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SubscribeTakePhotoRequest::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::CopyImpl,
::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::MergeImpl,
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SubscribeTakePhotoRequest::GetClassData() const { return &_class_data_; }
::PROTOBUF_NAMESPACE_ID::Metadata SubscribeTakePhotoRequest::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[4]);
}
// ===================================================================
class TakePhotoResponse::_Internal {
public:
};
TakePhotoResponse::TakePhotoResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.TakePhotoResponse)
}
TakePhotoResponse::TakePhotoResponse(const TakePhotoResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
index_ = from.index_;
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.TakePhotoResponse)
}
inline void TakePhotoResponse::SharedCtor() {
index_ = 0;
}
TakePhotoResponse::~TakePhotoResponse() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.TakePhotoResponse)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void TakePhotoResponse::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
}
void TakePhotoResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void TakePhotoResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.TakePhotoResponse)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
index_ = 0;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* TakePhotoResponse::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// int32 index = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) {
index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* TakePhotoResponse::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.TakePhotoResponse)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// int32 index = 1;
if (this->_internal_index() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteInt32ToArray(1, this->_internal_index(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.TakePhotoResponse)
return target;
}
size_t TakePhotoResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.TakePhotoResponse)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// int32 index = 1;
if (this->_internal_index() != 0) {
total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_index());
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData TakePhotoResponse::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
TakePhotoResponse::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*TakePhotoResponse::GetClassData() const { return &_class_data_; }
void TakePhotoResponse::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<TakePhotoResponse *>(to)->MergeFrom(
static_cast<const TakePhotoResponse &>(from));
}
void TakePhotoResponse::MergeFrom(const TakePhotoResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.TakePhotoResponse)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_index() != 0) {
_internal_set_index(from._internal_index());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void TakePhotoResponse::CopyFrom(const TakePhotoResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.TakePhotoResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TakePhotoResponse::IsInitialized() const {
return true;
}
void TakePhotoResponse::InternalSwap(TakePhotoResponse* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(index_, other->index_);
}
::PROTOBUF_NAMESPACE_ID::Metadata TakePhotoResponse::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[5]);
}
// ===================================================================
class RespondTakePhotoRequest::_Internal {
public:
static const ::mavsdk::rpc::camera_server::CaptureInfo& capture_info(const RespondTakePhotoRequest* msg);
};
const ::mavsdk::rpc::camera_server::CaptureInfo&
RespondTakePhotoRequest::_Internal::capture_info(const RespondTakePhotoRequest* msg) {
return *msg->capture_info_;
}
RespondTakePhotoRequest::RespondTakePhotoRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
}
RespondTakePhotoRequest::RespondTakePhotoRequest(const RespondTakePhotoRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_capture_info()) {
capture_info_ = new ::mavsdk::rpc::camera_server::CaptureInfo(*from.capture_info_);
} else {
capture_info_ = nullptr;
}
take_photo_feedback_ = from.take_photo_feedback_;
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
}
inline void RespondTakePhotoRequest::SharedCtor() {
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&capture_info_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&take_photo_feedback_) -
reinterpret_cast<char*>(&capture_info_)) + sizeof(take_photo_feedback_));
}
RespondTakePhotoRequest::~RespondTakePhotoRequest() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void RespondTakePhotoRequest::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
if (this != internal_default_instance()) delete capture_info_;
}
void RespondTakePhotoRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void RespondTakePhotoRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaForAllocation() == nullptr && capture_info_ != nullptr) {
delete capture_info_;
}
capture_info_ = nullptr;
take_photo_feedback_ = 0;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* RespondTakePhotoRequest::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.TakePhotoFeedback take_photo_feedback = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) {
uint64_t val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_take_photo_feedback(static_cast<::mavsdk::rpc::camera_server::TakePhotoFeedback>(val));
} else
goto handle_unusual;
continue;
// .mavsdk.rpc.camera_server.CaptureInfo capture_info = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) {
ptr = ctx->ParseMessage(_internal_mutable_capture_info(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* RespondTakePhotoRequest::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.TakePhotoFeedback take_photo_feedback = 1;
if (this->_internal_take_photo_feedback() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteEnumToArray(
1, this->_internal_take_photo_feedback(), target);
}
// .mavsdk.rpc.camera_server.CaptureInfo capture_info = 2;
if (this->_internal_has_capture_info()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(2, _Internal::capture_info(this),
_Internal::capture_info(this).GetCachedSize(), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
return target;
}
size_t RespondTakePhotoRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CaptureInfo capture_info = 2;
if (this->_internal_has_capture_info()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*capture_info_);
}
// .mavsdk.rpc.camera_server.TakePhotoFeedback take_photo_feedback = 1;
if (this->_internal_take_photo_feedback() != 0) {
total_size += 1 +
::_pbi::WireFormatLite::EnumSize(this->_internal_take_photo_feedback());
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData RespondTakePhotoRequest::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
RespondTakePhotoRequest::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*RespondTakePhotoRequest::GetClassData() const { return &_class_data_; }
void RespondTakePhotoRequest::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<RespondTakePhotoRequest *>(to)->MergeFrom(
static_cast<const RespondTakePhotoRequest &>(from));
}
void RespondTakePhotoRequest::MergeFrom(const RespondTakePhotoRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_has_capture_info()) {
_internal_mutable_capture_info()->::mavsdk::rpc::camera_server::CaptureInfo::MergeFrom(from._internal_capture_info());
}
if (from._internal_take_photo_feedback() != 0) {
_internal_set_take_photo_feedback(from._internal_take_photo_feedback());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void RespondTakePhotoRequest::CopyFrom(const RespondTakePhotoRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.RespondTakePhotoRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RespondTakePhotoRequest::IsInitialized() const {
return true;
}
void RespondTakePhotoRequest::InternalSwap(RespondTakePhotoRequest* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(RespondTakePhotoRequest, take_photo_feedback_)
+ sizeof(RespondTakePhotoRequest::take_photo_feedback_)
- PROTOBUF_FIELD_OFFSET(RespondTakePhotoRequest, capture_info_)>(
reinterpret_cast<char*>(&capture_info_),
reinterpret_cast<char*>(&other->capture_info_));
}
::PROTOBUF_NAMESPACE_ID::Metadata RespondTakePhotoRequest::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[6]);
}
// ===================================================================
class RespondTakePhotoResponse::_Internal {
public:
static const ::mavsdk::rpc::camera_server::CameraServerResult& camera_server_result(const RespondTakePhotoResponse* msg);
};
const ::mavsdk::rpc::camera_server::CameraServerResult&
RespondTakePhotoResponse::_Internal::camera_server_result(const RespondTakePhotoResponse* msg) {
return *msg->camera_server_result_;
}
RespondTakePhotoResponse::RespondTakePhotoResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
}
RespondTakePhotoResponse::RespondTakePhotoResponse(const RespondTakePhotoResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_camera_server_result()) {
camera_server_result_ = new ::mavsdk::rpc::camera_server::CameraServerResult(*from.camera_server_result_);
} else {
camera_server_result_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
}
inline void RespondTakePhotoResponse::SharedCtor() {
camera_server_result_ = nullptr;
}
RespondTakePhotoResponse::~RespondTakePhotoResponse() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void RespondTakePhotoResponse::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
if (this != internal_default_instance()) delete camera_server_result_;
}
void RespondTakePhotoResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void RespondTakePhotoResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaForAllocation() == nullptr && camera_server_result_ != nullptr) {
delete camera_server_result_;
}
camera_server_result_ = nullptr;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* RespondTakePhotoResponse::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_camera_server_result(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* RespondTakePhotoResponse::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
if (this->_internal_has_camera_server_result()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, _Internal::camera_server_result(this),
_Internal::camera_server_result(this).GetCachedSize(), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
return target;
}
size_t RespondTakePhotoResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult camera_server_result = 1;
if (this->_internal_has_camera_server_result()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*camera_server_result_);
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData RespondTakePhotoResponse::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
RespondTakePhotoResponse::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*RespondTakePhotoResponse::GetClassData() const { return &_class_data_; }
void RespondTakePhotoResponse::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<RespondTakePhotoResponse *>(to)->MergeFrom(
static_cast<const RespondTakePhotoResponse &>(from));
}
void RespondTakePhotoResponse::MergeFrom(const RespondTakePhotoResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (from._internal_has_camera_server_result()) {
_internal_mutable_camera_server_result()->::mavsdk::rpc::camera_server::CameraServerResult::MergeFrom(from._internal_camera_server_result());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void RespondTakePhotoResponse::CopyFrom(const RespondTakePhotoResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.RespondTakePhotoResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RespondTakePhotoResponse::IsInitialized() const {
return true;
}
void RespondTakePhotoResponse::InternalSwap(RespondTakePhotoResponse* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(camera_server_result_, other->camera_server_result_);
}
::PROTOBUF_NAMESPACE_ID::Metadata RespondTakePhotoResponse::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[7]);
}
// ===================================================================
class Information::_Internal {
public:
};
Information::Information(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.Information)
}
Information::Information(const Information& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
vendor_name_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
vendor_name_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (!from._internal_vendor_name().empty()) {
vendor_name_.Set(from._internal_vendor_name(),
GetArenaForAllocation());
}
model_name_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
model_name_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (!from._internal_model_name().empty()) {
model_name_.Set(from._internal_model_name(),
GetArenaForAllocation());
}
firmware_version_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
firmware_version_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (!from._internal_firmware_version().empty()) {
firmware_version_.Set(from._internal_firmware_version(),
GetArenaForAllocation());
}
definition_file_uri_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
definition_file_uri_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (!from._internal_definition_file_uri().empty()) {
definition_file_uri_.Set(from._internal_definition_file_uri(),
GetArenaForAllocation());
}
::memcpy(&focal_length_mm_, &from.focal_length_mm_,
static_cast<size_t>(reinterpret_cast<char*>(&definition_file_version_) -
reinterpret_cast<char*>(&focal_length_mm_)) + sizeof(definition_file_version_));
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.Information)
}
inline void Information::SharedCtor() {
vendor_name_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
vendor_name_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
model_name_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
model_name_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
firmware_version_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
firmware_version_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
definition_file_uri_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
definition_file_uri_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&focal_length_mm_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&definition_file_version_) -
reinterpret_cast<char*>(&focal_length_mm_)) + sizeof(definition_file_version_));
}
Information::~Information() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.Information)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void Information::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
vendor_name_.Destroy();
model_name_.Destroy();
firmware_version_.Destroy();
definition_file_uri_.Destroy();
}
void Information::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void Information::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.Information)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
vendor_name_.ClearToEmpty();
model_name_.ClearToEmpty();
firmware_version_.ClearToEmpty();
definition_file_uri_.ClearToEmpty();
::memset(&focal_length_mm_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&definition_file_version_) -
reinterpret_cast<char*>(&focal_length_mm_)) + sizeof(definition_file_version_));
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Information::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// string vendor_name = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
auto str = _internal_mutable_vendor_name();
ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
CHK_(::_pbi::VerifyUTF8(str, "mavsdk.rpc.camera_server.Information.vendor_name"));
} else
goto handle_unusual;
continue;
// string model_name = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) {
auto str = _internal_mutable_model_name();
ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
CHK_(::_pbi::VerifyUTF8(str, "mavsdk.rpc.camera_server.Information.model_name"));
} else
goto handle_unusual;
continue;
// string firmware_version = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 26)) {
auto str = _internal_mutable_firmware_version();
ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
CHK_(::_pbi::VerifyUTF8(str, "mavsdk.rpc.camera_server.Information.firmware_version"));
} else
goto handle_unusual;
continue;
// float focal_length_mm = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 37)) {
focal_length_mm_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// float horizontal_sensor_size_mm = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 45)) {
horizontal_sensor_size_mm_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// float vertical_sensor_size_mm = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 53)) {
vertical_sensor_size_mm_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// uint32 horizontal_resolution_px = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 56)) {
horizontal_resolution_px_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// uint32 vertical_resolution_px = 8;
case 8:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 64)) {
vertical_resolution_px_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// uint32 lens_id = 9;
case 9:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 72)) {
lens_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// uint32 definition_file_version = 10;
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 80)) {
definition_file_version_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// string definition_file_uri = 11;
case 11:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 90)) {
auto str = _internal_mutable_definition_file_uri();
ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
CHK_(::_pbi::VerifyUTF8(str, "mavsdk.rpc.camera_server.Information.definition_file_uri"));
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* Information::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.Information)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// string vendor_name = 1;
if (!this->_internal_vendor_name().empty()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_vendor_name().data(), static_cast<int>(this->_internal_vendor_name().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"mavsdk.rpc.camera_server.Information.vendor_name");
target = stream->WriteStringMaybeAliased(
1, this->_internal_vendor_name(), target);
}
// string model_name = 2;
if (!this->_internal_model_name().empty()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_model_name().data(), static_cast<int>(this->_internal_model_name().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"mavsdk.rpc.camera_server.Information.model_name");
target = stream->WriteStringMaybeAliased(
2, this->_internal_model_name(), target);
}
// string firmware_version = 3;
if (!this->_internal_firmware_version().empty()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_firmware_version().data(), static_cast<int>(this->_internal_firmware_version().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"mavsdk.rpc.camera_server.Information.firmware_version");
target = stream->WriteStringMaybeAliased(
3, this->_internal_firmware_version(), target);
}
// float focal_length_mm = 4;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_focal_length_mm = this->_internal_focal_length_mm();
uint32_t raw_focal_length_mm;
memcpy(&raw_focal_length_mm, &tmp_focal_length_mm, sizeof(tmp_focal_length_mm));
if (raw_focal_length_mm != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(4, this->_internal_focal_length_mm(), target);
}
// float horizontal_sensor_size_mm = 5;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_horizontal_sensor_size_mm = this->_internal_horizontal_sensor_size_mm();
uint32_t raw_horizontal_sensor_size_mm;
memcpy(&raw_horizontal_sensor_size_mm, &tmp_horizontal_sensor_size_mm, sizeof(tmp_horizontal_sensor_size_mm));
if (raw_horizontal_sensor_size_mm != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(5, this->_internal_horizontal_sensor_size_mm(), target);
}
// float vertical_sensor_size_mm = 6;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_vertical_sensor_size_mm = this->_internal_vertical_sensor_size_mm();
uint32_t raw_vertical_sensor_size_mm;
memcpy(&raw_vertical_sensor_size_mm, &tmp_vertical_sensor_size_mm, sizeof(tmp_vertical_sensor_size_mm));
if (raw_vertical_sensor_size_mm != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(6, this->_internal_vertical_sensor_size_mm(), target);
}
// uint32 horizontal_resolution_px = 7;
if (this->_internal_horizontal_resolution_px() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteUInt32ToArray(7, this->_internal_horizontal_resolution_px(), target);
}
// uint32 vertical_resolution_px = 8;
if (this->_internal_vertical_resolution_px() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteUInt32ToArray(8, this->_internal_vertical_resolution_px(), target);
}
// uint32 lens_id = 9;
if (this->_internal_lens_id() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteUInt32ToArray(9, this->_internal_lens_id(), target);
}
// uint32 definition_file_version = 10;
if (this->_internal_definition_file_version() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteUInt32ToArray(10, this->_internal_definition_file_version(), target);
}
// string definition_file_uri = 11;
if (!this->_internal_definition_file_uri().empty()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_definition_file_uri().data(), static_cast<int>(this->_internal_definition_file_uri().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"mavsdk.rpc.camera_server.Information.definition_file_uri");
target = stream->WriteStringMaybeAliased(
11, this->_internal_definition_file_uri(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.Information)
return target;
}
size_t Information::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.Information)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string vendor_name = 1;
if (!this->_internal_vendor_name().empty()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_vendor_name());
}
// string model_name = 2;
if (!this->_internal_model_name().empty()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_model_name());
}
// string firmware_version = 3;
if (!this->_internal_firmware_version().empty()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_firmware_version());
}
// string definition_file_uri = 11;
if (!this->_internal_definition_file_uri().empty()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_definition_file_uri());
}
// float focal_length_mm = 4;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_focal_length_mm = this->_internal_focal_length_mm();
uint32_t raw_focal_length_mm;
memcpy(&raw_focal_length_mm, &tmp_focal_length_mm, sizeof(tmp_focal_length_mm));
if (raw_focal_length_mm != 0) {
total_size += 1 + 4;
}
// float horizontal_sensor_size_mm = 5;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_horizontal_sensor_size_mm = this->_internal_horizontal_sensor_size_mm();
uint32_t raw_horizontal_sensor_size_mm;
memcpy(&raw_horizontal_sensor_size_mm, &tmp_horizontal_sensor_size_mm, sizeof(tmp_horizontal_sensor_size_mm));
if (raw_horizontal_sensor_size_mm != 0) {
total_size += 1 + 4;
}
// float vertical_sensor_size_mm = 6;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_vertical_sensor_size_mm = this->_internal_vertical_sensor_size_mm();
uint32_t raw_vertical_sensor_size_mm;
memcpy(&raw_vertical_sensor_size_mm, &tmp_vertical_sensor_size_mm, sizeof(tmp_vertical_sensor_size_mm));
if (raw_vertical_sensor_size_mm != 0) {
total_size += 1 + 4;
}
// uint32 horizontal_resolution_px = 7;
if (this->_internal_horizontal_resolution_px() != 0) {
total_size += ::_pbi::WireFormatLite::UInt32SizePlusOne(this->_internal_horizontal_resolution_px());
}
// uint32 vertical_resolution_px = 8;
if (this->_internal_vertical_resolution_px() != 0) {
total_size += ::_pbi::WireFormatLite::UInt32SizePlusOne(this->_internal_vertical_resolution_px());
}
// uint32 lens_id = 9;
if (this->_internal_lens_id() != 0) {
total_size += ::_pbi::WireFormatLite::UInt32SizePlusOne(this->_internal_lens_id());
}
// uint32 definition_file_version = 10;
if (this->_internal_definition_file_version() != 0) {
total_size += ::_pbi::WireFormatLite::UInt32SizePlusOne(this->_internal_definition_file_version());
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Information::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
Information::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Information::GetClassData() const { return &_class_data_; }
void Information::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<Information *>(to)->MergeFrom(
static_cast<const Information &>(from));
}
void Information::MergeFrom(const Information& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.Information)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (!from._internal_vendor_name().empty()) {
_internal_set_vendor_name(from._internal_vendor_name());
}
if (!from._internal_model_name().empty()) {
_internal_set_model_name(from._internal_model_name());
}
if (!from._internal_firmware_version().empty()) {
_internal_set_firmware_version(from._internal_firmware_version());
}
if (!from._internal_definition_file_uri().empty()) {
_internal_set_definition_file_uri(from._internal_definition_file_uri());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_focal_length_mm = from._internal_focal_length_mm();
uint32_t raw_focal_length_mm;
memcpy(&raw_focal_length_mm, &tmp_focal_length_mm, sizeof(tmp_focal_length_mm));
if (raw_focal_length_mm != 0) {
_internal_set_focal_length_mm(from._internal_focal_length_mm());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_horizontal_sensor_size_mm = from._internal_horizontal_sensor_size_mm();
uint32_t raw_horizontal_sensor_size_mm;
memcpy(&raw_horizontal_sensor_size_mm, &tmp_horizontal_sensor_size_mm, sizeof(tmp_horizontal_sensor_size_mm));
if (raw_horizontal_sensor_size_mm != 0) {
_internal_set_horizontal_sensor_size_mm(from._internal_horizontal_sensor_size_mm());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_vertical_sensor_size_mm = from._internal_vertical_sensor_size_mm();
uint32_t raw_vertical_sensor_size_mm;
memcpy(&raw_vertical_sensor_size_mm, &tmp_vertical_sensor_size_mm, sizeof(tmp_vertical_sensor_size_mm));
if (raw_vertical_sensor_size_mm != 0) {
_internal_set_vertical_sensor_size_mm(from._internal_vertical_sensor_size_mm());
}
if (from._internal_horizontal_resolution_px() != 0) {
_internal_set_horizontal_resolution_px(from._internal_horizontal_resolution_px());
}
if (from._internal_vertical_resolution_px() != 0) {
_internal_set_vertical_resolution_px(from._internal_vertical_resolution_px());
}
if (from._internal_lens_id() != 0) {
_internal_set_lens_id(from._internal_lens_id());
}
if (from._internal_definition_file_version() != 0) {
_internal_set_definition_file_version(from._internal_definition_file_version());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void Information::CopyFrom(const Information& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.Information)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Information::IsInitialized() const {
return true;
}
void Information::InternalSwap(Information* other) {
using std::swap;
auto* lhs_arena = GetArenaForAllocation();
auto* rhs_arena = other->GetArenaForAllocation();
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&vendor_name_, lhs_arena,
&other->vendor_name_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&model_name_, lhs_arena,
&other->model_name_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&firmware_version_, lhs_arena,
&other->firmware_version_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&definition_file_uri_, lhs_arena,
&other->definition_file_uri_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(Information, definition_file_version_)
+ sizeof(Information::definition_file_version_)
- PROTOBUF_FIELD_OFFSET(Information, focal_length_mm_)>(
reinterpret_cast<char*>(&focal_length_mm_),
reinterpret_cast<char*>(&other->focal_length_mm_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Information::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[8]);
}
// ===================================================================
class Position::_Internal {
public:
};
Position::Position(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.Position)
}
Position::Position(const Position& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&latitude_deg_, &from.latitude_deg_,
static_cast<size_t>(reinterpret_cast<char*>(&relative_altitude_m_) -
reinterpret_cast<char*>(&latitude_deg_)) + sizeof(relative_altitude_m_));
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.Position)
}
inline void Position::SharedCtor() {
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&latitude_deg_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&relative_altitude_m_) -
reinterpret_cast<char*>(&latitude_deg_)) + sizeof(relative_altitude_m_));
}
Position::~Position() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.Position)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void Position::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
}
void Position::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void Position::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.Position)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&latitude_deg_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&relative_altitude_m_) -
reinterpret_cast<char*>(&latitude_deg_)) + sizeof(relative_altitude_m_));
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Position::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// double latitude_deg = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 9)) {
latitude_deg_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr);
ptr += sizeof(double);
} else
goto handle_unusual;
continue;
// double longitude_deg = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 17)) {
longitude_deg_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr);
ptr += sizeof(double);
} else
goto handle_unusual;
continue;
// float absolute_altitude_m = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 29)) {
absolute_altitude_m_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// float relative_altitude_m = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 37)) {
relative_altitude_m_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* Position::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.Position)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// double latitude_deg = 1;
static_assert(sizeof(uint64_t) == sizeof(double), "Code assumes uint64_t and double are the same size.");
double tmp_latitude_deg = this->_internal_latitude_deg();
uint64_t raw_latitude_deg;
memcpy(&raw_latitude_deg, &tmp_latitude_deg, sizeof(tmp_latitude_deg));
if (raw_latitude_deg != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteDoubleToArray(1, this->_internal_latitude_deg(), target);
}
// double longitude_deg = 2;
static_assert(sizeof(uint64_t) == sizeof(double), "Code assumes uint64_t and double are the same size.");
double tmp_longitude_deg = this->_internal_longitude_deg();
uint64_t raw_longitude_deg;
memcpy(&raw_longitude_deg, &tmp_longitude_deg, sizeof(tmp_longitude_deg));
if (raw_longitude_deg != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteDoubleToArray(2, this->_internal_longitude_deg(), target);
}
// float absolute_altitude_m = 3;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_absolute_altitude_m = this->_internal_absolute_altitude_m();
uint32_t raw_absolute_altitude_m;
memcpy(&raw_absolute_altitude_m, &tmp_absolute_altitude_m, sizeof(tmp_absolute_altitude_m));
if (raw_absolute_altitude_m != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(3, this->_internal_absolute_altitude_m(), target);
}
// float relative_altitude_m = 4;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_relative_altitude_m = this->_internal_relative_altitude_m();
uint32_t raw_relative_altitude_m;
memcpy(&raw_relative_altitude_m, &tmp_relative_altitude_m, sizeof(tmp_relative_altitude_m));
if (raw_relative_altitude_m != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(4, this->_internal_relative_altitude_m(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.Position)
return target;
}
size_t Position::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.Position)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// double latitude_deg = 1;
static_assert(sizeof(uint64_t) == sizeof(double), "Code assumes uint64_t and double are the same size.");
double tmp_latitude_deg = this->_internal_latitude_deg();
uint64_t raw_latitude_deg;
memcpy(&raw_latitude_deg, &tmp_latitude_deg, sizeof(tmp_latitude_deg));
if (raw_latitude_deg != 0) {
total_size += 1 + 8;
}
// double longitude_deg = 2;
static_assert(sizeof(uint64_t) == sizeof(double), "Code assumes uint64_t and double are the same size.");
double tmp_longitude_deg = this->_internal_longitude_deg();
uint64_t raw_longitude_deg;
memcpy(&raw_longitude_deg, &tmp_longitude_deg, sizeof(tmp_longitude_deg));
if (raw_longitude_deg != 0) {
total_size += 1 + 8;
}
// float absolute_altitude_m = 3;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_absolute_altitude_m = this->_internal_absolute_altitude_m();
uint32_t raw_absolute_altitude_m;
memcpy(&raw_absolute_altitude_m, &tmp_absolute_altitude_m, sizeof(tmp_absolute_altitude_m));
if (raw_absolute_altitude_m != 0) {
total_size += 1 + 4;
}
// float relative_altitude_m = 4;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_relative_altitude_m = this->_internal_relative_altitude_m();
uint32_t raw_relative_altitude_m;
memcpy(&raw_relative_altitude_m, &tmp_relative_altitude_m, sizeof(tmp_relative_altitude_m));
if (raw_relative_altitude_m != 0) {
total_size += 1 + 4;
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Position::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
Position::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Position::GetClassData() const { return &_class_data_; }
void Position::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<Position *>(to)->MergeFrom(
static_cast<const Position &>(from));
}
void Position::MergeFrom(const Position& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.Position)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
static_assert(sizeof(uint64_t) == sizeof(double), "Code assumes uint64_t and double are the same size.");
double tmp_latitude_deg = from._internal_latitude_deg();
uint64_t raw_latitude_deg;
memcpy(&raw_latitude_deg, &tmp_latitude_deg, sizeof(tmp_latitude_deg));
if (raw_latitude_deg != 0) {
_internal_set_latitude_deg(from._internal_latitude_deg());
}
static_assert(sizeof(uint64_t) == sizeof(double), "Code assumes uint64_t and double are the same size.");
double tmp_longitude_deg = from._internal_longitude_deg();
uint64_t raw_longitude_deg;
memcpy(&raw_longitude_deg, &tmp_longitude_deg, sizeof(tmp_longitude_deg));
if (raw_longitude_deg != 0) {
_internal_set_longitude_deg(from._internal_longitude_deg());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_absolute_altitude_m = from._internal_absolute_altitude_m();
uint32_t raw_absolute_altitude_m;
memcpy(&raw_absolute_altitude_m, &tmp_absolute_altitude_m, sizeof(tmp_absolute_altitude_m));
if (raw_absolute_altitude_m != 0) {
_internal_set_absolute_altitude_m(from._internal_absolute_altitude_m());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_relative_altitude_m = from._internal_relative_altitude_m();
uint32_t raw_relative_altitude_m;
memcpy(&raw_relative_altitude_m, &tmp_relative_altitude_m, sizeof(tmp_relative_altitude_m));
if (raw_relative_altitude_m != 0) {
_internal_set_relative_altitude_m(from._internal_relative_altitude_m());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void Position::CopyFrom(const Position& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.Position)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Position::IsInitialized() const {
return true;
}
void Position::InternalSwap(Position* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(Position, relative_altitude_m_)
+ sizeof(Position::relative_altitude_m_)
- PROTOBUF_FIELD_OFFSET(Position, latitude_deg_)>(
reinterpret_cast<char*>(&latitude_deg_),
reinterpret_cast<char*>(&other->latitude_deg_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Position::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[9]);
}
// ===================================================================
class Quaternion::_Internal {
public:
};
Quaternion::Quaternion(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.Quaternion)
}
Quaternion::Quaternion(const Quaternion& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&w_, &from.w_,
static_cast<size_t>(reinterpret_cast<char*>(&z_) -
reinterpret_cast<char*>(&w_)) + sizeof(z_));
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.Quaternion)
}
inline void Quaternion::SharedCtor() {
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&z_) -
reinterpret_cast<char*>(&w_)) + sizeof(z_));
}
Quaternion::~Quaternion() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.Quaternion)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void Quaternion::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
}
void Quaternion::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void Quaternion::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.Quaternion)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&w_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&z_) -
reinterpret_cast<char*>(&w_)) + sizeof(z_));
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Quaternion::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// float w = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 13)) {
w_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// float x = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 21)) {
x_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// float y = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 29)) {
y_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
// float z = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 37)) {
z_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* Quaternion::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.Quaternion)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// float w = 1;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_w = this->_internal_w();
uint32_t raw_w;
memcpy(&raw_w, &tmp_w, sizeof(tmp_w));
if (raw_w != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(1, this->_internal_w(), target);
}
// float x = 2;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_x = this->_internal_x();
uint32_t raw_x;
memcpy(&raw_x, &tmp_x, sizeof(tmp_x));
if (raw_x != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(2, this->_internal_x(), target);
}
// float y = 3;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_y = this->_internal_y();
uint32_t raw_y;
memcpy(&raw_y, &tmp_y, sizeof(tmp_y));
if (raw_y != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(3, this->_internal_y(), target);
}
// float z = 4;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_z = this->_internal_z();
uint32_t raw_z;
memcpy(&raw_z, &tmp_z, sizeof(tmp_z));
if (raw_z != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteFloatToArray(4, this->_internal_z(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.Quaternion)
return target;
}
size_t Quaternion::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.Quaternion)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// float w = 1;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_w = this->_internal_w();
uint32_t raw_w;
memcpy(&raw_w, &tmp_w, sizeof(tmp_w));
if (raw_w != 0) {
total_size += 1 + 4;
}
// float x = 2;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_x = this->_internal_x();
uint32_t raw_x;
memcpy(&raw_x, &tmp_x, sizeof(tmp_x));
if (raw_x != 0) {
total_size += 1 + 4;
}
// float y = 3;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_y = this->_internal_y();
uint32_t raw_y;
memcpy(&raw_y, &tmp_y, sizeof(tmp_y));
if (raw_y != 0) {
total_size += 1 + 4;
}
// float z = 4;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_z = this->_internal_z();
uint32_t raw_z;
memcpy(&raw_z, &tmp_z, sizeof(tmp_z));
if (raw_z != 0) {
total_size += 1 + 4;
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Quaternion::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
Quaternion::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Quaternion::GetClassData() const { return &_class_data_; }
void Quaternion::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<Quaternion *>(to)->MergeFrom(
static_cast<const Quaternion &>(from));
}
void Quaternion::MergeFrom(const Quaternion& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.Quaternion)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_w = from._internal_w();
uint32_t raw_w;
memcpy(&raw_w, &tmp_w, sizeof(tmp_w));
if (raw_w != 0) {
_internal_set_w(from._internal_w());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_x = from._internal_x();
uint32_t raw_x;
memcpy(&raw_x, &tmp_x, sizeof(tmp_x));
if (raw_x != 0) {
_internal_set_x(from._internal_x());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_y = from._internal_y();
uint32_t raw_y;
memcpy(&raw_y, &tmp_y, sizeof(tmp_y));
if (raw_y != 0) {
_internal_set_y(from._internal_y());
}
static_assert(sizeof(uint32_t) == sizeof(float), "Code assumes uint32_t and float are the same size.");
float tmp_z = from._internal_z();
uint32_t raw_z;
memcpy(&raw_z, &tmp_z, sizeof(tmp_z));
if (raw_z != 0) {
_internal_set_z(from._internal_z());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void Quaternion::CopyFrom(const Quaternion& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.Quaternion)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Quaternion::IsInitialized() const {
return true;
}
void Quaternion::InternalSwap(Quaternion* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(Quaternion, z_)
+ sizeof(Quaternion::z_)
- PROTOBUF_FIELD_OFFSET(Quaternion, w_)>(
reinterpret_cast<char*>(&w_),
reinterpret_cast<char*>(&other->w_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Quaternion::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[10]);
}
// ===================================================================
class CaptureInfo::_Internal {
public:
static const ::mavsdk::rpc::camera_server::Position& position(const CaptureInfo* msg);
static const ::mavsdk::rpc::camera_server::Quaternion& attitude_quaternion(const CaptureInfo* msg);
};
const ::mavsdk::rpc::camera_server::Position&
CaptureInfo::_Internal::position(const CaptureInfo* msg) {
return *msg->position_;
}
const ::mavsdk::rpc::camera_server::Quaternion&
CaptureInfo::_Internal::attitude_quaternion(const CaptureInfo* msg) {
return *msg->attitude_quaternion_;
}
CaptureInfo::CaptureInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.CaptureInfo)
}
CaptureInfo::CaptureInfo(const CaptureInfo& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
file_url_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
file_url_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (!from._internal_file_url().empty()) {
file_url_.Set(from._internal_file_url(),
GetArenaForAllocation());
}
if (from._internal_has_position()) {
position_ = new ::mavsdk::rpc::camera_server::Position(*from.position_);
} else {
position_ = nullptr;
}
if (from._internal_has_attitude_quaternion()) {
attitude_quaternion_ = new ::mavsdk::rpc::camera_server::Quaternion(*from.attitude_quaternion_);
} else {
attitude_quaternion_ = nullptr;
}
::memcpy(&time_utc_us_, &from.time_utc_us_,
static_cast<size_t>(reinterpret_cast<char*>(&index_) -
reinterpret_cast<char*>(&time_utc_us_)) + sizeof(index_));
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.CaptureInfo)
}
inline void CaptureInfo::SharedCtor() {
file_url_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
file_url_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&position_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&index_) -
reinterpret_cast<char*>(&position_)) + sizeof(index_));
}
CaptureInfo::~CaptureInfo() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.CaptureInfo)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void CaptureInfo::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
file_url_.Destroy();
if (this != internal_default_instance()) delete position_;
if (this != internal_default_instance()) delete attitude_quaternion_;
}
void CaptureInfo::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void CaptureInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.CaptureInfo)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
file_url_.ClearToEmpty();
if (GetArenaForAllocation() == nullptr && position_ != nullptr) {
delete position_;
}
position_ = nullptr;
if (GetArenaForAllocation() == nullptr && attitude_quaternion_ != nullptr) {
delete attitude_quaternion_;
}
attitude_quaternion_ = nullptr;
::memset(&time_utc_us_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&index_) -
reinterpret_cast<char*>(&time_utc_us_)) + sizeof(index_));
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CaptureInfo::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.Position position = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_position(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// .mavsdk.rpc.camera_server.Quaternion attitude_quaternion = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) {
ptr = ctx->ParseMessage(_internal_mutable_attitude_quaternion(), ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// uint64 time_utc_us = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) {
time_utc_us_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// bool is_success = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 32)) {
is_success_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// int32 index = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 40)) {
index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// string file_url = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 50)) {
auto str = _internal_mutable_file_url();
ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
CHK_(::_pbi::VerifyUTF8(str, "mavsdk.rpc.camera_server.CaptureInfo.file_url"));
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* CaptureInfo::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.CaptureInfo)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.Position position = 1;
if (this->_internal_has_position()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, _Internal::position(this),
_Internal::position(this).GetCachedSize(), target, stream);
}
// .mavsdk.rpc.camera_server.Quaternion attitude_quaternion = 2;
if (this->_internal_has_attitude_quaternion()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(2, _Internal::attitude_quaternion(this),
_Internal::attitude_quaternion(this).GetCachedSize(), target, stream);
}
// uint64 time_utc_us = 3;
if (this->_internal_time_utc_us() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteUInt64ToArray(3, this->_internal_time_utc_us(), target);
}
// bool is_success = 4;
if (this->_internal_is_success() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteBoolToArray(4, this->_internal_is_success(), target);
}
// int32 index = 5;
if (this->_internal_index() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteInt32ToArray(5, this->_internal_index(), target);
}
// string file_url = 6;
if (!this->_internal_file_url().empty()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_file_url().data(), static_cast<int>(this->_internal_file_url().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"mavsdk.rpc.camera_server.CaptureInfo.file_url");
target = stream->WriteStringMaybeAliased(
6, this->_internal_file_url(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.CaptureInfo)
return target;
}
size_t CaptureInfo::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.CaptureInfo)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string file_url = 6;
if (!this->_internal_file_url().empty()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_file_url());
}
// .mavsdk.rpc.camera_server.Position position = 1;
if (this->_internal_has_position()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*position_);
}
// .mavsdk.rpc.camera_server.Quaternion attitude_quaternion = 2;
if (this->_internal_has_attitude_quaternion()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*attitude_quaternion_);
}
// uint64 time_utc_us = 3;
if (this->_internal_time_utc_us() != 0) {
total_size += ::_pbi::WireFormatLite::UInt64SizePlusOne(this->_internal_time_utc_us());
}
// bool is_success = 4;
if (this->_internal_is_success() != 0) {
total_size += 1 + 1;
}
// int32 index = 5;
if (this->_internal_index() != 0) {
total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_index());
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData CaptureInfo::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
CaptureInfo::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*CaptureInfo::GetClassData() const { return &_class_data_; }
void CaptureInfo::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<CaptureInfo *>(to)->MergeFrom(
static_cast<const CaptureInfo &>(from));
}
void CaptureInfo::MergeFrom(const CaptureInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.CaptureInfo)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (!from._internal_file_url().empty()) {
_internal_set_file_url(from._internal_file_url());
}
if (from._internal_has_position()) {
_internal_mutable_position()->::mavsdk::rpc::camera_server::Position::MergeFrom(from._internal_position());
}
if (from._internal_has_attitude_quaternion()) {
_internal_mutable_attitude_quaternion()->::mavsdk::rpc::camera_server::Quaternion::MergeFrom(from._internal_attitude_quaternion());
}
if (from._internal_time_utc_us() != 0) {
_internal_set_time_utc_us(from._internal_time_utc_us());
}
if (from._internal_is_success() != 0) {
_internal_set_is_success(from._internal_is_success());
}
if (from._internal_index() != 0) {
_internal_set_index(from._internal_index());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void CaptureInfo::CopyFrom(const CaptureInfo& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.CaptureInfo)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CaptureInfo::IsInitialized() const {
return true;
}
void CaptureInfo::InternalSwap(CaptureInfo* other) {
using std::swap;
auto* lhs_arena = GetArenaForAllocation();
auto* rhs_arena = other->GetArenaForAllocation();
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&file_url_, lhs_arena,
&other->file_url_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(CaptureInfo, index_)
+ sizeof(CaptureInfo::index_)
- PROTOBUF_FIELD_OFFSET(CaptureInfo, position_)>(
reinterpret_cast<char*>(&position_),
reinterpret_cast<char*>(&other->position_));
}
::PROTOBUF_NAMESPACE_ID::Metadata CaptureInfo::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[11]);
}
// ===================================================================
class CameraServerResult::_Internal {
public:
};
CameraServerResult::CameraServerResult(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) {
SharedCtor();
// @@protoc_insertion_point(arena_constructor:mavsdk.rpc.camera_server.CameraServerResult)
}
CameraServerResult::CameraServerResult(const CameraServerResult& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
result_str_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
result_str_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (!from._internal_result_str().empty()) {
result_str_.Set(from._internal_result_str(),
GetArenaForAllocation());
}
result_ = from.result_;
// @@protoc_insertion_point(copy_constructor:mavsdk.rpc.camera_server.CameraServerResult)
}
inline void CameraServerResult::SharedCtor() {
result_str_.InitDefault();
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
result_str_.Set("", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
result_ = 0;
}
CameraServerResult::~CameraServerResult() {
// @@protoc_insertion_point(destructor:mavsdk.rpc.camera_server.CameraServerResult)
if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) {
(void)arena;
return;
}
SharedDtor();
}
inline void CameraServerResult::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
result_str_.Destroy();
}
void CameraServerResult::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void CameraServerResult::Clear() {
// @@protoc_insertion_point(message_clear_start:mavsdk.rpc.camera_server.CameraServerResult)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
result_str_.ClearToEmpty();
result_ = 0;
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CameraServerResult::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::_pbi::ReadTag(ptr, &tag);
switch (tag >> 3) {
// .mavsdk.rpc.camera_server.CameraServerResult.Result result = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) {
uint64_t val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_result(static_cast<::mavsdk::rpc::camera_server::CameraServerResult_Result>(val));
} else
goto handle_unusual;
continue;
// string result_str = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) {
auto str = _internal_mutable_result_str();
ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
CHK_(::_pbi::VerifyUTF8(str, "mavsdk.rpc.camera_server.CameraServerResult.result_str"));
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* CameraServerResult::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:mavsdk.rpc.camera_server.CameraServerResult)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
// .mavsdk.rpc.camera_server.CameraServerResult.Result result = 1;
if (this->_internal_result() != 0) {
target = stream->EnsureSpace(target);
target = ::_pbi::WireFormatLite::WriteEnumToArray(
1, this->_internal_result(), target);
}
// string result_str = 2;
if (!this->_internal_result_str().empty()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_result_str().data(), static_cast<int>(this->_internal_result_str().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"mavsdk.rpc.camera_server.CameraServerResult.result_str");
target = stream->WriteStringMaybeAliased(
2, this->_internal_result_str(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:mavsdk.rpc.camera_server.CameraServerResult)
return target;
}
size_t CameraServerResult::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:mavsdk.rpc.camera_server.CameraServerResult)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string result_str = 2;
if (!this->_internal_result_str().empty()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_result_str());
}
// .mavsdk.rpc.camera_server.CameraServerResult.Result result = 1;
if (this->_internal_result() != 0) {
total_size += 1 +
::_pbi::WireFormatLite::EnumSize(this->_internal_result());
}
return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);
}
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData CameraServerResult::_class_data_ = {
::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck,
CameraServerResult::MergeImpl
};
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*CameraServerResult::GetClassData() const { return &_class_data_; }
void CameraServerResult::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to,
const ::PROTOBUF_NAMESPACE_ID::Message& from) {
static_cast<CameraServerResult *>(to)->MergeFrom(
static_cast<const CameraServerResult &>(from));
}
void CameraServerResult::MergeFrom(const CameraServerResult& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:mavsdk.rpc.camera_server.CameraServerResult)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (!from._internal_result_str().empty()) {
_internal_set_result_str(from._internal_result_str());
}
if (from._internal_result() != 0) {
_internal_set_result(from._internal_result());
}
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
}
void CameraServerResult::CopyFrom(const CameraServerResult& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:mavsdk.rpc.camera_server.CameraServerResult)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CameraServerResult::IsInitialized() const {
return true;
}
void CameraServerResult::InternalSwap(CameraServerResult* other) {
using std::swap;
auto* lhs_arena = GetArenaForAllocation();
auto* rhs_arena = other->GetArenaForAllocation();
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&result_str_, lhs_arena,
&other->result_str_, rhs_arena
);
swap(result_, other->result_);
}
::PROTOBUF_NAMESPACE_ID::Metadata CameraServerResult::GetMetadata() const {
return ::_pbi::AssignDescriptors(
&descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_getter, &descriptor_table_camera_5fserver_2fcamera_5fserver_2eproto_once,
file_level_metadata_camera_5fserver_2fcamera_5fserver_2eproto[12]);
}
// @@protoc_insertion_point(namespace_scope)
} // namespace camera_server
} // namespace rpc
} // namespace mavsdk
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::SetInformationRequest*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::SetInformationRequest >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::SetInformationRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::SetInformationResponse*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::SetInformationResponse >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::SetInformationResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::SetInProgressRequest*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::SetInProgressRequest >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::SetInProgressRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::SetInProgressResponse*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::SetInProgressResponse >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::SetInProgressResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::SubscribeTakePhotoRequest*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::SubscribeTakePhotoRequest >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::SubscribeTakePhotoRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::TakePhotoResponse*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::TakePhotoResponse >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::TakePhotoResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::RespondTakePhotoRequest*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::RespondTakePhotoRequest >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::RespondTakePhotoRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::RespondTakePhotoResponse*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::RespondTakePhotoResponse >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::RespondTakePhotoResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::Information*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::Information >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::Information >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::Position*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::Position >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::Position >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::Quaternion*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::Quaternion >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::Quaternion >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::CaptureInfo*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::CaptureInfo >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::CaptureInfo >(arena);
}
template<> PROTOBUF_NOINLINE ::mavsdk::rpc::camera_server::CameraServerResult*
Arena::CreateMaybeMessage< ::mavsdk::rpc::camera_server::CameraServerResult >(Arena* arena) {
return Arena::CreateMessageInternal< ::mavsdk::rpc::camera_server::CameraServerResult >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 40.331405 | 192 | 0.744459 | hamishwillee |
c4c097d367481bfdb40a6fdfc522bb94a6b33db3 | 13,071 | cpp | C++ | data/627.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/627.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/627.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int AJ,vaBae
,//y38
uvxYkLF , x94ea
, u1, u5//D
,JtNU ,/*Q*/
UR , ajM0,
Fuz
/*bOM*/, A, otxhG,ny ,/*DFb*/wLF /*gk*/,V,Ol ,w2s, Tf
,/**/SI7,
Ae4Z
,kw,
l1, f,aVQR ,WwiI
, md, z3BV8p
,Ko9i//6b
,FBUU9 ,SI2Uo ,//te
CMoBR,B3Jr ,
WKM, GOTsm/**/, Ks2 ,R , //X
Bjd ,Tmd
/*D*/
,
RDy9d ,
Z2eEw
,pJ7
,
ULa3J ,k9d , QKvV ,
VF5E4N
;
void
f_f0() {volatile int
o9 ,RbZ/*Pmc*/
,PV,
NaMa , bg
;if( true )
if(
true )
{{if(true )
{{int ticc,
V9 ;volatile int X7r/*I*/,cke , yN
; if(
true)V9 = yN +
X7r ;else ticc= cke; } }else ;
{{ return
; }
}/*Af4y*/{ int k5fL ;
volatile int m,xO1, sls;if//w
(
true/*4f*/
)
if ( true)
if//B
(true){ }else return ;
else ;else ;for/*pa4Y*/
(int i=1; i<1 ;++i )
k5fL= sls/**///8u
+ m+xO1 ;{
{
}}return ;}{//YcjP
;
{
{ /*C*/} { } } {
}}}
for //
(int i=1
;i<//
2
;++i//Fw40
){ volatile int MoZ0
, UT
,Y;
if( true
) ;/*FZtK*/ else//vu8c
{
int LNri; volatile int gZUho , dRH
,
V6z ;return ; LNri
=
V6z +gZUho/*w*/ +
dRH
; }
VF5E4N //BGc
= Y +
//a8aa
MoZ0+ UT ;
}for(int i=1;i< 3//j
;++i
)
{
volatile int xR7E ,nisr
,bGd ,lz , LM5
;if(
true) for (int i=1;i<4;++i) return ; else
AJ= LM5+ //qd
xR7E +nisr +bGd+lz;
{
{{ } {{}} { }} return ;};}}else
return
;else vaBae
=
bg
+ o9 + RbZ
+
PV
+
NaMa; {{
return ; return ;
}
for
(int i=1; i< 5
;++i
)return
;/*a*//*VWi*/;
{{//Bup
//w
volatile int uiY6,Sgk
, /**/EuPh ,//iA
Lm
; {
//XRvPV
} uvxYkLF =
Lm /*tE*/+uiY6+ /*y*/Sgk+
EuPh ;{} for(int i=1 ; i< 6//5k8C
;++i)
{ ; }
}{{ volatile int//i5N
ha4/*IF*/, nNh ,s50b ; {
}/**/ x94ea
=s50b
+ha4+
nNh//JL9
;}for(int i=1 ; i< 7
//j
;++i)return ;
} {{ if
( true
){}else{
}{for
(int i=1; i< 8 ;++i/*X*/ )//r
for(int
i=1
;i< //KhdC
9;++i )return
/*Umbrx*/ ;}
} }if( true )
{ for
(int i=1; i<//8ET
10 ;++i)//7J
//iU2
; if
(
true ){{ return ;}{ } }else
return //cD
;
} else
{
/*cpE*/volatile int
NfLMr , j0iC; ;u1 =j0iC + NfLMr ;
{ }}} }; for (int //gv
//blu
i=1
;
i<11 ;++i
) { {; {for (int i=1;
i<12;++i ){ //Ruy2
{ }
}for (int i=1//RqE
; i<13
;++i );{ return ;}
}{{} }} return ;
return//Dv2
; { {volatile int
fX ,
VejTz; for(int i=1 ; i<
14 ;++i);return
;
{ }
return ; if(true ) if (
true) {
;
}
else u5
=
VejTz +
fX/*1*/
;else return ;};}}return ; }void f_f1(){ volatile int w3n ,
rc4 ,QtaQ, A8
,EwE
, r9 ;for /*Q*/(int i=1/*z3*/
;i<15;++i ) {int eA2m
; volatile int oDETT,
Ne,
UP
,Vg/*5*/ , Fc,S
,
Ma0Y ,x3OJc6
,Gfq0 ;
{
{{}/*y*/ {
}/*GFyS*/{;
{
} return/**/ ;} for/*eA*/ (int
i=1
;i<16
;++i)return ; {} }
{
if (true)
{ if/*h*//*hiAGz*/(true
) //
return ;//ZaF
else {
{}
}
} else {}{}
{ {volatile int nPZ
;{}if (/*f*/
true) ; else JtNU
= nPZ
;}}{volatile int HMf,Z,//v
jeg; UR
=jeg + HMf +Z ;} { } }
for(int
//no
i=1//a
; /*Gk*/ i<
17;++i )return ; {
{}
} /*8*/}
ajM0=//8n7
Gfq0+ oDETT +Ne+ UP+Vg ;
for(int i=1 ; i< 18;++i
)
{volatile int
GY,ZCt//E1
,
//JG
KGF5
,SxK
;if (
true
)
Fuz =SxK +
GY+//9
ZCt+KGF5;else/*asVQ*/ {; for(int i=1;i<19
;++i )
{ {}{{ } if (true) {}else{}}} }if (true )
for(int i=1; i<20/*48v*/ ;++i
)/*s*/for
(int
i=1;i<
//q
21;++i ) if
(
true )
return ;else{
int I47
,
KS
;
//
volatile int O ,Xh, kodB , GooBuNt
;KS = GooBuNt+
O; I47 //W
=
Xh//EfzL
/*2uba*/+
kodB ;{ {
}
{
{
}{
volatile int urt;for(int i=1 ;
/*ELO0*/i< 22
;++i) A =urt ;//gQsh7
}
}return ;} } else{int MG/*fUs*/;
volatile int byApK , vg4mD,Gjzp , VVX ;for
(int
i=1; i<23;++i ){/*KY*/{ }
}MG =VVX+ byApK+vg4mD+/*70*/
Gjzp ;return /*2DJ*/ ;}
}{
for//aw
(int i=1 ;
i<24 ;++i)
return
; for//a08E
(int i=1
;i<
25 ;++i
) { for (int i=1;i<26;++i)//
{ {}
}}} {//07Z
;; return
;}
eA2m =
Fc +
S +Ma0Y +x3OJc6 ; } { volatile int
//H
gI4,
Paukv, l/*p*/, /*kuD*/T,
Ki
;/*Q*/
return ;otxhG
=
Ki +gI4//NWo
+
Paukv +l
+T
;
return ; {
volatile int
T5D , FTS,/*ZziVK*/PEJ ;
ny =
PEJ+
/*iZ1H*/ T5D//gyU
+FTS ;
;{{ int gH3//SR
;//8
volatile int HxQH,
//vd
fn , TckB
;
gH3= TckB/*os*/
+
//0
HxQH+fn;
for(int i=1;i< //
27 ;++i
)
return
;{ }}; {
for(int i=1;i< 28
;++i ) { } }{int UY;volatile int
Aw,in//Mn
;//TUF
{ //7rW
/*x*/}
for
(int i=1
;i</*Enw*/29;++i)UY= in+ Aw ;} }
}{ volatile int ubOEWn,X,
v33l,
Gn ;
wLF
= Gn+ ubOEWn +
X
+v33l;;{ //c
{}{
}; ;} } }
{ volatile int LgNjUb
,iJz, v/*1p*/,z
; {
;return ;
{
{
return ;} {;}
{ //k
}
}} { volatile int/*zc*/ cn//dcdo
, /*N1m*/Ck ,Y91A, HVF;
{{ volatile int FiZh;
V= FiZh;//XfS
}} for(int
i=1;
i<
30 ;++i)
Ol /*G*/
=HVF+ cn
//GzzF
+//lk
Ck +
Y91A;{
int
Tw;
volatile int
Knp ,
f3h//T5u
,SaO,
Vf
, AJr ,/**/RD6//
;
{} Tw= RD6 +
Knp /*gvP*/+f3h;{; } w2s=SaO
+ Vf +AJr//G
;} for(int i=1; i< 31;++i);} {{
{/*Fd*/ {}}}return ;
}Tf =z+ LgNjUb
+iJz+
v ;
{{ for (int i=1 ; i<32//2N
;++i ) for/*Q*/(int i=1
;i< 33 ;++i){
;}
}
{volatile int Rv, rdV3,Q0U;
SI7
=Q0U +
Rv +rdV3 ;{
}
} { return ; return ; {
{ }
;return ;/*uD*/{
}}}
{{
}{/*5F*/{
{ }
/*niC*/}}
}} {
{/*7vy*/;} {/**/for(int i=1 ;i<34
;++i) ; } for(int i=1
;i< /*b7g35*/35;++i){{ int zkjR
;volatile int YF,
HVN2O2z;zkjR
//
= HVN2O2z +YF;
for
(int
i=1
;i<36;++i) {}for (int i=1 ;/*T*/
i< 37;++i )
{
}{ }}for(int
/*vd*/ i=1 ; i<38;++i)if(true )
return/*VY*/ ;else ;
{ }}
}}
{{ {
{{}} //GoKfwy
;
{
}}for(int
i=1 ; //AWK6
/**/i< 39
;++i
)if(
true )
{ { }//Acp
} else ;
} { {{; {} }
} for(int
i=1
;
i<40 ;++i)
{int Q8WA ;volatile int/*Stv*/ M0wk0,
gz,FLnW/*Vf*/, z9K,/*qs*/ o5Tme/*uW4*/ , YZ
; /*E*/Ae4Z=
YZ+//yVp
M0wk0 +
gz
; if
( true ) ;
//
else for(int i=1
;
i<41;++i )
{} Q8WA=FLnW +z9K
+ /*T*/ o5Tme;
} }for (int i=1;
i<42
;++i) {{ return ;/*Kg*/ }{int
QF3jR ;volatile int ce62, hD8S
;
{} for//ZVcof
(int i=1
;i<43 ;++i)
;QF3jR
=hD8S +ce62 ;}}if ( true) {for (int i=1; i< 44
;++i ) //t
; {{}/*hv*/
{
{;{} return
; }} } } else
if(true)
{
//7
volatile int/*loF*/ Nr , B99lL, m0qN
, gk;
{ {
for/*JFK*//*vSCh*/ (int i=1; i<45;++i){//KtP
//0
}} {
} }if(true
){ //S7Jw
for (int
i=1//e8
;i<
46 ;++i) {volatile int/*71*/ MJWY
, Yh8L ,//
eJe;if ( true)
/*Wx*/ { }/*k*/else ;kw=
eJe +
MJWY+Yh8L ;
}
{for(int i=1
; i<
47;++i )
if
(true
)/*s*/
if ( true) return ;else{ for(int
i=1
;i<48 //SA
;++i)/*j*/ {
}
} else
{}{{}} }/**/} else l1 =gk
+//X
Nr+ B99lL+
m0qN
;{
/*M*/if/**/ (
true ){int Q7sa; volatile int/**/ e5,XojCf
; { } if(
true)Q7sa=
XojCf
+ e5
; else for(int i=1;i<49 ;++i ) return ;
}
else
for(int i=1 ; i<50;++i)
{
}}} else {
volatile int l0k,zaQZ,jqbHg2;//W5s
{if
( true
); else if (true){ }else
{{ }/*Hc*/} //M
{{{ }
}
}}
for//8aYZ
(int /*gY*/i=1; i< 51
;++i
) f/**/=
jqbHg2+
l0k+zaQZ/*8j*/ ;
for(int i=1;i<
52 //Bh
;++i){{{ }
} if
(
true )for
(int
i=1; i< 53
;++i/*z*/
) {//uOp
/*u*/{}}else {volatile int BGbu ,
Waeb;aVQR
= Waeb +BGbu ; } {//
{ } } } }}
WwiI = r9+w3n+ rc4
+ QtaQ +
A8+ EwE; return ;
return
; }void f_f2(){volatile int lo ,fkF
,
rMz,
OQt,nSgRK8 ; md= nSgRK8 +
lo//MUy
+
fkF +
rMz +OQt
; {
; {{for (int i=1
; i< 54;++i
) {
if
(true
//4l
)
{} else /*1L1*/ return ; return
;
return ;}
}{;{; {} if(/*B*/true ){volatile int wdi, PPg
;
return ;
z3BV8p = //E
PPg/*Q9d*/+/*m29*/
wdi ;} else //I
{}
} }return
;
/*i*/ return ;}for(int i=1;i<
55;++i) {volatile int//8f
pud,iWfNS,
khP/*b2I*/, sPu05Wo ; {; ;
{{ }for(int
i=1;i<56
;++i)
{/*m*/} {}{{ } ;}
}} return ;for
(int /*k*/i=1 ;i< 57 //sfl
;++i
){volatile int
b7 ,O0nEm,ILPJU; {
int B0 ;volatile int
/**/ hUlV, L ,
lP3zc; B0= lP3zc+ hUlV +L
; return ; }Ko9i= /*8o*/ILPJU +b7+O0nEm ;
;{}}
{ int sKOZ ;volatile int CqsXp ,
GReG,b ;sKOZ = b
+
CqsXp+GReG ;{
return ;} }
/**/
FBUU9 =
sPu05Wo /*So*/+
pud +iWfNS
+khP;} if(true)/*9p8*//*T*/{
{ int pRS; volatile int h4
,G2
;pRS//3
=
G2 +
h4 /*MM6*/ ; return ; } if(true)return ; /*A*/else if(true)
{{for
//Z
(int i=1 ;i< //l8BZ
58;++i)
{ }
}for
(int i=1 ; i<59;++i ) { } }else
for (int
i=1 ;
i<
60;++i ){{ { } } {/*UU*/volatile int
F31
;SI2Uo
=F31;}} } else
return
;
}
{ if//44jbl8y
(
/*YlE*/true)
{
for(int
i=1
;i<
61 ;++i/*EE6*/) { { {volatile int uq,
V6; for
(int /**/i=1 ;
i< 62;++i ) {
for (int i=1 ;
i<63;++i)
return
; }CMoBR
//o
= V6 +uq;}}{ { //dh
}} {
{
return ;
{
}
;}}
} { int ey ;volatile int gN
, tpIMK//XeC
,
cQ3I, OGU
;
ey =OGU +
gN + tpIMK
+ cQ3I ;
return ;}/*EL*/{{
for/*rEV*/
(int //
i=1 ;i<64/*Yysn*/;++i) ;/*C2i*/}{
for (int i=1;
i< 65
;++i )
{ }/*HPf*/} for
(int i=1//a
; i</*Z*/ 66;++i
) { }{ int
S6M9 ;volatile int au
/**/ , s ;{ } if
( true
) S6M9
= s+ au
;else
{}}}{for//kHl
(int i=1
;
i<67 ;++i)
{
if(
true ) ;else{}
}}}else{{
int SVN7; volatile int MFz
, hS3J
,RS2 ; if( /*xVAU*/true
){
}else if(true){{ { if( true
) { }else/*Vy*/ if(
true ) return ;//G
else{}
} //kz
}
} else ;SVN7
=//
RS2 +
MFz +hS3J; }//cK
{
if( true ){
/*mr1*/int GafAJ;
volatile int
kZ,Fihkt, e3rU
,Q; GafAJ=Q+kZ+Fihkt//RJ
+e3rU
; }else for(int
i=1
; i<
68;++i) {/*FCE*/volatile int FU7B
,BcB ,
F1Zq ;B3Jr=F1Zq +FU7B
/*ei*/+ BcB
/*h*/; }//jGy
{;}
{
{}//ty
} /*lX3*/}}
return
;{
if//
(true
)
; else{ return
;} //32
if(true){ {} {
{ /*tg6D*/ } //c
/*xj4m*/if
(true ) if (
true
)return
;
else{}
else {}}
} else ;{ if (true//vs1Q
)
return ;else{
{ }
}}} }
;return ; } int//m
main (){
volatile int
XSj,//i
g, //V
NtL//Ujb
,ph
,
yl
; { {/*cBMQ*/int
XnvYZ
; volatile int
z5bB,UU, q,//MDN
qp , jiw, Gb
,sF
; {{ { }//
} //R
//m
{ if
(
true
) ; //gM
/*qm*/else{//xGn
}/*zs*/{int ik;volatile int e;{
} ik = e;
}}//W
return 930134187 //
; }{ volatile int
kb78P ,
ZVNKO /**/; if
( true) //5
WKM =
ZVNKO+
kb78P//GkqYBn
;else/*4l*/ return 478038699;}//pJ
GOTsm=
sF +z5bB+UU
+q ;if//
(true) /*jbc*/XnvYZ/*LCKh*/=qp
+jiw+ Gb
;else{volatile int Zj , KGszh,Mz, Xe ;{} { } Ks2/*tP*/=Xe
+Zj
+KGszh+//
Mz ;}
}{/**/ for (int i=1
;i<
69;++i//vPV
){
volatile int MJ6
,
kO1xn6
; {volatile int m7mS4//fvZ
,
A2;
for
(int
i=1 ;i< 70 ;++i){{}for(int
i=1//3D
; i<
71//VH
;++i
)
return 46971695
;} if (
true ) {
; }
else if( true ) R/*Q48d*/
/*5TwJ2*/ = A2 +
m7mS4; else/*a*/{
}
{{} }
}
Bjd/**/=kO1xn6 +MJ6; return
1482348458;}for(int i=1
;i<72;++i) {//t
int Aca ;
volatile int FN2i,Pii8 ,
Li0DW ,G5 ;
{ {
int p;/*Ic*/volatile int lu1,gPe , BNJ4;return 293325026
;if
(true )p
=/*P*/ BNJ4 ;else if
( true) for
(int i=1;i< 73 ;++i ){ }else Tmd/*G8g*/=
lu1
+
gPe
; }
}
Aca =G5+
FN2i +Pii8+
Li0DW ;} if(true ){{ { if(
true);else
{}
{ }
} }} else if ( true ){//xPIo
if( true) return/*IT*/ 1538199053; else { {{{}} }} { } }
else {
{ }/*g7*/}}for
(int
i=1;i<74;++i )
{ if/**/( true) { int aB
;volatile int mN3 ,GLt;
aB=GLt
+mN3 ;}else if
(true )if
(true ) {volatile int
N10 ,/*YK*/
wU0d , n2Q
,
NMIB ;
RDy9d=NMIB
+N10 +wU0d+ n2Q;{ {
//4
{ }{} if(true
) {} else ; } } ;
}else
{for(int //DXj
i=1 ; i<75;++i ) {/*9b8*/return 2095662402 ; if(true
)if
( true
)//
;else return 1018612394
;
else for (int //z
i=1
;i<76
;++i ) {
{ }}}}
else //v
return 1774500152 ; {//yZQ
/*rd*/;}return 785199703
;}/*TBA*/} ;{ int
iJu
;
volatile int Rid28a,
dD ,lawf, jwO8Pc; { int hz;/*C*/ volatile int
jp
,//jTa
o,XoF,
lY
/**/; hz=lY+
jp
+o +XoF;
{{
}
{
}for (int
i=1; i<77 ;++i) { ; { int sf5w,Pvekk67 ; volatile int MBU2
,//
IDI,
hvM; for(int i=1;i< 78;++i//9Q
)Pvekk67
=hvM
;
sf5w = //lg
//k
MBU2+ IDI;; } if( true)
if ( true)return //DF
1232281831
; else for(int i=1 //k
;i<79 ;++i/*QAGq*/
) { }else {}//tKU
} } }
//N
{ int
G ; volatile int Niedt, tDAb , pba;return 92264665 //u2
;
if (true)
{ for(int
i=1
; i<
80
;++i/*oA*/){volatile int lO0p
;
Z2eEw =lO0p;
}} else
G =pba+Niedt+tDAb
;
;//c
/*fg*/}if( true
)if(
true )for
(int i=1//L
; i</*btyamH*/ 81;++i)/*Z3M*/ {
{{
{
}{
{}return 327558265 ;
} ;/**/
} }return 1572568547;}
else iJu
= jwO8Pc
+ Rid28a+
dD
+lawf
;else
for (int i=1
; i<
82 //U
;++i ){return
159735872//vag
//ep
; ;}
return 551747984 ; {
{
{
{
} ;{;} {}
}if( //mD
true);
else {
//
{
}/*2oG*/}{ return
1790378835; { ;
}}}
{for
(int i=1;
i< 83;++i){
} } {
for(int /*5*/ /*dO*/i=1 ;i<84 ;++i
){ } if(
true/*C4N*/ ) { {
} ;{
} } else{ {/*qopE*/ }{ }//
} }{/*p8Uk*/ for(int i=1 ;
i<85
;++i
)/*09q*/;//n1FN
}
{//TRf
volatile int lBG , Cq , cmPES
;
for
(int i=1 ;//
i< 86 ;++i //zhb
)pJ7 = cmPES + lBG
+
/*Z*/ Cq;
}if
(true )
{//e9fY1H
;} else //sz
{ {
{} }}//
}
} ULa3J = yl +XSj +g+
NtL
+ ph;{volatile int kl, IBy6,lD2u6QI,RsfHt
,KQ,VT
,//T
Qb, SCY ; /*KZ*//*IObjc*/k9d/*1*/=SCY+
kl +
/*7T6*/IBy6+
lD2u6QI; QKvV= RsfHt+KQ + VT + Qb/**/
; ;/*6*/}
} | 11.366087 | 66 | 0.461633 | TianyiChen |
c4c3479200066b5e42319d90e068c50b6b0cf80d | 14,588 | cpp | C++ | libs/fnd/cctype/test/src/unit_test_fnd_cctype_isgraph.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/cctype/test/src/unit_test_fnd_cctype_isgraph.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/cctype/test/src/unit_test_fnd_cctype_isgraph.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file unit_test_fnd_cctype_isgraph.cpp
*
* @brief isgraph のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/cctype/isgraph.hpp>
#include <bksge/fnd/config.hpp>
#include <gtest/gtest.h>
#include "constexpr_test.hpp"
namespace bksge_cctype_test
{
namespace isgraph_test
{
GTEST_TEST(CCTypeTest, IsGraphTest)
{
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x00)); // control codes (NUL, etc.)
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x08));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x09)); // tab (\t)
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x0A)); // whitespaces (\n, \v, \f, \r)
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x0D));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x0E)); // control codes
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x1F));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x20)); // space
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x21)); // !"#$%&'()*+,-./
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x2F));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x30)); // 0123456789
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x39));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x3A)); // :;<=>?@
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x40));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x41)); // ABCDEF
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x46));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x47)); // GHIJKLMNOPQRSTUVWXYZ
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x5A));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x5B)); // [\]^_`
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x60));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x61)); // abcdef
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x66));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x67)); // ghijklmnopqrstuvwxyz
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x7A));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x7B)); // {|}~
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(0x7E));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(0x7F)); // backspace character (DEL)
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(EOF));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(WEOF));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('0'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('1'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('2'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('3'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('4'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('5'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('6'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('7'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('8'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('9'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('A'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('B'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('C'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('D'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('E'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('F'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('G'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('H'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('I'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('J'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('K'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('L'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('M'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('N'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('O'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('P'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('Q'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('R'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('S'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('T'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('U'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('V'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('W'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('X'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('Y'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('Z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('a'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('b'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('c'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('d'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('e'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('f'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('g'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('h'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('i'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('j'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('k'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('l'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('m'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('n'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('o'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('p'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('q'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('r'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('s'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('t'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('u'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('v'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('w'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('x'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('y'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('!'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('"'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('#'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('$'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('%'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('&'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('\''));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('('));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(')'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('*'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('+'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(','));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('-'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('.'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('/'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(':'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(';'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('<'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('='));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('>'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('?'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('@'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('['));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('\\'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(']'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('^'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('_'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('`'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('{'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('|'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('}'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph('~'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(' '));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph('\f'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph('\n'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph('\r'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph('\t'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph('\v'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'0'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'1'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'2'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'3'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'4'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'5'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'6'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'7'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'8'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'9'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'A'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'B'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'C'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'D'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'E'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'F'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'G'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'H'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'I'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'J'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'K'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'L'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'M'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'N'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'O'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'P'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'Q'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'R'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'S'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'T'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'U'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'V'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'W'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'X'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'Y'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'Z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'a'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'b'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'c'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'd'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'e'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'f'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'g'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'h'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'i'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'j'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'k'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'l'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'm'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'n'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'o'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'p'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'q'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'r'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L's'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L't'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'u'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'v'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'w'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'x'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'y'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'!'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'"'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'#'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'$'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'%'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'&'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'\''));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'('));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L')'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'*'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'+'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L','));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'-'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'.'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'/'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L':'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L';'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'<'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'='));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'>'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'?'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'@'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'['));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'\\'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L']'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'^'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'_'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'`'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'{'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'|'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'}'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(L'~'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(L' '));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(L'\f'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(L'\n'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(L'\r'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(L'\t'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(L'\v'));
#if defined(BKSGE_HAS_CXX20_CHAR8_T)
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'0'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'9'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'A'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'Z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'a'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u8'!'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(u8' '));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(u8'\n'));
#endif
#if defined(BKSGE_HAS_CXX11_CHAR16_T)
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'0'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'9'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'A'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'Z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'a'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(u'!'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(u' '));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(u'\n'));
#endif
#if defined(BKSGE_HAS_CXX11_CHAR32_T)
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'0'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'9'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'A'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'Z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'a'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'z'));
BKSGE_CONSTEXPR_EXPECT_TRUE (bksge::isgraph(U'!'));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(U' '));
BKSGE_CONSTEXPR_EXPECT_FALSE(bksge::isgraph(U'\n'));
#endif
}
} // namespace isgraph_test
} // namespace bksge_cctype_test
| 48.304636 | 85 | 0.751234 | myoukaku |
c4c386ed6ec04217de9acf9177b5619084e84b1f | 1,612 | cpp | C++ | BOJ_solve/16583.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 4 | 2021-01-27T11:51:30.000Z | 2021-01-30T17:02:55.000Z | BOJ_solve/16583.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | null | null | null | BOJ_solve/16583.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 5 | 2021-01-27T11:46:12.000Z | 2021-05-06T05:37:47.000Z | #include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 5e18;
const long long mod = 1e9+7;
const long long hmod1 = 1e9+409;
const long long hmod2 = 1e9+433;
const long long base = 257;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
int n,m,c[200005];
int p[200005],o[200005],g;
vec v[200005];
struct Ans {int x,y,z;};
vector <Ans> ans;
int Find(int x) {return (p[x]^x ? p[x] = Find(p[x]) : x);}
int dfs(int x,int pr) {
int st = 0;
c[x] = 1;
for(int i : v[x]) {
if(i == pr) continue;
int tmp = dfs(i,x);
if(tmp) {
if(st) ans.pb({o[st],o[x],o[i]}), st = 0;
else st = i;
}
}
if(st&&pr != -1) {
ans.pb({o[st],o[x],o[pr]});
return 0;
}
return 1;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
cin >> n >> m; g = n;
for(int i = 1;i <= n;i++) p[i] = o[i] = i;
for(int i = 1;i <= m;i++) {
int x,y; cin >> x >> y;
if(Find(x)^Find(y)) v[x].pb(y), v[y].pb(x), p[Find(y)] = Find(x);
else v[x].pb(++g), v[g].pb(x), o[g] = y;
}
for(int i = 1;i <= g;i++) {
if(!c[i]) dfs(i,-1);
}
cout << ans.size() << '\n';
for(Ans i : ans) cout << i.x << ' ' << i.y << ' ' << i.z << '\n';
}
| 24.424242 | 73 | 0.519231 | python-programmer1512 |
c4c42acc715932ef9b303cad4b0597f08c75f643 | 1,142 | cpp | C++ | Stack/Stack_01_IMPLEMENT_USING_ARRAY.cpp | compl3xX/ROAD-TO-DSA | 2261c112135a51d9d88c4b57e6f062f6b32550a7 | [
"MIT"
] | null | null | null | Stack/Stack_01_IMPLEMENT_USING_ARRAY.cpp | compl3xX/ROAD-TO-DSA | 2261c112135a51d9d88c4b57e6f062f6b32550a7 | [
"MIT"
] | null | null | null | Stack/Stack_01_IMPLEMENT_USING_ARRAY.cpp | compl3xX/ROAD-TO-DSA | 2261c112135a51d9d88c4b57e6f062f6b32550a7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack
{
int top;
public:
int a[MAX];
Stack() { top = -1; }
void push(int x);
int pop();
int peek();
bool isempty();
};
void Stack::push(int x)
{
if (top >= (MAX - 1))
{
cout << "Stack Overflow";
}
else
{
a[++top] = x;
cout << x << "Pushed into Stack\n";
}
}
int Stack::pop()
{
if (top < 0)
{
cout << "Stack is Empty";
return 0;
}
else
{
int x = a[top--];
return x;
}
}
int Stack::peek()
{
if (top < 0)
{
cout << "Stack is Empty";
return 0;
}
else
{
int x = a[top];
return x;
}
}
bool Stack::isempty()
{
return (top < 0);
}
int main()
{
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from the stack\n ";
cout << "Elements present in the stack ";
while (!s.isempty())
{
cout << s.peek() << " ";
s.pop();
}
return 0;
}
| 15.226667 | 52 | 0.408056 | compl3xX |
c4c4e01696c18cdeaa7407ac894763a2ce5802da | 3,552 | hpp | C++ | apps/Cocles/old_src/ledger/internal/Database.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | 1 | 2022-02-11T21:25:53.000Z | 2022-02-11T21:25:53.000Z | apps/Cocles/old_src/ledger/internal/Database.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | 15 | 2021-08-21T13:41:29.000Z | 2022-03-08T14:13:43.000Z | apps/Cocles/old_src/ledger/internal/Database.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | null | null | null | // License: The Unlicense (https://unlicense.org)
#ifndef COCLES_LEDGER_INTERNAL_DATABASE_HPP
#define COCLES_LEDGER_INTERNAL_DATABASE_HPP
#include "AccountEntry.hpp"
#include "AccountTypeEntry.hpp"
#include "AdjustmentEntry.hpp"
#include "FilteredTableView.hpp"
#include "RecordKeeper.hpp"
#include "TransactionEntry.hpp"
template <typename TYPE> struct TableView;
struct Database {
Database();
// Methods for querying AccountTypes
TableView<AccountType> get_account_type_table() const;
const std::string& get_name(AccountTypeEntry record) const;
AccountTypeEntry find_account_type_by_name(const std::string& name) const;
// Methods for interacting with Accounts
TableView<Account> get_account_table() const;
AccountEntry new_account();
AccountEntry new_account(const std::string& name, AccountTypeEntry type);
void clear_account_table();
void delete_account(AccountEntry record);
const std::string& get_name(AccountEntry record) const;
void set_name(AccountEntry record, const std::string& name);
AccountEntry find_account_by_name(const std::string& name) const;
AccountTypeEntry get_type(AccountEntry record) const;
void set_type(AccountEntry record, AccountTypeEntry type);
// TODO(tybl): find_account_by_type should be able to return many AccountEntrys
FilteredTableView<Account> find_account_by_type(AccountTypeEntry type) const;
// Methods for interacting with Transactions
TableView<Transaction> get_transaction_table() const;
TransactionEntry new_transaction();
TransactionEntry new_transaction(const date::year_month_day& date, const std::string& memo);
void clear_transaction_table();
void delete_transaction(TransactionEntry record);
const date::year_month_day get_date(TransactionEntry record) const;
void set_date(TransactionEntry record, const date::year_month_day& date);
// TODO(tybl): find_transaction_by_date should be able to return many TransactionEntrys
FilteredTableView<Transaction> find_transaction_by_date(const date::year_month_day& date) const;
const std::string& get_memo(TransactionEntry record) const;
void set_memo(TransactionEntry record, const std::string& memo);
TransactionEntry find_transaction_by_memo(const std::string& memo) const;
// Methods for interacting with Adjustments
TableView<Adjustment> get_adjustment_table() const;
AdjustmentEntry new_adjustment();
AdjustmentEntry new_adjustment(AccountEntry account, TransactionEntry transaction);
void clear_adjustment_table();
void delete_adjustment(AdjustmentEntry record);
AccountEntry get_account(AdjustmentEntry record) const;
void set_account(AdjustmentEntry record, AccountEntry account);
// TODO(tybl): find_adjustment_by_account shoule be able to return many AdjustmentEntrys
AdjustmentEntry find_adjustment_by_account(AccountEntry account) const;
TransactionEntry get_transaction(AdjustmentEntry record) const;
void set_transaction(AdjustmentEntry record, TransactionEntry transaction);
// TODO(tybl): find_adjustment_by_transaction should be able to return many AdjustmentEntrys
AdjustmentEntry find_adjustment_by_transaction(TransactionEntry transaction) const;
private:
ledger::internal::RecordKeeper<Account> account_table;
ledger::internal::RecordKeeper<AccountType> account_type_table;
ledger::internal::RecordKeeper<Adjustment> adjustment_table;
ledger::internal::RecordKeeper<Transaction> transaction_table;
};
#endif // COCLES_LEDGER_INTERNAL_DATABASE_HPP
| 33.509434 | 99 | 0.798142 | tybl |
c4c5967a1fdc234c240577ee2dc274dfb50c5df2 | 9,922 | cpp | C++ | OcularCore/src/Scene/Routines/FreeFlyController.cpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 8 | 2017-01-27T01:06:06.000Z | 2020-11-05T20:23:19.000Z | OcularCore/src/Scene/Routines/FreeFlyController.cpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 39 | 2016-06-03T02:00:36.000Z | 2017-03-19T17:47:39.000Z | OcularCore/src/Scene/Routines/FreeFlyController.cpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 4 | 2019-05-22T09:13:36.000Z | 2020-12-01T03:17:45.000Z | /**
* Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)
*
* 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 "Scene/Routines/FreeFlyController.hpp"
#include "Scene/SceneObject.hpp"
#include "Events/Events/KeyboardInputEvent.hpp"
#include "Math/Matrix3x3.hpp"
#include "OcularEngine.hpp"
OCULAR_REGISTER_ROUTINE(Ocular::Core::FreeFlyController, "FreeFlyController")
namespace
{
const float StaticSensitivityScale = 0.001f; ///< Default scaling applied to mouse looking, as even a sensitivity of 1.0 is extremely high.
}
//------------------------------------------------------------------------------------------
namespace Ocular
{
namespace Core
{
//----------------------------------------------------------------------------------
// CONSTRUCTORS
//----------------------------------------------------------------------------------
FreeFlyController::FreeFlyController()
: ARoutine("FreeFlyController", "FreeFlyController"),
m_LookSensitivity(1.0f),
m_MovementSpeed(1.0f),
m_BurstModifier(5.0f),
m_PreventRoll(true),
m_IsInBurst(false)
{
OcularEvents->registerListener(this, Priority::Medium);
OCULAR_EXPOSE(m_LookSensitivity);
OCULAR_EXPOSE(m_MovementSpeed);
OCULAR_EXPOSE(m_BurstModifier);
OCULAR_EXPOSE(m_BurstModifier);
OCULAR_EXPOSE(m_IsInBurst);
}
FreeFlyController::~FreeFlyController()
{
OcularEvents->unregisterListener(this);
}
//----------------------------------------------------------------------------------
// PUBLIC METHODS
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Inherited Methods
//----------------------------------------------------------------------------------
void FreeFlyController::onUpdate(float const delta)
{
ARoutine::onUpdate(delta);
if(m_Parent)
{
handleMovement(delta);
handleMouseRotation();
}
}
bool FreeFlyController::onEvent(std::shared_ptr<AEvent> event)
{
if(event->isType<KeyboardInputEvent>())
{
KeyboardInputEvent* inputEvent = dynamic_cast<KeyboardInputEvent*>(event.get());
switch(inputEvent->key)
{
case KeyboardKeys::W:
case KeyboardKeys::UpArrow:
{
if(inputEvent->state == KeyState::Pressed)
{
m_MovementVector.z = -1.0f;
}
else
{
m_MovementVector.z = 0.0f;
}
break;
}
case KeyboardKeys::A:
case KeyboardKeys::LeftArrow:
{
if(inputEvent->state == KeyState::Pressed)
{
m_MovementVector.x = -1.0f;
}
else
{
m_MovementVector.x = 0.0f;
}
break;
}
case KeyboardKeys::S:
case KeyboardKeys::DownArrow:
{
if(inputEvent->state == KeyState::Pressed)
{
m_MovementVector.z = 1.0f;
}
else
{
m_MovementVector.z = 0.0f;
}
break;
}
case KeyboardKeys::D:
case KeyboardKeys::RightArrow:
{
if(inputEvent->state == KeyState::Pressed)
{
m_MovementVector.x = 1.0f;
}
else
{
m_MovementVector.x = 0.0f;
}
break;
}
case KeyboardKeys::Q:
{
if(inputEvent->state == KeyState::Pressed)
{
m_MovementVector.y = 1.0f;
}
else
{
m_MovementVector.y = 0.0f;
}
break;
}
case KeyboardKeys::Z:
{
if(inputEvent->state == KeyState::Pressed)
{
m_MovementVector.y = -1.0f;
}
else
{
m_MovementVector.y = 0.0f;
}
break;
}
case KeyboardKeys::ShiftLeft:
{
if(inputEvent->state == KeyState::Pressed)
{
m_IsInBurst = true;
}
else
{
m_IsInBurst = false;
}
break;
}
case KeyboardKeys::Space:
{
if(inputEvent->state == KeyState::Released)
{
if(m_Parent)
{
m_Euler.x = 0.0f;
m_Euler.y = 0.0f;
m_Parent->resetRotation();
}
}
break;
}
default:
break;
}
}
return true;
}
//----------------------------------------------------------------------------------
// Controller Specific Methods
//----------------------------------------------------------------------------------
void FreeFlyController::setLookSensitivity(float sensitivity)
{
m_LookSensitivity = sensitivity;
}
float FreeFlyController::getLookSensitivity() const
{
return m_LookSensitivity;
}
void FreeFlyController::setMovementSpeed(float speed)
{
m_MovementSpeed = speed;
}
float FreeFlyController::getMovementSpeed() const
{
return m_MovementSpeed;
}
void FreeFlyController::setBurstSpeedModifier(float modifier)
{
m_BurstModifier = modifier;
}
float FreeFlyController::getBurstSpeedModifier() const
{
return m_BurstModifier;
}
void FreeFlyController::setPreventRoll(bool prevent)
{
m_PreventRoll = prevent;
}
bool FreeFlyController::getPreventRoll() const
{
return m_PreventRoll;
}
//----------------------------------------------------------------------------------
// PROTECTED METHODS
//----------------------------------------------------------------------------------
void FreeFlyController::handleMovement(float delta)
{
float speed = m_MovementSpeed;
if(m_IsInBurst)
{
speed *= m_BurstModifier;
}
m_Parent->translate(m_MovementVector * speed * delta);
}
void FreeFlyController::handleMouseRotation()
{
const Math::Vector2i currentMousePos = OcularInput->getMousePosition();
if(currentMousePos != m_LastMousePos)
{
const float dX = (static_cast<float>(currentMousePos.x) - static_cast<float>(m_LastMousePos.x)) * (StaticSensitivityScale * m_LookSensitivity);
const float dY = (static_cast<float>(currentMousePos.y) - static_cast<float>(m_LastMousePos.y)) * (StaticSensitivityScale * m_LookSensitivity);
if(m_PreventRoll)
{
m_Euler.x += -dY;
m_Euler.y += -dX;
m_Parent->setRotation(Math::Quaternion(m_Euler));
}
else
{
Math::Quaternion rotation = Math::Quaternion(Math::Vector3f(-dX, dY, 0.0f));
m_Parent->rotate(rotation);
Math::Quaternion rotX = Math::Quaternion(Math::Vector3f(-dX, 0.0f, 0.0f));
Math::Quaternion rotY = Math::Quaternion(Math::Vector3f(0.0f, dY, 0.0f));
m_Parent->rotate(rotY);
m_Parent->rotate(rotX);
}
m_LastMousePos = currentMousePos;
}
}
//----------------------------------------------------------------------------------
// PRIVATE METHODS
//----------------------------------------------------------------------------------
}
} | 31.398734 | 159 | 0.395586 | ssell |
c4cc1dc3cdae8ced08454b7bd6976ab3a3f096e7 | 809 | cpp | C++ | Documents/RacimoAire/Libreria/Prueba3PMS/mainwindow.cpp | JoseSalamancaCoy/RACIMO_AIRE | 628d6ff184a30af0efd25bff675b0006500d4ba2 | [
"MIT"
] | null | null | null | Documents/RacimoAire/Libreria/Prueba3PMS/mainwindow.cpp | JoseSalamancaCoy/RACIMO_AIRE | 628d6ff184a30af0efd25bff675b0006500d4ba2 | [
"MIT"
] | null | null | null | Documents/RacimoAire/Libreria/Prueba3PMS/mainwindow.cpp | JoseSalamancaCoy/RACIMO_AIRE | 628d6ff184a30af0efd25bff675b0006500d4ba2 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#define GPIOSet 16
#define GPIOReSet 12
#define GPIORX 26
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
GPIO = new Crpigpio;
PMSSensor = new PMS(GPIO,GPIOSet, GPIOReSet, GPIORX);
connect(PMSSensor, SIGNAL(newData(uint16_t,uint16_t,uint16_t)),this, SLOT(newDataPMS(uint16_t,uint16_t,uint16_t)));
}
MainWindow::~MainWindow()
{
PMSSensor->sleep();
delete PMSSensor;
delete GPIO,
delete ui;
}
void MainWindow::newDataPMS(uint16_t PM_1_0, uint16_t PM_2_5, uint16_t PM_10)
{
QString comando= "clear";
system(qPrintable(comando));
qDebug() << "Data PM1 ="<< PM_1_0;
qDebug() << "Data PM2.5 ="<< PM_2_5;
qDebug() << "Data PM10 ="<< PM_10;
}
| 23.794118 | 119 | 0.677379 | JoseSalamancaCoy |
c4cdce569be7011bc86b2d30d36a72431a396384 | 2,567 | cpp | C++ | src/ui/gtk3/window/FileSelectWindow.cpp | jmdaemon/oggex | ae6153c021cbbfb784ffee5da4b1769d3fbf5617 | [
"MIT"
] | null | null | null | src/ui/gtk3/window/FileSelectWindow.cpp | jmdaemon/oggex | ae6153c021cbbfb784ffee5da4b1769d3fbf5617 | [
"MIT"
] | null | null | null | src/ui/gtk3/window/FileSelectWindow.cpp | jmdaemon/oggex | ae6153c021cbbfb784ffee5da4b1769d3fbf5617 | [
"MIT"
] | null | null | null | #include "FileSelectWindow.h"
#include <iostream>
#include <exception>
FileSelectWindow::FileSelectWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refBuilder)
: Gtk::ApplicationWindow(cobject), m_refBuilder(refBuilder) {
}
//: Gtk::ApplicationWindow(cobject), m_refBuilder(refBuilder), m_Button_File("Choose File"), m_Button_Folder("Choose Folder") {
FileSelectWindow* FileSelectWindow::create() {
//auto refBuilder = Gtk::Builder::create_from_file("../../Dashboard.glade");
//auto refBuilder = Gtk::Builder::create_from_resource("");
auto refBuilder = Gtk::Builder::create_from_file("resources/xml/FileSelect.glade");
FileSelectWindow* window = nullptr;
refBuilder->get_widget_derived("FileSelect", window);
if (!window)
throw std::runtime_error("No \"FileSelect\" object in FileSelect.glade");
return window;
}
void FileSelectWindow::open_file_view(const Glib::RefPtr<Gio::File>&) { }
//void FileSelectWindow::on_button_folder_clicked() {
//Gtk::FileChooserDialog dialog("Please choose a folder", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
//dialog.set_transient_for(*this);
//dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
//dialog.add_button("Select", Gtk::RESPONSE_OK);
//int result = dialog.run();
//switch(result) {
//case(Gtk::RESPONSE_OK): {
//std::cout << "Select clicked." << std::endl;
//std::cout << "Folder selected: " << dialog.get_filename()
//<< std::endl;
//break;
//}
//case(Gtk::RESPONSE_CANCEL): {
//std::cout << "Cancel clicked." << std::endl;
//break;
//}
//default: {
//std::cout << "Unexpected button clicked." << std::endl;
//break;
//}
//}
//}
//void FileSelectWindow::on_button_file_clicked() {
//Gtk::FileChooserDialog dialog("Please choose a file",
//Gtk::FILE_CHOOSER_ACTION_OPEN);
//dialog.set_transient_for(*this);
////Add response buttons the the dialog:
//dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
//dialog.add_button("_Open", Gtk::RESPONSE_OK);
//int result = dialog.run();
//switch(result) {
//case(Gtk::RESPONSE_OK): {
//std::cout << "Open clicked." << std::endl;
//std::string filename = dialog.get_filename();
//std::cout << "File selected: " << filename << std::endl;
//break;
//}
//case(Gtk::RESPONSE_CANCEL): {
//std::cout << "Cancel clicked." << std::endl;
//break;
//}
//default: {
//std::cout << "Unexpected button clicked." << std::endl;
//break;
//}
//}
//}
| 29.848837 | 127 | 0.643553 | jmdaemon |
c4d16931a4b2c2f323dd4905eb1e62c6304aefc9 | 2,395 | cpp | C++ | BOJ/06000~06999/6000~6099/6091.cpp | shinkeonkim/today-ps | f3e5e38c5215f19579bb0422f303a9c18c626afa | [
"Apache-2.0"
] | 2 | 2020-01-29T06:54:41.000Z | 2021-11-07T13:23:27.000Z | BOJ/06000~06999/6000~6099/6091.cpp | shinkeonkim/Today_PS | bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44 | [
"Apache-2.0"
] | null | null | null | BOJ/06000~06999/6000~6099/6091.cpp | shinkeonkim/Today_PS | bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#define for1(s,n) for(int i = s; i < n; i++)
#define for1j(s,n) for(int j = s; j < n; j++)
#define foreach(k) for(auto i : k)
#define foreachj(k) for(auto j : k)
#define pb(a) push_back(a)
#define sz(a) a.size()
#define INF (ll)1e18
#define MAX 1100
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef vector <int> iv1;
typedef vector <vector<int>> iv2;
typedef vector <ll> llv1;
typedef vector <llv1> llv2;
typedef unsigned int uint;
typedef vector <ull> ullv1;
typedef vector <vector <ull>> ullv2;
ll N;
struct edge {
ll crt;
ll node, cost;
};
struct WGraph {
ll V;
vector<edge> adj[MAX];
vector<ll> prev;
WGraph(ll V) : V{V} {}
void addEdge(ll s, ll e, ll cost) {
adj[s].push_back({s, e, cost});
adj[e].push_back({e, s, cost});
}
ll prim(vector<edge> &selected) { // selected에 선택된 간선정보 vector 담김
selected.clear();
vector<bool> added(V, false);
llv1 minWeight(V, INF), parent(V, -1);
ll ret = 0;
minWeight[0] = parent[0] = 0;
for (int iter = 0; iter < V; iter++) {
int u = -1;
for (int v = 0; v < V; v++) {
if (!added[v] && (u == -1 || minWeight[u]>minWeight[v]))
u = v;
}
if (parent[u] != u)
selected.push_back({parent[u], u, minWeight[u]});
ret += minWeight[u];
added[u] = true;
for1(0, sz(adj[u])) {
int v = adj[u][i].node, weight = adj[u][i].cost;
if (!added[v] && minWeight[v]>weight) {
parent[v] = u;
minWeight[v] = weight;
}
}
}
return ret;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N;
WGraph W = WGraph(N);
for1(0, N-1) {
for1j(i+1, N) {
ll a;
cin >> a;
W.addEdge(i,j,a);
}
}
vector <edge> ret;
ll ans = W.prim(ret);
llv1 V[N];
foreach(ret) {
V[i.crt].pb(i.node);
V[i.node].pb(i.crt);
}
for1(0, N) {
cout << V[i].size() << " ";
sort(V[i].begin(), V[i].end());
foreachj(V[i]) {
cout << j + 1 << " ";
}
cout <<"\n";
}
} | 22.383178 | 72 | 0.460125 | shinkeonkim |
c4d46b3df02f299b3d31c1640d207587e516ceb8 | 6,094 | cpp | C++ | examples/imgui/main.cpp | jayrulez/LLGI | a0836e6db18e444d4534deb8eedb18263439fc4c | [
"Zlib"
] | 166 | 2019-06-19T19:51:45.000Z | 2022-03-24T13:03:29.000Z | examples/imgui/main.cpp | jayrulez/LLGI | a0836e6db18e444d4534deb8eedb18263439fc4c | [
"Zlib"
] | 312 | 2019-06-13T19:39:25.000Z | 2022-03-02T18:37:22.000Z | examples/imgui/main.cpp | jayrulez/LLGI | a0836e6db18e444d4534deb8eedb18263439fc4c | [
"Zlib"
] | 23 | 2019-10-04T11:02:21.000Z | 2021-12-24T16:34:52.000Z |
#ifdef _WIN32
#define GLFW_EXPOSE_NATIVE_WIN32 1
#endif
#ifdef __APPLE__
#define GLFW_EXPOSE_NATIVE_COCOA 1
#endif
#ifdef __linux__
#define GLFW_EXPOSE_NATIVE_X11 1
#undef Always
#endif
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#ifdef __linux__
#undef Always
#endif
#include <LLGI.CommandList.h>
#include <LLGI.Graphics.h>
#include <LLGI.Platform.h>
#include <LLGI.Texture.h>
#ifdef _WIN32
#pragma comment(lib, "d3dcompiler.lib")
#elif __APPLE__
#endif
// Use a library to use imgui with LLGI
#include <ImGuiPlatform.h>
#ifdef _WIN32
#include <ImGuiPlatformDX12.h>
#elif __APPLE__
#include <ImGuiPlatformMetal.h>
#endif
#ifdef ENABLE_VULKAN
#include <ImGuiPlatformVulkan.h>
#endif
#include <imgui_impl_glfw.h>
class LLGIWindow : public LLGI::Window
{
GLFWwindow* window_ = nullptr;
public:
LLGIWindow(GLFWwindow* window) : window_(window) {}
bool OnNewFrame() override { return glfwWindowShouldClose(window_) == GL_FALSE; }
void* GetNativePtr(int32_t index) override
{
#ifdef _WIN32
if (index == 0)
{
return glfwGetWin32Window(window_);
}
return (HINSTANCE)GetModuleHandle(0);
#endif
#ifdef __APPLE__
return glfwGetCocoaWindow(window_);
#endif
#ifdef __linux__
if (index == 0)
{
return glfwGetX11Display();
}
return reinterpret_cast<void*>(glfwGetX11Window(window_));
#endif
}
LLGI::Vec2I GetWindowSize() const override
{
int w, h;
glfwGetWindowSize(window_, &w, &h);
return LLGI::Vec2I(w, h);
}
LLGI::Vec2I GetFrameBufferSize() const override
{
int w, h;
glfwGetFramebufferSize(window_, &w, &h);
return LLGI::Vec2I(w, h);
}
};
static void glfw_error_callback(int error, const char* description) { fprintf(stderr, "Glfw Error %d: %s\n", error, description); }
int main()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
auto window = glfwCreateWindow(1280, 720, "Example imgui", nullptr, nullptr);
auto llgiwindow = new LLGIWindow(window);
LLGI::DeviceType deviceType = LLGI::DeviceType::Default;
#ifdef ENABLE_VULKAN
deviceType = LLGI::DeviceType::Vulkan;
#endif
LLGI::PlatformParameter platformParam;
platformParam.Device = deviceType;
auto platform = LLGI::CreatePlatform(platformParam, llgiwindow);
auto graphics = platform->CreateGraphics();
auto sfMemoryPool = graphics->CreateSingleFrameMemoryPool(1024 * 1024, 128);
auto commandList = graphics->CreateCommandList(sfMemoryPool);
LLGI::Color8 color;
color.R = 50;
color.G = 50;
color.B = 50;
color.A = 255;
// Create simple texture
LLGI::TextureInitializationParameter textureParam;
textureParam.Size = LLGI::Vec2I(256, 256);
auto texture = LLGI::CreateSharedPtr(graphics->CreateTexture(textureParam));
{
auto ptr = static_cast<LLGI::Color8*>(texture->Lock());
if (ptr != nullptr)
{
for (size_t y = 0; y < 256; y++)
{
for (size_t x = 0; x < 256; x++)
{
ptr[x + y * 256].R = static_cast<uint8_t>(x);
ptr[x + y * 256].G = static_cast<uint8_t>(y);
ptr[x + y * 256].B = 0;
ptr[x + y * 256].A = 255;
}
}
texture->Unlock();
}
}
LLGI::RenderTextureInitializationParameter textureParam2;
textureParam2.Size = LLGI::Vec2I(256, 256);
auto texture2 = LLGI::CreateSharedPtr(graphics->CreateRenderTexture(textureParam2));
{
auto ptr = static_cast<LLGI::Color8*>(texture2->Lock());
if (ptr != nullptr)
{
for (size_t y = 0; y < 256; y++)
{
for (size_t x = 0; x < 256; x++)
{
ptr[x + y * 256].R = static_cast<uint8_t>(x);
ptr[x + y * 256].G = static_cast<uint8_t>(y);
ptr[x + y * 256].B = 0;
ptr[x + y * 256].A = 255;
}
}
texture2->Unlock();
}
}
// Setup Dear ImGui context
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
(void)io;
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForVulkan(window, true);
std::shared_ptr<ImguiPlatform> imguiPlatform;
#ifdef ENABLE_VULKAN
if (deviceType == LLGI::DeviceType::Vulkan)
{
imguiPlatform = std::make_shared<ImguiPlatformVulkan>(graphics, platform);
}
#endif
if (imguiPlatform == nullptr)
{
#if defined(_WIN32)
imguiPlatform = std::make_shared<ImguiPlatformDX12>(graphics);
#elif defined(__APPLE__)
imguiPlatform = std::make_shared<ImguiPlatformMetal>(graphics);
#endif
}
while (glfwWindowShouldClose(window) == GL_FALSE)
{
platform->SetWindowSize(llgiwindow->GetWindowSize());
if (!platform->NewFrame())
break;
sfMemoryPool->NewFrame();
auto renderPass = platform->GetCurrentScreen(color, true);
imguiPlatform->NewFrame(renderPass);
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
{
ImGui::Begin("Window");
ImGui::Text("Hello, Altseed");
{
auto texturePtr = imguiPlatform->GetTextureIDToRender(texture.get(), commandList);
if (texturePtr != nullptr)
{
ImGui::Image(texturePtr, ImVec2(256, 256));
}
}
{
auto texturePtr = imguiPlatform->GetTextureIDToRender(texture2.get(), commandList);
if (texturePtr != nullptr)
{
ImGui::Image(texturePtr, ImVec2(256, 256));
}
}
ImGui::End();
}
// It need to create a command buffer between NewFrame and Present.
// Because get current screen returns other values by every frame.
commandList->Begin();
commandList->BeginRenderPass(renderPass);
// imgui
ImGui::Render();
imguiPlatform->RenderDrawData(ImGui::GetDrawData(), commandList);
commandList->EndRenderPass();
commandList->End();
graphics->Execute(commandList);
platform->Present();
// glfwSwapBuffers(window);
glfwPollEvents();
}
graphics->WaitFinish();
imguiPlatform.reset();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
LLGI::SafeRelease(sfMemoryPool);
LLGI::SafeRelease(commandList);
LLGI::SafeRelease(graphics);
LLGI::SafeRelease(platform);
delete llgiwindow;
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
| 21.233449 | 131 | 0.698392 | jayrulez |
c4d55018ad52bb8e87654d41fe73702b41dde485 | 717 | cpp | C++ | src/Utility.cpp | kmc7468/IceScript | b11ea9dce5507949badfaeffa337c780cdf6ec5e | [
"MIT"
] | null | null | null | src/Utility.cpp | kmc7468/IceScript | b11ea9dce5507949badfaeffa337c780cdf6ec5e | [
"MIT"
] | null | null | null | src/Utility.cpp | kmc7468/IceScript | b11ea9dce5507949badfaeffa337c780cdf6ec5e | [
"MIT"
] | null | null | null | #include <ice/Utility.hpp>
namespace ice {
std::string Format(const std::string& format, const std::vector<std::string>& arguments) {
std::string result;
std::size_t begin = 0;
std::size_t percent;
std::size_t index = 0;
while ((percent = format.find('%', begin)) != std::string::npos) {
result.insert(result.end(), format.begin() + begin, format.begin() + percent);
if (percent + 1 < format.size() && format[percent + 1] == '%') {
result.push_back('%');
begin = percent + 2;
} else {
result.append(arguments[index++]);
begin = percent + 1;
}
}
if (begin < format.size()) {
result.insert(result.end(), format.begin() + begin, format.end());
}
return result;
}
} | 25.607143 | 91 | 0.606695 | kmc7468 |
c4d5a0b731a7a1ba3e6610fa55646d0dfe4163a8 | 8,275 | cpp | C++ | Iron/opening/macroitem.cpp | biug/titan | aacb4e2dc4d55601abd45cb8321d8e5160851eec | [
"MIT"
] | null | null | null | Iron/opening/macroitem.cpp | biug/titan | aacb4e2dc4d55601abd45cb8321d8e5160851eec | [
"MIT"
] | null | null | null | Iron/opening/macroitem.cpp | biug/titan | aacb4e2dc4d55601abd45cb8321d8e5160851eec | [
"MIT"
] | null | null | null | #include "macroitem.h"
#include <regex>
namespace iron
{
int GetIntFromString(const string & s)
{
stringstream ss(s);
int a = 0;
ss >> a;
return a;
}
// Make a Type string look pretty for the UI
string NiceTypeName(const string & s)
{
string inputName(s);
replace(inputName.begin(), inputName.end(), '_', ' ');
transform(inputName.begin(), inputName.end(), inputName.begin(), ::tolower);
return inputName;
}
MacroLocation MacroItem::GetMacroLocationFromString(string & s)
{
if (s == "natural")
{
return MacroLocation::Natural;
}
if (s == "main")
{
return MacroLocation::Main;
}
return MacroLocation::Anywhere;
}
MacroItem::MacroItem()
: m_type(MacroItems::Default)
, m_race(Races::None)
, m_macroLocation(MacroLocation::Anywhere)
{
}
// Create a MacroItem from its name, like "drone" or "hatchery @ minonly".
// String comparison here is case-insensitive.
MacroItem::MacroItem(const string & name)
: m_type(MacroItems::Default)
, m_race(Races::None)
, m_macroLocation(MacroLocation::Anywhere)
{
string inputName(NiceTypeName(name));
// Commands like "go gas until 100". 100 is the amount.
if (inputName.substr(0, 3) == string("go "))
{
for (const MacroCommandType t : MacroCommand::AllCommandTypes())
{
string commandName = MacroCommand::GetName(t);
if (MacroCommand::HasArgument(t))
{
// There's an argument. Match the command name and parse out the argument.
regex commandWithArgRegex(commandName + " (\\d+)");
smatch m;
if (regex_match(inputName, m, commandWithArgRegex)) {
int amount = GetIntFromString(m[1].str());
if (amount >= 0) {
*this = MacroItem(t, amount);
return;
}
}
}
else
{
// No argument. Just compare for equality.
if (commandName == inputName)
{
*this = MacroItem(t);
return;
}
}
}
}
MacroLocation specifiedMacroLocation(MacroLocation::Anywhere); // the default
// Buildings can specify a location, like "hatchery @ expo".
// It's meaningless and ignored for anything except a building.
// Here we parse out the building and its location.
// Since buildings are units, only UnitType below sets _macroLocation.
regex macroLocationRegex("([a-z_ ]+[a-z])\\s*\\@\\s*([a-z][a-z ]+)");
smatch m;
if (regex_match(inputName, m, macroLocationRegex)) {
specifiedMacroLocation = GetMacroLocationFromString(m[2].str());
// Don't change inputName before using the results from the regex.
// Fix via gnuborg, who credited it to jaj22.
inputName = m[1].str();
}
for (const UnitType & unitType : UnitTypes::allUnitTypes())
{
// check to see if the names match exactly
string typeName(NiceTypeName(unitType.getName()));
if (typeName == inputName)
{
*this = MacroItem(UnitType(unitType));
m_macroLocation = specifiedMacroLocation;
return;
}
// check to see if the names match without the race prefix
string raceName = unitType.getRace().getName();
transform(raceName.begin(), raceName.end(), raceName.begin(), ::tolower);
if ((typeName.length() > raceName.length()) && (typeName.compare(raceName.length() + 1, typeName.length(), inputName) == 0))
{
*this = MacroItem(UnitType(unitType));
m_macroLocation = specifiedMacroLocation;
return;
}
}
for (const TechType & techType : TechTypes::allTechTypes())
{
string typeName(NiceTypeName(techType.getName()));
if (typeName == inputName)
{
*this = MacroItem(techType);
return;
}
}
for (const UpgradeType & upgradeType : UpgradeTypes::allUpgradeTypes())
{
string typeName(NiceTypeName(upgradeType.getName()));
if (typeName == inputName)
{
*this = MacroItem(upgradeType);
return;
}
}
m_name = GetName();
}
MacroItem::MacroItem(UnitType t)
: m_unitType(t)
, m_type(MacroItems::Unit)
, m_race(t.getRace())
, m_macroLocation(MacroLocation::Anywhere)
{
m_name = GetName();
}
MacroItem::MacroItem(UnitType t, MacroLocation loc)
: m_unitType(t)
, m_type(MacroItems::Unit)
, m_race(t.getRace())
, m_macroLocation(loc)
{
m_name = GetName();
}
MacroItem::MacroItem(TechType t)
: m_techType(t)
, m_type(MacroItems::Tech)
, m_race(t.getRace())
, m_macroLocation(MacroLocation::Anywhere)
{
m_name = GetName();
}
MacroItem::MacroItem(UpgradeType t)
: m_upgradeType(t)
, m_type(MacroItems::Upgrade)
, m_race(t.getRace())
, m_macroLocation(MacroLocation::Anywhere)
{
m_name = GetName();
}
MacroItem::MacroItem(MacroCommandType t)
: m_macroCommandType(t)
, m_type(MacroItems::Command)
, m_race(Races::Terran)
, m_macroLocation(MacroLocation::Anywhere)
{
m_name = GetName();
}
MacroItem::MacroItem(MacroCommandType t, int amount)
: m_macroCommandType(t, amount)
, m_type(MacroItems::Command)
, m_race(Races::Terran) // irrelevant
, m_macroLocation(MacroLocation::Anywhere)
{
m_name = GetName();
}
const size_t & MacroItem::type() const
{
return m_type;
}
bool MacroItem::IsUnit() const
{
return m_type == MacroItems::Unit;
}
bool MacroItem::IsTech() const
{
return m_type == MacroItems::Tech;
}
bool MacroItem::IsUpgrade() const
{
return m_type == MacroItems::Upgrade;
}
bool MacroItem::IsCommand() const
{
return m_type == MacroItems::Command;
}
const Race & MacroItem::GetRace() const
{
return m_race;
}
bool MacroItem::IsBuilding() const
{
return m_type == MacroItems::Unit && m_unitType.isBuilding();
}
bool MacroItem::IsBuildingAddon() const
{
return m_type == MacroItems::Unit && m_unitType.isAddon();
}
bool MacroItem::IsRefinery() const
{
return m_type == MacroItems::Unit && m_unitType.isRefinery();
}
// The standard supply unit, ignoring the hatchery (which provides 1 supply).
bool MacroItem::IsSupply() const
{
return IsUnit() &&
(m_unitType == Terran_Supply_Depot
|| m_unitType == Protoss_Pylon
|| m_unitType == Zerg_Overlord);
}
const UnitType & MacroItem::GetUnitType() const
{
return m_unitType;
}
const TechType & MacroItem::GetTechType() const
{
return m_techType;
}
const UpgradeType & MacroItem::GetUpgradeType() const
{
return m_upgradeType;
}
const MacroCommand MacroItem::GetCommandType() const
{
return m_macroCommandType;
}
const MacroLocation MacroItem::GetMacroLocation() const
{
return m_macroLocation;
}
int MacroItem::supplyRequired() const
{
if (IsUnit())
{
return m_unitType.supplyRequired();
}
return 0;
}
// NOTE Because upgrades vary in price with level, this is context dependent.
int MacroItem::mineralPrice() const
{
if (IsCommand())
{
return 0;
}
if (IsUnit())
{
return m_unitType.mineralPrice();
}
if (IsTech())
{
return m_techType.mineralPrice();
}
if (IsUpgrade())
{
if (m_upgradeType.maxRepeats() > 1 && Broodwar->self()->getUpgradeLevel(m_upgradeType) > 0)
{
return m_upgradeType.mineralPrice(1 + Broodwar->self()->getUpgradeLevel(m_upgradeType));
}
return m_upgradeType.mineralPrice();
}
return 0;
}
// NOTE Because upgrades vary in price with level, this is context dependent.
int MacroItem::gasPrice() const
{
if (IsCommand()) {
return 0;
}
if (IsUnit())
{
return m_unitType.gasPrice();
}
if (IsTech())
{
return m_techType.gasPrice();
}
if (IsUpgrade())
{
if (m_upgradeType.maxRepeats() > 1 && Broodwar->self()->getUpgradeLevel(m_upgradeType) > 0)
{
return m_upgradeType.gasPrice(1 + Broodwar->self()->getUpgradeLevel(m_upgradeType));
}
return m_upgradeType.gasPrice();
}
return 0;
}
UnitType MacroItem::whatBuilds() const
{
if (IsCommand()) {
return UnitTypes::None;
}
UnitType buildType = IsUnit() ? m_unitType.whatBuilds().first : (IsTech() ? m_techType.whatResearches() : m_upgradeType.whatUpgrades());
return buildType;
}
string MacroItem::GetName() const
{
if (IsUnit())
{
return m_unitType.getName();
}
if (IsUpgrade())
{
return m_upgradeType.getName();
}
if (IsTech())
{
return m_techType.getName();
}
if (IsCommand())
{
return m_macroCommandType.GetName();
}
return "error";
}
} | 22.364865 | 138 | 0.659698 | biug |
c4d971e6fb2c5248bb1da7022e68c69e5c2cf5b9 | 2,378 | hpp | C++ | boost/actor/policy/sequential_invoke.hpp | syoummer/boost.actor | 58f35499bac8871b8f5b0b024246a467b63c6fb0 | [
"BSL-1.0"
] | 2 | 2015-03-20T21:11:16.000Z | 2020-01-20T08:05:41.000Z | boost/actor/policy/sequential_invoke.hpp | syoummer/boost.actor | 58f35499bac8871b8f5b0b024246a467b63c6fb0 | [
"BSL-1.0"
] | null | null | null | boost/actor/policy/sequential_invoke.hpp | syoummer/boost.actor | 58f35499bac8871b8f5b0b024246a467b63c6fb0 | [
"BSL-1.0"
] | null | null | null | /******************************************************************************\
* *
* ____ _ _ _ *
* | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ *
* | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| *
* | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | *
* |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| *
* *
* *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* Distributed under the Boost Software License, Version 1.0. See *
* accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt *
\******************************************************************************/
#ifndef BOOST_ACTOR_THREADLESS_HPP
#define BOOST_ACTOR_THREADLESS_HPP
#include "boost/actor/atom.hpp"
#include "boost/actor/behavior.hpp"
#include "boost/actor/duration.hpp"
#include "boost/actor/policy/invoke_policy.hpp"
namespace boost {
namespace actor { namespace policy {
/**
* @brief An actor that is scheduled or otherwise managed.
*/
class sequential_invoke : public invoke_policy<sequential_invoke> {
public:
inline bool hm_should_skip(mailbox_element*) {
return false;
}
template<class Actor>
inline mailbox_element* hm_begin(Actor* self, mailbox_element* node) {
auto previous = self->current_node();
self->current_node(node);
return previous;
}
template<class Actor>
inline void hm_cleanup(Actor* self, mailbox_element*) {
self->current_node(self->dummy_node());
}
template<class Actor>
inline void hm_revert(Actor* self, mailbox_element* previous) {
self->current_node(previous);
}
};
} } // namespace actor
} // namespace boost::policy
#endif // BOOST_ACTOR_THREADLESS_HPP
| 36.584615 | 80 | 0.433558 | syoummer |
c4dbb710846d892b5562fc123745778edd9f3e45 | 2,055 | cc | C++ | tree/1609.cc | MingfeiPan/leetcode | 55dc878cfb7b15a34252410ae7420a656da604f8 | [
"Apache-2.0"
] | null | null | null | tree/1609.cc | MingfeiPan/leetcode | 55dc878cfb7b15a34252410ae7420a656da604f8 | [
"Apache-2.0"
] | null | null | null | tree/1609.cc | MingfeiPan/leetcode | 55dc878cfb7b15a34252410ae7420a656da604f8 | [
"Apache-2.0"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
struct Item {
TreeNode* node;
int level;
};
public:
bool isEvenOddTree(TreeNode* root) {
// use a vector for each level node
std::vector<int> last_;
std::queue<Item> q_;
q_.emplace(Item{root, 0});
while (!q_.empty()) {
Item i = q_.front();
q_.pop();
if (last_.size() <= i.level) {
if (i.level % 2 == 0) {
if (i.node->val % 2 == 0)
return false;
} else {
if (i.node->val % 2 != 0)
return false;
}
last_.emplace_back(i.node->val);
} else {
// check odd even
if (i.level % 2 == 0) {
if (i.node->val % 2 == 0)
return false;
if (i.node->val <= last_[i.level]) {
return false;
} else {
last_[i.level] = i.node->val;
}
} else {
if (i.node->val % 2 != 0)
return false;
if (i.node->val >= last_[i.level]) {
return false;
} else {
last_[i.level] = i.node->val;
}
}
}
if (i.node->left) {
q_.emplace(Item{i.node->left, i.level+1});
}
if (i.node->right) {
q_.emplace(Item{i.node->right, i.level+1});
}
}
return true;
}
};
| 31.615385 | 93 | 0.373723 | MingfeiPan |
c4dd6a879e608c28f2d3f92a4b6213cee9eef290 | 1,577 | cpp | C++ | tutorial_publisher/src/talker.cpp | ryo4432/ros2_tutorial_collection | 4e7ed30e35009f07bd219c762d68b4b8022d4d9d | [
"Apache-2.0"
] | null | null | null | tutorial_publisher/src/talker.cpp | ryo4432/ros2_tutorial_collection | 4e7ed30e35009f07bd219c762d68b4b8022d4d9d | [
"Apache-2.0"
] | null | null | null | tutorial_publisher/src/talker.cpp | ryo4432/ros2_tutorial_collection | 4e7ed30e35009f07bd219c762d68b4b8022d4d9d | [
"Apache-2.0"
] | null | null | null | /*
# Copyright 2019 Open Source Robotics Foundation, 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.
*/
#include <chrono>
#include <cstdio>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
class Talker : public rclcpp::Node
{
private:
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_;
rclcpp::TimerBase::SharedPtr timer_;
public:
Talker(const std::string & node_name, const std::string & topic_name)
: Node(node_name)
{
pub_ = this->create_publisher<std_msgs::msg::String>(topic_name, 10);
auto msg_ = std_msgs::msg::String();
msg_.data = "Hello world";
auto publish_message =
[this, msg_]() -> void {
RCLCPP_INFO(this->get_logger(), "%s", msg_.data.c_str());
this->pub_->publish(msg_);
};
timer_ = create_wall_timer(100ms, publish_message);
}
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<Talker>("talker", "topic"));
rclcpp::shutdown();
return 0;
}
| 26.728814 | 74 | 0.700063 | ryo4432 |
c4dec47b393ea9fc4c51411e2fe9a8ac4f702c79 | 2,596 | hpp | C++ | include/drag/detail/utils.hpp | bigno78/drag | a7fc1ff77a0e743bbe9a9e72a310a015f6f3b098 | [
"BSD-3-Clause"
] | 3 | 2020-07-29T19:38:51.000Z | 2022-01-28T05:13:55.000Z | include/drag/detail/utils.hpp | bigno78/drag | a7fc1ff77a0e743bbe9a9e72a310a015f6f3b098 | [
"BSD-3-Clause"
] | 2 | 2020-09-05T19:59:15.000Z | 2021-12-05T20:50:41.000Z | include/drag/detail/utils.hpp | bigno78/drag | a7fc1ff77a0e743bbe9a9e72a310a015f6f3b098 | [
"BSD-3-Clause"
] | 2 | 2020-07-29T19:44:52.000Z | 2022-01-28T05:13:59.000Z | #pragma once
#include <string>
#include <vector>
#include <drag/vec2.hpp>
#include <drag/types.hpp>
namespace drag {
template <typename T>
T sgn(T val) { return ( T(0) < val ) - ( val < T(0) ); }
template<typename T>
struct range {
T r_start;
T r_end;
int step;
range(T start, T end, int step = 1) : r_start(start), r_end(end), step(step) {}
struct iterator {
T val;
int step;
iterator(T val, int step) : val(val), step(step) {}
T operator*() { return val; }
friend bool operator==(const iterator& lhs, const iterator& rhs) { return lhs.val == rhs.val; }
friend bool operator!=(const iterator& lhs, const iterator& rhs) { return !(lhs == rhs); }
iterator& operator++() { val += step; return *this; }
};
iterator begin() const { return iterator(r_start, step); }
iterator end() const { return iterator(r_end, step); }
};
template<typename T>
struct chain_range {
const T& first;
const T& second;
chain_range(const T& first, const T& second) : first(first), second(second) {}
struct iterator {
using It = typename T::const_iterator;
It curr;
It st_end;
It nd_beg;
iterator(It curr, It st_end, It nd_beg)
: curr(curr)
, st_end(st_end)
, nd_beg(nd_beg)
{
if (curr == st_end) {
this->curr = nd_beg;
}
}
typename T::value_type operator*() { return *curr; }
friend bool operator==(const iterator& lhs, const iterator& rhs) { return lhs.curr == rhs.curr; }
friend bool operator!=(const iterator& lhs, const iterator& rhs) { return !(lhs == rhs); }
iterator& operator++() {
if (++curr == st_end) {
curr = nd_beg;
}
return *this;
}
};
iterator begin() {
return iterator( std::begin(first), std::end(first), std::begin(second) );
}
iterator begin() const {
return iterator( std::begin(first), std::end(first), std::begin(second) );
}
iterator end() {
return iterator( std::end(second), std::end(first), std::begin(second) );
}
iterator end() const {
return iterator( std::end(second), std::end(first), std::begin(second) );
}
};
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& vec) {
const char* sep = "";
for (const auto& x : vec) {
out << sep << x;
sep = ", ";
}
return out;
}
} //namespace drag
| 26.222222 | 105 | 0.547766 | bigno78 |
c4df2d75c14d83b0119c74cd216535da3a4d9c9e | 3,001 | hpp | C++ | masterui/display.hpp | rickfoosusa/dnp | ec17eb20817db32cc6356139afd2daaa1803576f | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2017-09-19T16:37:59.000Z | 2017-09-19T16:37:59.000Z | masterui/display.hpp | rickfoosusa/dnp | ec17eb20817db32cc6356139afd2daaa1803576f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | masterui/display.hpp | rickfoosusa/dnp | ec17eb20817db32cc6356139afd2daaa1803576f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | //
// $Id$
//
// Copyright (C) 2007 Turner Technolgoies Inc. http://www.turner.ca
//
// 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.
#ifndef DISPLAY_H
#define DISPLAY_H
#include <QString>
#include <QWidget>
#include <QDateTime>
#include "common.hpp"
#include "event_interface.hpp"
class QGroupBox;
class QTreeView;
class QAbstractItemModel;
class DataDisplay : public QWidget
{
Q_OBJECT
public:
DataDisplay();
// returns true if it is a Change Of State (COS)
virtual bool updateData( QString name,
EventInterface::PointType_t pointType,
int value,
DnpTime_t timestamp=0);
virtual void createDataModel();
protected:
virtual void addRow( QString name,
EventInterface::PointType_t pointType,
int value,
DnpTime_t timestamp=0);
void addParent( EventInterface::PointType_t pointType);
QAbstractItemModel *dataModel;
QGroupBox *dataGroupBox;
QTreeView *dataView;
static const QString ptNames[EventInterface::NUM_POINT_TYPES];
};
class CosDisplay : public DataDisplay
{
Q_OBJECT
public:
CosDisplay();
public:
virtual void createDataModel();
// return value shuold not be used
// it is the callers responsibility not to call this method if it
// it not an event
bool updateData( QString name,
EventInterface::PointType_t pointType,
int value,
DnpTime_t timestamp=0);
private:
void addRow( QString name,
EventInterface::PointType_t,
int value,
DnpTime_t timestamp=0);
QDateTime dateTime;
};
#endif
| 29.712871 | 71 | 0.626458 | rickfoosusa |
c4df6e50171420d497d76d5afe8636009394b043 | 3,393 | cpp | C++ | mini/tor/circuit_node_crypto_state.cpp | geralltf/mini-tor | 61d58749431fba970e19e0d35a53811956c69b16 | [
"MIT"
] | 380 | 2016-07-20T10:22:37.000Z | 2022-03-30T08:47:44.000Z | mini/tor/circuit_node_crypto_state.cpp | geralltf/mini-tor | 61d58749431fba970e19e0d35a53811956c69b16 | [
"MIT"
] | 24 | 2016-08-13T12:56:03.000Z | 2021-05-26T01:59:17.000Z | mini/tor/circuit_node_crypto_state.cpp | geralltf/mini-tor | 61d58749431fba970e19e0d35a53811956c69b16 | [
"MIT"
] | 105 | 2016-07-20T14:34:52.000Z | 2022-02-17T13:31:25.000Z | #include "circuit_node_crypto_state.h"
#include "relay_cell.h"
#include <mini/stack_buffer.h>
#include <mini/io/memory_stream.h>
#include <mini/io/stream_wrapper.h>
#include <mini/logger.h>
namespace mini::tor {
circuit_node_crypto_state::circuit_node_crypto_state(
const byte_buffer_ref key_material
)
{
io::memory_stream key_material_stream(key_material);
io::stream_wrapper key_material_buffer(key_material_stream);
stack_byte_buffer<crypto::sha1::hash_size_in_bytes> df;
key_material_buffer.read(df);
_forward_digest.update(df);
stack_byte_buffer<crypto::sha1::hash_size_in_bytes> db;
key_material_buffer.read(db);
_backward_digest.update(db);
stack_byte_buffer<aes_ctr_128::key_size_in_bytes> kf;
key_material_buffer.read(kf);
_forward_cipher.init(aes_ctr_128::key(kf));
stack_byte_buffer<aes_ctr_128::key_size_in_bytes> kb;
key_material_buffer.read(kb);
_backward_cipher.init(aes_ctr_128::key(kb));
}
void
circuit_node_crypto_state::encrypt_forward_cell(
relay_cell& cell
)
{
byte_buffer relay_payload_bytes(cell::payload_size);
if (cell.get_payload().is_empty())
{
io::memory_stream relay_payload_stream(relay_payload_bytes);
io::stream_wrapper relay_payload_buffer(relay_payload_stream, endianness::big_endian);
relay_payload_buffer.write(cell.get_relay_command());
relay_payload_buffer.write(static_cast<uint16_t>(0)); // 'recognized'
relay_payload_buffer.write(cell.get_stream_id());
relay_payload_buffer.write(static_cast<uint32_t>(0)); // digest placeholder
relay_payload_buffer.write(static_cast<payload_size_type>(cell.get_relay_payload().get_size()));
relay_payload_buffer.write(cell.get_relay_payload());
//
// update digest field in the payload
//
_forward_digest.update(relay_payload_bytes);
auto digest = _forward_digest.duplicate().get();
memory::copy(&relay_payload_bytes[5], &digest[0], sizeof(uint32_t));
}
else
{
relay_payload_bytes.insert_many(cell.get_payload(), 0);
}
//
// encrypt the payload
//
auto encrypted_payload = _forward_cipher.encrypt(relay_payload_bytes);
mini_assert(encrypted_payload.get_size() == cell::payload_size);
//
// set the payload
//
cell.set_payload(encrypted_payload);
}
bool
circuit_node_crypto_state::decrypt_backward_cell(
cell& cell
)
{
mini_assert(cell.get_payload().get_size() == cell::payload_size);
auto decrypted_payload = _backward_cipher.decrypt(cell.get_payload());
mini_assert(decrypted_payload.get_size() == cell::payload_size);
cell.set_payload(decrypted_payload);
//
// check if this is a cell for us.
//
if (cell.is_recognized())
{
//
// remove the digest from the payload
//
byte_buffer payload_without_digest(cell.get_payload());
memory::zero(payload_without_digest.get_buffer() + 5, sizeof(uint32_t));
stack_byte_buffer<sizeof(uint32_t)> payload_digest;
memory::copy(payload_digest.get_buffer(), cell.get_payload().get_buffer() + 5, sizeof(uint32_t));
auto backward_digest_clone = _backward_digest.duplicate();
backward_digest_clone.update(payload_without_digest);
auto digest = backward_digest_clone.get();
if (memory::equal(payload_digest.get_buffer(), &digest[0], sizeof(payload_digest)))
{
_backward_digest.update(payload_without_digest);
return true;
}
}
return false;
}
}
| 28.041322 | 101 | 0.7486 | geralltf |
c4e04900cf25da6cc065194c8b82d97bfd57337c | 1,925 | cpp | C++ | src/private/PZGBeaconData.cpp | ruurdadema/zg_choir | 6de0e8be497974c0e56bb87139b18f0d6f5b4ee3 | [
"BSD-3-Clause"
] | null | null | null | src/private/PZGBeaconData.cpp | ruurdadema/zg_choir | 6de0e8be497974c0e56bb87139b18f0d6f5b4ee3 | [
"BSD-3-Clause"
] | null | null | null | src/private/PZGBeaconData.cpp | ruurdadema/zg_choir | 6de0e8be497974c0e56bb87139b18f0d6f5b4ee3 | [
"BSD-3-Clause"
] | null | null | null | #include "zg/private/PZGBeaconData.h"
namespace zg_private
{
void PZGBeaconData :: Flatten(uint8 *buffer) const
{
const uint32 numItems = _dbis.GetNumItems();
const uint32 dbiFlatSize = PZGDatabaseStateInfo::FlattenedSize();
muscleCopyOut(buffer, B_HOST_TO_LENDIAN_INT32(numItems)); buffer += sizeof(uint32);
for (uint32 i=0; i<numItems; i++) {_dbis[i].Flatten(buffer); buffer += dbiFlatSize;}
}
status_t PZGBeaconData :: Unflatten(const uint8 *buf, uint32 size)
{
if (size < sizeof(uint32)) return B_BAD_DATA;
const uint32 itemFlatSize = PZGDatabaseStateInfo::FlattenedSize();
const uint32 newNumItems = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(buf)); buf += sizeof(uint32); size -= sizeof(uint32);
if (size < (newNumItems*itemFlatSize)) return B_BAD_DATA;
MRETURN_ON_ERROR(_dbis.EnsureSize(newNumItems, true));
for (uint32 i=0; i<newNumItems; i++)
{
MRETURN_ON_ERROR(_dbis[i].Unflatten(buf, itemFlatSize));
buf += itemFlatSize; size -= itemFlatSize;
}
return B_NO_ERROR;
}
PZGBeaconDataRef GetBeaconDataFromPool()
{
static ObjectPool<PZGBeaconData> _infoListPool;
return PZGBeaconDataRef(_infoListPool.ObtainObject());
}
uint32 PZGBeaconData :: CalculateChecksum() const
{
const uint32 numItems = _dbis.GetNumItems();
uint32 ret = numItems;
for (uint32 i=0; i<numItems; i++) ret += (i+1)*(_dbis[i].CalculateChecksum());
return ret;
}
void PZGBeaconData :: PrintToStream() const
{
puts(ToString()());
}
String PZGBeaconData :: ToString() const
{
String ret;
char buf[128];
for (uint32 i=0; i<_dbis.GetNumItems(); i++)
{
muscleSprintf(buf, " DBI #" UINT32_FORMAT_SPEC ": ", i);
ret += buf;
ret += _dbis[i].ToString();
ret += '\n';
}
return ret;
}
bool PZGBeaconData :: operator == (const PZGBeaconData & rhs) const
{
return (_dbis == rhs._dbis);
}
}; // end namespace zg_private
| 26.013514 | 129 | 0.686753 | ruurdadema |
c4e1c2f5ec6fb5b8c322d1497c5992c18e382612 | 402 | cpp | C++ | AIC/AIC'20 - Level 1 Training Contests/Contest #6 (Online)/H.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 3 | 2020-11-01T06:31:30.000Z | 2022-02-21T20:37:51.000Z | AIC/AIC'20 - Level 1 Training Contests/Contest #6 (Online)/H.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | null | null | null | AIC/AIC'20 - Level 1 Training Contests/Contest #6 (Online)/H.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 1 | 2021-05-05T18:56:31.000Z | 2021-05-05T18:56:31.000Z | //https://codeforces.com/group/aDFQm4ed6d/contest/274872/problem/H
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef long long ll;
typedef long double ld;
ll mod = 1e9 + 7;
int main ()
{
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
ll k, n, s, p;
cin >> k >> n >> s >> p;
ll x = (n + s - 1) / s;
cout << ((k * x) + p - 1) / p;
}
| 21.157895 | 66 | 0.577114 | MaGnsio |
c4e3b64788f0256a3afac60415999e1650d2725b | 1,191 | cpp | C++ | 1142/a.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | 1 | 2021-10-24T00:46:37.000Z | 2021-10-24T00:46:37.000Z | 1142/a.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | 1142/a.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
long long gcd(long long a, long long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
void solve(long long a, long long b, long long len, long long &mn, long long &mx) {
long long step;
if (a > b) {
step = len - (a - b);
} else {
step = b - a;
}
// cout << "a = " << a << ", b = " << b << ", step = " << step << endl;
// if (step == 0) {
// mn = 1;
// mx = len;
// return;
// }
long long res = len / gcd(len, step);
// cout << "len = " << len << ", step = " << step << ", res = " << res << endl;
mn = min(mn, res);
mx = max(mx, res);
}
int main() {
long long n, k;
long long a, b;
cin >> n >> k;
cin >> a >> b;
if (n == 1 && k == 1) {
cout << 1 << " " << 1 << "\n";
return 0;
}
long long mn = 1e18;
long long mx = 1;
for (long long cur_b = b, cur_next_b = k - b; cur_b < n * k; cur_b += k, cur_next_b += k) {
// cout << "cur_b = " << cur_b << ", cur_next_b = " << cur_next_b << endl;
solve(a, cur_b, n * k, mn, mx);
solve(k - a, cur_b, n * k, mn, mx);
}
cout << mn << " " << mx << "\n";
return 0;
}
| 19.85 | 93 | 0.455919 | vladshablinsky |
c4e625a98b552cf6e92bf5fc7f2d46aed001c7a0 | 520 | cpp | C++ | source/ItemShotgun.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | 1 | 2016-08-15T16:11:40.000Z | 2016-08-15T16:11:40.000Z | source/ItemShotgun.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | null | null | null | source/ItemShotgun.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | null | null | null |
#include "ItemShotgun.h"
ItemShotgun::ItemShotgun(int _x, int _y):
x(_x),
y(_y)
{
sprite = new cgf::Sprite();
sprite->load("data/img/shotgun.png");
sprite->scale(1.2, 1.2);
sf::Vector2f vpos = sf::Vector2f();
vpos.x = x;
vpos.y = y;
sprite->setPosition(vpos);
}
ItemShotgun::~ItemShotgun(){
if (sprite){
delete sprite;
}
}
void ItemShotgun::visit(Inventory *iv) {
iv->addShotgun();
}
void ItemShotgun::draw(cgf::Game* game){
game->getScreen()->draw(*sprite);
}
| 16.25 | 41 | 0.6 | fgrehm |
c4eabc24d27ea35b73a8be559fea0a51971629d2 | 1,327 | cc | C++ | src/dictionaries/node_webrtc/rtc_offer_options.cc | elofun/node-webrtc | be63c8c007402c25962df9e30c9813ba70b8a17b | [
"Apache-2.0"
] | 1,302 | 2018-11-26T03:29:51.000Z | 2022-03-31T23:38:34.000Z | src/dictionaries/node_webrtc/rtc_offer_options.cc | elofun/node-webrtc | be63c8c007402c25962df9e30c9813ba70b8a17b | [
"Apache-2.0"
] | 311 | 2018-11-26T14:22:19.000Z | 2022-03-28T09:47:38.000Z | src/dictionaries/node_webrtc/rtc_offer_options.cc | elofun/node-webrtc | be63c8c007402c25962df9e30c9813ba70b8a17b | [
"Apache-2.0"
] | 233 | 2018-11-26T18:08:11.000Z | 2022-03-30T01:29:50.000Z | #include "src/dictionaries/node_webrtc/rtc_offer_options.h"
#include "src/functional/maybe.h"
#include "src/functional/validation.h"
namespace node_webrtc {
#define RTC_OFFER_OPTIONS_FN CreateRTCOfferOptions
static Validation<RTC_OFFER_OPTIONS> RTC_OFFER_OPTIONS_FN(
const bool voiceActivityDetection,
const bool iceRestart,
const Maybe<bool> offerToReceiveAudio,
const Maybe<bool> offerToReceiveVideo) {
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
options.ice_restart = iceRestart;
options.voice_activity_detection = voiceActivityDetection;
options.offer_to_receive_audio = offerToReceiveAudio.Map([](auto boolean) {
return boolean
? webrtc::PeerConnectionInterface::RTCOfferAnswerOptions::kOfferToReceiveMediaTrue
: 0;
}).FromMaybe(webrtc::PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined);
options.offer_to_receive_video = offerToReceiveVideo.Map([](auto boolean) {
return boolean
? webrtc::PeerConnectionInterface::RTCOfferAnswerOptions::kOfferToReceiveMediaTrue
: 0;
}).FromMaybe(webrtc::PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined);
return Pure(RTC_OFFER_OPTIONS(options));
}
} // namespace node_webrtc
#define DICT(X) RTC_OFFER_OPTIONS ## X
#include "src/dictionaries/macros/impls.h"
#undef DICT
| 36.861111 | 90 | 0.788244 | elofun |
c4ebcceb99ea1493cdca6d9dfd62fecda016417a | 6,732 | cpp | C++ | CQGLFlocking/src/CQGLFlocking.cpp | colinw7/CQDemos | a66452e0f963613ae351fea4d078552c19aa002b | [
"MIT"
] | 2 | 2019-12-22T09:49:25.000Z | 2021-12-23T02:22:34.000Z | CQGLFlocking/src/CQGLFlocking.cpp | colinw7/CQDemos | a66452e0f963613ae351fea4d078552c19aa002b | [
"MIT"
] | null | null | null | CQGLFlocking/src/CQGLFlocking.cpp | colinw7/CQDemos | a66452e0f963613ae351fea4d078552c19aa002b | [
"MIT"
] | 1 | 2019-04-01T13:35:49.000Z | 2019-04-01T13:35:49.000Z | #include <CQGLFlocking.h>
#include <CFlocking.h>
#include <CQMenu.h>
#include <CQGLControl.h>
#include <CGLTexture.h>
#include <QApplication>
#include <QTimer>
#include <QVBoxLayout>
#include "images/bird1.xpm"
#include "images/bird2.xpm"
#include "images/bird3.xpm"
#include "images/bird4.xpm"
int
main(int argc, char **argv)
{
QApplication app(argc, argv);
CQGLFlocking *flocking = new CQGLFlocking;
flocking->init();
flocking->resize(400, 400);
flocking->show();
return app.exec();
}
//------
CQGLFlocking::
CQGLFlocking() :
CQMainWindow("CQGLFlocking")
{
flocking_ = new CFlocking;
}
QWidget *
CQGLFlocking::
createCentralWidget()
{
QWidget *frame = new QWidget;
QVBoxLayout *layout = new QVBoxLayout(frame);
canvas_ = new CQGLFlockingCanvas(this);
control_ = new CQGLControl(canvas_);
toolbar_ = control_->createToolBar();
connect(control_, SIGNAL(stateChanged()), this, SLOT(controlSlot()));
layout->addWidget(toolbar_);
layout->addWidget(canvas_);
timer_ = new QTimer;
connect(timer_, SIGNAL(timeout()), this, SLOT(updateFlocking()));
timer_->start(10);
return frame;
}
void
CQGLFlocking::
createWorkspace()
{
}
void
CQGLFlocking::
createMenus()
{
fileMenu_ = new CQMenu(this, "&File");
CQMenuItem *quitItem = new CQMenuItem(fileMenu_, "&Quit");
quitItem->setShortcut("Ctrl+Q");
quitItem->setStatusTip("Quit the application");
connect(quitItem->getAction(), SIGNAL(triggered()), this, SLOT(close()));
//----
helpMenu_ = new CQMenu(this, "&Help");
//----
CQMenuItem *aboutItem = new CQMenuItem(helpMenu_, "&About");
aboutItem->setStatusTip("Show the application's About box");
//connect(aboutItem->getAction(), SIGNAL(triggered()), this, SLOT(aboutSlot()));
}
void
CQGLFlocking::
createToolBars()
{
}
void
CQGLFlocking::
createStatusBar()
{
}
void
CQGLFlocking::
createDockWindows()
{
}
void
CQGLFlocking::
controlSlot()
{
canvas_->update();
}
void
CQGLFlocking::
updateFlocking()
{
flocking_->update(0.01);
canvas_->update();
}
//------
#define IMAGE_DATA(I) I, sizeof(I)/sizeof(char *)
CQGLFlockingCanvas::
CQGLFlockingCanvas(CQGLFlocking *flocking) :
QGLWidget(flocking), flocking_(flocking)
{
textures_[0] = NULL;
textures_[1] = NULL;
textures_[2] = NULL;
textures_[3] = NULL;
setFocusPolicy(Qt::StrongFocus);
}
void
CQGLFlockingCanvas::
paintGL()
{
static GLfloat light_position[] = { 50.0, 50.0, 50.0, 0.0 };
static GLfloat colors[][4] = {
{ 1.0, 0.0, 0.0, 1.0 },
{ 0.0, 1.0, 0.0, 1.0 },
{ 0.0, 0.0, 1.0, 1.0 },
{ 1.0, 1.0, 0.0, 1.0 }
};
static bool texture = false;
if (textures_[0] == NULL) {
textures_[0] = new CGLTexture;
textures_[1] = new CGLTexture;
textures_[2] = new CGLTexture;
textures_[3] = new CGLTexture;
textures_[0]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird1_data))));
textures_[1]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird2_data))));
textures_[2]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird3_data))));
textures_[3]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird4_data))));
}
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHT0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
CQGLControl *control = flocking_->getControl();
control->getDepthTest () ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST);
control->getCullFace () ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE);
control->getLighting () ? glEnable(GL_LIGHTING) : glDisable(GL_LIGHTING);
control->getOutline () ? glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) :
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
control->getFrontFace () ? glFrontFace(GL_CW) : glFrontFace(GL_CCW);
control->getSmoothShade() ? glShadeModel(GL_SMOOTH) : glShadeModel(GL_FLAT);
CFlocking *flocking = flocking_->getFlocking();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (texture) {
glEnable(GL_TEXTURE_2D);
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
}
const CFlocking::BoidList &boids = flocking->getBoids();
CFlocking::BoidList::const_iterator pb1, pb2;
for (pb1 = boids.begin(), pb2 = boids.end(); pb1 != pb2; ++pb1) {
const CBoid *boid = *pb1;
const CVector3D &pos = boid->getPos();
int id = boid->getFlock()->getId() % 4;
if (texture)
textures_[id]->bind();
CVector3D vel = boid->getVelocity().normalized();
CVector3D vel1(vel.getY(), -vel.getX(), vel.getZ());
CVector3D pos1 = pos + vel;
CVector3D pos2 = pos + vel/2 + vel1/2;
CVector3D pos3 = pos + vel/2 - vel1/2;
//CVector3D pvel = vel.perp();
//CVector3D pos2 = pos + pvel/2;
//CVector3D pos3 = pos - pvel/2;
//const CRGBA &rgba = boid->getFlock()->getColor();
if (texture) {
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2d(0,0); glVertex3f(pos .getX(), pos .getY(), pos .getZ()); // Bottom Left
glTexCoord2d(0,1); glVertex3f(pos2.getX(), pos2.getY(), pos2.getZ()); // Top Left
glTexCoord2d(1,0); glVertex3f(pos3.getX(), pos3.getY(), pos3.getZ()); // Bottom Right
glTexCoord2d(1,1); glVertex3f(pos1.getX(), pos1.getY(), pos1.getZ()); // Top Right
//glVertex3d(pos1.getX(), pos1.getY(), pos1.getZ());
//glVertex3d(pos2.getX(), pos2.getY(), pos2.getZ());
//glVertex3d(pos3.getX(), pos3.getY(), pos3.getZ());
glEnd();
}
else {
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(colors[id]);
glTexCoord2d(0,0); glVertex3f(pos .getX(), pos .getY(), pos .getZ()); // Bottom Left
glTexCoord2d(0,1); glVertex3f(pos2.getX(), pos2.getY(), pos2.getZ()); // Top Left
glTexCoord2d(1,0); glVertex3f(pos3.getX(), pos3.getY(), pos3.getZ()); // Bottom Right
glTexCoord2d(1,1); glVertex3f(pos1.getX(), pos1.getY(), pos1.getZ()); // Top Right
glEnd();
}
}
}
void
CQGLFlockingCanvas::
resizeGL(int width, int height)
{
CQGLControl *control = flocking_->getControl();
control->handleResize(width, height);
}
void
CQGLFlockingCanvas::
mousePressEvent(QMouseEvent *e)
{
CQGLControl *control = flocking_->getControl();
control->handleMousePress(e);
update();
}
void
CQGLFlockingCanvas::
mouseReleaseEvent(QMouseEvent *e)
{
CQGLControl *control = flocking_->getControl();
control->handleMouseRelease(e);
update();
}
void
CQGLFlockingCanvas::
mouseMoveEvent(QMouseEvent *e)
{
CQGLControl *control = flocking_->getControl();
control->handleMouseMotion(e);
update();
}
void
CQGLFlockingCanvas::
keyPressEvent(QKeyEvent *)
{
}
| 21.646302 | 93 | 0.670826 | colinw7 |
c4f0c2c7196823dc9b7e4df7ce7ecaa079388207 | 4,070 | hpp | C++ | krest/core/AbstractDataSink.hpp | mwoehlke-kitware/krest | fe83740bd685507e358c4cdfb2438b3e3e70266f | [
"BSD-3-Clause"
] | 1 | 2021-04-06T16:07:59.000Z | 2021-04-06T16:07:59.000Z | krest/core/AbstractDataSink.hpp | mwoehlke-kitware/krest | fe83740bd685507e358c4cdfb2438b3e3e70266f | [
"BSD-3-Clause"
] | 1 | 2021-01-13T16:49:46.000Z | 2021-01-13T16:49:46.000Z | krest/core/AbstractDataSink.hpp | mwoehlke-kitware/krest | fe83740bd685507e358c4cdfb2438b3e3e70266f | [
"BSD-3-Clause"
] | 2 | 2021-01-19T15:14:50.000Z | 2021-01-19T15:16:16.000Z | /* This file is part of Krest, and is distributed under the OSI-approved BSD
* 3-Clause License. See top-level LICENSE file or
* https://github.com/Kitware/krest/blob/master/LICENSE for details. */
#ifndef krest_core_AbstractDataSink_hpp
#define krest_core_AbstractDataSink_hpp
#include <krest/core/Export.h>
#include <vital/types/transform_2d.h>
#include <QObject>
class QAbstractItemModel;
class QUrl;
namespace krest
{
namespace core
{
class VideoSource;
// ============================================================================
class KREST_CORE_EXPORT AbstractDataSink : public QObject
{
Q_OBJECT
public:
AbstractDataSink(QObject* parent = nullptr);
~AbstractDataSink() override;
/// Sets the (primary) data to be written by the sink.
///
/// This method is used to tell the sink what data to write. Typically, the
/// sink will perform some collation of the input data.
///
/// This method returns \c false if the sink does not find any data to write.
/// Typically, the caller will use this to determine if there is anything to
/// be written before prompting the user for the destination to which the
/// data will be written.
///
/// \note Changing the model data after calling #setData and before calling
/// #writeData may result in undefined behavior.
///
/// \note Setting the primary data may erase any supplemental data that has
/// been added using #addData and may reset the primary transformation
/// supplied by #setTransform. Users should call this method \em first.
virtual bool setData(VideoSource* video, QAbstractItemModel* model,
bool includeHidden = false) = 0;
/// Sets the transform to be used for supplemental data.
///
/// This method specifies a transform that maps from the primary data's
/// coordinate space into a common coordinate space. This is required in
/// order to use supplemental data. If the sink does not support supplemental
/// data, or cannot compute the required inverse transform, this method will
/// return \c false.
///
/// \note Changing the transform may erase any supplemental data that has
/// been added using #addData.
virtual bool setTransform(kwiver::vital::transform_2d_sptr const& transform);
/// Adds supplemental data to be written by the sink.
///
/// This method is used to add supplemental data for the sink to write.
/// Typically, the sink will perform some collation of the input data.
///
/// Supplemental data exists in a different coordinate space than the primary
/// data. The provided transform is used to map supplemental data into a
/// common coordinate space, which is \em not the same as the primary data's
/// coordinate space.
///
/// This method returns \c false if the sink does not find any data to write,
/// or does not support supplemental data. Typically, the caller will use
/// this to determine if there is anything to be written before prompting the
/// user for the destination to which the data will be written.
///
/// \note This method may fail if no primary data has been provided.
///
/// \sa #setTransform
virtual bool addData(QAbstractItemModel* model,
kwiver::vital::transform_2d_sptr const& transform,
bool includeHidden = false);
/// Write data to the specified URI.
///
/// This instructs the sink to write the data that was previously provided by
/// a call to #setData to the specified URI. Data writing is synchronous; the
/// call will not return until the data has been written. (However, the sink
/// may internally implement an event loop.)
///
/// If an error occurs, #failed will be emitted, and the contents of the
/// specified output location are unspecified. (For example, if the URI named
/// an existing file, its contents may have been overwritten.)
virtual void writeData(QUrl const& uri) const = 0;
signals:
void failed(QString const& message) const;
};
} // namespace core
} // namespace krest
#endif
| 37.685185 | 79 | 0.696314 | mwoehlke-kitware |
c4f555afb2e4dd6f69ddfbeee7a363d0ec688111 | 16,222 | cpp | C++ | install/halodi_msgs/include/halodi_msgs/msg/feedback_parameters3_d__type_support.cpp | AHGOverbeek/halodi-messages | 4286676cb85cc4d5b2684523c1482afc9eef6ec9 | [
"Apache-2.0"
] | null | null | null | install/halodi_msgs/include/halodi_msgs/msg/feedback_parameters3_d__type_support.cpp | AHGOverbeek/halodi-messages | 4286676cb85cc4d5b2684523c1482afc9eef6ec9 | [
"Apache-2.0"
] | 3 | 2020-11-05T14:53:41.000Z | 2021-04-27T13:40:47.000Z | install/halodi_msgs/include/halodi_msgs/msg/feedback_parameters3_d__type_support.cpp | AHGOverbeek/halodi-messages | 4286676cb85cc4d5b2684523c1482afc9eef6ec9 | [
"Apache-2.0"
] | 1 | 2021-10-05T14:08:08.000Z | 2021-10-05T14:08:08.000Z | // generated from rosidl_typesupport_introspection_cpp/resource/idl__type_support.cpp.em
// with input from halodi_msgs:msg/FeedbackParameters3D.idl
// generated code does not contain a copyright notice
#include "array"
#include "cstddef"
#include "string"
#include "vector"
#include "rosidl_generator_c/message_type_support_struct.h"
#include "rosidl_typesupport_cpp/message_type_support.hpp"
#include "rosidl_typesupport_interface/macros.h"
#include "halodi_msgs/msg/feedback_parameters3_d__struct.hpp"
#include "rosidl_typesupport_introspection_cpp/field_types.hpp"
#include "rosidl_typesupport_introspection_cpp/identifier.hpp"
#include "rosidl_typesupport_introspection_cpp/message_introspection.hpp"
#include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp"
#include "rosidl_typesupport_introspection_cpp/visibility_control.h"
namespace halodi_msgs
{
namespace msg
{
namespace rosidl_typesupport_introspection_cpp
{
void FeedbackParameters3D_init_function(
void * message_memory, rosidl_generator_cpp::MessageInitialization _init)
{
new (message_memory) halodi_msgs::msg::FeedbackParameters3D(_init);
}
void FeedbackParameters3D_fini_function(void * message_memory)
{
auto typed_message = static_cast<halodi_msgs::msg::FeedbackParameters3D *>(message_memory);
typed_message->~FeedbackParameters3D();
}
size_t size_function__FeedbackParameters3D__integral(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<geometry_msgs::msg::Vector3> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__integral(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<geometry_msgs::msg::Vector3> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__integral(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<geometry_msgs::msg::Vector3> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__integral(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<geometry_msgs::msg::Vector3> *>(untyped_member);
member->resize(size);
}
size_t size_function__FeedbackParameters3D__maximum_proportional_error(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<double> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__maximum_proportional_error(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<double> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__maximum_proportional_error(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<double> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__maximum_proportional_error(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<double> *>(untyped_member);
member->resize(size);
}
size_t size_function__FeedbackParameters3D__maximum_integral_windup(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<double> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__maximum_integral_windup(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<double> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__maximum_integral_windup(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<double> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__maximum_integral_windup(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<double> *>(untyped_member);
member->resize(size);
}
size_t size_function__FeedbackParameters3D__maximum_derivative_error(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<double> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__maximum_derivative_error(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<double> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__maximum_derivative_error(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<double> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__maximum_derivative_error(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<double> *>(untyped_member);
member->resize(size);
}
size_t size_function__FeedbackParameters3D__maximum_feedback(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<double> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__maximum_feedback(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<double> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__maximum_feedback(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<double> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__maximum_feedback(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<double> *>(untyped_member);
member->resize(size);
}
size_t size_function__FeedbackParameters3D__maximum_feedback_rate(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<double> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__maximum_feedback_rate(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<double> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__maximum_feedback_rate(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<double> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__maximum_feedback_rate(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<double> *>(untyped_member);
member->resize(size);
}
size_t size_function__FeedbackParameters3D__integral_leakage(const void * untyped_member)
{
const auto * member = reinterpret_cast<const std::vector<double> *>(untyped_member);
return member->size();
}
const void * get_const_function__FeedbackParameters3D__integral_leakage(const void * untyped_member, size_t index)
{
const auto & member =
*reinterpret_cast<const std::vector<double> *>(untyped_member);
return &member[index];
}
void * get_function__FeedbackParameters3D__integral_leakage(void * untyped_member, size_t index)
{
auto & member =
*reinterpret_cast<std::vector<double> *>(untyped_member);
return &member[index];
}
void resize_function__FeedbackParameters3D__integral_leakage(void * untyped_member, size_t size)
{
auto * member =
reinterpret_cast<std::vector<double> *>(untyped_member);
member->resize(size);
}
static const ::rosidl_typesupport_introspection_cpp::MessageMember FeedbackParameters3D_message_member_array[9] = {
{
"proportional", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<geometry_msgs::msg::Vector3>(), // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, proportional), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"integral", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<geometry_msgs::msg::Vector3>(), // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, integral), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__integral, // size() function pointer
get_const_function__FeedbackParameters3D__integral, // get_const(index) function pointer
get_function__FeedbackParameters3D__integral, // get(index) function pointer
resize_function__FeedbackParameters3D__integral // resize(index) function pointer
},
{
"derivative", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<geometry_msgs::msg::Vector3>(), // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, derivative), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"maximum_proportional_error", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_DOUBLE, // type
0, // upper bound of string
nullptr, // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, maximum_proportional_error), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__maximum_proportional_error, // size() function pointer
get_const_function__FeedbackParameters3D__maximum_proportional_error, // get_const(index) function pointer
get_function__FeedbackParameters3D__maximum_proportional_error, // get(index) function pointer
resize_function__FeedbackParameters3D__maximum_proportional_error // resize(index) function pointer
},
{
"maximum_integral_windup", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_DOUBLE, // type
0, // upper bound of string
nullptr, // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, maximum_integral_windup), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__maximum_integral_windup, // size() function pointer
get_const_function__FeedbackParameters3D__maximum_integral_windup, // get_const(index) function pointer
get_function__FeedbackParameters3D__maximum_integral_windup, // get(index) function pointer
resize_function__FeedbackParameters3D__maximum_integral_windup // resize(index) function pointer
},
{
"maximum_derivative_error", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_DOUBLE, // type
0, // upper bound of string
nullptr, // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, maximum_derivative_error), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__maximum_derivative_error, // size() function pointer
get_const_function__FeedbackParameters3D__maximum_derivative_error, // get_const(index) function pointer
get_function__FeedbackParameters3D__maximum_derivative_error, // get(index) function pointer
resize_function__FeedbackParameters3D__maximum_derivative_error // resize(index) function pointer
},
{
"maximum_feedback", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_DOUBLE, // type
0, // upper bound of string
nullptr, // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, maximum_feedback), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__maximum_feedback, // size() function pointer
get_const_function__FeedbackParameters3D__maximum_feedback, // get_const(index) function pointer
get_function__FeedbackParameters3D__maximum_feedback, // get(index) function pointer
resize_function__FeedbackParameters3D__maximum_feedback // resize(index) function pointer
},
{
"maximum_feedback_rate", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_DOUBLE, // type
0, // upper bound of string
nullptr, // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, maximum_feedback_rate), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__maximum_feedback_rate, // size() function pointer
get_const_function__FeedbackParameters3D__maximum_feedback_rate, // get_const(index) function pointer
get_function__FeedbackParameters3D__maximum_feedback_rate, // get(index) function pointer
resize_function__FeedbackParameters3D__maximum_feedback_rate // resize(index) function pointer
},
{
"integral_leakage", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_DOUBLE, // type
0, // upper bound of string
nullptr, // members of sub message
true, // is array
1, // array size
true, // is upper bound
offsetof(halodi_msgs::msg::FeedbackParameters3D, integral_leakage), // bytes offset in struct
nullptr, // default value
size_function__FeedbackParameters3D__integral_leakage, // size() function pointer
get_const_function__FeedbackParameters3D__integral_leakage, // get_const(index) function pointer
get_function__FeedbackParameters3D__integral_leakage, // get(index) function pointer
resize_function__FeedbackParameters3D__integral_leakage // resize(index) function pointer
}
};
static const ::rosidl_typesupport_introspection_cpp::MessageMembers FeedbackParameters3D_message_members = {
"halodi_msgs::msg", // message namespace
"FeedbackParameters3D", // message name
9, // number of fields
sizeof(halodi_msgs::msg::FeedbackParameters3D),
FeedbackParameters3D_message_member_array, // message members
FeedbackParameters3D_init_function, // function to initialize message memory (memory has to be allocated)
FeedbackParameters3D_fini_function // function to terminate message instance (will not free memory)
};
static const rosidl_message_type_support_t FeedbackParameters3D_message_type_support_handle = {
::rosidl_typesupport_introspection_cpp::typesupport_identifier,
&FeedbackParameters3D_message_members,
get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_introspection_cpp
} // namespace msg
} // namespace halodi_msgs
namespace rosidl_typesupport_introspection_cpp
{
template<>
ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC
const rosidl_message_type_support_t *
get_message_type_support_handle<halodi_msgs::msg::FeedbackParameters3D>()
{
return &::halodi_msgs::msg::rosidl_typesupport_introspection_cpp::FeedbackParameters3D_message_type_support_handle;
}
} // namespace rosidl_typesupport_introspection_cpp
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, halodi_msgs, msg, FeedbackParameters3D)() {
return &::halodi_msgs::msg::rosidl_typesupport_introspection_cpp::FeedbackParameters3D_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
| 38.901679 | 134 | 0.774011 | AHGOverbeek |
c4f5838d7ff632354152537fc38e2044a64591d6 | 418 | cpp | C++ | Challenges - Sorting & Searching/Winning CB Scholarship.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | 3 | 2019-10-04T13:24:16.000Z | 2020-01-22T05:07:02.000Z | Challenges - Sorting & Searching/Winning CB Scholarship.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | null | null | null | Challenges - Sorting & Searching/Winning CB Scholarship.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ll N, M, X, Y, r_cpn, c_cpn, ans = INT_MIN;
cin >> N >> M >> X >> Y;
ll st = 1, ed = N;
ll mid = (st+ed)/2;
while(st <= ed){
mid = (st+ed)/2;
r_cpn = mid*X;
c_cpn = M + (N-mid)*Y;
if(r_cpn > c_cpn)
ed = mid-1;
else if(r_cpn <= c_cpn){
ans = max(ans, mid);
st = mid+1;
}
}
cout << ans;
return 0;
} | 14.413793 | 44 | 0.502392 | helewrer3 |
c4f71328bc68fc79f731aa6cb23abc7869f33e4d | 400 | cpp | C++ | practice/algorithms/birthday-cake-candles.cpp | geezardo/hackerrank | c3dd829ba803bd21ec3f432f419e40415cf6a6a8 | [
"MIT"
] | null | null | null | practice/algorithms/birthday-cake-candles.cpp | geezardo/hackerrank | c3dd829ba803bd21ec3f432f419e40415cf6a6a8 | [
"MIT"
] | null | null | null | practice/algorithms/birthday-cake-candles.cpp | geezardo/hackerrank | c3dd829ba803bd21ec3f432f419e40415cf6a6a8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a (n);
for (int i = 0; i < n; i++) cin >> a[i];
sort(a.begin(), a.end());
auto lb = lower_bound(a.begin(), a.end(), a[n - 1]);
int sum = 0;
for (auto it = lb; it != a.end(); it++) sum++;
cout << sum << endl;
return 0;
}
| 14.814815 | 54 | 0.5175 | geezardo |
c4f73ea2e0c7a774f1a8ce6f901f00efd9361853 | 2,146 | cpp | C++ | src/widgets/outlineprovider.cpp | l1422586361/vnote | 606dcef16f882350cc2be2fd108625894d13143b | [
"MIT"
] | 8,054 | 2016-10-19T14:59:52.000Z | 2020-10-11T06:21:15.000Z | src/widgets/outlineprovider.cpp | micalstanley/vnote-1 | 606dcef16f882350cc2be2fd108625894d13143b | [
"MIT"
] | 1,491 | 2017-03-06T02:31:32.000Z | 2020-10-11T02:14:32.000Z | src/widgets/outlineprovider.cpp | micalstanley/vnote-1 | 606dcef16f882350cc2be2fd108625894d13143b | [
"MIT"
] | 986 | 2017-02-14T05:45:13.000Z | 2020-10-10T07:42:31.000Z | #include "outlineprovider.h"
using namespace vnotex;
void Outline::clear()
{
m_headings.clear();
}
bool Outline::operator==(const Outline &p_a) const
{
return m_headings == p_a.m_headings;
}
bool Outline::isEmpty() const
{
return m_headings.isEmpty();
}
Outline::Heading::Heading(const QString &p_name, int p_level)
: m_name(p_name),
m_level(p_level)
{
}
bool Outline::Heading::operator==(const Outline::Heading &p_a) const
{
return m_level == p_a.m_level && m_name == p_a.m_name;
}
OutlineProvider::OutlineProvider(QObject *p_parent)
: QObject(p_parent)
{
}
OutlineProvider::~OutlineProvider()
{
}
void OutlineProvider::setOutline(const QSharedPointer<Outline> &p_outline)
{
m_outline = p_outline;
m_currentHeadingIndex = -1;
emit outlineChanged();
}
const QSharedPointer<Outline> &OutlineProvider::getOutline() const
{
return m_outline;
}
int OutlineProvider::getCurrentHeadingIndex() const
{
return m_currentHeadingIndex;
}
void OutlineProvider::setCurrentHeadingIndex(int p_idx)
{
if (m_currentHeadingIndex == p_idx) {
return;
}
m_currentHeadingIndex = p_idx;
emit currentHeadingChanged();
}
void OutlineProvider::increaseSectionNumber(SectionNumber &p_sectionNumber, int p_level, int p_baseLevel)
{
Q_ASSERT(p_level >= 1 && p_level < p_sectionNumber.size());
if (p_level < p_baseLevel) {
p_sectionNumber.fill(0);
return;
}
++p_sectionNumber[p_level];
for (int i = p_level + 1; i < p_sectionNumber.size(); ++i) {
p_sectionNumber[i] = 0;
}
}
QString OutlineProvider::joinSectionNumber(const SectionNumber &p_sectionNumber, bool p_endingDot)
{
QString res;
for (auto sec : p_sectionNumber) {
if (sec != 0) {
if (res.isEmpty()) {
res = QString::number(sec);
} else {
res += '.' + QString::number(sec);
}
} else if (res.isEmpty()) {
continue;
} else {
break;
}
}
if (p_endingDot && !res.isEmpty()) {
return res + '.';
} else {
return res;
}
}
| 20.634615 | 105 | 0.632805 | l1422586361 |
c4fbc70e4741770df8cd09eb41601131ae677538 | 3,090 | hpp | C++ | include/SSVStart/Assets/Internal/Loader.hpp | vittorioromeo/SSVStart | ba604007e54462df30346d9c0545ba3274850f49 | [
"AFL-3.0"
] | 11 | 2015-01-27T09:45:11.000Z | 2017-10-05T17:14:40.000Z | include/SSVStart/Assets/Internal/Loader.hpp | vittorioromeo/SSVStart | ba604007e54462df30346d9c0545ba3274850f49 | [
"AFL-3.0"
] | 2 | 2019-12-16T00:24:29.000Z | 2019-12-17T13:57:42.000Z | include/SSVStart/Assets/Internal/Loader.hpp | vittorioromeo/SSVStart | ba604007e54462df30346d9c0545ba3274850f49 | [
"AFL-3.0"
] | 7 | 2015-01-29T17:05:52.000Z | 2020-08-12T22:59:47.000Z | // Copyright (c) 2013-2015 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#pragma once
#include "SSVStart/BitmapText/BitmapText.hpp"
#include "SSVStart/Tileset/Tileset.hpp"
#include "SSVStart/Assets/Internal/Helper.hpp"
#include <SSVUtils/Core/FileSystem/Path.hpp>
#include <cstddef>
namespace ssvs::Impl
{
template <typename T>
struct Loader // Most resources can be loaded only from Path, Memory or
// Stream
{
template <typename... TArgs>
static auto load(TArgs&&... mArgs)
{
return Helper<Mode::Load, T>::load(mArgs...);
}
};
template <>
struct Loader<sf::Texture> // Texture can also be loaded from Image
{
using T = sf::Texture;
static auto load(const ssvu::FileSystem::Path& mPath)
{
return Helper<Mode::Load, T>::load(mPath);
}
static auto load(const void* mData, std::size_t mSize)
{
return Helper<Mode::Load, T>::load(mData, mSize);
}
static auto load(sf::InputStream& mStream)
{
return Helper<Mode::Load, T>::load(mStream);
}
static auto load(const sf::Image& mImage)
{
return Helper<Mode::Image, T>::load(mImage);
}
};
template <>
struct Loader<sf::SoundBuffer> // SoundBuffer can also be loaded from
// samples
{
using T = sf::SoundBuffer;
static auto load(const ssvu::FileSystem::Path& mPath)
{
return Helper<Mode::Load, T>::load(mPath);
}
static auto load(const void* mData, std::size_t mSize)
{
return Helper<Mode::Load, T>::load(mData, mSize);
}
static auto load(sf::InputStream& mStream)
{
return Helper<Mode::Load, T>::load(mStream);
}
static auto load(const sf::Int16* mSamples, std::size_t mSampleCount,
unsigned int mChannelCount, unsigned int mSampleRate)
{
return Helper<Mode::Samples, T>::load(
mSamples, mSampleCount, mChannelCount, mSampleRate);
}
};
template <>
struct Loader<sf::Music> // Music can be opened from Path, Memory or
// StreamloadFromFile
{
using T = sf::Music;
template <typename... TArgs>
static auto load(TArgs&&... mArgs)
{
return Helper<Mode::Open, T>::load(FWD(mArgs)...);
}
};
template <>
struct Loader<sf::Shader> // Shader has unique syntax
{
using T = sf::Shader;
template <typename... TArgs>
static auto load(TArgs&&... mArgs)
{
return Helper<Mode::Shader, T>::load(FWD(mArgs)...);
}
};
template <>
struct Loader<BitmapFont> // BitmapFont has unique syntax
{
using T = BitmapFont;
template <typename... TArgs>
static auto load(TArgs&&... mArgs)
{
return Helper<Mode::BitmapFont, T>::load(FWD(mArgs)...);
}
};
template <>
struct Loader<Tileset> // Tileset has unique syntax
{
using T = Tileset;
template <typename... TArgs>
static auto load(TArgs&&... mArgs)
{
return Helper<Mode::Tileset, T>::load(FWD(mArgs)...);
}
};
} // namespace ssvs::Impl
| 23.769231 | 73 | 0.615858 | vittorioromeo |
c4fe06d0e89af85642f74102c029023403bba445 | 917 | hpp | C++ | src/Jogo/Resources/TexturesHolder.hpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | src/Jogo/Resources/TexturesHolder.hpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | src/Jogo/Resources/TexturesHolder.hpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | //
// TexturesHolder.hpp
// Jogo-SFML
//
// Created by Matheus Kunnen Ledesma on 10/6/19.
// Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved.
//
#ifndef TexturesHolder_hpp
#define TexturesHolder_hpp
#include "../base_includes.hpp"
#include "ResourcesHolder.hpp"
namespace Game { namespace Resources{
namespace Textures {
enum ID {bg_menu, bg_config, bg_ranking, bg_fase, bg_game, bg_pause, jogador_a, jogador_b, narcotraficante, desmatador, narcotraficante_desmatador, planta_venenosa, pedra, espinhos, projetil};
}
class TextureHolder : public ResourceHolder<sf::Texture, Textures::ID>{
private:
// Attributes
static map<Textures::ID, string> default_filenames;
// Const
static const string DEFAULT_NOT_FILE;
public:
TextureHolder();
~TextureHolder();
// Methods
static const string& getFilename(Textures::ID id);
};
};};
#endif /* TexturesHolder_hpp */
| 26.2 | 196 | 0.730643 | MatheusKunnen |
c4fef3501d1e79063d25b709e2a8c0c0df6017e9 | 289 | cpp | C++ | Dataset/Leetcode/test/112/795.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/112/795.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/112/795.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
bool XXX(TreeNode* root, int sum) {
if(root==nullptr) return false;//空树
sum-=root->val;
if(root->left==nullptr&&root->right==nullptr) //叶节点
return sum==0;
return XXX(root->left,sum)||XXX(root->right,sum);
}
};
| 24.083333 | 59 | 0.557093 | kkcookies99 |
f2021f7c98f0cb0d818ce3b84d16ae26332d5d05 | 1,029 | cpp | C++ | Classes/Character/Traps/FallingTrap2.cpp | HoangTrongMinhDuc/JMOK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | 1 | 2019-07-11T08:06:06.000Z | 2019-07-11T08:06:06.000Z | Classes/Character/Traps/FallingTrap2.cpp | HoangTrongMinhDuc/JOMK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | null | null | null | Classes/Character/Traps/FallingTrap2.cpp | HoangTrongMinhDuc/JOMK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | 1 | 2021-09-13T12:00:12.000Z | 2021-09-13T12:00:12.000Z | #include "FallingTrap2.h"
#include "Helper\Helper.h"
FallingTrap2::FallingTrap2()
{
m_sprite = NULL;
m_isFall = false;
}
void FallingTrap2::update(float deltaTime)
{
Trap::update(deltaTime);
if (m_isFall)
m_physicsBody->SetType(b2_dynamicBody);
}
void FallingTrap2::collision(LivingObject *lObj, void *data)
{
if (!m_isFall) {
bool *p = &m_isFall;
std::function<void(void)> func([p](){
*p = true;
});
Helper::waitAndExecute(500, func);
}
}
void FallingTrap2::setAttribute(const rapidjson::GenericValue < rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator
< rapidjson::CrtAllocator >> *attribute)
{
if (attribute->FindMember("Sprite") != attribute->MemberEnd()) {
auto sprite = &(*attribute)["Sprite"];
if (sprite->FindMember("Image") != sprite->MemberEnd()) {
std::string link = (*sprite)["Image"].GetString();
m_sprite = Sprite::create(link);
m_sprite->retain();
}
if (sprite->FindMember("Scale") != sprite->MemberEnd())
m_sprite->setScale((*sprite)["Scale"].GetFloat());
}
} | 22.866667 | 117 | 0.677357 | HoangTrongMinhDuc |
f2035d55167952bad1b2980f66af46a14e20d846 | 268 | cpp | C++ | lldb/packages/Python/lldbsuite/test/commands/process/launch/main.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp | DalavanCloud/lldb | e913eaf2468290fb94c767d474d611b41a84dd69 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp | DalavanCloud/lldb | e913eaf2468290fb94c767d474d611b41a84dd69 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | #include <stdio.h>
#include <stdlib.h>
int
main (int argc, char **argv)
{
char buffer[1024];
fgets (buffer, sizeof (buffer), stdin);
fprintf (stdout, "%s", buffer);
fgets (buffer, sizeof (buffer), stdin);
fprintf (stderr, "%s", buffer);
return 0;
}
| 14.888889 | 41 | 0.619403 | medismailben |
f203968e1899e726d69b2e8a57e506a629b2fe7c | 712 | cpp | C++ | Week 6/Lab/Old/Week 6 Sample Programs/Pr9-8.cpp | sugamkarki/NAMI-Year-II-Term-I-Software_Engineering | 39182816b670dcb75ec322e24b346a4cfeb80be0 | [
"Apache-2.0"
] | null | null | null | Week 6/Lab/Old/Week 6 Sample Programs/Pr9-8.cpp | sugamkarki/NAMI-Year-II-Term-I-Software_Engineering | 39182816b670dcb75ec322e24b346a4cfeb80be0 | [
"Apache-2.0"
] | null | null | null | Week 6/Lab/Old/Week 6 Sample Programs/Pr9-8.cpp | sugamkarki/NAMI-Year-II-Term-I-Software_Engineering | 39182816b670dcb75ec322e24b346a4cfeb80be0 | [
"Apache-2.0"
] | null | null | null | // This program uses the address of each element in the array.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int NUM_COINS = 5;
double coins[NUM_COINS] = {0.05, 0.1, 0.25, 0.5, 1.0};
double *doublePtr; // Pointer to a double
int count; // Array index
// Use the pointer to display the values in the array.
cout << "Here are the values in the coins array:\n";
for (count = 0; count < NUM_COINS; count++)
{
// Get the address of an array element.
doublePtr = &coins[count];
// Display the contents of the element.
cout << *doublePtr << " ";
}
cout << endl;
system("PAUSE");
return 0;
} | 27.384615 | 63 | 0.592697 | sugamkarki |
f206c47f392e55176ed6e6d6daa1da23e72fe2ee | 67,074 | cpp | C++ | Object_Recognition/src/pnp/signature.cpp | EricCJoyce/The-Recognitions | 05aafbcd124988d58b1cc60070b9ad17d49322d7 | [
"MIT"
] | 1 | 2021-06-29T20:53:18.000Z | 2021-06-29T20:53:18.000Z | Object_Recognition/src/pnp/signature.cpp | EricCJoyce/The-Recognitions | 05aafbcd124988d58b1cc60070b9ad17d49322d7 | [
"MIT"
] | null | null | null | Object_Recognition/src/pnp/signature.cpp | EricCJoyce/The-Recognitions | 05aafbcd124988d58b1cc60070b9ad17d49322d7 | [
"MIT"
] | 1 | 2021-09-26T03:14:49.000Z | 2021-09-26T03:14:49.000Z | #ifndef __SIGNATURE_CPP
#define __SIGNATURE_CPP
#include "signature.h"
/**************************************************************************************************
Constructors */
/* Signature constructor, no data given */
Signature::Signature()
{
unsigned int i;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::Signature()" << endl;
#endif
_numPoints = 0;
_numMutex = 0;
filenameLen = 0;
if((descriptorCtr = (unsigned int*)malloc(_DESCRIPTOR_TOTAL * sizeof(int))) == NULL)
{
cout << "ERROR: Unable to allocate signature descriptor-count vector." << endl;
exit(1);
}
_index = -1;
bboxminX = 0.0;
bboxminY = 0.0;
bboxminZ = 0.0;
bboxmaxX = 0.0;
bboxmaxY = 0.0;
bboxmaxZ = 0.0;
for(i = 0; i < _DESCRIPTOR_TOTAL; i++) // Blank out descriptor counters
descriptorCtr[i] = 0;
for(i = 0; i < 512; i++) // Blank out header
hdr[i] = 0;
}
/**************************************************************************************************
Destructor */
Signature::~Signature()
{
if(filenameLen > 0)
free(_filename);
free(descriptorCtr);
if(_numPoints > 0)
free(d);
}
/**************************************************************************************************
Load from file */
/* Read the given file into a presently allocated Signature. */
bool Signature::load(char* filepath)
{
FILE* fp; // .3df file
unsigned char totalDesc;
unsigned char flagArray;
float x, y, z; // Temp storage
unsigned char desc;
unsigned char descLen;
float size, angle, response;
signed int octave;
unsigned char* ucharBuffer;
float* floatBuffer;
unsigned int i;
bool good;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::load(" << filepath << ")" << endl;
#endif
if(filenameLen > 0) // Did we have a file name stored already?
free(_filename);
if(_numPoints > 0) // Did we have Descriptors stored already?
free(d);
for(i = 0; i < _DESCRIPTOR_TOTAL; i++) // Reset descriptor counters
descriptorCtr[i] = 0;
filenameLen = strlen(filepath); // Save the length of the string
if((_filename = (char*)malloc((filenameLen + 1) * sizeof(char))) == NULL)
{
cout << "ERROR: Unable to allocate signature file name buffer." << endl;
return false;
}
for(i = 0; i < filenameLen; i++) // Copy file name
_filename[i] = filepath[i];
_filename[i] = '\0'; // NULL-cap the string
if((fp = fopen(_filename, "rb")) == NULL) // Open file for reading
{
cout << "ERROR: Unable to open \"" << _filename << "\"." << endl;
return false;
}
fseek(fp, 0, SEEK_SET); // Start at the beginning
good = ((fread(hdr, sizeof(char), 512, fp)) == 512); // Read the 512-byte header
good = ((fread(&_numPoints, sizeof(int), 1, fp)) == 1); // unsigned int: Total number of feature-points
good = ((fread(&_numMutex, sizeof(int), 1, fp)) == 1); // unsigned int: Total number of exclusivity-constraints
good = ((fread(&totalDesc, sizeof(char), 1, fp)) == 1); // unsigned char: Total number of descriptors
good = ((fread(&flagArray, sizeof(char), 1, fp)) == 1); // unsigned char: descriptor boolean array
good = ((fread(&bboxminX, sizeof(float), 1, fp)) == 1); // Read bounding box min-min-min
good = ((fread(&bboxminY, sizeof(float), 1, fp)) == 1);
good = ((fread(&bboxminZ, sizeof(float), 1, fp)) == 1);
good = ((fread(&bboxmaxX, sizeof(float), 1, fp)) == 1); // Read bounding box max-max-max
good = ((fread(&bboxmaxY, sizeof(float), 1, fp)) == 1);
good = ((fread(&bboxmaxZ, sizeof(float), 1, fp)) == 1);
#ifdef __SIGNATURE_DEBUG
cout << " header: " << hdr << endl;
cout << " numPoints: " << +_numPoints << endl;
cout << " numMutex: " << +_numMutex << endl;
cout << " totalDesc: " << +totalDesc << endl; // Total number of descriptors possible
cout << " flagArray: ";
if((flagArray & 8) == 8) // SURF
cout << "1";
else
cout << "0";
if((flagArray & 4) == 4) // SIFT
cout << "1";
else
cout << "0";
if((flagArray & 2) == 2) // ORB
cout << "1";
else
cout << "0";
if((flagArray & 1) == 1) // BRISK
cout << "1";
else
cout << "0";
cout << endl;
cout << " bbox min (" << bboxminX << ", " << bboxminY << ", " << bboxminZ <<
"), bbox max (" << bboxmaxX << ", " << bboxmaxY << ", " << bboxmaxZ << ")" << endl;
#endif
if(!good)
{
cout << "ERROR: Unable to read from \"" << _filename << "\"." << endl;
return false;
}
if((d = (Descriptor**)malloc(_numPoints * sizeof(Descriptor*))) == NULL)
{
cout << "ERROR: Unable to allocate descriptor-pointer buffer for \"" << _filename << "\"." << endl;
return false;
}
i = 0;
while(!feof(fp) && i < _numPoints) // Continue reading feature-points and feature-vectors
{
good = ((fread(&desc, sizeof(char), 1, fp)) == 1); // Read descriptor flag
good = ((fread(&x, sizeof(float), 1, fp)) == 1); // Read feature-point coordinates
good = ((fread(&y, sizeof(float), 1, fp)) == 1);
good = ((fread(&z, sizeof(float), 1, fp)) == 1);
good = ((fread(&size, sizeof(float), 1, fp)) == 1); // Read feature-point details
good = ((fread(&angle, sizeof(float), 1, fp)) == 1);
good = ((fread(&response, sizeof(float), 1, fp)) == 1);
good = ((fread(&octave, sizeof(int), 1, fp)) == 1);
good = ((fread(&descLen, sizeof(char), 1, fp)) == 1); // Read feature-point vector length
if(good)
{
switch(desc)
{
case _BRISK:
if((ucharBuffer = (unsigned char*)malloc(_BRISK_DESCLEN * sizeof(char))) == NULL)
{
cout << "ERROR: Unable to allocate BRISK descriptor vector buffer." << endl;
return false;
}
// Read in a descriptor-length's worth of chars
fread(ucharBuffer, sizeof(char), _BRISK_DESCLEN, fp);
d[i] = new BRISKDesc(ucharBuffer); // Create a new (BRISK) descriptor
d[i]->XYZ(x, y, z); // Save its 3D location
d[i]->setSize(size); // Save its details
d[i]->setAngle(angle);
d[i]->setResponse(response);
d[i]->setOctave(octave);
descriptorCtr[_BRISK]++; // Increment the count for this type of descriptor
free(ucharBuffer);
i++;
break;
case _ORB:
if((ucharBuffer = (unsigned char*)malloc(_ORB_DESCLEN * sizeof(char))) == NULL)
{
cout << "ERROR: Unable to allocate ORB descriptor vector buffer." << endl;
return false;
}
// Read in a descriptor-length's worth of chars
fread(ucharBuffer, sizeof(char), _ORB_DESCLEN, fp);
d[i] = new ORBDesc(ucharBuffer); // Create a new (ORB) descriptor
d[i]->XYZ(x, y, z); // Save its 3D location
d[i]->setSize(size); // Save its details
d[i]->setAngle(angle);
d[i]->setResponse(response);
d[i]->setOctave(octave);
descriptorCtr[_ORB]++; // Increment the count for this type of descriptor
free(ucharBuffer);
i++;
break;
case _SIFT:
if((floatBuffer = (float*)malloc(_SIFT_DESCLEN * sizeof(float))) == NULL)
{
cout << "ERROR: Unable to allocate SIFT descriptor vector buffer." << endl;
return false;
}
// Read in a descriptor-length's worth of floats
fread(floatBuffer, sizeof(float), _SIFT_DESCLEN, fp);
d[i] = new SIFTDesc(floatBuffer); // Create a new (SIFT) descriptor
d[i]->XYZ(x, y, z); // Save its 3D location
d[i]->setSize(size); // Save its details
d[i]->setAngle(angle);
d[i]->setResponse(response);
d[i]->setOctave(octave);
descriptorCtr[_SIFT]++; // Increment the count for this type of descriptor
free(floatBuffer);
i++;
break;
case _SURF:
if((floatBuffer = (float*)malloc(_SURF_DESCLEN * sizeof(float))) == NULL)
{
cout << "ERROR: Unable to allocate SURF descriptor vector buffer." << endl;
return false;
}
// Read in a descriptor-length's worth of floats
fread(floatBuffer, sizeof(float), _SURF_DESCLEN, fp);
d[i] = new SURFDesc(floatBuffer); // Create a new (SURF) descriptor
d[i]->XYZ(x, y, z); // Save its 3D location
d[i]->setSize(size); // Save its details
d[i]->setAngle(angle);
d[i]->setResponse(response);
d[i]->setOctave(octave);
descriptorCtr[_SURF]++; // Increment the count for this type of descriptor
free(floatBuffer);
i++;
break;
}
}
}
fclose(fp);
return true;
}
/**************************************************************************************************
Write to file */
/* Write in the .3df format */
bool Signature::write(char* fname) const
{
FILE* fp; // .3df file
unsigned char totalDesc = _DESCRIPTOR_TOTAL;
unsigned char flagArray = 0;
float x, y, z; // Temp storage
unsigned char desc;
unsigned char descLen;
float size, angle, response;
signed int octave;
unsigned char* ucharBuffer;
float* floatBuffer;
unsigned int i;
bool good;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::write(" << fname << ")" << endl;
#endif
if((fp = fopen(fname, "wb")) == NULL) // Open file for writing
{
cout << "ERROR: Unable to create \"" << fname << "\"." << endl;
return false;
}
good = ((fwrite(hdr, sizeof(char), 512, fp)) == 512); // Write the 512-byte header
good = ((fwrite(&_numPoints, sizeof(int), 1, fp)) == 1); // unsigned int: Total number of feature-points
good = ((fwrite(&_numMutex, sizeof(int), 1, fp)) == 1); // unsigned int: Total number of exclusivity-constraints
if(descriptorCtr[_BRISK] > 0)
flagArray |= 1;
if(descriptorCtr[_ORB] > 0)
flagArray |= 2;
if(descriptorCtr[_SIFT] > 0)
flagArray |= 4;
if(descriptorCtr[_SURF] > 0)
flagArray |= 8;
good = ((fwrite(&totalDesc, sizeof(char), 1, fp)) == 1); // unsigned char: Total number of descriptors
good = ((fwrite(&flagArray, sizeof(char), 1, fp)) == 1); // unsigned char: descriptor boolean array
good = ((fwrite(&bboxminX, sizeof(float), 1, fp)) == 1); // Read bounding box min-min-min
good = ((fwrite(&bboxminY, sizeof(float), 1, fp)) == 1);
good = ((fwrite(&bboxminZ, sizeof(float), 1, fp)) == 1);
good = ((fwrite(&bboxmaxX, sizeof(float), 1, fp)) == 1); // Read bounding box max-max-max
good = ((fwrite(&bboxmaxY, sizeof(float), 1, fp)) == 1);
good = ((fwrite(&bboxmaxZ, sizeof(float), 1, fp)) == 1);
if(!good)
{
cout << "ERROR: Unable to write to \"" << fname << "\"." << endl;
return false;
}
for(i = 0; i < _numPoints; i++)
{
desc = d[i]->type(); // Get the descriptor flag
good = ((fwrite(&desc, sizeof(char), 1, fp)) == 1); // Write descriptor flag
x = d[i]->x(); // Get the coordinates
y = d[i]->y();
z = d[i]->z();
good = ((fwrite(&x, sizeof(float), 1, fp)) == 1); // Write feature-point coordinates
good = ((fwrite(&y, sizeof(float), 1, fp)) == 1);
good = ((fwrite(&z, sizeof(float), 1, fp)) == 1);
size = d[i]->size(); // Get the interest point attributes
angle = d[i]->angle();
response = d[i]->response();
octave = d[i]->octave();
good = ((fwrite(&size, sizeof(float), 1, fp)) == 1); // Write feature-point details
good = ((fwrite(&angle, sizeof(float), 1, fp)) == 1);
good = ((fwrite(&response, sizeof(float), 1, fp)) == 1);
good = ((fwrite(&octave, sizeof(int), 1, fp)) == 1);
descLen = d[i]->len();
good = ((fwrite(&descLen, sizeof(char), 1, fp)) == 1); // Write feature-point vector length
if(good)
{
switch(desc)
{
case _BRISK:
d[i]->vec(&ucharBuffer); // Copy i-th Descriptor (a BRISK) to uchar buffer
good = ((fwrite(ucharBuffer, sizeof(char), _BRISK_DESCLEN, fp)) == _BRISK_DESCLEN);
free(ucharBuffer);
break;
case _ORB:
d[i]->vec(&ucharBuffer); // Copy i-th Descriptor (an ORB) to uchar buffer
good = ((fwrite(ucharBuffer, sizeof(char), _ORB_DESCLEN, fp)) == _ORB_DESCLEN);
free(ucharBuffer);
break;
case _SIFT:
d[i]->vec(&floatBuffer); // Copy i-th Descriptor (a SIFT) to float buffer
good = ((fwrite(floatBuffer, sizeof(float), _SIFT_DESCLEN, fp)) == _SIFT_DESCLEN);
free(floatBuffer);
break;
case _SURF:
d[i]->vec(&floatBuffer); // Copy i-th Descriptor (a SURF) to float buffer
good = ((fwrite(floatBuffer, sizeof(float), _SURF_DESCLEN, fp)) == _SURF_DESCLEN);
free(floatBuffer);
break;
}
}
if(!good)
{
cout << "ERROR: Write to file failed" << endl;
return false;
}
}
fclose(fp);
return true;
}
/* Write as ASCII text.
Signature file details will include the original file name, though this is written to a file under the given name. */
bool Signature::toText(char* fname) const
{
ofstream fh; // Output file handle
unsigned int i, j;
fh.open(fname);
fh << _filename << endl;
for(i = 0; i < filenameLen; i++)
fh << "=";
fh << endl << hdr << endl;
fh << +_numPoints << " features" << endl;
for(i = 0; i < _DESCRIPTOR_TOTAL; i++)
{
fh << " " << +descriptorCtr[i] << " ";
switch(i)
{
case _BRISK: fh << "BRISK" << endl; break;
case _ORB: fh << "ORB" << endl; break;
case _SIFT: fh << "SIFT" << endl; break;
case _SURF: fh << "SURF" << endl; break;
}
}
fh << +_numMutex << " mutual exclusions" << endl;
fh << "Bounding box: (" << bboxminX << ", " << bboxminY << ", " << bboxminZ << ")" << endl;
fh << " to (" << bboxmaxX << ", " << bboxmaxY << ", " << bboxmaxZ << ")" << endl;
for(i = 0; i < _numPoints; i++)
{
fh << "(" << d[i]->x() << ", " << d[i]->y() << ", " << d[i]->z() << ") ";
switch(d[i]->type())
{
case _BRISK: fh << "BRISK: "; break;
case _ORB: fh << "ORB: "; break;
case _SIFT: fh << "SIFT: "; break;
case _SURF: fh << "SURF: "; break;
}
if(d[i]->type() == _BRISK || d[i]->type() == _ORB)
{
for(j = 0; j < d[i]->len(); j++) // Fetch and write uchars to file
fh << d[i]->atu(j) << " ";
fh << endl;
}
else
{
for(j = 0; j < d[i]->len(); j++) // Fetch and write floats to file
fh << d[i]->atf(j) << " ";
fh << endl;
}
}
fh.close();
return true;
}
/**************************************************************************************************
Descriptor collection */
/* Fill a buffer with concatenated vectors of the given descriptor type.
Given 'type' in {BRISK, ORB, SIFT, SURF} write to a 1-dimensional buffer of length N x D,
where N is the number of features in stored using descriptor 'type'
and D is the length of that descriptor vector.
That is, if this Signature stores features in both BRISK and SURF,
then toBuffer(_BRISK) will fill (unsigned char*)'buffer' with N BRISK row-vectors,
and toBuffer(_SURF) will fill (float*)'buffer' with N SURF row-vectors. */
unsigned int Signature::toBuffer(unsigned char type, void** buffer) const
{
unsigned int i, j;
unsigned char k;
unsigned int len = 0;
unsigned char* ucharTmp; // Copy the vector from the Descriptor object
float* floatTmp;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::toBuffer(" << +type << ")" << endl;
cout << " " << +descriptorCtr[type] << " feature vectors" << endl;
#endif
if(descriptorCtr[type] > 0) // Are there any descriptors of the given type?
{
if(type == _BRISK) // Allocate the right buffer, the right amount
{
len = descriptorCtr[type] * _BRISK_DESCLEN;
if(((*buffer) = malloc(len * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate unsigned char buffer for BRISK output to void*." << endl;
#endif
return 0;
}
}
else if(type == _ORB)
{
len = descriptorCtr[type] * _ORB_DESCLEN;
if(((*buffer) = malloc(len * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate unsigned char buffer for ORB output to void*." << endl;
#endif
return 0;
}
}
else if(type == _SIFT)
{
len = descriptorCtr[type] * _SIFT_DESCLEN;
if(((*buffer) = malloc(len * sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate float buffer for SIFT output to void*." << endl;
#endif
return 0;
}
}
else if(type == _SURF)
{
len = descriptorCtr[type] * _SURF_DESCLEN;
if(((*buffer) = malloc(len * sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate float buffer for SURF output to void*." << endl;
#endif
return 0;
}
}
j = 0; // Offset into the buffer
for(i = 0; i < _numPoints; i++) // Now that we've allocated space, fill in that space
{
if(d[i]->type() == type) // If this is a Descriptor of the type we asked for...
{
if(type == _BRISK)
{
d[i]->vec(&ucharTmp); // Copy this descriptor to temp
for(k = 0; k < _BRISK_DESCLEN; k++) // Copy the temp into the total buffer
(*((unsigned char**)buffer))[j * _BRISK_DESCLEN + k] = ucharTmp[k];
free(ucharTmp); // Dump temp
}
else if(type == _ORB)
{
d[i]->vec(&ucharTmp); // Copy this descriptor to temp
for(k = 0; k < _ORB_DESCLEN; k++) // Copy the temp into the total buffer
(*((unsigned char**)buffer))[j * _ORB_DESCLEN + k] = ucharTmp[k];
free(ucharTmp); // Dump temp
}
else if(type == _SIFT)
{
d[i]->vec(&floatTmp); // Copy this descriptor to temp
for(k = 0; k < _SIFT_DESCLEN; k++) // Copy the temp into the total buffer
(*((float**)buffer))[j * _SIFT_DESCLEN + k] = floatTmp[k];
free(floatTmp); // Dump temp
}
else if(type == _SURF)
{
d[i]->vec(&floatTmp); // Copy this descriptor to temp
for(k = 0; k < _SURF_DESCLEN; k++) // Copy the temp into the total buffer
(*((float**)buffer))[j * _SURF_DESCLEN + k] = floatTmp[k];
free(floatTmp); // Dump temp
}
j++; // Increment offset into buffer
}
}
}
return len;
}
/* Export a cv::Mat using a specific descriptor type.
Compare to Extractor::descMat().
Given 'type' in {BRISK, ORB, SIFT, SURF} return an N x D cv::Mat
where N is the number of features in stored using descriptor 'type'
and D is the length of that descriptor vector.
That is, if this Signature stores features in both BRISK and SURF,
then toMat(_BRISK, mat) will fill 'mat' with N BRISK row-vectors,
and descMat(_SURF, mat) will fill 'mat' with N SURF row-vectors. */
void Signature::toMat(unsigned char type, cv::Mat* mat) const
{
unsigned char* ucharBuffer; // Accumulators
float* floatBuffer;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::toMat(" << +type << ")" << endl;
cout << " " << +descriptorCtr[type] << " feature vectors" << endl;
#endif
if(descriptorCtr[type] > 0) // Are there any descriptors of the given type?
{
if(type == _BRISK)
{
toBuffer(_BRISK, (void**)(&ucharBuffer));
(*mat) = cv::Mat(descriptorCtr[_BRISK], _BRISK_DESCLEN, CV_8U);
memcpy(mat->data, ucharBuffer, descriptorCtr[_BRISK] * _BRISK_DESCLEN * sizeof(char));
free(ucharBuffer);
}
else if(type == _ORB)
{
toBuffer(_ORB, (void**)(&ucharBuffer));
(*mat) = cv::Mat(descriptorCtr[_ORB], _ORB_DESCLEN, CV_8U);
memcpy(mat->data, ucharBuffer, descriptorCtr[_ORB] * _ORB_DESCLEN * sizeof(char));
free(ucharBuffer);
}
else if(type == _SIFT)
{
toBuffer(_SIFT, (void**)(&floatBuffer));
(*mat) = cv::Mat(descriptorCtr[_SIFT], _SIFT_DESCLEN, CV_32F);
memcpy(mat->data, floatBuffer, descriptorCtr[_SIFT] * _SIFT_DESCLEN * sizeof(float));
free(floatBuffer);
}
else if(type == _SURF)
{
toBuffer(_SURF, (void**)(&floatBuffer));
(*mat) = cv::Mat(descriptorCtr[_SURF], _SURF_DESCLEN, CV_32F, floatBuffer);
memcpy(mat->data, floatBuffer, descriptorCtr[_SURF] * _SURF_DESCLEN * sizeof(float));
free(floatBuffer);
}
}
return;
}
/* Write the i-th descriptor vector (of whatever type that is) to buffer */
unsigned char Signature::desc(unsigned int i, void** buffer) const
{
unsigned char len = 0;
unsigned char j;
if(i < _numPoints)
{
switch(d[i]->type())
{
case _BRISK: len = d[i]->len();
if(((*buffer) = malloc(len * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate void* buffer for " << +i << "-th feature." << endl;
#endif
return 0;
}
for(j = 0; j < len; j++)
(*((unsigned char**)buffer))[j] = d[i]->atu(j);
break;
case _ORB: len = d[i]->len();
if(((*buffer) = malloc(len * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate void* buffer for " << +i << "-th feature." << endl;
#endif
return 0;
}
for(j = 0; j < len; j++)
(*((unsigned char**)buffer))[j] = d[i]->atu(j);
break;
case _SIFT: len = d[i]->len();
if(((*buffer) = malloc(len * sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate void* buffer for " << +i << "-th feature." << endl;
#endif
return 0;
}
for(j = 0; j < len; j++)
(*((float**)buffer))[j] = d[i]->atf(j);
break;
case _SURF: len = d[i]->len();
if(((*buffer) = malloc(len * sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate void* buffer for " << +i << "-th feature." << endl;
#endif
return 0;
}
for(j = 0; j < len; j++)
(*((float**)buffer))[j] = d[i]->atf(j);
break;
}
}
return len;
}
/* Write the i-th descriptor vector of GIVEN type to buffer */
unsigned char Signature::descType(unsigned int i, unsigned char type, void** buffer) const
{
unsigned int index;
unsigned int j;
if(descriptorCtr[type] > 0) // Are there ANY Descriptors of this type?
{
index = 0;
j = 0;
while(index < _numPoints && j != i)
{
if(d[index]->type() == type)
j++;
index++;
}
return desc(j, buffer);
}
return 0;
}
/**************************************************************************************************
Details */
/* Return the count of features that use the given type of Descriptor */
unsigned int Signature::count(unsigned char type) const
{
if(type < _DESCRIPTOR_TOTAL)
return descriptorCtr[type];
return 0;
}
/* Return a flag-array (uchar) indicating which descriptors are in this Signature */
unsigned char Signature::flags(void) const
{
unsigned char f = 0;
if(descriptorCtr[_BRISK] > 0)
f |= 1;
if(descriptorCtr[_ORB] > 0)
f |= 2;
if(descriptorCtr[_SIFT] > 0)
f |= 4;
if(descriptorCtr[_SURF] > 0)
f |= 8;
return f;
}
/**************************************************************************************************
Pack-up */
/* Return the number of bytes */
unsigned int Signature::writeByteArray(char** buffer) const
{
unsigned int len = 0;
char* cast;
unsigned int i, j;
unsigned char k;
float tmpFloat;
int tmpInt;
unsigned char* ucharBuffer;
float* floatBuffer;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::writeByteArray()" << endl;
#endif
len += SIGNATURE_HEADER_LENGTH; // Characters in the header
len += (unsigned int)(sizeof(int) / sizeof(char)); // numPoints
len += (unsigned int)(sizeof(int) / sizeof(char)); // numMutex
len += filenameLen + 1; // filenameLen characters, plus the char for filenameLen
// A count for each descriptor the system can handle
len += (unsigned int)(sizeof(int) / sizeof(char)) * _DESCRIPTOR_TOTAL;
len += (unsigned int)(sizeof(float) / sizeof(char)); // bboxminX
len += (unsigned int)(sizeof(float) / sizeof(char)); // bboxminY
len += (unsigned int)(sizeof(float) / sizeof(char)); // bboxminZ
len += (unsigned int)(sizeof(float) / sizeof(char)); // bboxmaxX
len += (unsigned int)(sizeof(float) / sizeof(char)); // bboxmaxY
len += (unsigned int)(sizeof(float) / sizeof(char)); // bboxmaxZ
len += (unsigned int)(sizeof(int) / sizeof(char)); // index
for(i = 0; i < _numPoints; i++)
{
len += 2; // type and len
len += (unsigned int)(sizeof(float) / sizeof(char)); // x
len += (unsigned int)(sizeof(float) / sizeof(char)); // y
len += (unsigned int)(sizeof(float) / sizeof(char)); // z
len += (unsigned int)(sizeof(float) / sizeof(char)); // size
len += (unsigned int)(sizeof(float) / sizeof(char)); // angle
len += (unsigned int)(sizeof(float) / sizeof(char)); // response
len += (unsigned int)(sizeof(int) / sizeof(char)); // octave
len += (unsigned int)(sizeof(int) / sizeof(char)); // signature
switch(d[i]->type()) // Add the descriptor lengths
{
case _BRISK: len += _BRISK_DESCLEN; break; // Characters
case _ORB: len += _ORB_DESCLEN; break; // Characters
// Floats
case _SIFT: len += _SIFT_DESCLEN * (unsigned int)(sizeof(float) / sizeof(char));
break;
// Floats
case _SURF: len += _SURF_DESCLEN * (unsigned int)(sizeof(float) / sizeof(char));
break;
}
}
if(((*buffer) = (char*)malloc(len * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate byte array for Signature." << endl;
#endif
return 0;
}
len = 0; // Reset
for(i = 0; i < SIGNATURE_HEADER_LENGTH; i++) // Header
(*buffer)[len + i] = hdr[i];
len += i;
cast = (char*)(&_numPoints); // numPoints
for(i = 0; i < (unsigned char)(sizeof(int) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&_numMutex); // numMutex
for(i = 0; i < (unsigned char)(sizeof(int) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
(*buffer)[len] = filenameLen; // filenameLen
len++;
for(i = 0; i < filenameLen; i++) // filename
(*buffer)[len + i] = _filename[i];
len += filenameLen;
for(i = 0; i < _DESCRIPTOR_TOTAL; i++) // Counts for each descriptor type
{
tmpInt = descriptorCtr[i];
cast = (char*)(&tmpInt); // descriptorCtr[i]
for(j = 0; j < (unsigned char)(sizeof(int) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
}
cast = (char*)(&bboxminX); // bboxminX
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&bboxminY); // bboxminY
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&bboxminZ); // bboxminZ
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&bboxmaxX); // bboxmaxX
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&bboxmaxY); // bboxmaxY
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&bboxmaxZ); // bboxmaxZ
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
cast = (char*)(&_index); // index
for(i = 0; i < (unsigned char)(sizeof(int) / sizeof(char)); i++)
(*buffer)[len + i] = cast[i];
len += i;
for(i = 0; i < _numPoints; i++)
{
(*buffer)[len] = d[i]->type();
len++;
switch(d[i]->type())
{
case _BRISK: (*buffer)[len] = _BRISK_DESCLEN; break;
case _ORB: (*buffer)[len] = _ORB_DESCLEN; break;
case _SIFT: (*buffer)[len] = _SIFT_DESCLEN; break;
case _SURF: (*buffer)[len] = _SURF_DESCLEN; break;
}
len++;
tmpFloat = d[i]->x(); // x
cast = (char*)(&tmpFloat);
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpFloat = d[i]->y(); // y
cast = (char*)(&tmpFloat);
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpFloat = d[i]->z(); // z
cast = (char*)(&tmpFloat);
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpFloat = d[i]->size(); // size
cast = (char*)(&tmpFloat);
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpFloat = d[i]->angle(); // angle
cast = (char*)(&tmpFloat);
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpFloat = d[i]->response(); // response
cast = (char*)(&tmpFloat);
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpInt = d[i]->octave(); // octave
cast = (char*)(&tmpInt);
for(j = 0; j < (unsigned char)(sizeof(int) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
tmpInt = d[i]->signature(); // signature
cast = (char*)(&tmpInt);
for(j = 0; j < (unsigned char)(sizeof(int) / sizeof(char)); j++)
(*buffer)[len + j] = cast[j];
len += j;
switch(d[i]->type())
{
case _BRISK: d[i]->vec(&ucharBuffer);
for(j = 0; j < _BRISK_DESCLEN; j++)
(*buffer)[len + j] = ucharBuffer[j];
len += j;
free(ucharBuffer);
break;
case _ORB: d[i]->vec(&ucharBuffer);
for(j = 0; j < _ORB_DESCLEN; j++)
(*buffer)[len + j] = ucharBuffer[j];
len += j;
free(ucharBuffer);
break;
case _SIFT: d[i]->vec(&floatBuffer);
for(j = 0; j < _SIFT_DESCLEN; j++)
{
cast = (char*)(&floatBuffer[j]);
for(k = 0; k < (unsigned char)(sizeof(float) / sizeof(char)); k++)
(*buffer)[len + k] = cast[k];
len += k;
}
free(floatBuffer);
break;
case _SURF: d[i]->vec(&floatBuffer);
for(j = 0; j < _SURF_DESCLEN; j++)
{
cast = (char*)(&floatBuffer[j]);
for(k = 0; k < (unsigned char)(sizeof(float) / sizeof(char)); k++)
(*buffer)[len + k] = cast[k];
len += k;
}
free(floatBuffer);
break;
}
}
return len;
}
/* Update attributes according to the given byte array 'buffer' */
bool Signature::readByteArray(char* buffer)
{
unsigned int len = 0;
unsigned int i, j;
unsigned char k;
char* cast;
unsigned char tmp_type;
float tmp_x, tmp_y, tmp_z;
float tmp_size, tmp_angle, tmp_response;
int tmp_octave, tmp_signature;
unsigned char* ucharBuffer;
float* floatBuffer;
#ifdef __SIGNATURE_DEBUG
cout << "Signature::readByteArray()" << endl;
#endif
if(filenameLen > 0) // Was there an existing file name?
free(_filename);
free(descriptorCtr);
if(_numPoints > 0) // Were there any existing descriptors?
free(d);
for(i = 0; i < SIGNATURE_HEADER_LENGTH; i++) // header
hdr[i] = buffer[len + i];
len += i;
if((cast = (char*)malloc(sizeof(int))) == NULL) // numPoints
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.numPoints." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(int) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&_numPoints, cast, sizeof(_numPoints));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(int))) == NULL) // numMutex
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.numMutex." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(int) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&_numMutex, cast, sizeof(_numMutex));
free(cast);
len += i;
filenameLen = buffer[len]; // filenameLen
len++;
if((_filename = (char*)malloc((filenameLen + 1) * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate Signature.filename." << endl;
#endif
return false;
}
for(i = 0; i < filenameLen; i++) // filename
_filename[i] = buffer[len + i];
_filename[i] = '\0';
len += i;
if((descriptorCtr = (unsigned int*)malloc(_DESCRIPTOR_TOTAL * sizeof(int))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate Signature.descriptorCtr." << endl;
#endif
return false;
}
for(i = 0; i < _DESCRIPTOR_TOTAL; i++) // Load up descriptorCtr
{
if((cast = (char*)malloc(sizeof(int))) == NULL) // descriptorCtr[i]
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.descriptorCtr[" << +i << "]." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(int) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(descriptorCtr + i, cast, sizeof(int));
free(cast);
len += j;
}
if((cast = (char*)malloc(sizeof(float))) == NULL) // bboxminX
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.bboxminX." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&bboxminX, cast, sizeof(bboxminX));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(float))) == NULL) // bboxminY
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.bboxminY." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&bboxminY, cast, sizeof(bboxminY));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(float))) == NULL) // bboxminZ
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.bboxminZ." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&bboxminZ, cast, sizeof(bboxminZ));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(float))) == NULL) // bboxmaxX
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.bboxmaxX." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&bboxmaxX, cast, sizeof(bboxmaxX));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(float))) == NULL) // bboxmaxY
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.bboxmaxY." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&bboxmaxY, cast, sizeof(bboxmaxY));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(float))) == NULL) // bboxmaxZ
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.bboxmaxZ." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(float) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&bboxmaxZ, cast, sizeof(bboxmaxZ));
free(cast);
len += i;
if((cast = (char*)malloc(sizeof(int))) == NULL) // index
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature.index." << endl;
#endif
return false;
}
for(i = 0; i < (unsigned char)(sizeof(int) / sizeof(char)); i++)
cast[i] = buffer[len + i];
memcpy(&_index, cast, sizeof(_index));
free(cast);
len += i;
if((d = (Descriptor**)malloc(_numPoints * sizeof(Descriptor*))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate descriptor-pointer buffer from byte-array." << endl;
#endif
return false;
}
for(i = 0; i < _numPoints; i++)
{
tmp_type = buffer[len]; // Skip the length; we'll look it up
len += 2;
if((cast = (char*)malloc(sizeof(float))) == NULL) // x
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].x." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_x, cast, sizeof(tmp_x));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(float))) == NULL) // y
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].y." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_y, cast, sizeof(tmp_y));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(float))) == NULL) // z
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].z." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_z, cast, sizeof(tmp_z));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(float))) == NULL) // size
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].size." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_size, cast, sizeof(tmp_size));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(float))) == NULL) // angle
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].angle." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_angle, cast, sizeof(tmp_angle));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(float))) == NULL) // response
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].response." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_response, cast, sizeof(tmp_response));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(float))) == NULL) // octave
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].octave." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(float) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_octave, cast, sizeof(tmp_octave));
free(cast);
len += j;
if((cast = (char*)malloc(sizeof(int))) == NULL) // signature
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].signature." << endl;
#endif
return false;
}
for(j = 0; j < (unsigned char)(sizeof(int) / sizeof(char)); j++)
cast[j] = buffer[len + j];
memcpy(&tmp_signature, cast, sizeof(tmp_signature));
free(cast);
len += j;
switch(tmp_type)
{
case _BRISK: if((ucharBuffer = (unsigned char*)malloc(_BRISK_DESCLEN * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary uchar array for reading Signature[" << +i << "] vector." << endl;
#endif
return false;
}
for(j = 0; j < _BRISK_DESCLEN; j++)
ucharBuffer[j] = buffer[len + j];
len += j;
d[i] = new BRISKDesc(ucharBuffer);
d[i]->XYZ(tmp_x, tmp_y, tmp_z);
d[i]->setSize(tmp_size);
d[i]->setAngle(tmp_angle);
d[i]->setResponse(tmp_response);
d[i]->setOctave(tmp_octave);
d[i]->setSignature(tmp_signature);
free(ucharBuffer);
break;
case _ORB: if((ucharBuffer = (unsigned char*)malloc(_ORB_DESCLEN * sizeof(char))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary uchar array for reading Signature[" << +i << "] vector." << endl;
#endif
return false;
}
for(j = 0; j < _ORB_DESCLEN; j++)
ucharBuffer[j] = buffer[len + j];
len += j;
d[i] = new ORBDesc(ucharBuffer);
d[i]->XYZ(tmp_x, tmp_y, tmp_z);
d[i]->setSize(tmp_size);
d[i]->setAngle(tmp_angle);
d[i]->setResponse(tmp_response);
d[i]->setOctave(tmp_octave);
d[i]->setSignature(tmp_signature);
free(ucharBuffer);
break;
case _SIFT: if((floatBuffer = (float*)malloc(_SIFT_DESCLEN * sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary float array for reading Signature[" << +i << "] vector." << endl;
#endif
return false;
}
if((cast = (char*)malloc(sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].response." << endl;
#endif
return false;
}
for(j = 0; j < _SIFT_DESCLEN; j++)
{
for(k = 0; k < (unsigned char)(sizeof(float) / sizeof(char)); k++)
cast[k] = buffer[len + k];
memcpy(&floatBuffer[j], cast, sizeof(float));
len += k;
}
free(cast);
d[i] = new SIFTDesc(floatBuffer);
d[i]->XYZ(tmp_x, tmp_y, tmp_z);
d[i]->setSize(tmp_size);
d[i]->setAngle(tmp_angle);
d[i]->setResponse(tmp_response);
d[i]->setOctave(tmp_octave);
d[i]->setSignature(tmp_signature);
free(floatBuffer);
break;
case _SURF: if((floatBuffer = (float*)malloc(_SURF_DESCLEN * sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary float array for reading Signature[" << +i << "] vector." << endl;
#endif
return false;
}
if((cast = (char*)malloc(sizeof(float))) == NULL)
{
#ifdef __SIGNATURE_DEBUG
cout << "ERROR: Unable to allocate temporary byte array for reading Signature[" << +i << "].response." << endl;
#endif
return false;
}
for(j = 0; j < _SURF_DESCLEN; j++)
{
for(k = 0; k < (unsigned char)(sizeof(float) / sizeof(char)); k++)
cast[k] = buffer[len + k];
memcpy(&floatBuffer[j], cast, sizeof(float));
len += k;
}
free(cast);
d[i] = new SURFDesc(floatBuffer);
d[i]->XYZ(tmp_x, tmp_y, tmp_z);
d[i]->setSize(tmp_size);
d[i]->setAngle(tmp_angle);
d[i]->setResponse(tmp_response);
d[i]->setOctave(tmp_octave);
d[i]->setSignature(tmp_signature);
free(floatBuffer);
break;
}
}
return true;
}
/**************************************************************************************************
Display */
void Signature::summary(void) const
{
unsigned int i;
cout << _filename << endl;
for(i = 0; i < filenameLen; i++)
cout << "=";
cout << endl << hdr << endl;
cout << +_numPoints << " features" << endl;
for(i = 0; i < _DESCRIPTOR_TOTAL; i++)
{
cout << " " << +descriptorCtr[i] << " ";
switch(i)
{
case _BRISK: cout << "BRISK" << endl; break;
case _ORB: cout << "ORB" << endl; break;
case _SIFT: cout << "SIFT" << endl; break;
case _SURF: cout << "SURF" << endl; break;
}
}
cout << +_numMutex << " mutual exclusions" << endl;
cout << "Bounding box: (" << bboxminX << ", " << bboxminY << ", " << bboxminZ << ")" << endl;
cout << " to (" << bboxmaxX << ", " << bboxmaxY << ", " << bboxmaxZ << ")" << endl;
return;
}
void Signature::print(void) const
{
unsigned int i;
summary();
for(i = 0; i < _numPoints; i++)
d[i]->print();
return;
}
void Signature::printFilename(void) const
{
cout << _filename;
return;
}
/**************************************************************************************************
Setters */
/* Sets attribute '_index' and '_signature' of all Descriptors */
void Signature::setIndex(signed int index)
{
unsigned int i;
_index = index; // Set the Signature's '_index'
for(i = 0; i < _numPoints; i++) // Set all Descriptors' '_signature's
d[i]->setSignature(index);
return;
}
void Signature::setXYZ(unsigned int i, float x, float y, float z)
{
if(i < _numPoints)
d[i]->XYZ(x, y, z);
return;
}
/**************************************************************************************************
Getters */
/* Return the number of interest points in this signature */
unsigned int Signature::numPoints() const
{
return _numPoints;
}
/* Return the number of mutual exclusions in this signature */
unsigned int Signature::numMutex() const
{
return _numMutex;
}
/* Return the coord-th coordinate of this signature's minimum bounding box vertex.
This method can receive characters (upper and lower case) and indices in {0, 1, 2}. */
float Signature::bboxMin(unsigned char coord) const
{
switch(coord)
{
case 0:
case 'x':
case 'X': return bboxminX;
case 1:
case 'y':
case 'Y': return bboxminY;
case 2:
case 'z':
case 'Z': return bboxminZ;
}
return -INFINITY;
}
/* Return the coord-th coordinate of this signature's maximum bounding box vertex.
This method can receive characters (upper and lower case) and indices in {0, 1, 2}. */
float Signature::bboxMax(unsigned char coord) const
{
switch(coord)
{
case 0:
case 'x':
case 'X': return bboxmaxX;
case 1:
case 'y':
case 'Y': return bboxmaxY;
case 2:
case 'z':
case 'Z': return bboxmaxZ;
}
return INFINITY;
}
/* Copy this signature's file name to the given buffer and return the strings's length. */
unsigned char Signature::filename(char** buffer) const
{
unsigned char i;
if(((*buffer) = (char*)malloc((filenameLen + 1) * sizeof(char))) == NULL)
return 0;
for(i = 0; i < filenameLen; i++)
(*buffer)[i] = _filename[i];
(*buffer)[i] = '\0';
return filenameLen;
}
/* Build and return a string that is just the file name without the path or the extension. */
char* Signature::fileStem() const
{
char* ret;
signed int i = (signed int)filenameLen - 1;
signed int j;
unsigned char k;
while(i > 0 && _filename[i] != '.') // Find the '.' before the file extension
i--;
j = i;
while(j > 0 && _filename[j] != '/') // Find the '/' before the file path (or the head of the string)
j--;
if((ret = (char*)malloc((i - j) * sizeof(char))) == NULL)
return NULL;
for(k = 0; k < (i - j - 1); k++)
ret[k] = _filename[j + 1 + k];
ret[k] = '\0'; // NULL-cap
return ret;
}
/* Copy this signature's header to the given buffer and return the header's length
(which is always equal to SIGNATURE_HEADER_LENGTH). */
unsigned int Signature::header(char** buffer) const
{
unsigned int i = 0;
if(((*buffer) = (char*)malloc(SIGNATURE_HEADER_LENGTH * sizeof(char))) == NULL)
return 0;
while(i < SIGNATURE_HEADER_LENGTH && hdr[i] != '\0')
{
(*buffer)[i] = hdr[i];
i++;
}
for(; i < SIGNATURE_HEADER_LENGTH; i++)
(*buffer)[i] = '\0';
return SIGNATURE_HEADER_LENGTH;
}
/* A signature's 'index' should be equal to its position in the array of all signatures in the partent program.
Unless this value is set, it is -1. */
signed int Signature::index(void) const
{
return _index;
}
/* Return {_BRISK, _ORB, _SIFT, _SURF} according to the type of the i-th Descriptor */
unsigned char Signature::type(unsigned int i) const
{
if(i < _numPoints)
return d[i]->type();
return _DESCRIPTOR_TOTAL;
}
/* Return the length of the i-th feature descriptor vector. */
unsigned char Signature::len(unsigned int i) const
{
if(i < _numPoints)
return d[i]->len();
return 0;
}
/* Return the i-th interest point's X coordinate */
float Signature::x(unsigned int i) const
{
if(i < _numPoints)
return d[i]->x();
return INFINITY;
}
/* Return the i-th interest point's Y coordinate */
float Signature::y(unsigned int i) const
{
if(i < _numPoints)
return d[i]->y();
return INFINITY;
}
/* Return the i-th interest point's Z coordinate */
float Signature::z(unsigned int i) const
{
if(i < _numPoints)
return d[i]->z();
return INFINITY;
}
/* Return the i-th interest point's size */
float Signature::size(unsigned int i) const
{
if(i < _numPoints)
return d[i]->size();
return INFINITY;
}
/* Return the i-th interest point's angle */
float Signature::angle(unsigned int i) const
{
if(i < _numPoints)
return d[i]->angle();
return INFINITY;
}
/* Return the i-th interest point's response */
float Signature::response(unsigned int i) const
{
if(i < _numPoints)
return d[i]->response();
return INFINITY;
}
/* Return the i-th interest point's octave */
signed int Signature::octave(unsigned int i) const
{
if(i < _numPoints)
return d[i]->octave();
return INT_MAX;
}
/* Return the X-coordinate of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
float Signature::x(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->x();
}
return INFINITY;
}
/* Return the Y-coordinate of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
float Signature::y(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->y();
}
return INFINITY;
}
/* Return the Z-coordinate of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
float Signature::z(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->z();
}
return INFINITY;
}
/* Return the size of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
float Signature::size(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->size();
}
return INFINITY;
}
/* Return the angle of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
float Signature::angle(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->angle();
}
return INFINITY;
}
/* Return the response of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
float Signature::response(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->response();
}
return INFINITY;
}
/* Return the octave of the i-th (or last) interest point that is described using 'type'.
If there are no interest points that use this type, return infinity. */
signed int Signature::octave(unsigned int index, unsigned char type) const
{
unsigned int i, j;
if(descriptorCtr[type] > 0)
{
i = 0;
j = 0;
while(i < _numPoints && !(j == index && d[j]->type() == type))
{
if(d[j]->type() == type)
j++;
i++;
}
return d[j]->octave();
}
return INT_MAX;
}
#endif | 36.793198 | 141 | 0.451606 | EricCJoyce |
f20a3e12339a04abdf34db7fda92ed68117f4f5e | 1,331 | cpp | C++ | C_CPP/final/KMP.cpp | dengchongsen/study_codes | 29d74c05d340117f76aafcc320766248a0f8386b | [
"MulanPSL-1.0"
] | null | null | null | C_CPP/final/KMP.cpp | dengchongsen/study_codes | 29d74c05d340117f76aafcc320766248a0f8386b | [
"MulanPSL-1.0"
] | null | null | null | C_CPP/final/KMP.cpp | dengchongsen/study_codes | 29d74c05d340117f76aafcc320766248a0f8386b | [
"MulanPSL-1.0"
] | null | null | null | #include <iostream>
using namespace std;
const int maxn = 1000005;
char s[maxn];
char p[maxn];
int nex[maxn];
int pl, ml;
int ans = 0;
void init()
{
pl = 0;
ml = 0;
int i = 0, j = 0;
while (s[i] != '\0')
s[i++] = '\0';
while (p[j] != '\0')
p[j++] = '\0';
}
// 获取窗口滑动位置
void getnex()
{
nex[0] = -1;
for (int i = 0, j = -1; i < pl;)
{
if (j == -1 || p[i] == p[j])
nex[++i] = ++j;
else
j = nex[j];
}
}
int Kmp()
{
getnex();
int i = 0, j = 0;
while (i <= ml && j <= pl)
{
// 当前位置匹配
if (j == -1 || s[i] == p[j])
{
if (j == pl - 1)
{ //匹配成功
int index = i - pl + 1;
ans++;
j = 0;
i = index + 1;
// cout<<"chengong"<<endl;
}
// 主串跟模式串指针同时移向下一位
i++;
j++;
}
// 失配则j回到next[j]的位置
else
{
j = nex[j];
}
}
return -1;
}
void getlen()
{
ml = 0;
int i = 0;
while (s[i++] != '\0')
ml++;
}
int main()
{
init();
while (cin >> s)
{
getlen();
int n;
cin >> n;
while (n--)
{
int j = 0;
while (p[j] != '\0')
{
p[j++] = '\0';
};
cin >> p;
pl = 0;
int jj = 0;
while (p[jj++] != '\0')
pl++;
ans = 0;
Kmp();
cout << p << ":" << ans << endl;
}
}
return 0;
} | 13.581633 | 38 | 0.352367 | dengchongsen |
f2102881aec08af853984f88ca90789b059c05e0 | 21,007 | cpp | C++ | source/game_state.cpp | Craig-J/RhythMIR | 37165688b5bf925a1570ed1daf6e1b21892456b2 | [
"MIT"
] | null | null | null | source/game_state.cpp | Craig-J/RhythMIR | 37165688b5bf925a1570ed1daf6e1b21892456b2 | [
"MIT"
] | 3 | 2016-07-17T15:26:12.000Z | 2016-07-17T15:32:38.000Z | source/game_state.cpp | Craig-J/RhythMIR | 37165688b5bf925a1570ed1daf6e1b21892456b2 | [
"MIT"
] | null | null | null | #include "game_state.h"
#include "app_state_machine.h"
#include "menu_state.h"
#include <SFML_Extensions/global.h>
namespace
{
sf::Vector2f window_centre;
sf::Vector2f window_size;
float path_start_y;
float path_end_y;
float path_x;
float path_x_offset;
float note_length;
bool interpolate_beats;
sf::Time beat_interval;
sf::Time beat_time;
const int performance_statistic_count = 10;
const int performance_y_offset = 24.0f;
}
GameState::GameState(AppStateMachine& _state_machine,
UniqueStatePtr<AppState>& _state,
BeatmapPtr _beatmap,
GameSettings _settings) :
AppState(_state_machine, _state),
beatmap_(std::move(_beatmap)),
settings_(std::move(_settings)),
play_clock_(),
paused_(false),
finished_(false),
hit_counters_(true),
current_section_(nullptr)
{
}
void GameState::InitializeState()
{
textures_ = sfx::TextureFileVector
{
{ machine_.background_texture_, "skins/default/play_background.png" },
{ pause_background_texture_, "skins/default/pause_background.png" },
{ white_circle_texture_, "skins/default/circle_white.png", },
{ beat_texture_, "skins/default/beat.png" }
};
sfx::Global::TextureManager.Load(textures_);
machine_.background_.setTexture(*machine_.background_texture_);
sounds_ = sfx::SoundFileVector
{
{ deep_hit_sound_, "skins/default/deep_hit.wav" },
{ soft_hit_sound_, "skins/default/soft_hit.wav" },
{ miss_sound_, "skins/default/combobreak.wav" }
};
sfx::Global::AudioManager.Load(sounds_);
window_centre = sf::Vector2f(machine_.window_.getSize().x * 0.5, machine_.window_.getSize().y * 0.5);
window_size = sf::Vector2f(machine_.window_.getSize());
pause_background_ = sfx::Sprite(window_centre, pause_background_texture_);
// Clock text initialization
clock_text_.setFont(machine_.font_);
clock_text_.setCharacterSize(45);
clock_text_.setColor(sf::Color::Color(255, 69, 0));
clock_text_.setPosition(sf::Vector2f(window_size.x, 0.0f));
// Countdown text initialization
countdown_text_.setFont(machine_.font_);
countdown_text_.setCharacterSize(120);
countdown_text_.setColor(sf::Color::Color(255, 69, 0));
countdown_text_.setPosition(window_centre);
// Score initialization
score_text_.setFont(machine_.font_);
score_text_.setCharacterSize(60);
score_text_.setColor(sf::Color::Color(255, 69, 0));
score_text_.setPosition(sf::Vector2f(window_size.x, 0.0f));
score_ = 0;
// Hit counters initialization
performance_text_.setFont(machine_.font_);
performance_text_.setCharacterSize(30);
performance_text_.setPosition(sf::Vector2f(5.0f, window_size.y - performance_y_offset * 10 - 5.0f));
perfect_hits_ = 0;
great_hits_ = 0;
good_hits_ = 0;
misses_ = 0;
hit_combo_ = 0;
max_combo_ = 0;
average_hit_ = 0.0f;
unstable_rate_ = 0.0f;
earliest_hit_ = -300;
latest_hit_ = 300;
hits_.clear();
// Beatmap initialization
sections_ = beatmap_->CopyTimingSections();
interpolate_beats = false;
switch (settings_.beat_style)
{
case GameSettings::HIDDEN:
break;
case GameSettings::INTERPOLATED:
if (sections_.front().BPM != 0.0f && sections_.front().offset != sf::Time::Zero)
{
interpolate_beats = true;
beat_interval = sf::milliseconds(1000 * 60 / sections_.front().BPM);
beat_time = beat_interval;
}
break;
case GameSettings::GENERATED:
beatqueue_ = beatmap_->CopyBeats();
break;
}
if (!beatmap_->music_)
beatmap_->LoadMusic();
beatmap_->music_->setPlayingOffset(sf::Time::Zero);
srand(time(0));
machine_.settings_.limit_framerate_ = false;
machine_.settings_.display_hud_ = false;
switch (beatmap_->play_mode_)
{
case VISUALIZATION:
settings_.path_count = sections_.front().notes.size();
InitializeVisualizationMode();
break;
case SINGLE:
InitializeFourKeyMode();
break;
case FOURKEY:
InitializeFourKeyMode();
break;
}
}
void GameState::TerminateState()
{
sfx::Global::TextureManager.Unload(textures_);
textures_.clear();
sfx::Global::AudioManager.Unload(sounds_);
sounds_.clear();
}
bool GameState::Update(const float _delta_time)
{
if (finished_)
{
if (sfx::Global::Input.KeyPressed(sf::Keyboard::BackSpace))
{
ChangeState<MenuState>(std::move(beatmap_));
return true;
}
if (sfx::Global::Input.KeyPressed(sf::Keyboard::Return))
{
ChangeState<GameState>(std::move(beatmap_), std::move(settings_));
return true;
}
if (!PauseMenu())
{
return true;
}
}
else
{
if (sfx::Global::Input.KeyPressed(sf::Keyboard::Escape))
{
paused_ = !paused_;
}
if (settings_.music_volume != beatmap_->music_->getVolume())
beatmap_->music_->setVolume(settings_.music_volume);
if (paused_)
{
play_clock_.Stop();
if (beatmap_->music_->getStatus() == sf::Music::Playing)
beatmap_->music_->pause();
if (sfx::Global::Input.KeyPressed(sf::Keyboard::BackSpace))
{
ChangeState<MenuState>(std::move(beatmap_));
return true;
}
if (sfx::Global::Input.KeyPressed(sf::Keyboard::Return))
{
ChangeState<GameState>(std::move(beatmap_), std::move(settings_));
return true;
}
if (!PauseMenu())
{
return true;
}
}
else
{
play_clock_.Start();
auto time_elapsed = play_clock_.GetTimeElapsed();
// If more than the play offset (intro time) seconds and
// less than the duration of the music + play offset seconds has elapsed then...
if (time_elapsed > settings_.countdown_time && time_elapsed < beatmap_->music_->getDuration() + settings_.countdown_time)
{
auto current_offset = time_elapsed - settings_.countdown_time + settings_.play_offset;
auto current_approach_offset = current_offset + settings_.approach_time;
// Play music if it's not already playing
if (beatmap_->music_->getStatus() != sf::Music::Playing)
beatmap_->music_->play();
// If sections isn't empty
if (!sections_.empty())
{
// See if the next one's offset is less than the current approach offset
auto next_section = sections_.front();
if (current_approach_offset > next_section.offset)
{
current_section_.reset(new TimingSection(next_section));
sections_.pop();
SpawnBeat();
}
}
if (current_section_)
{
if (!interpolate_beats)
{
if (beatqueue_)
{
if (!beatqueue_->empty())
{
auto next_beat_offset = beatqueue_->front().offset;
if (current_approach_offset - settings_.play_offset > next_beat_offset)
{
SpawnBeat();
beatqueue_->pop();
}
}
}
}
else
{
beat_time -= sf::seconds(_delta_time);
if (beat_time < sf::Time::Zero)
{
SpawnBeat();
beat_time += beat_interval;
}
}
if (!current_section_->notes.empty())
{
for (auto notequeue = current_section_->notes.begin(); notequeue != current_section_->notes.end(); ++notequeue)
{
int index = notequeue - current_section_->notes.begin();
// If there are any notes remaining in the current section
if (!notequeue->empty())
{
// Get the next one
auto next_onset_offset = notequeue->front().offset;
// If the next notes offset is less than the current approach offset
if (current_approach_offset > next_onset_offset)
{
// Just spawn a random note
if (settings_.duncan_factor)
SpawnNote(note_paths_[rand() % note_paths_.size()]);
else
SpawnNote(note_paths_[index]);
notequeue->pop();
}
}
}
}
else
{
Log::Error("Notequeue vector is empty.");
}
if (!settings_.auto_play)
{
for (int index = 0; index < note_paths_.size(); ++index)
{
if (sfx::Global::Input.KeyPressed(settings_.keybinds[index]))
{
AttemptNoteHit(note_paths_[index]);
}
}
}
for (auto &beat : beats_)
{
beat.UpdatePosition(_delta_time);
beat.offset_from_perfect -= sf::seconds(_delta_time);
}
while (!beats_.empty() && beats_.front().offset_from_perfect < sf::Time::Zero)
{
beats_.erase(beats_.begin());
}
// Update note positions and remove offscreen notes
for (auto &path : note_paths_)
{
for (auto ¬e : path.notes)
{
note.UpdatePosition(_delta_time);
note.offset_from_perfect -= sf::seconds(_delta_time);
if (!note.VerifyPosition(machine_.window_))
{
// Note went offscreen, so it's a miss
if (hit_combo_ > 10)
PlayMissSound();
hit_combo_ = 0;
misses_++;
}
if (settings_.auto_play && note.offset_from_perfect < sf::Time::Zero)
{
AttemptNoteHit(path);
}
}
auto path_index = path.notes.begin();
while (path_index != path.notes.end())
{
if (path_index->visibility() == false)
{
path_index = path.notes.erase(path_index);
}
else
++path_index;
}
}
}
}
else if (time_elapsed > beatmap_->music_->getDuration() + settings_.countdown_time)
{
beatmap_->music_->stop();
play_clock_.Stop();
finished_ = true;
}
}
if (!active_sounds_.empty())
{
for (auto iterator = active_sounds_.begin(); iterator != active_sounds_.end();)
{
if ((*iterator)->getStatus() == sf::Sound::Stopped)
{
iterator = active_sounds_.erase(iterator);
}
if (iterator != active_sounds_.end())
iterator++;
}
}
}
return true;
}
void GameState::Render(const float _delta_time)
{
for (auto beat : beats_)
{
machine_.window_.draw(beat);
}
for (auto path : note_paths_)
{
machine_.window_.draw(path.target);
for (auto note : path.notes)
{
machine_.window_.draw(note);
}
}
auto time_elapsed = play_clock_.GetTimeElapsed();
if (time_elapsed < settings_.countdown_time)
{
countdown_text_.setString("Countdown: " + agn::to_string_precise(settings_.countdown_time.asSeconds() - time_elapsed.asSeconds(), 1));
countdown_text_.setPosition(sf::Vector2f(0.0f, window_centre.y));
machine_.window_.draw(countdown_text_);
}
switch (settings_.progress_bar_position)
{
case GameSettings::TOPRIGHT:
ImGui::SetNextWindowPos(ImVec2(window_size.x * 0.9f, 120));
ImGui::SetNextWindowSize(ImVec2(window_size.x * 0.1f, 10));
break;
case GameSettings::ALONGTOP:
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(window_size.x, 10));
break;
case GameSettings::ALONGBOTTOM:
ImGui::SetNextWindowPos(ImVec2(0, window_size.y - 30));
ImGui::SetNextWindowSize(ImVec2(window_size.x , 10));
break;
}
if (!ImGui::Begin("Progress", &settings_.show_progress_bar, ImVec2(0.0f, 0.0f), 0.3f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))
{
ImGui::End();
return;
}
ImGui::ProgressBar(time_elapsed / beatmap_->music_->getDuration());
ImGui::End();
score_text_.setString("Score: " + std::to_string(score_));
score_text_.move(-(score_text_.getGlobalBounds().width + 15.0f), (score_text_.getGlobalBounds().top));
machine_.window_.draw(score_text_);
score_text_.move((score_text_.getGlobalBounds().width + 15.0f), -(score_text_.getGlobalBounds().top));
clock_text_.setString(agn::to_string_precise(play_clock_.GetTimeElapsed().asSeconds(), 3) + "s");
clock_text_.move(-(clock_text_.getGlobalBounds().width + 15.0f), (score_text_.getLocalBounds().height));
machine_.window_.draw(clock_text_);
clock_text_.move((clock_text_.getGlobalBounds().width + 15.0f), -(score_text_.getLocalBounds().height));
performance_text_.setPosition(sf::Vector2f(5.0f, window_size.y - performance_y_offset * 15 - 5.0f));
for (int index = 0; index < performance_statistic_count; ++index)
{
switch (index)
{
case 0:
performance_text_.setString("Combo: " + std::to_string(hit_combo_));
performance_text_.setColor(sf::Color::White);
break;
case 1:
performance_text_.setString("Max Combo: " + std::to_string(max_combo_));
performance_text_.setColor(sf::Color::White);
performance_text_.move(0.0f, (performance_y_offset));
break;
case 2:
performance_text_.setString("Hits: " + std::to_string(hits_.size()));
performance_text_.setColor(sf::Color::White);
break;
case 3:
performance_text_.setString("Perfect: " + std::to_string(perfect_hits_));
performance_text_.setColor(sf::Color::Cyan);
break;
case 4:
performance_text_.setString("Great: " + std::to_string(great_hits_));
performance_text_.setColor(sf::Color::Green);
break;
case 5:
performance_text_.setString("Good: " + std::to_string(good_hits_));
performance_text_.setColor(sf::Color::Yellow);
break;
case 6:
performance_text_.setString("Miss: " + std::to_string(misses_));
performance_text_.setColor(sf::Color::Red);
break;
case 7:
performance_text_.setString("-" + std::to_string(std::abs(earliest_hit_)) + "ms ~ +" + std::to_string(std::abs(latest_hit_)) + "ms");
performance_text_.setColor(sf::Color::White);
performance_text_.move(0.0f, (performance_y_offset));
break;
case 8:
performance_text_.setString("Average: " + agn::to_string_precise(average_hit_, 2));
performance_text_.setColor(sf::Color::White);
break;
case 9:
performance_text_.setString("Deviation: " + agn::to_string_precise(unstable_rate_, 2));
performance_text_.setColor(sf::Color::White);
break;
}
machine_.window_.draw(performance_text_);
performance_text_.move(0.0f, (performance_y_offset));
}
if (paused_)
{
machine_.window_.draw(pause_background_);
}
}
void GameState::ProcessEvent(sf::Event& _event)
{
switch (_event.type)
{
case sf::Event::Resized:
window_size = sf::Vector2f(_event.size.width, _event.size.height);
break;
}
}
void GameState::ReloadSkin()
{}
bool GameState::PauseMenu()
{
ImGui::SetNextWindowPos(ImVec2(window_centre.x - window_size.x * 0.2f, window_centre.y));
ImGui::SetNextWindowSize(ImVec2(window_size.x * 0.4f, 400));
if (!ImGui::Begin("Pause Menu", nullptr, ImVec2(0, 0), -1.f,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))
{
// Early out if the window is collapsed, as an optimization.
ImGui::End();
return true;
}
if (!finished_)
{
if (ImGui::Button("Resume (Escape)", ImVec2(ImGui::GetWindowContentRegionWidth(), 60)))
{
paused_ = false;
ImGui::End();
return true;
}
}
if (ImGui::Button("Restart (Enter)", ImVec2(ImGui::GetWindowContentRegionWidth(), 60)))
{
ChangeState<GameState>(std::move(beatmap_), std::move(settings_));
ImGui::End();
return false;
}
if (ImGui::Button("Quit (Backspace)", ImVec2(ImGui::GetWindowContentRegionWidth(), 60)))
{
ChangeState<MenuState>(std::move(beatmap_));
ImGui::End();
return false;
}
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
const char* hitsounds[] = { "None", "Soft", "Deep" };
ImGui::Combo("Hitsound", &settings_.hitsound, hitsounds, 3);
ImGui::SliderFloat("Music Volume", &settings_.music_volume, 0, 100);
ImGui::SliderFloat("SFX Volume", &settings_.sfx_volume, 0, 100);
ImGui::Spacing();
const char* barpositions[] = { "Top Right", "Along Top", "Along Bottom" };
ImGui::Combo("Progress Bar Position", &settings_.progress_bar_position, barpositions, 3);
ImGui::End();
return true;
}
void GameState::SpawnBeat()
{
if (beatmap_->play_mode_ == VISUALIZATION)
{
beats_.emplace_back(NoteObject(sf::Vector2f(path_x + window_size.x * 0.4f, path_start_y),
sf::Vector2f(path_x + window_size.x * 0.4f, path_end_y),
settings_.approach_time,
beat_texture_,
sf::Color(255, 69, 0, 128)));
beats_.back().SetDimensions(sf::Vector2f(window_size.x * 0.8f, 5.0f));
}
else
{
beats_.emplace_back(NoteObject(sf::Vector2f(path_x + window_size.x * 0.15f, path_start_y),
sf::Vector2f(path_x + window_size.x * 0.15f, path_end_y),
settings_.approach_time,
beat_texture_,
sf::Color(255, 69, 0, 128)));
beats_.back().SetDimensions(sf::Vector2f(window_size.x * 0.4f, 5.0f));
}
}
void GameState::SpawnNote(NotePath& _path)
{
_path.notes.emplace_back(NoteObject(_path.start_position,
_path.target_position,
_path.approach_time,
_path.note_texture,
_path.note_color));
if (settings_.path_count > 6)
_path.notes.back().SetDimensions(sf::Vector2f(note_length, note_length));
}
void GameState::AttemptNoteHit(NotePath& _path)
{
if (!_path.notes.empty())
{
auto& note = _path.notes.front();
// Note offset is the time (in ms) that the note is offset from a perfect hit
int note_offset = note.offset_from_perfect.asMilliseconds();
int abs_note_offset = abs(note.offset_from_perfect.asMilliseconds());
// Ignore press when the offset is more than 300ms
if (abs_note_offset < 300)
{
if (abs_note_offset < 30)
{
perfect_hits_++;
hit_combo_++;
score_ += hit_combo_ * 300;
PlayHitSound();
}
else if (abs_note_offset < 60)
{
great_hits_++;
hit_combo_++;
score_ += hit_combo_ * 100;
PlayHitSound();
}
else if (abs_note_offset < 120)
{
good_hits_++;
hit_combo_++;
score_ += hit_combo_ * 50;
PlayHitSound();
}
else
{
misses_++;
if (hit_combo_ > max_combo_)
max_combo_ = hit_combo_;
if(hit_combo_ > 10)
PlayMissSound();
hit_combo_ = 0;
}
if (hit_combo_ > max_combo_)
max_combo_ = hit_combo_;
if (note_offset < latest_hit_)
latest_hit_ = note_offset;
if (note_offset > earliest_hit_)
earliest_hit_ = note_offset;
hits_.emplace_back(note_offset);
auto mean = int();
for (auto hit : hits_)
{
mean += hit;
}
average_hit_ = (float)mean / (float)hits_.size();
std::vector<float> sqdiffs;
for (auto hit : hits_)
{
auto sqdiff = float();
sqdiff = std::pow((float)hit - average_hit_, 2);
sqdiffs.push_back(sqdiff);
}
for (auto v : sqdiffs)
{
unstable_rate_ += v;
}
unstable_rate_ /= sqdiffs.size();
unstable_rate_ = std::sqrt(unstable_rate_);
// Set not visible (will get erased at end of update)
note.SetVisibility(false);
}
}
}
void GameState::InitializeFourKeyMode()
{
// NotePath initialization
note_paths_.reserve(settings_.path_count);
if (settings_.flipped)
{
path_start_y = window_size.y;
path_end_y = window_size.y * 0.1f;
}
else
{
path_start_y = 0.0f;
path_end_y = window_size.y * 0.9f;
}
path_x = window_size.x * 0.2f;
path_x_offset = window_size.x * 0.1f;
for (int index = 0; index < settings_.path_count; ++index)
{
sf::Color note_color;
switch (index)
{
case 0:
note_color = sf::Color::Green;
break;
case 1:
note_color = sf::Color::Red;
break;
case 2:
note_color = sf::Color::Cyan;
break;
case 3:
note_color = sf::Color(255, 69, 0);
break;
}
note_paths_.emplace_back(NotePath(sf::Vector2f(path_x + path_x_offset * index, path_start_y),
sf::Vector2f(path_x + path_x_offset * index, path_end_y),
settings_.approach_time,
1,
white_circle_texture_,
note_color));
}
}
void GameState::InitializeVisualizationMode()
{
// NotePath initialization
note_paths_.reserve(settings_.path_count);
if (settings_.flipped)
{
path_start_y = window_size.y;
path_end_y = window_size.y * 0.1f;
}
else
{
path_start_y = 0.0f;
path_end_y = window_size.y * 0.9f;
}
path_x = window_size.x * 0.1f;
path_x_offset = window_size.x * 0.8f / settings_.path_count;
if(settings_.path_count > 5)
note_length = path_x_offset * 0.75f;
else if(settings_.path_count > 10)
note_length = path_x_offset - 5;
for (int index = 0; index < settings_.path_count; ++index)
{
int hue = (int)(((float)index / (float)settings_.path_count) * 360.0f);
sf::Color note_color(sfx::HSL(hue, 100, 50).HSLToRGB());
note_paths_.emplace_back(NotePath(sf::Vector2f(path_x + path_x_offset * index, path_start_y),
sf::Vector2f(path_x + path_x_offset * index, path_end_y),
settings_.approach_time,
1,
white_circle_texture_,
note_color));
if (settings_.path_count > 5)
note_paths_.back().target.SetDimensions(sf::Vector2f(note_length, note_length));
}
}
void GameState::PlayHitSound()
{
sf::Sound* hitsound;
switch (settings_.hitsound)
{
case GameSettings::SOFT:
hitsound = new sf::Sound(*soft_hit_sound_);
break;
case GameSettings::DEEP:
hitsound = new sf::Sound(*deep_hit_sound_);
break;
}
if (!settings_.hitsound == GameSettings::NONE)
{
hitsound->setVolume(settings_.sfx_volume);
hitsound->play();
active_sounds_.emplace_back(hitsound);
}
}
void GameState::PlayMissSound()
{
if (!settings_.hitsound == GameSettings::NONE)
{
sf::Sound* hitsound = new sf::Sound(*miss_sound_);
hitsound->setVolume(settings_.sfx_volume);
hitsound->play();
active_sounds_.emplace_back(hitsound);
}
}
| 26.794643 | 205 | 0.674347 | Craig-J |
f2121a9ace2020ef7de22565827ac127ac416f18 | 2,763 | cc | C++ | src/carnot/exec/ml/kmeans_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 1,821 | 2020-04-08T00:45:27.000Z | 2021-09-01T14:56:25.000Z | src/carnot/exec/ml/kmeans_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 142 | 2020-04-09T06:23:46.000Z | 2021-08-24T06:02:12.000Z | src/carnot/exec/ml/kmeans_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 105 | 2021-09-08T10:26:50.000Z | 2022-03-29T09:13:36.000Z | /*
* Copyright 2018- The Pixie Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <set>
#include <vector>
#include "src/carnot/exec/ml/coreset.h"
#include "src/carnot/exec/ml/eigen_test_utils.h"
#include "src/carnot/exec/ml/kmeans.h"
namespace px {
namespace carnot {
namespace exec {
namespace ml {
TEST(KMeans, basic) {
int k = 5;
Eigen::MatrixXf points(k, k);
points << Eigen::MatrixXf::Identity(k, k);
auto weights = Eigen::VectorXf::Ones(k);
auto set = std::make_shared<WeightedPointSet>(points, weights);
KMeans kmeans(k);
kmeans.Fit(set);
// In this simple case the centroids should be the input points.
EXPECT_THAT(kmeans.centroids(), UnorderedRowsAre(points, 1e-6f));
}
TEST(KMeans, serialize_deserialize) {
int k = 5;
Eigen::MatrixXf points(k, k);
points << Eigen::MatrixXf::Identity(k, k);
auto weights = Eigen::VectorXf::Ones(k);
auto set = std::make_shared<WeightedPointSet>(points, weights);
KMeans kmeans(k);
kmeans.Fit(set);
auto serialized = kmeans.ToJSON();
KMeans kmeans2(k);
kmeans2.FromJSON(serialized);
// In this simple case the centroids should be the input points.
EXPECT_THAT(kmeans2.centroids(), UnorderedRowsAre(points, 1e-6f));
}
TEST(KMeans, trimodal_normal_dist) {
int k = 3;
Eigen::MatrixXf points = kmeans_test_data();
Eigen::VectorXf weights = Eigen::VectorXf::Ones(60);
Eigen::MatrixXf expected_centroids = kmeans_expected_centroids();
auto set = std::make_shared<WeightedPointSet>(points, weights);
KMeans kmeans(k);
kmeans.Fit(set);
ASSERT_THAT(kmeans.centroids(), UnorderedRowsAre(expected_centroids, 0.15));
std::set<size_t> taken_inds;
for (int i = 0; i < 3; i++) {
std::vector<size_t> cluster_inds;
for (int j = 0; j < 20; j++) {
cluster_inds.push_back(kmeans.Transform(points(20 * i + j, Eigen::all).transpose()));
}
EXPECT_EQ(taken_inds.find(cluster_inds[0]), taken_inds.end());
EXPECT_THAT(cluster_inds, ::testing::Each(cluster_inds[0]));
taken_inds.insert(cluster_inds[0]);
}
}
} // namespace ml
} // namespace exec
} // namespace carnot
} // namespace px
| 26.825243 | 91 | 0.702135 | hangqiu |
f21222388a6463740758275ff3ae120e631f9a15 | 638 | cpp | C++ | src/RE/BSLightingShaderMaterialFacegenTint.cpp | powerof3/CommonLibVR | c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f | [
"MIT"
] | null | null | null | src/RE/BSLightingShaderMaterialFacegenTint.cpp | powerof3/CommonLibVR | c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f | [
"MIT"
] | null | null | null | src/RE/BSLightingShaderMaterialFacegenTint.cpp | powerof3/CommonLibVR | c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f | [
"MIT"
] | null | null | null | #include "RE/BSLightingShaderMaterialFacegenTint.h"
#include "RE/Offsets.h"
#include "REL/Relocation.h"
namespace RE
{
BSLightingShaderMaterialFacegenTint* BSLightingShaderMaterialFacegenTint::CreateMaterial()
{
auto material = malloc<BSLightingShaderMaterialFacegenTint>();
material->ctor();
material->tintColor = NiColor(1.0f, 1.0f, 1.0f);
return material;
}
BSLightingShaderMaterialFacegenTint* BSLightingShaderMaterialFacegenTint::ctor()
{
using func_t = decltype(&BSLightingShaderMaterialFacegenTint::ctor);
REL::Offset<func_t> func(Offset::BSLightingShaderMaterialFacegenTint::Ctor);
return func(this);
}
}
| 25.52 | 91 | 0.783699 | powerof3 |
f212eb472a77987f912edc19f46952d9c5e71b96 | 1,979 | cpp | C++ | src/cookie.cpp | kamchatka-volcano/hot_teacup | ef894b6f333364f9768f1d2477580604affada87 | [
"MS-PL"
] | null | null | null | src/cookie.cpp | kamchatka-volcano/hot_teacup | ef894b6f333364f9768f1d2477580604affada87 | [
"MS-PL"
] | null | null | null | src/cookie.cpp | kamchatka-volcano/hot_teacup | ef894b6f333364f9768f1d2477580604affada87 | [
"MS-PL"
] | null | null | null | #include <hot_teacup/cookie.h>
#include <sfun/string_utils.h>
namespace http{
namespace str = sfun::string_utils;
Cookie::Cookie(std::string name,
std::string value,
int maxAgeSec,
std::string domain,
std::string path)
: header_("Set-Cookie", "")
, name_(std::move(name))
, value_(std::move(value))
{
header_.setParam(name_, value_);
if (maxAgeSec >= 0)
header_.setParam("Max-Age", std::to_string(maxAgeSec));
if (!domain.empty())
header_.setParam("Domain", std::move(domain));
if (!path.empty())
header_.setParam("Path", std::move(path));
header_.setParam("Version", "1");
}
const std::string& Cookie::name() const
{
return name_;
}
const std::string& Cookie::value() const
{
return value_;
}
void Cookie::setDomain(std::string domain)
{
if (!domain.empty())
header_.setParam("Domain", std::move(domain));
}
void Cookie::setPath(std::string path)
{
if (!path.empty())
header_.setParam("Path", std::move(path));
}
void Cookie::setMaxAge(int maxAgeSec)
{
if (maxAgeSec >= 0)
header_.setParam("Max-Age", std::to_string(maxAgeSec));
}
void Cookie::remove()
{
header_.setParam("Expires", "Fri, 01-Jan-1971 01:00:00 GMT");
}
void Cookie::secure()
{
header_.setParam("Secure", "");
}
std::string Cookie::toString() const
{
return header_.toString();
}
bool Cookie::operator==(const Cookie& other) const
{
return name_ == other.name_ &&
value_ == other.value_;
}
Cookies cookiesFromString(std::string_view input)
{
auto result = Cookies{};
std::vector<std::string> cookies = str::split(input, ";");
for(const std::string& cookie : cookies){
auto name = str::before(cookie, "=");
auto value = str::after(cookie, "=");
if (!name.empty() && !value.empty())
result.emplace_back(str::trim(name), str::trim(value));
}
return result;
}
}
| 22.488636 | 67 | 0.605356 | kamchatka-volcano |
f215ae93708125a7a55390132439a0ccd9c084e0 | 2,033 | cpp | C++ | src/classad_support/coll-serv-inst.cpp | sridish123/htcondor | 481d975fd8602242f6a052aab04e20b0b560db89 | [
"Apache-2.0"
] | 217 | 2015-01-08T04:49:42.000Z | 2022-03-27T10:11:58.000Z | src/classad_support/coll-serv-inst.cpp | sridish123/htcondor | 481d975fd8602242f6a052aab04e20b0b560db89 | [
"Apache-2.0"
] | 185 | 2015-05-03T13:26:31.000Z | 2022-03-28T03:08:59.000Z | src/classad_support/coll-serv-inst.cpp | sridish123/htcondor | 481d975fd8602242f6a052aab04e20b0b560db89 | [
"Apache-2.0"
] | 133 | 2015-02-11T09:17:45.000Z | 2022-03-31T07:28:54.000Z | /***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "classad/common.h"
#include "classad/collection.h"
#include "collectionServer.h"
#include "classad/transaction.h"
using namespace std;
namespace classad {
//-------------collection server templates-------------
// view content
template multiset<ViewMember, ViewMemberLT>;
template multiset<ViewMember, ViewMemberLT>::iterator;
// list of sub-views
template slist<View*>;
// view registry
template hash_map<string,View*,StringHash>;
template hash_map<string,View*,StringHash>::iterator;
// index
template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator,
StringHash>::iterator;
template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator,
StringHash>;
// main classad table
template map<string, int>;
template hash_map<string,int,StringHash>;
template hash_map<string,int,StringHash>::iterator;
template hash_map<string, ClassAdProxy, StringHash>;
template hash_map<string, ClassAdProxy, StringHash>::iterator;
// transaction registry
template hash_map<string, ServerTransaction*, StringHash>;
template hash_map<string, ServerTransaction*, StringHash>::iterator;
// operations in transaction
template list<XactionRecord>;
}
| 33.327869 | 75 | 0.702902 | sridish123 |
f2167268765ffe76e761cc6761bc607ce690351d | 7,801 | cpp | C++ | src/nnfusion/core/operators/generic_op/generic_op_define/MaxPool.cpp | nox-410/nnfusion | 0777e297299c4e7a5071dc2ee97b87adcd22840e | [
"MIT"
] | 639 | 2020-09-05T10:00:59.000Z | 2022-03-30T08:42:39.000Z | src/nnfusion/core/operators/generic_op/generic_op_define/MaxPool.cpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 252 | 2020-09-09T05:35:36.000Z | 2022-03-29T04:58:41.000Z | src/nnfusion/core/operators/generic_op/generic_op_define/MaxPool.cpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 104 | 2020-09-05T10:01:08.000Z | 2022-03-23T10:59:13.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "nnfusion/core/operators/generic_op/generic_op.hpp"
REGISTER_OP(MaxPool)
.infershape(nnfusion::op::infershape::unimplemented_and_not_used)
/*
.translate([](std::shared_ptr<graph::GNode> curr) -> std::string {
auto _op = static_pointer_cast<nnfusion::op::MaxPool>(curr->get_op_ptr());
NNFUSION_CHECK_NOT_NULLPTR(_op) << "Node type is not " << curr->get_op_ptr()->get_op_type();
const auto& kernel = _op->get_window_shape();
const auto& stride = _op->get_window_movement_strides();
const auto& padding_below = _op->get_padding_below();
const auto& padding_above = _op->get_padding_above();
uint64_t padding[] = {
padding_below[1], padding_below[0], padding_above[1], padding_above[0]};
return op::create_code_from_template(
R"( - input("input0", @input_shape@); output(@output_shape@, topi=topi.nn.pool(args("input0"), kernel=@kernel@, stride=@stride@, padding=@padding@, pool_type="max")); )",
{{"input_shape", vector_to_string(curr->get_input_shape(0))},
{"output_shape", vector_to_string(curr->get_output_shape(0))},
{"kernel", vector_to_string(kernel)},
{"stride", vector_to_string(stride)},
{"padding", vector_to_string(padding)}});
})
*/
.translate_v2([](std::shared_ptr<graph::GNode> curr) -> std::string {
auto _op = static_pointer_cast<nnfusion::op::MaxPool>(curr->get_op_ptr());
auto& input_shape = curr->get_input_shape(0);
auto& output_shape = curr->get_output_shape(0);
auto& dtype = curr->get_element_type();
bool is_1d = (output_shape.size() == 3);
const bool is_nchw = _op->get_data_format() == "NCHW" ? true : false;
auto& m_strides = _op->get_window_movement_strides();
auto& strides = _op->get_window_shape();
auto& padding_below = _op->get_padding_below();
auto& padding_above = _op->get_padding_above();
if (!(padding_below.size() == padding_above.size()))
{
return std::string();
}
if (!(padding_below.size() >= 1))
{
return std::string();
}
if (!is_1d)
{
if (!(padding_below.size() == 2))
{
return std::string();
}
}
auto expression_template =
R"( @output0@@output0_layout@ >=! @input0@@input0_layout@@conditions@; )";
std::string conditions;
std::string when_condition;
std::string where_condition;
auto output_layout = std::vector<std::string>{"N"};
auto input_layout = std::vector<std::string>{"N"};
if (is_nchw)
{
output_layout.push_back("C");
input_layout.push_back("C");
output_layout.push_back("HO");
input_layout.push_back("HO * " + to_string(m_strides[0]) + " + KH - " +
to_string(padding_below[0]));
if (padding_below[0] > 0)
{
when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] + " >=0";
}
if (padding_above[0] > 0)
{
when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] + " < " +
to_string(input_shape[2]);
}
where_condition += (where_condition.empty() ? "" : " , ") + output_layout[2] + " in " +
to_string(output_shape[2]) + ", KH in " + to_string(strides[0]);
if (!is_1d)
{
output_layout.push_back("WO");
input_layout.push_back("WO * " + to_string(m_strides[1]) + " + KW - " +
to_string(padding_below[1]));
if (padding_below[0] > 0)
{
when_condition +=
(when_condition.empty() ? "" : " , ") + input_layout[3] + " >=0";
}
if (padding_above[0] > 0)
{
when_condition += (when_condition.empty() ? "" : " , ") + input_layout[3] +
" < " + to_string(input_shape[3]);
}
where_condition += (where_condition.empty() ? "" : " , ") + output_layout[3] +
" in " + to_string(output_shape[3]) + ", KW in " +
to_string(strides[1]);
}
}
else
{
output_layout.push_back("HO");
input_layout.push_back("HO * " + to_string(m_strides[0]) + " + KH - " +
to_string(padding_below[0]));
if (padding_below[0] > 0)
{
when_condition += (when_condition.empty() ? "" : " , ") + input_layout[1] + " >=0";
}
if (padding_above[0] > 0)
{
when_condition += (when_condition.empty() ? "" : " , ") + input_layout[1] + " < " +
to_string(input_shape[1]);
}
where_condition += (where_condition.empty() ? "" : " , ") + output_layout[1] + " in " +
to_string(output_shape[1]) + ", KH in " + to_string(strides[0]);
if (!is_1d)
{
output_layout.push_back("WO");
input_layout.push_back("WO * " + to_string(m_strides[1]) + " + KW - " +
to_string(padding_below[1]));
if (padding_below[0] > 0)
{
when_condition +=
(when_condition.empty() ? "" : " , ") + input_layout[2] + " >=0";
}
if (padding_above[0] > 0)
{
when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] +
" < " + to_string(input_shape[2]);
}
where_condition += (where_condition.empty() ? "" : " , ") + output_layout[2] +
" in " + to_string(output_shape[2]) + ", KW in " +
to_string(strides[1]);
}
output_layout.push_back("C");
input_layout.push_back("C");
}
if (!when_condition.empty())
{
std::string min_value;
if (dtype == nnfusion::element::f32)
{
min_value = "-3.4e38";
}
else if (dtype == nnfusion::element::f16)
{
min_value = "-6.55e4";
}
else if (dtype == nnfusion::element::i8)
{
min_value = "-128";
}
else
{
NNFUSION_LOG(INFO) << "not support padding with data type " << dtype
<< " yet, fallback";
return std::string();
}
when_condition = ".when([" + when_condition + "], " + min_value + ")";
}
if (!where_condition.empty())
{
where_condition = " where " + where_condition;
}
conditions = when_condition + where_condition;
op::OpConfig::any config;
config["conditions"] = conditions;
config["output0_layout"] = vector_to_string<std::vector<std::string>>(output_layout);
config["input0_layout"] = vector_to_string<std::vector<std::string>>(input_layout);
auto expression_code = op::create_code_from_template(expression_template, config);
return expression_code;
});
| 43.099448 | 182 | 0.483912 | nox-410 |
f217aaea17f8a57ecb3b96c89935b9862d806b2b | 2,485 | cpp | C++ | src/blinkit/blink/renderer/platform/shared_buffer.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 13 | 2020-04-21T13:14:00.000Z | 2021-11-13T14:55:12.000Z | src/blinkit/blink/renderer/platform/shared_buffer.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | null | null | null | src/blinkit/blink/renderer/platform/shared_buffer.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 4 | 2020-04-21T13:15:43.000Z | 2021-11-13T14:55:00.000Z | // -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
// File Name: shared_buffer.cpp
// Description: SharedBuffer Class
// Author: Ziming Li
// Created: 2019-09-29
// -------------------------------------------------
// Copyright (C) 2019 MingYang Software Technology.
// -------------------------------------------------
#include "./SharedBuffer.h"
#include "third_party/zed/include/zed/memory.hpp"
namespace blink {
SharedBuffer::SharedBuffer(const char *data, size_t length)
{
if (length > 0)
append(data, length);
}
std::shared_ptr<SharedBuffer> SharedBuffer::adoptVector(std::vector<char> &v)
{
auto ret = create();
if (ret)
ret->m_data.swap(v);
return ret;
}
void SharedBuffer::append(const char *data, size_t length)
{
ASSERT(length > 0);
size_t oldLength = m_data.size();
m_data.resize(oldLength + length);
memcpy(m_data.data() + oldLength, data, length);
}
std::shared_ptr<SharedBuffer> SharedBuffer::create(void)
{
return zed::wrap_shared(new SharedBuffer);
}
std::shared_ptr<SharedBuffer> SharedBuffer::create(const char *data, size_t length)
{
return zed::wrap_shared(new SharedBuffer(data, length));
}
std::shared_ptr<SharedBuffer> SharedBuffer::create(const unsigned char* data, size_t length)
{
return zed::wrap_shared(new SharedBuffer(reinterpret_cast<const char *>(data), length));
}
size_t SharedBuffer::getSomeData(const char *&data, size_t position) const
{
if (position >= m_data.size())
{
data = nullptr;
return 0;
}
ASSERT(position < m_data.size());
data = m_data.data();
return m_data.size();
}
bool SharedBuffer::isLocked(void) const
{
return true; // BKTODO: Check the logic.
}
#ifdef BLINKIT_UI_ENABLED
PassRefPtr<SkData> SharedBuffer::getAsSkData() const
{
size_t bufferLength = size();
SkData *data = SkData::NewUninitialized(bufferLength);
char *buffer = static_cast<char *>(data->writable_data());
const char *segment = nullptr;
size_t position = 0;
while (size_t segmentSize = getSomeData(segment, position))
{
memcpy(buffer + position, segment, segmentSize);
position += segmentSize;
}
if (position != bufferLength)
{
ASSERT_NOT_REACHED();
// Don't return the incomplete SkData.
return nullptr;
}
return adoptRef(data);
}
#endif
} // namespace blink
| 24.85 | 92 | 0.616901 | titilima |
f218d21c79bde9079b3dfe9c8a08d2cb52b571b7 | 8,355 | cpp | C++ | src/+ffmpeg/audioread.cpp | hokiedsp/matlab-ffmpeg | 60162157ab8e6ac1c4a4e6e8894e95a6eb2099ed | [
"BSD-2-Clause"
] | 3 | 2017-09-06T18:11:37.000Z | 2020-04-14T09:17:36.000Z | src/+ffmpeg/audioread.cpp | hokiedsp/matlab-ffmpeg | 60162157ab8e6ac1c4a4e6e8894e95a6eb2099ed | [
"BSD-2-Clause"
] | 1 | 2019-06-19T16:34:57.000Z | 2019-07-07T01:20:27.000Z | src/+ffmpeg/audioread.cpp | hokiedsp/matlab-ffmpeg | 60162157ab8e6ac1c4a4e6e8894e95a6eb2099ed | [
"BSD-2-Clause"
] | null | null | null | #include <mex.h>
#include <ffmpegReader.h>
#include <ffmpegPtrs.h>
#include <ffmpegTimeUtil.h>
#include "../utils/mxutils.h"
#include "@Reader/mexReaderPostOps.h"
#include <mexGetString.h>
extern "C"
{
#include <libavutil/dict.h>
}
#include <algorithm>
#include <chrono>
typedef std::chrono::duration<double> mex_duration_t;
bool log_uninit = true;
// [Y, FS]=audioread(FILENAME)
// [Y, FS]=audioread(FILENAME, [START END])
// [Y, FS]=audioread(FILENAME, DATATYPE)
// [Y, FS]=audioread(FILENAME, [START END], DATATYPE);
struct InputArgs
{
std::string url;
size_t start;
size_t end;
AVSampleFormat format;
mxClassID class_id;
InputArgs(int nrhs, const mxArray *prhs[]);
};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// initialize ffmpeg::Exception
if (log_uninit)
{
ffmpeg::Exception::initialize();
// ffmpeg::Exception::log_fcn = [](const auto &msg) {
// mexPrintf("%s\n", msg.c_str());
// };
log_uninit = false;
}
if (nlhs > 2 || nrhs < 1 || nrhs > 3)
mexErrMsgIdAndTxt("ffmpeg.audioinfo:invalidNumberOfArguments",
"Invalid number of input or output arguments specified.");
// parse the input arguments
InputArgs args(nrhs, prhs);
// open the audio file
ffmpeg::Reader<ffmpeg::AVFrameQueueST> reader;
reader.openFile(args.url);
// add audio stream (throws InvalidStreamSpecifier if no audio stream found)
int stream_id = reader.addStream(AVMEDIA_TYPE_AUDIO);
ffmpeg::InputAudioStream &stream =
dynamic_cast<ffmpeg::InputAudioStream &>(reader.getStream(stream_id));
// activate the reader
reader.activate();
// set postop filter if needed
AVSampleFormat format = stream.getFormat();
if (args.format == AV_SAMPLE_FMT_NONE)
{
args.format = av_get_packed_sample_fmt(format);
switch (args.format)
{
case AV_SAMPLE_FMT_U8: args.class_id = mxUINT8_CLASS; break;
case AV_SAMPLE_FMT_S16: args.class_id = mxINT16_CLASS; break;
case AV_SAMPLE_FMT_S32: args.class_id = mxINT32_CLASS; break;
case AV_SAMPLE_FMT_S64: args.class_id = mxINT64_CLASS; break;
case AV_SAMPLE_FMT_FLT: args.class_id = mxSINGLE_CLASS; break;
default: args.class_id = mxDOUBLE_CLASS;
}
}
if (args.format != format)
{
format = args.format;
reader.setPostOp<mexFFmpegAudioPostOp>(stream_id, format);
}
// analyze time-base & sample rate
int fs = stream.getSampleRate();
AVRational tb = stream.getTimeBase();
bool tbIsSamplePeriod = tb.num == 1 && tb.den == fs;
AVRational tb2Period = av_mul_q(tb, AVRational({fs, 1}));
auto get_frame_time = [tbIsSamplePeriod, tb2Period](const AVFrame *frame) {
return tbIsSamplePeriod ? frame->best_effort_timestamp
: av_rescale(frame->best_effort_timestamp,
tb2Period.num, tb2Period.den);
};
// set start & end 0-based sample indices
uint64_t start(0), end(0);
bool toEOF(!args.end);
if (args.start) { start = args.start - 1; }
if (toEOF)
end = stream.getTotalNumberOfSamples();
else
end = args.end;
// get estimated number of samples to be read
size_t N = end - start;
size_t Nch = stream.getChannels();
mxArray *Yt = mxCreateNumericMatrix(Nch, N, args.class_id, mxREAL);
uint8_t *data = (uint8_t *)mxGetData(Yt);
size_t elsz = mxGetElementSize(Yt);
size_t n_left = N; // bytes left in the buffer
uint8_t *dst[AV_NUM_DATA_POINTERS];
dst[0] = data;
dst[1] = nullptr;
// number of bytes/sample
size_t nbuf = elsz * Nch;
AVFrame *frame = av_frame_alloc();
ffmpeg::AVFramePtr frame_cleanup(frame, ffmpeg::delete_av_frame);
auto copy_data = [&dst, &n_left, &Yt, nbuf, format](const AVFrame *frame,
int n, int offset = 0) {
if (n_left < n)
{
// if run out of space, expand the mxArray
uint8_t *data = (uint8_t *)mxGetData(Yt);
size_t elsz = mxGetElementSize(Yt);
size_t dst_offset = dst[0] - data;
size_t N = mxGetN(Yt) + (n - n_left);
data = (uint8_t *)mxRealloc(data, N * frame->channels * elsz);
mxSetData(Yt, data);
mxSetN(Yt, N);
dst[0] = data + dst_offset;
n_left = 0;
}
else
{
n_left -= n;
}
av_samples_copy(dst, frame->data, 0, offset, n, frame->channels, format);
dst[0] += nbuf * n;
};
// seek to near the starting frame
reader.seek(mex_duration_t(start / (double)fs), false);
// get the first frame
reader.readNextFrame(frame, stream_id);
if (start > 0)
{
// get frames until reader's next frame is past the starting time while
// the last read frame contains the requested start time
mex_duration_t t0(start / (double)fs);
while (!reader.atEndOfStream(stream_id) &&
reader.getTimeStamp<mex_duration_t>(stream_id) < t0)
{
av_frame_unref(frame);
reader.readNextFrame(frame, stream_id);
}
}
// no data (shouldn't happen)
if (frame->nb_samples == 0)
mexErrMsgIdAndTxt("ffmpeg:audioread:NoData", "No data found.");
// copy the data from the first frame
int offset = (int)(start - get_frame_time(frame));
if (offset < 0)
mexErrMsgIdAndTxt("ffmpeg:audioread:BadOffset", "Seek failed.");
int n = frame->nb_samples - offset;
copy_data(frame, (toEOF || n < n_left) ? n : (int)n_left, offset);
// work the remaining frames
while (!reader.atEndOfStream(stream_id) && (toEOF || n_left > 0))
{
reader.readNextFrame(frame, stream_id);
n = frame->nb_samples;
if (!toEOF && n > n_left) n = (int)n_left;
copy_data(frame, n);
}
// call MATLAB transpose function to finalize combined-audio output
mxArray *Y;
mexCallMATLAB(1, &Y, 1, &Yt, "transpose");
mxDestroyArray(Yt);
plhs[0] = Y;
if (nlhs > 1) plhs[1] = mxCreateDoubleScalar(fs);
}
// [Y, FS]=audioread(FILENAME)
// [Y, FS]=audioread(FILENAME, [START END])
// [Y, FS]=audioread(FILENAME, DATATYPE)
// [Y, FS]=audioread(FILENAME, [START END], DATATYPE);
InputArgs::InputArgs(int nrhs, const mxArray *prhs[])
: start(0), end(0), format(AV_SAMPLE_FMT_DBL), class_id(mxDOUBLE_CLASS)
{
mxArray *mxURL;
mexCallMATLAB(1, &mxURL, 1, (mxArray **)prhs, "which");
url = mexGetString(mxURL);
int arg(1);
if (nrhs > 1 && !mxIsChar(prhs[1]))
{
if (!(mxIsDouble(prhs[1]) && mxGetNumberOfElements(prhs[1]) == 2))
mexErrMsgIdAndTxt(
"ffmpeg:audioread:InvalidInputArguments",
"[START END] vector must exactly contain 2 double elements");
double *data = mxGetPr(prhs[1]);
start = (size_t)data[0];
end = (size_t)data[1];
if (start != data[0] || end != data[1])
mexErrMsgIdAndTxt(
"ffmpeg:audioread:InvalidInputArguments",
"Expected [START END] input argument to be integer-valued");
if (start == 0 || end == 0)
mexErrMsgIdAndTxt("ffmpeg:audioread:InvalidInputArguments",
"Expected [START END] input argument to be positive");
if (start > end)
mexErrMsgIdAndTxt("ffmpeg:audioread:InvalidInputArguments",
"START input argument must be less than or equal to "
"END input argument");
arg = 2;
}
if (nrhs > arg)
{
if (!(mxIsChar(prhs[arg])))
mexErrMsgIdAndTxt("ffmpeg:audioread:InvalidInputArguments",
"DATATYPE must be character array.");
std::string mxtype = mexGetString(prhs[arg]);
if (mxtype == "native") { format = AV_SAMPLE_FMT_NONE; }
else if (mxtype == "uint8")
{
class_id = mxUINT8_CLASS;
format = AV_SAMPLE_FMT_U8;
}
else if (mxtype == "int16")
{
class_id = mxINT16_CLASS;
format = AV_SAMPLE_FMT_S16;
}
else if (mxtype == "int32")
{
class_id = mxINT32_CLASS;
format = AV_SAMPLE_FMT_S32;
}
else if (mxtype == "int64")
{
class_id = mxINT64_CLASS;
format = AV_SAMPLE_FMT_S64;
}
else if (mxtype == "single")
{
class_id = mxSINGLE_CLASS;
format = AV_SAMPLE_FMT_FLT;
}
else if (mxtype == "double")
{
class_id = mxDOUBLE_CLASS;
format = AV_SAMPLE_FMT_DBL;
}
else
{
mexErrMsgIdAndTxt("ffmpeg:audioread:InvalidInputArguments",
"Unknown DATATYPE given %s.", mxtype.c_str());
}
}
}
| 29.839286 | 80 | 0.636744 | hokiedsp |
35e9c6bda47f6d686260a9b56053968e37ddce62 | 1,804 | cpp | C++ | expvar/main.cpp | dtoma/cpp | 1c6c726071092d9e238c6fb3de22fed833a148b2 | [
"MIT"
] | null | null | null | expvar/main.cpp | dtoma/cpp | 1c6c726071092d9e238c6fb3de22fed833a148b2 | [
"MIT"
] | null | null | null | expvar/main.cpp | dtoma/cpp | 1c6c726071092d9e238c6fb3de22fed833a148b2 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <signal.h>
#include <thread>
#include "http.h"
#include "network.h"
#include "db.h"
namespace {
class expvar {
std::thread t;
public:
template <typename T>
expvar(T&& function) : t(function) {
}
~expvar() {
t.join();
}
expvar(expvar const&) = delete;
expvar(expvar&&) = delete;
expvar& operator=(expvar const&) = delete;
expvar& operator=(expvar&&) = delete;
};
template <typename T>
auto run_expvar_server(T* db) {
auto sockfd = dt::net::create_and_bind_socket();
auto listening = dt::net::start_listening(sockfd);
if (!listening) {
return 1;
}
auto ready = dt::net::setup_dead_proc_catcher();
if (!ready) {
return 1;
}
printf("socket waiting for connections\n");
while(1) { // main accept() loop
auto new_fd = dt::net::accept_client(sockfd);
if (new_fd == -1) {
continue;
}
if (!fork()) { // this is the child process
dt::http::handle_request(db, sockfd, new_fd);
}
close(new_fd); // parent doesn't need this
}
}
}
int main() {
auto db = dt::db::open_database();
auto op = dt::db::put(db, "Hello", "World");
if (!op.ok()) {
return 1;
}
op = dt::db::put(db, "Foo", "Bar");
op = dt::db::put(db, "Ping", "Pong");
op = dt::db::put(db, "The Answer", "42");
printf("Database dump:\n");
dt::db::map(db, [](auto key, auto value) {
printf("\t%-12s: %s\n", key.c_str(), value.c_str());
});
expvar e([&db]() { run_expvar_server(db); });
}
| 23.428571 | 64 | 0.5 | dtoma |
35eb358a8aa5bf3c0da7d1e0e8f6f987445bfe82 | 1,081 | hxx | C++ | time.hxx | Arcoth/VTMPL | d83e4c6ab2e931bce60761997c782d6679a7cba4 | [
"BSL-1.0"
] | null | null | null | time.hxx | Arcoth/VTMPL | d83e4c6ab2e931bce60761997c782d6679a7cba4 | [
"BSL-1.0"
] | null | null | null | time.hxx | Arcoth/VTMPL | d83e4c6ab2e931bce60761997c782d6679a7cba4 | [
"BSL-1.0"
] | null | null | null | /* Copyright (c) Arcoth, 2013-2014.
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) */
#ifndef TIME_HXX_INCLUDED
#define TIME_HXX_INCLUDED
#include "string.hxx"
#include "parsers.hxx"
namespace vtmpl
{
template <typename format = VTMPL_STRING("HhMmSs")>
constexpr std::uintmax_t time()
{
using str = VTMPL_STRING( __TIME__ );
auto const Hh = parse_unsigned<str>().first;
auto const Mm = parse_unsigned<str>(3).first;
auto const Ss = parse_unsigned<str>(6).first;
std::uintmax_t rval = 0;
for (auto c : format::array)
{
rval *= 10;
if( isdigit(c) )
rval += c - '0';
else switch(c)
{
case 'H': rval += Hh / 10; break;
case 'h': rval += Hh % 10; break;
case 'M': rval += Mm / 10; break;
case 'm': rval += Mm % 10; break;
case 'S': rval += Ss / 10; break;
case 's': rval += Ss % 10; break;
default:
vtmpl::assert(0, "Invalid time format string!");
}
}
return rval;
}
}
#endif // TIME_HXX_INCLUDED
| 20.788462 | 91 | 0.629047 | Arcoth |
35f2d80b23e75ccd71a142d1576cb22247a87735 | 24,966 | cpp | C++ | main.cpp | ghsecuritylab/BLEClient_mbedDevConn_Watson | f162ec8a99ab3b21cee28aaed65da60cf5dd6618 | [
"Apache-2.0"
] | 1 | 2019-05-28T04:54:23.000Z | 2019-05-28T04:54:23.000Z | main.cpp | ghsecuritylab/BLEClient_mbedDevConn_Watson | f162ec8a99ab3b21cee28aaed65da60cf5dd6618 | [
"Apache-2.0"
] | 1 | 2017-02-20T10:48:02.000Z | 2017-02-21T11:34:16.000Z | main.cpp | ghsecuritylab/BLEClient_mbedDevConn_Watson | f162ec8a99ab3b21cee28aaed65da60cf5dd6618 | [
"Apache-2.0"
] | 3 | 2017-02-07T15:06:06.000Z | 2021-02-19T13:56:31.000Z | /*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* 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.
*/
/*
TODO:
1. Remove references to K64F & use NUCLEO_F429ZI only.
2. Tested with Ethernet. Remove references to wireless technologies.
3. More formatting / code clean up when I find some free time.
*/
#include "simpleclient.h"
#include <string>
#include <sstream>
#include <vector>
#include "mbed-trace/mbed_trace.h"
#include "mbedtls/entropy_poll.h"
#include <events/mbed_events.h>
#include <mbed.h>
#include "ble\BLE.h"
#include "ble\DiscoveredCharacteristic.h"
#include "ble\DiscoveredService.h"
#include "security.h"
#include "mbed.h"
#include "rtos.h"
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
#include "ESP8266Interface.h"
ESP8266Interface esp(MBED_CONF_APP_WIFI_TX, MBED_CONF_APP_WIFI_RX);
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
#include "EthernetInterface.h"
EthernetInterface eth;
#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND
#define MESH
#include "NanostackInterface.h"
LoWPANNDInterface mesh;
#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD
#define MESH
#include "NanostackInterface.h"
ThreadInterface mesh;
#endif
#if defined(MESH)
#if MBED_CONF_APP_MESH_RADIO_TYPE == ATMEL
#include "NanostackRfPhyAtmel.h"
NanostackRfPhyAtmel rf_phy(ATMEL_SPI_MOSI, ATMEL_SPI_MISO, ATMEL_SPI_SCLK, ATMEL_SPI_CS,
ATMEL_SPI_RST, ATMEL_SPI_SLP, ATMEL_SPI_IRQ, ATMEL_I2C_SDA, ATMEL_I2C_SCL);
#elif MBED_CONF_APP_MESH_RADIO_TYPE == MCR20
#include "NanostackRfPhyMcr20a.h"
NanostackRfPhyMcr20a rf_phy(MCR20A_SPI_MOSI, MCR20A_SPI_MISO, MCR20A_SPI_SCLK, MCR20A_SPI_CS, MCR20A_SPI_RST, MCR20A_SPI_IRQ);
#endif //MBED_CONF_APP_RADIO_TYPE
#endif //MESH
#ifndef MESH
// This is address to mbed Device Connector
#define MBED_SERVER_ADDRESS "coap://api.connector.mbed.com:5684"
#else
// This is address to mbed Device Connector
#define MBED_SERVER_ADDRESS "coaps://[2607:f0d0:2601:52::20]:5684"
#endif
Serial output(USBTX, USBRX);
// Status indication
DigitalOut red_led(LED1);
DigitalOut green_led(LED2);
DigitalOut blue_led(LED3);
Ticker status_ticker;
/************************************************************BLE Stuff from here *********************************/
BLE &ble = BLE::Instance();
static DiscoveredCharacteristic optCharacteristic;
static bool triggerLedCharacteristic;
static const char PEER_NAME[] = "OPT3001";
uint16_t payload_length = 0;
uint8_t dataforClient[] = {0};
uint32_t final_dataforClient = 0;
static EventQueue eventQueue(
/* event count */ 16 * /* event size */ 32
);
void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
// parse the advertising payload, looking for data type COMPLETE_LOCAL_NAME
// The advertising payload is a collection of key/value records where
// byte 0: length of the record excluding this byte
// byte 1: The key, it is the type of the data
// byte [2..N] The value. N is equal to byte0 - 1
//printf("Starting advertisementCallback...\r\n");
for (uint8_t i = 0; i < params->advertisingDataLen; ++i) {
const uint8_t record_length = params->advertisingData[i];
if (record_length == 0) {
continue;
}
const uint8_t type = params->advertisingData[i + 1];
const uint8_t* value = params->advertisingData + i + 2;
const uint8_t value_length = record_length - 1;
if(type == GapAdvertisingData::COMPLETE_LOCAL_NAME) {
if ((value_length == sizeof(PEER_NAME)) && (memcmp(value, PEER_NAME, value_length) == 0)) {
printf(
"adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2],
params->peerAddr[1], params->peerAddr[0], params->rssi, params->isScanResponse, params->type
);
BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
break;
}
}
i += record_length;
}
}
void serviceDiscoveryCallback(const DiscoveredService *service) {
if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
printf("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
} else {
printf("S UUID-");
const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
printf("%02x", longUUIDBytes[i]);
}
printf(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
}
}
//This function is not used. ToDo: get rid of it and any references.
void updateLedCharacteristic(void) {
if (!BLE::Instance().gattClient().isServiceDiscoveryActive()) {
optCharacteristic.read();
}
}
void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
printf(" C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
if (characteristicP->getUUID().getShortUUID() == 0xA001) { /* !ALERT! Alter this filter to suit your device. */
optCharacteristic = *characteristicP;
triggerLedCharacteristic = true;
}
}
void discoveryTerminationCallback(Gap::Handle_t connectionHandle) {
printf("terminated SD for handle %u\r\n", connectionHandle);
if(connectionHandle != 0) {
// led2 = 1;
}
if (triggerLedCharacteristic) {
triggerLedCharacteristic = false;
eventQueue.call(updateLedCharacteristic);
}
}
void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
printf("Connected to OPT3001 now...\r\n");
if (params->role == Gap::CENTRAL) {
BLE &ble = BLE::Instance();
ble.gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
ble.gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xA000, 0xA001);
}
}
//ASHOK's triggerRead function
void triggerRead(const GattReadCallbackParams *response) {
if (response->handle == optCharacteristic.getValueHandle()) {
optCharacteristic.read();
// printf("payload length = %d\r\n", response-> len);
payload_length = response-> len;
//printf("************OPT Characteristic value = ", optCharacteristic);
for(int i=0; i< response-> len; i++) {
//printf("%02x", response->data[i]);
dataforClient[i] = response -> data[i];
// printf("%d", dataforClient[i]);
}
//BLE packet contains 4 bytes of 8 bit int's each. Combine all of them to form a single 32-bit int.
final_dataforClient = ((uint32_t)dataforClient[3]<<24) | (dataforClient[2]<<16) | (dataforClient[1] << 8) | (dataforClient[0]);
printf("Final data for cleint = %x\r\n", final_dataforClient);
// printf("\r\n");
optCharacteristic.read();
}
}
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *) {
printf("disconnected\r\n");
/* Start scanning and try to connect again */
BLE::Instance().gap().startScan(advertisementCallback);
}
void onBleInitError(BLE &ble, ble_error_t error)
{
/* Initialization error handling should go here */
printf("BLE Error = %u\r\n", error);
}
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
printf("I'm inside BLE init\r\n");
BLE& ble = params->ble;
ble_error_t error = params->error;
ble_error_t error1 = params->error;
if (error != BLE_ERROR_NONE) {
/* In case of error, forward the error handling to onBleInitError */
onBleInitError(ble, error);
return;
}
/* Ensure that it is the default instance of BLE */
if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
printf("Not the default instance\r\n");
return;
}
ble.gap().onDisconnection(disconnectionCallback);
ble.gap().onConnection(connectionCallback);
// On reading data, call triggerRead function.
ble.gattClient().onDataRead(triggerRead);
// scan interval: 400ms and scan window: 400ms.
// Every 400ms the device will scan for 400ms
// This means that the device will scan continuously.
ble.gap().setScanParams(400, 400);
error = ble.gap().startScan(advertisementCallback);
printf("BLE Error startScan = %u\r\n", error);
}
void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
BLE &ble = BLE::Instance();
eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
}
/************************************************************BLE Stuff to here *********************************/
void blinky() {
green_led = !green_led;
}
// These are example resource values for the Device Object
struct MbedClientDevice device = {
"Manufacturer_String", // Manufacturer
"Type_String", // Type
"ModelNumber_String", // ModelNumber
"SerialNumber_String" // SerialNumber
};
// Instantiate the class which implements LWM2M Client API (from simpleclient.h)
MbedClient mbed_client(device);
// In case of K64F board , there is button resource available
// to change resource value and unregister
#ifdef TARGET_K64F
// Set up Hardware interrupt button.
InterruptIn obs_button(SW2);
InterruptIn unreg_button(SW3);
#else
//In non K64F boards , set up a timer to simulate updating resource,
// there is no functionality to unregister.
Ticker timer;
#endif
/*
* Arguments for running "blink" in it's own thread.
*/
class BlinkArgs {
public:
BlinkArgs() {
clear();
}
void clear() {
position = 0;
blink_pattern.clear();
}
uint16_t position;
std::vector<uint32_t> blink_pattern;
};
/*
* The Led contains one property (pattern) and a function (blink).
* When the function blink is executed, the pattern is read, and the LED
* will blink based on the pattern.
*/
class LedResource {
public:
LedResource() {
// create ObjectID with metadata tag of '3201', which is 'digital output'
led_object = M2MInterfaceFactory::create_object("3201");
M2MObjectInstance* led_inst = led_object->create_object_instance();
// 5853 = Multi-state output
M2MResource* pattern_res = led_inst->create_dynamic_resource("5853", "Pattern",
M2MResourceInstance::STRING, false);
// read and write
pattern_res->set_operation(M2MBase::GET_PUT_ALLOWED);
// set initial pattern (toggle every 200ms. 7 toggles in total)
pattern_res->set_value((const uint8_t*)"500:500:500:500:500:500:500", 27);
// there's not really an execute LWM2M ID that matches... hmm...
M2MResource* led_res = led_inst->create_dynamic_resource("5850", "Blink",
M2MResourceInstance::OPAQUE, false);
// we allow executing a function here...
led_res->set_operation(M2MBase::POST_ALLOWED);
// when a POST comes in, we want to execute the led_execute_callback
led_res->set_execute_function(execute_callback(this, &LedResource::blink));
// Completion of execute function can take a time, that's why delayed response is used
led_res->set_delayed_response(true);
blink_args = new BlinkArgs();
}
~LedResource() {
delete blink_args;
}
M2MObject* get_object() {
return led_object;
}
void blink(void *argument) {
// read the value of 'Pattern'
status_ticker.detach();
red_led = 1;
M2MObjectInstance* inst = led_object->object_instance();
M2MResource* res = inst->resource("5853");
// Clear previous blink data
blink_args->clear();
// values in mbed Client are all buffers, and we need a vector of int's
uint8_t* buffIn = NULL;
uint32_t sizeIn;
res->get_value(buffIn, sizeIn);
// turn the buffer into a string, and initialize a vector<int> on the heap
std::string s((char*)buffIn, sizeIn);
free(buffIn);
output.printf("led_execute_callback pattern=%s\r\n", s.c_str());
// our pattern is something like 500:200:500, so parse that
std::size_t found = s.find_first_of(":");
while (found!=std::string::npos) {
blink_args->blink_pattern.push_back(atoi((const char*)s.substr(0,found).c_str()));
s = s.substr(found+1);
found=s.find_first_of(":");
if(found == std::string::npos) {
blink_args->blink_pattern.push_back(atoi((const char*)s.c_str()));
}
}
// check if POST contains payload
if (argument) {
M2MResource::M2MExecuteParameter* param = (M2MResource::M2MExecuteParameter*)argument;
String object_name = param->get_argument_object_name();
uint16_t object_instance_id = param->get_argument_object_instance_id();
String resource_name = param->get_argument_resource_name();
int payload_length = param->get_argument_value_length();
uint8_t* payload = param->get_argument_value();
output.printf("Resource: %s/%d/%s executed\r\n", object_name.c_str(), object_instance_id, resource_name.c_str());
output.printf("Payload: %.*s\r\n", payload_length, payload);
}
// do_blink is called with the vector, and starting at -1
blinky_thread.start(this, &LedResource::do_blink);
}
private:
M2MObject* led_object;
Thread blinky_thread;
BlinkArgs *blink_args;
void do_blink() {
// blink the LED
red_led = !red_led;
// up the position, if we reached the end of the vector
if (blink_args->position >= blink_args->blink_pattern.size()) {
// send delayed response after blink is done
M2MObjectInstance* inst = led_object->object_instance();
M2MResource* led_res = inst->resource("5850");
led_res->send_delayed_post_response();
red_led = 1;
status_ticker.attach_us(blinky, 250000);
return;
}
// Invoke same function after `delay_ms` (upping position)
Thread::wait(blink_args->blink_pattern.at(blink_args->position));
blink_args->position++;
do_blink();
}
};
/*
* The button contains one property (click count).
* When `handle_button_click` is executed, the counter updates.
*/
class ButtonResource {
public:
ButtonResource(): counter(0) {
// create ObjectID with metadata tag of 'OPT', which is 'digital input'
btn_object = M2MInterfaceFactory::create_object("OPT");
M2MObjectInstance* btn_inst = btn_object->create_object_instance();
// create resource with ID '5501', which is digital input counter
M2MResource* btn_res = btn_inst->create_dynamic_resource("5501", "Button",
M2MResourceInstance::INTEGER, true /* observable */);
// we can read this value
btn_res->set_operation(M2MBase::GET_ALLOWED);
// set initial value (all values in mbed Client are buffers)
// to be able to read this data easily in the Connector console, we'll use a string
btn_res->set_value((uint8_t*)"0", 1);
}
~ButtonResource() {
}
M2MObject* get_object() {
return btn_object;
}
/*
* When you press the button, we read the current value of the click counter
* from mbed Device Connector, then up the value with one.
*/
void handle_button_click() {
M2MObjectInstance* inst = btn_object->object_instance();
M2MResource* res = inst->resource("5501");
// up counter
//counter++;
// for(int i=0; i< payload_length; i++) {
//printf("%02x", response->data[i]);
//dataforClient[i] = response -> data[i];
// printf("%x", dataforClient[i]);
// }
// printf("\r\n");
/*************************** Implement OPT data copy to payload here instead of counter ******************/
#ifdef TARGET_K64F
printf("handle_button_click, new value of counter is %d\r\n", counter);
#else
printf("OPT3001 value sent to connector = %x\r\n", final_dataforClient);
#endif
// serialize the value of counter as a string, and tell connector
char buffer[20];
int size = sprintf(buffer,"%x",final_dataforClient);
res->set_value((uint8_t*)buffer, size);
}
private:
M2MObject* btn_object;
uint16_t counter;
};
class BigPayloadResource {
public:
BigPayloadResource() {
big_payload = M2MInterfaceFactory::create_object("1000");
M2MObjectInstance* payload_inst = big_payload->create_object_instance();
M2MResource* payload_res = payload_inst->create_dynamic_resource("1", "BigData",
M2MResourceInstance::STRING, true /* observable */);
payload_res->set_operation(M2MBase::GET_PUT_ALLOWED);
payload_res->set_value((uint8_t*)"0", 1);
payload_res->set_incoming_block_message_callback(
incoming_block_message_callback(this, &BigPayloadResource::block_message_received));
payload_res->set_outgoing_block_message_callback(
outgoing_block_message_callback(this, &BigPayloadResource::block_message_requested));
}
M2MObject* get_object() {
return big_payload;
}
void block_message_received(M2MBlockMessage *argument) {
if (argument) {
if (M2MBlockMessage::ErrorNone == argument->error_code()) {
if (argument->is_last_block()) {
output.printf("Last block received\r\n");
}
output.printf("Block number: %d\r\n", argument->block_number());
// First block received
if (argument->block_number() == 0) {
// Store block
// More blocks coming
} else {
// Store blocks
}
} else {
output.printf("Error when receiving block message! - EntityTooLarge\r\n");
}
output.printf("Total message size: %d\r\n", argument->total_message_size());
}
}
void block_message_requested(const String& resource, uint8_t *&/*data*/, uint32_t &/*len*/) {
output.printf("GET request received for resource: %s\r\n", resource.c_str());
// Copy data and length to coap response
}
private:
M2MObject* big_payload;
};
// Network interaction must be performed outside of interrupt context
Semaphore updates(0);
volatile bool registered = false;
volatile bool clicked = false;
osThreadId mainThread;
void unregister() {
registered = false;
updates.release();
}
void button_clicked() {
clicked = true;
updates.release();
}
// debug printf function
void trace_printer(const char* str) {
printf("%s\r\n", str);
}
/****************************************************************More BLE Stuff from here****************/
//BLE thread init and further calls to other BLE methods.
void BLE_thread_init(void){
printf("I'm inside BLE thread.....\r\n");
eventQueue.call_every(500, blinky);
//Schedule events before starting the thread since there might be some missed events while scanning / pairing.
ble.onEventsToProcess(scheduleBleEventsProcessing);
ble.init(bleInitComplete);
//Loop forever the BLE thread
eventQueue.dispatch_forever();
}
/****************************************************************More BLE Stuff to here****************/
// Entry point to the program
int main() {
unsigned int seed;
size_t len;
//Create a new thread for BLE
Thread BLE_thread;
#ifdef MBEDTLS_ENTROPY_HARDWARE_ALT
// Used to randomize source port
mbedtls_hardware_poll(NULL, (unsigned char *) &seed, sizeof seed, &len);
#elif defined MBEDTLS_TEST_NULL_ENTROPY
#warning "mbedTLS security feature is disabled. Connection will not be secure !! Implement proper hardware entropy for your selected hardware."
// Used to randomize source port
mbedtls_null_entropy_poll( NULL,(unsigned char *) &seed, sizeof seed, &len);
#else
#error "This hardware does not have entropy, endpoint will not register to Connector.\
You need to enable NULL ENTROPY for your application, but if this configuration change is made then no security is offered by mbed TLS.\
Add MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES and MBEDTLS_TEST_NULL_ENTROPY in mbed_app.json macros to register your endpoint."
#endif
srand(seed);
red_led = 1;
blue_led = 1;
status_ticker.attach_us(blinky, 250000);
// Keep track of the main thread
mainThread = osThreadGetId();
// Sets the console baud-rate
output.baud(9600);
output.printf("Starting mbed Client example...\r\n");
mbed_trace_init();
mbed_trace_print_function_set(trace_printer);
NetworkInterface *network_interface = 0;
int connect_success = -1;
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
output.printf("\n\rUsing WiFi \r\n");
output.printf("\n\rConnecting to WiFi..\r\n");
connect_success = esp.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD);
network_interface = &esp;
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
output.printf("Using Ethernet\r\n");
connect_success = eth.connect();
network_interface = ð
#endif
#ifdef MESH
output.printf("Using Mesh\r\n");
output.printf("\n\rConnecting to Mesh..\r\n");
mesh.initialize(&rf_phy);
connect_success = mesh.connect();
network_interface = &mesh;
#endif
if(connect_success == 0) {
output.printf("\n\rConnected to Network successfully\r\n");
} else {
output.printf("\n\rConnection to Network Failed %d! Exiting application....\r\n", connect_success);
return 0;
}
const char *ip_addr = network_interface->get_ip_address();
if (ip_addr) {
output.printf("IP address %s\r\n", ip_addr);
} else {
output.printf("No IP address\r\n");
}
// we create our button and LED resources
ButtonResource button_resource;
LedResource led_resource;
BigPayloadResource big_payload_resource;
#ifdef TARGET_K64F
// On press of SW3 button on K64F board, example application
// will call unregister API towards mbed Device Connector
//unreg_button.fall(&mbed_client,&MbedClient::test_unregister);
unreg_button.fall(&unregister);
// Observation Button (SW2) press will send update of endpoint resource values to connector
obs_button.fall(&button_clicked);
#else
// Send update of endpoint resource values to connector every 5 seconds periodically
timer.attach(&button_clicked, 5.0);
#endif
// Create endpoint interface to manage register and unregister
mbed_client.create_interface(MBED_SERVER_ADDRESS, network_interface);
// Create Objects of varying types, see simpleclient.h for more details on implementation.
M2MSecurity* register_object = mbed_client.create_register_object(); // server object specifying connector info
M2MDevice* device_object = mbed_client.create_device_object(); // device resources object
// Create list of Objects to register
M2MObjectList object_list;
// Add objects to list
object_list.push_back(device_object);
object_list.push_back(button_resource.get_object());
object_list.push_back(led_resource.get_object());
object_list.push_back(big_payload_resource.get_object());
// Set endpoint registration object
mbed_client.set_register_object(register_object);
// Register with mbed Device Connector
mbed_client.test_register(register_object, object_list);
registered = true;
//Start BLE thread after connection is established to device connector. Else, there is conflict.
BLE_thread.start(BLE_thread_init);
while (true) {
printf("inside main for client\n");
triggerLedCharacteristic = false;
updates.wait(25000);
if(registered) {
if(!clicked) {
//printf("Inside registered ... clicked \r\n");
mbed_client.test_update_register();
}
}else {
break;
}
if(clicked) {
clicked = false;
button_resource.handle_button_click();
}
}
mbed_client.test_unregister();
status_ticker.detach();
}
| 35.819225 | 187 | 0.665665 | ghsecuritylab |
35f701f1ab7d83d91cbd9e7f9eb415b23acb9406 | 1,238 | cc | C++ | media/gpu/android/mock_android_video_surface_chooser.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | media/gpu/android/mock_android_video_surface_chooser.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | media/gpu/android/mock_android_video_surface_chooser.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/gpu/android/mock_android_video_surface_chooser.h"
namespace media {
MockAndroidVideoSurfaceChooser::MockAndroidVideoSurfaceChooser() = default;
MockAndroidVideoSurfaceChooser::~MockAndroidVideoSurfaceChooser() = default;
void MockAndroidVideoSurfaceChooser::SetClientCallbacks(
UseOverlayCB use_overlay_cb,
UseTextureOwnerCB use_texture_owner_cb) {
MockSetClientCallbacks();
use_overlay_cb_ = std::move(use_overlay_cb);
use_texture_owner_cb_ = std::move(use_texture_owner_cb);
}
void MockAndroidVideoSurfaceChooser::UpdateState(
base::Optional<AndroidOverlayFactoryCB> factory,
const State& new_state) {
MockUpdateState();
if (factory) {
factory_ = std::move(*factory);
MockReplaceOverlayFactory(!factory_.is_null());
}
current_state_ = new_state;
}
void MockAndroidVideoSurfaceChooser::ProvideTextureOwner() {
use_texture_owner_cb_.Run();
}
void MockAndroidVideoSurfaceChooser::ProvideOverlay(
std::unique_ptr<AndroidOverlay> overlay) {
use_overlay_cb_.Run(std::move(overlay));
}
} // namespace media
| 30.195122 | 76 | 0.78433 | zipated |
35f767f33774d158c13387495c68f16022c9407f | 209 | cpp | C++ | src/module_args/args_args.cpp | Sonotsugipaa/csono | 7e08734b982bc22758ee76fc09ade46f67195e8a | [
"MIT"
] | null | null | null | src/module_args/args_args.cpp | Sonotsugipaa/csono | 7e08734b982bc22758ee76fc09ade46f67195e8a | [
"MIT"
] | null | null | null | src/module_args/args_args.cpp | Sonotsugipaa/csono | 7e08734b982bc22758ee76fc09ade46f67195e8a | [
"MIT"
] | null | null | null | #include <csono/args.hpp>
namespace csono {
Argument::Argument(): a_value(), a_position(-1) { }
Argument::Argument(std::string val, unsigned pos):
a_value(std::move(val)),
a_position(pos)
{ }
}
| 13.933333 | 52 | 0.650718 | Sonotsugipaa |
35fcfaf76da268c75972bbd0932dd996a96d523f | 119 | cpp | C++ | src/FilterIterator.cpp | adsharma/iterlib | eacc729b7ec8be7376e1d1bf5e9edd4dade3f222 | [
"BSD-3-Clause"
] | 76 | 2016-11-11T18:08:12.000Z | 2018-06-04T23:14:43.000Z | src/FilterIterator.cpp | adsharma/iterlib | eacc729b7ec8be7376e1d1bf5e9edd4dade3f222 | [
"BSD-3-Clause"
] | 13 | 2016-11-16T00:25:54.000Z | 2017-04-18T21:14:14.000Z | src/FilterIterator.cpp | adsharma/iterlib | eacc729b7ec8be7376e1d1bf5e9edd4dade3f222 | [
"BSD-3-Clause"
] | 5 | 2016-11-12T00:02:34.000Z | 2017-06-22T22:06:14.000Z | #include "iterlib/FilterIterator.h"
namespace iterlib {
namespace detail {
template class FilterIterator<Item>;
}
}
| 11.9 | 36 | 0.764706 | adsharma |
35ffc9324e782737a9bb66b6ab459d3809c006d4 | 720 | cpp | C++ | src/ext/openexr/Contrib/Photoshop/src/framework/PSAutoBuffer.cpp | tomoya5296/pbrt-cv | f5078db1e42bb8305aa386bda1ba26c528dec489 | [
"BSD-2-Clause"
] | 21 | 2016-12-14T09:46:27.000Z | 2021-12-28T10:05:04.000Z | src/ext/openexr/Contrib/Photoshop/src/framework/PSAutoBuffer.cpp | tomoya5296/pbrt-cv | f5078db1e42bb8305aa386bda1ba26c528dec489 | [
"BSD-2-Clause"
] | 2 | 2015-10-09T19:13:25.000Z | 2018-12-25T17:16:54.000Z | src/ext/openexr/Contrib/Photoshop/src/framework/PSAutoBuffer.cpp | tomoya5296/pbrt-cv | f5078db1e42bb8305aa386bda1ba26c528dec489 | [
"BSD-2-Clause"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | // ===========================================================================
// PSAutoBuffer.cp Part of OpenEXR
// ===========================================================================
//
#if MSWindows
#pragma warning (disable: 161)
#endif
#include "PSAutoBuffer.h"
#include <new>
PSAutoBuffer::PSAutoBuffer
(
int32 inSize,
BufferProcs* inProcs
)
{
OSErr err;
mBufferID = 0;
mProcs = inProcs;
err = mProcs->allocateProc (inSize, &mBufferID);
if (err != noErr)
{
throw std::bad_alloc();
}
}
PSAutoBuffer::~PSAutoBuffer ()
{
if (mBufferID != 0)
{
mProcs->freeProc (mBufferID);
mBufferID = 0;
}
}
Ptr PSAutoBuffer::Lock ()
{
return mProcs->lockProc (mBufferID, false);
}
| 15.319149 | 78 | 0.506944 | tomoya5296 |
c401731f8ee6fcef335edaccdf03a53c2e0d7768 | 4,166 | hh | C++ | lsl/runtime/types.hh | vinzenz/lsl-emu | 3f799248ee57d0d11d6f12e6ff0f48cf359ced1e | [
"Apache-2.0"
] | 1 | 2018-03-28T19:26:44.000Z | 2018-03-28T19:26:44.000Z | lsl/runtime/types.hh | vinzenz/lsl-emu | 3f799248ee57d0d11d6f12e6ff0f48cf359ced1e | [
"Apache-2.0"
] | null | null | null | lsl/runtime/types.hh | vinzenz/lsl-emu | 3f799248ee57d0d11d6f12e6ff0f48cf359ced1e | [
"Apache-2.0"
] | null | null | null | // Copyright 2014 Vinzenz Feenstra
//
// 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.
#ifndef GUARD_LSL_RUNTIME_TYPES_HH_INCLUDED
#define GUARD_LSL_RUNTIME_TYPES_HH_INCLUDED
#include <lsl/runtime/vector.hh>
#include <lsl/runtime/quaternion.hh>
#include <lsl/types.hh>
#include <boost/variant.hpp>
#include <boost/ref.hpp>
#include <sstream>
namespace lsl {
namespace runtime {
typedef std::string String;
typedef int32_t Integer;
typedef double Float;
typedef lsl::Key Key;
typedef Quaternion Rotation;
inline String to_string(Integer val) {
std::ostringstream ostr;
ostr << val;
return ostr.str();
}
inline String to_string(Float val) {
std::ostringstream ostr;
ostr << std::setiosflags(std::ios::fixed) << std::setprecision(6) << val;
return ostr.str();
}
inline String to_string(Vector val) {
std::ostringstream ostr;
ostr << '<' << std::setiosflags(std::ios::fixed) << std::setprecision(5)
<< val.x
<< ", "
<< val.y
<< ", "
<< val.z
<< '>';
return ostr.str();
}
inline String to_string(Quaternion val) {
std::ostringstream ostr;
ostr << '<' << std::setiosflags(std::ios::fixed) << std::setprecision(5)
<< val.x
<< ", "
<< val.y
<< ", "
<< val.z
<< ", "
<< val.s
<< '>';
return ostr.str();
}
enum class ValueType : lsl::runtime::Integer {
Void = 0,
Integer = 1,
Float = 2,
String = 3,
Key = 4,
Vector = 5,
Rotation = 6,
List = 7
};
struct ScriptValue {
typedef String string_type;
typedef Key key_type;
typedef Integer integer_type;
typedef Float float_type;
typedef Vector vector_type;
typedef Quaternion rotation_type;
typedef boost::make_recursive_variant<
string_type,
key_type,
rotation_type,
vector_type,
integer_type,
float_type,
boost::reference_wrapper<ScriptValue>,// References to Variables global or local
boost::reference_wrapper<float_type>, // Members of Vector or Quaternion
std::vector<ScriptValue>
>::type value_type;
typedef std::vector<ScriptValue> list_type;
ScriptValue() : type(), value(), reference(false){}
ScriptValue(ValueType t, value_type const & v, bool r) : type(t), value(v), reference(r){}
ValueType type;
value_type value;
bool reference;
key_type as_key() const;
string_type as_string() const;
integer_type as_integer() const;
float_type as_float() const;
vector_type as_vector() const;
rotation_type as_rotation() const;
list_type as_list() const;
integer_type as_bool() const;
rotation_type & get_rotation();
vector_type & get_vector();
string_type & get_string();
key_type & get_key();
integer_type & get_integer();
float_type & get_float();
list_type & get_list();
boost::reference_wrapper<float_type> & get_member_ref();
boost::reference_wrapper<ScriptValue> & get_ref();
};
bool operator==(ScriptValue const & left, ScriptValue const & right);
bool operator<(ScriptValue const & left, ScriptValue const & right);
inline bool operator>(ScriptValue const & left, ScriptValue const & right) {
return right < left;
}
typedef ScriptValue::list_type List;
}}
namespace std {
template<>
struct hash<lsl::Key> : std::hash<lsl::String> {};
}
#endif //GUARD_LSL_RUNTIME_TYPES_HH_INCLUDED
| 27.407895 | 94 | 0.62722 | vinzenz |
c401bc08ec86b95b8a9224ce279252c9a2ee9c31 | 2,553 | cc | C++ | tests/testfoundation/ringbuffertest.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 377 | 2018-10-24T08:34:21.000Z | 2022-03-31T23:37:49.000Z | tests/testfoundation/ringbuffertest.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 11 | 2020-01-22T13:34:46.000Z | 2022-03-07T10:07:34.000Z | tests/testfoundation/ringbuffertest.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 23 | 2019-07-13T16:28:32.000Z | 2022-03-20T09:00:59.000Z | //------------------------------------------------------------------------------
// ringbuffertest.cc
// (C) 2008 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "ringbuffertest.h"
#include "util/ringbuffer.h"
namespace Test
{
__ImplementClass(Test::RingBufferTest, 'RBTT', Test::TestCase);
using namespace Util;
//------------------------------------------------------------------------------
/**
*/
void
RingBufferTest::Run()
{
RingBuffer<int> rb(5);
VERIFY(rb.Size() == 0);
VERIFY(rb.Capacity() == 5);
VERIFY(rb.IsEmpty());
rb.Add(1);
VERIFY(rb.Size() == 1);
VERIFY(!rb.IsEmpty());
VERIFY(rb.Front() == 1);
VERIFY(rb.Back() == 1);
VERIFY(1 == rb[0]);
rb.Add(2);
VERIFY(rb.Size() == 2);
VERIFY(rb.Front() == 1);
VERIFY(rb.Back() == 2);
VERIFY(1 == rb[0]);
VERIFY(2 == rb[1]);
rb.Add(3);
VERIFY(rb.Size() == 3);
VERIFY(rb.Front() == 1);
VERIFY(rb.Back() == 3);
VERIFY(1 == rb[0]);
VERIFY(2 == rb[1]);
VERIFY(3 == rb[2]);
rb.Add(4);
VERIFY(rb.Size() == 4);
VERIFY(rb.Front() == 1);
VERIFY(rb.Back() == 4);
VERIFY(1 == rb[0]);
VERIFY(2 == rb[1]);
VERIFY(3 == rb[2]);
VERIFY(4 == rb[3]);
rb.Add(5);
VERIFY(rb.Size() == 5);
VERIFY(rb.Front() == 1);
VERIFY(rb.Back() == 5);
VERIFY(1 == rb[0]);
VERIFY(2 == rb[1]);
VERIFY(3 == rb[2]);
VERIFY(4 == rb[3]);
VERIFY(5 == rb[4]);
rb.Add(6);
VERIFY(rb.Size() == 5);
VERIFY(rb.Front() == 2);
VERIFY(rb.Back() == 6);
VERIFY(2 == rb[0]);
VERIFY(3 == rb[1]);
VERIFY(4 == rb[2]);
VERIFY(5 == rb[3]);
VERIFY(6 == rb[4]);
rb.Add(7);
VERIFY(rb.Size() == 5);
VERIFY(rb.Front() == 3);
VERIFY(rb.Back() == 7);
VERIFY(3 == rb[0]);
VERIFY(4 == rb[1]);
VERIFY(5 == rb[2]);
VERIFY(6 == rb[3]);
VERIFY(7 == rb[4]);
// test copy constructor and assignment operator
RingBuffer<int> rb1 = rb;
VERIFY(rb1.Size() == 5);
VERIFY(rb1.Front() == 3);
VERIFY(rb1.Back() == 7);
VERIFY(3 == rb1[0]);
VERIFY(4 == rb1[1]);
VERIFY(5 == rb1[2]);
VERIFY(6 == rb1[3]);
VERIFY(7 == rb1[4]);
rb1.Reset();
VERIFY(rb1.Size() == 0);
rb1 = rb;
VERIFY(rb1.Size() == 5);
VERIFY(rb1.Front() == 3);
VERIFY(rb1.Back() == 7);
VERIFY(3 == rb1[0]);
VERIFY(4 == rb1[1]);
VERIFY(5 == rb1[2]);
VERIFY(6 == rb1[3]);
VERIFY(7 == rb1[4]);
}
} // namespace Test | 23.209091 | 80 | 0.444967 | sirAgg |
c402b271c528f3f30ac1d07b1a9ade6e3719f17d | 1,291 | cpp | C++ | ml_belowzerosrc/src/sys/_windows/msys_debugOS.cpp | mudlord/demos | 359bada56a27ddbd4fcb846c0ff34bc474cb7f05 | [
"Unlicense"
] | 20 | 2017-12-12T16:37:25.000Z | 2022-02-19T10:35:46.000Z | ml_noisecorpsesrc/src/sys/_windows/msys_debugOS.cpp | mudlord/demos | 359bada56a27ddbd4fcb846c0ff34bc474cb7f05 | [
"Unlicense"
] | null | null | null | ml_noisecorpsesrc/src/sys/_windows/msys_debugOS.cpp | mudlord/demos | 359bada56a27ddbd4fcb846c0ff34bc474cb7f05 | [
"Unlicense"
] | 7 | 2017-12-29T23:19:18.000Z | 2021-08-17T09:53:15.000Z | //--------------------------------------------------------------------------//
// iq . 2003/2008 . code for 64 kb intros by RGBA //
//--------------------------------------------------------------------------//
#ifdef DEBUG
#include <windows.h>
#include <stdio.h>
#include <stdarg.h>
#include "../msys_debug.h"
static FILE *fp;
int msys_debugInit( void )
{
fp = fopen( "debug.txt", "wt" );
if( !fp )
return( 0 );
fprintf( fp, "debug file\n" );
fprintf( fp, "-------------------------\n" );
fflush( fp );
return( 1 );
}
void msys_debugEnd( void )
{
fprintf( fp, "-------------------------\n" );
fflush( fp );
fclose( fp );
}
void msys_debugPrintf( char *format, ... )
{
va_list arglist;
va_start( arglist, format );
vfprintf( fp, format, arglist );
fflush( fp );
va_end( arglist );
}
void msys_debugCheckfor( bool expression, char *format, ... )
{
char str[1024];
if( !expression )
{
va_list arglist;
va_start( arglist, format );
vsprintf( str, format, arglist );
va_end( arglist );
msys_debugHaltProgram( str );
}
}
void msys_debugHaltProgram( char *str )
{
MessageBox( 0, str, "error", MB_OK );
DebugBreak();
}
#endif
| 19.861538 | 78 | 0.464756 | mudlord |
c404f608c89c74c706284a3c2458289f6764d91d | 1,021 | hpp | C++ | files/src/app-helpers/cpp/ezored/helpers/MapHelper.hpp | Leo-Neves/ezored | 924a6c10bdedd9d3115b31cb56c81c671f524c49 | [
"MIT"
] | null | null | null | files/src/app-helpers/cpp/ezored/helpers/MapHelper.hpp | Leo-Neves/ezored | 924a6c10bdedd9d3115b31cb56c81c671f524c49 | [
"MIT"
] | null | null | null | files/src/app-helpers/cpp/ezored/helpers/MapHelper.hpp | Leo-Neves/ezored | 924a6c10bdedd9d3115b31cb56c81c671f524c49 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "rapidjson/document.h"
using std::string;
using std::unordered_map;
using std::vector;
using rapidjson::Document;
namespace ezored
{
namespace helpers
{
class MapHelper
{
public:
virtual ~MapHelper() {}
static Document toJson(const string &data);
static string toString(const Document &json);
static string toJsonString(const unordered_map<string, string> &data);
static unordered_map<string, string> fromJsonString(const string &data);
static string getValue(const string &key, const unordered_map<string, string> &data, const string &defaultValue);
static string getString(const string key, const Document &data);
static int getInt(const string &key, const Document &data);
static double getDouble(const string &key, const Document &data);
static bool getBool(const string &key, const Document &data);
};
} // namespace helpers
} // namespace ezored
| 26.179487 | 117 | 0.742409 | Leo-Neves |
c40c540782938c034f29377cfd660fbb877bbc01 | 394 | cpp | C++ | Solutions/CF1543D1.cpp | SamuNatsu/icpc-solution | 17facc464a042026ff117ab33b439e87615de74b | [
"MIT"
] | null | null | null | Solutions/CF1543D1.cpp | SamuNatsu/icpc-solution | 17facc464a042026ff117ab33b439e87615de74b | [
"MIT"
] | null | null | null | Solutions/CF1543D1.cpp | SamuNatsu/icpc-solution | 17facc464a042026ff117ab33b439e87615de74b | [
"MIT"
] | null | null | null | #include <cstdio>
int t, n, k, r;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &k);
int q = 0, lst = 0;
for (int i = 0; i < n; ++i) {
q = lst ^ i;
lst ^= q;
printf("%d\n", q);
fflush(stdout);
scanf("%d", &r);
if (r)
break;
}
}
return 0;
}
| 17.909091 | 37 | 0.307107 | SamuNatsu |
c40d812bb32a7fde40a87b21fa899cad836e5948 | 348 | cc | C++ | leetcode/leetcode_218.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_218.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_218.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
vector<pair<int, int>> result;
int buildings idx = 0;
while (true) {
}
return result;
}
int main( int argc, char *argv[] ) {
return 0;
}
| 15.818182 | 67 | 0.637931 | math715 |
c4165c13cd4a8bee3f87127c8beddb720f43bd98 | 12,157 | hpp | C++ | src/framework/shared/inc/private/common/fxirp.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/shared/inc/private/common/fxirp.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 9 | 2015-03-19T08:40:01.000Z | 2019-03-24T22:54:51.000Z | src/framework/shared/inc/private/common/fxirp.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft Corporation
Module Name:
FxIrp.hpp
Abstract:
This module implements a class for handling irps.
Author:
Environment:
Both kernel and user mode
Revision History:
// A function for when not assigning
MdIrp
GetIrp(
VOID
);
VOID
CompleteRequest(
__in_opt CCHAR PriorityBoost=IO_NO_INCREMENT
);
NTSTATUS
CallDriver(
__in MdDeviceObject DeviceObject
);
NTSTATUS
PoCallDriver(
__in MdDeviceObject DeviceObject
);
VOID
StartNextPowerIrp(
);
MdCompletionRoutine
GetNextCompletionRoutine(
VOID
);
VOID
SetCompletionRoutine(
__in MdCompletionRoutine CompletionRoutine,
__in PVOID Context,
__in BOOLEAN InvokeOnSuccess = TRUE,
__in BOOLEAN InvokeOnError = TRUE,
__in BOOLEAN InvokeOnCancel = TRUE
);
VOID
SetCompletionRoutineEx(
__in MdDeviceObject DeviceObject,
__in MdCompletionRoutine CompletionRoutine,
__in PVOID Context,
__in BOOLEAN InvokeOnSuccess = TRUE,
__in BOOLEAN InvokeOnError = TRUE,
__in BOOLEAN InvokeOnCancel = TRUE
);
MdCancelRoutine
SetCancelRoutine(
__in_opt MdCancelRoutine CancelRoutine
);
//
// SendIrpSynchronously achieves synchronous behavior by waiting on an
// event after submitting the IRP. The event creation can fail in UM, but
// not in KM. Hence, in UM the return code could either indicate event
// creation failure or it could indicate the status set on the IRP by the
// lower driver. In KM, the return code only indicates the status set on
// the IRP by the lower lower, because event creation cannot fail.
//
CHECK_RETURN_IF_USER_MODE
NTSTATUS
SendIrpSynchronously(
__in MdDeviceObject DeviceObject
);
VOID
CopyCurrentIrpStackLocationToNext(
VOID
);
VOID
CopyToNextIrpStackLocation(
__in PIO_STACK_LOCATION Stack
);
VOID
SetNextIrpStackLocation(
VOID
);
UCHAR
GetMajorFunction(
VOID
);
UCHAR
GetMinorFunction(
VOID
);
UCHAR
GetCurrentStackFlags(
VOID
);
MdFileObject
GetCurrentStackFileObject(
VOID
);
KPROCESSOR_MODE
GetRequestorMode(
VOID
);
VOID
SetContext(
__in ULONG Index,
__in PVOID Value
);
VOID
SetSystemBuffer(
__in PVOID Value
);
VOID
SetUserBuffer(
__in PVOID Value
);
VOID
SetMdlAddress(
__in PMDL Value
);
VOID
SetFlags(
__in ULONG Flags
);
PVOID
GetContext(
__in ULONG Index
);
ULONG
GetFlags(
VOID
);
PIO_STACK_LOCATION
GetCurrentIrpStackLocation(
VOID
);
PIO_STACK_LOCATION
GetNextIrpStackLocation(
VOID
);
static
PIO_STACK_LOCATION
_GetAndClearNextStackLocation(
__in MdIrp Irp
);
VOID
SkipCurrentIrpStackLocation(
VOID
);
VOID
MarkIrpPending(
);
BOOLEAN
PendingReturned(
);
VOID
PropagatePendingReturned(
VOID
);
VOID
SetStatus(
__in NTSTATUS Status
);
NTSTATUS
GetStatus(
);
BOOLEAN
Cancel(
VOID
);
VOID
SetCancel(
__in BOOLEAN Cancel
);
BOOLEAN
IsCanceled(
);
KIRQL
GetCancelIrql(
);
VOID
SetInformation(
__in ULONG_PTR Information
);
ULONG_PTR
GetInformation(
);
CCHAR
GetCurrentIrpStackLocationIndex(
);
CCHAR
GetStackCount(
);
PLIST_ENTRY
ListEntry(
);
PVOID
GetSystemBuffer(
);
PVOID
GetOutputBuffer(
);
PMDL
GetMdl(
);
PMDL*
GetMdlAddressPointer(
);
PVOID
GetUserBuffer(
);
VOID
Reuse(
__in NTSTATUS Status = STATUS_SUCCESS
);
//
// Methods for IO_STACK_LOCATION members
//
VOID
SetMajorFunction(
__in UCHAR MajorFunction
);
VOID
SetMinorFunction(
__in UCHAR MinorFunction
);
//
// Get Methods for IO_STACK_LOCATION.Parameters.Power
//
SYSTEM_POWER_STATE_CONTEXT
GetParameterPowerSystemPowerStateContext(
);
POWER_STATE_TYPE
GetParameterPowerType(
);
POWER_STATE
GetParameterPowerState(
);
DEVICE_POWER_STATE
GetParameterPowerStateDeviceState(
);
SYSTEM_POWER_STATE
GetParameterPowerStateSystemState(
);
POWER_ACTION
GetParameterPowerShutdownType(
);
MdFileObject
GetFileObject(
VOID
);
//
// Get/Set Method for IO_STACK_LOCATION.Parameters.QueryDeviceRelations
//
DEVICE_RELATION_TYPE
GetParameterQDRType(
);
VOID
SetParameterQDRType(
__in DEVICE_RELATION_TYPE DeviceRelation
);
//
// Get/Set Methods for IO_STACK_LOCATION.Parameters.DeviceCapabilities
//
PDEVICE_CAPABILITIES
GetParameterDeviceCapabilities(
);
VOID
SetCurrentDeviceObject(
__in MdDeviceObject DeviceObject
);
MdDeviceObject
GetDeviceObject(
VOID
);
VOID
SetParameterDeviceCapabilities(
__in PDEVICE_CAPABILITIES DeviceCapabilities
);
//
// Get/Set Methods for IO_STACK_LOCATION.Parameters.Write.ByteOffset.QuadPart
//
LONGLONG
GetParameterWriteByteOffsetQuadPart(
);
VOID
SetNextParameterWriteByteOffsetQuadPart(
__in LONGLONG DeviceOffset
);
//
// Get/Set Methods for IO_STACK_LOCATION.Parameters.Write.Length
//
ULONG
GetCurrentParameterWriteLength(
);
VOID
SetNextParameterWriteLength(
__in ULONG IoLength
);
PVOID*
GetNextStackParameterOthersArgument1Pointer(
);
VOID
SetNextStackParameterOthersArgument1(
__in PVOID Argument1
);
PVOID*
GetNextStackParameterOthersArgument2Pointer(
);
PVOID*
GetNextStackParameterOthersArgument4Pointer(
);
//
// Get/Set Methods for IO_STACK_LOCATION.Parameters.StartDevice
//
PCM_RESOURCE_LIST
GetParameterAllocatedResources(
);
VOID
SetParameterAllocatedResources(
__in PCM_RESOURCE_LIST AllocatedResources
);
PCM_RESOURCE_LIST
GetParameterAllocatedResourcesTranslated(
);
VOID
SetParameterAllocatedResourcesTranslated(
__in PCM_RESOURCE_LIST AllocatedResourcesTranslated
);
//
// Get Method for IO_STACK_LOCATION.Parameters.QueryDeviceText
//
LCID
GetParameterQueryDeviceTextLocaleId(
);
DEVICE_TEXT_TYPE
GetParameterQueryDeviceTextType(
);
//
// Get Method for IO_STACK_LOCATION.Parameters.SetLock
//
BOOLEAN
GetParameterSetLockLock(
);
//
// Get Method for IO_STACK_LOCATION.Parameters.QueryId
//
BUS_QUERY_ID_TYPE
GetParameterQueryIdType(
);
//
// Get/Set Methods for IO_STACK_LOCATION.Parameters.QueryInterface
//
PINTERFACE
GetParameterQueryInterfaceInterface(
);
const GUID*
GetParameterQueryInterfaceType(
);
USHORT
GetParameterQueryInterfaceVersion(
);
USHORT
GetParameterQueryInterfaceSize(
);
PVOID
GetParameterQueryInterfaceInterfaceSpecificData(
);
VOID
SetParameterQueryInterfaceInterface(
__in PINTERFACE Interface
);
VOID
SetParameterQueryInterfaceType(
__in const GUID* InterfaceType
);
VOID
SetParameterQueryInterfaceVersion(
__in USHORT Version
);
VOID
SetParameterQueryInterfaceSize(
__in USHORT Size
);
VOID
SetParameterQueryInterfaceInterfaceSpecificData(
__in PVOID InterfaceSpecificData
);
//
// Get Method for IO_STACK_LOCATION.Parameters.UsageNotification
//
DEVICE_USAGE_NOTIFICATION_TYPE
GetParameterUsageNotificationType(
);
BOOLEAN
GetParameterUsageNotificationInPath(
);
VOID
SetParameterUsageNotificationInPath(
__in BOOLEAN InPath
);
BOOLEAN
GetNextStackParameterUsageNotificationInPath(
);
ULONG
GetParameterIoctlCode(
VOID
);
ULONG
GetParameterIoctlCodeBufferMethod(
VOID
);
ULONG
GetParameterIoctlInputBufferLength(
VOID
);
ULONG
GetParameterIoctlOutputBufferLength(
VOID
);
PVOID
GetParameterIoctlType3InputBuffer(
VOID
);
//
// Set Methods for IO_STACK_LOCATION.Parameters.DeviceControl members
//
VOID
SetParameterIoctlCode(
__in ULONG DeviceIoControlCode
);
VOID
SetParameterIoctlInputBufferLength(
__in ULONG InputBufferLength
);
VOID
SetParameterIoctlOutputBufferLength(
__in ULONG OutputBufferLength
);
VOID
SetParameterIoctlType3InputBuffer(
__in PVOID Type3InputBuffer
);
ULONG
GetParameterReadLength(
VOID
);
ULONG
GetParameterWriteLength(
VOID
);
VOID
SetNextStackFlags(
__in UCHAR Flags
);
VOID
SetNextStackFileObject(
_In_ MdFileObject FileObject
);
PVOID
GetCurrentParametersPointer(
VOID
);
//
// Methods for IO_STACK_LOCATION
//
VOID
ClearNextStack(
VOID
);
VOID
ClearNextStackLocation(
VOID
);
VOID
InitNextStackUsingStack(
__in FxIrp* Irp
);
ULONG
GetCurrentFlags(
VOID
);
VOID
FreeIrp(
VOID
);
MdEThread
GetThread(
VOID
);
BOOLEAN
Is32bitProcess(
VOID
);
private:
static
NTSTATUS
_IrpSynchronousCompletion(
__in MdDeviceObject DeviceObject,
__in MdIrp OriginalIrp,
__in PVOID Context
);
public:
_Must_inspect_result_
static
MdIrp
AllocateIrp(
_In_ CCHAR StackSize,
_In_opt_ FxDevice* Device = NULL
);
static
MdIrp
GetIrpFromListEntry(
__in PLIST_ENTRY Ple
);
_Must_inspect_result_
static
NTSTATUS
RequestPowerIrp(
__in MdDeviceObject DeviceObject,
__in UCHAR MinorFunction,
__in POWER_STATE PowerState,
__in MdRequestPowerComplete CompletionFunction,
__in PVOID Context
);
PIO_STATUS_BLOCK
GetStatusBlock(
VOID
);
PVOID
GetDriverContext(
);
ULONG
GetDriverContextSize(
);
VOID
CopyParameters(
_Out_ PWDF_REQUEST_PARAMETERS Parameters
);
VOID
CopyStatus(
_Out_ PIO_STATUS_BLOCK StatusBlock
);
BOOLEAN
HasStack(
_In_ UCHAR StackCount
);
BOOLEAN
IsCurrentIrpStackLocationValid(
VOID
);
#if (FX_CORE_MODE == FX_CORE_USER_MODE)
IWudfIoIrp*
GetIoIrp(
VOID
);
IWudfIoIrp2*
GetIoIrp2(
VOID
);
IWudfPnpIrp*
GetPnpIrp(
VOID
);
#endif
};
//
// FxAutoIrp adds value to FxIrp by automatically freeing the associated MdIrp
// when it goes out of scope
//
struct FxAutoIrp : public FxIrp {
FxAutoIrp(
__in_opt MdIrp Irp = NULL
) :
FxIrp(Irp)
{
}
~FxAutoIrp();
};
#endif // _FXIRP_H_
| 14.302353 | 81 | 0.591182 | IT-Enthusiast-Nepal |
c41a5ca1692f2e46445f7554bebb80107923a3a9 | 2,571 | cpp | C++ | AliceEngine/ALC/Rendering/Camera.cpp | ARAMODODRAGON/Project-Alice | 49d3189ba065911c8495cfb04761a2050d3a0702 | [
"MIT"
] | null | null | null | AliceEngine/ALC/Rendering/Camera.cpp | ARAMODODRAGON/Project-Alice | 49d3189ba065911c8495cfb04761a2050d3a0702 | [
"MIT"
] | null | null | null | AliceEngine/ALC/Rendering/Camera.cpp | ARAMODODRAGON/Project-Alice | 49d3189ba065911c8495cfb04761a2050d3a0702 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2021 Domara Shlimon
*
* 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 "Camera.hpp"
#include <glm\gtc\matrix_transform.hpp>
#include "../SceneManager.hpp"
namespace ALC {
Camera::Camera() : m_position(0.0f), m_size(0.0f) {
m_size = SceneManager::GetWindow()->GetScreenSize();
}
Camera::~Camera() { }
vec2 Camera::GetPosition() {
return m_position;
}
void Camera::SetPosition(const vec2& position_) {
m_position = position_;
}
vec2 Camera::GetCameraSize() const {
return m_size;
}
void Camera::SetCameraSize(const vec2& size_) {
m_size = size_;
}
mat4 Camera::GetTransform() const {
mat4 transform(1.0f);
// create the view
transform = glm::translate(transform, -vec3(m_position, 0.0f));
// create the ortho
vec2 halfsize = m_size * 0.5f;
transform = transform * glm::ortho(-halfsize.x, halfsize.x, -halfsize.y, halfsize.y);
// return the transform
return transform;
}
mat4 Camera::GetScreenToWorld() const {
return GetScreenToWorld(SceneManager::GetWindow()->GetScreenSize());
}
mat4 Camera::GetScreenToWorld(const vec2& screensize) const {
mat4 screen = glm::ortho(0.0f, screensize.x, 0.0f, screensize.y);
return glm::inverse(GetTransform()) * screen;
}
mat4 Camera::GetWorldToScreen() const {
return GetWorldToScreen(SceneManager::GetWindow()->GetScreenSize());
}
mat4 Camera::GetWorldToScreen(const vec2& screensize) const {
mat4 screen = glm::ortho(0.0f, screensize.x, 0.0f, screensize.y);
return glm::inverse(screen) * GetTransform();
}
}
| 30.607143 | 87 | 0.731622 | ARAMODODRAGON |
c41b278b7639f741d3c23c2ca68c682efbed0483 | 248 | cpp | C++ | work/desenet-sensor/src/common/platform/nucleo-stm32l476rg/board/display/eplib/hal/gpio.cpp | MacherelR/DeSemProject_20212022 | 7314e5787a3ff2ca5bf95c6de7fbbee9598b98ea | [
"MIT"
] | null | null | null | work/desenet-sensor/src/common/platform/nucleo-stm32l476rg/board/display/eplib/hal/gpio.cpp | MacherelR/DeSemProject_20212022 | 7314e5787a3ff2ca5bf95c6de7fbbee9598b98ea | [
"MIT"
] | null | null | null | work/desenet-sensor/src/common/platform/nucleo-stm32l476rg/board/display/eplib/hal/gpio.cpp | MacherelR/DeSemProject_20212022 | 7314e5787a3ff2ca5bf95c6de7fbbee9598b98ea | [
"MIT"
] | null | null | null | #include "gpio.h"
namespace ep {
/**
* @brief Construct a new GPIO object
*
* @param p1 Pin Number
* @param port Port Name
*/
Gpio::Gpio(GPIO_TypeDef * port, uint32_t pin) :
port(port),
pin(pin)
{
}
} // namespace ep
| 13.052632 | 48 | 0.580645 | MacherelR |
c41ba80f75e10deb60a3e4f03c58eea1f2a0a099 | 829 | cpp | C++ | CSES/1640.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2020-10-16T18:14:30.000Z | 2020-10-16T18:14:30.000Z | CSES/1640.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | null | null | null | CSES/1640.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2021-01-06T04:45:38.000Z | 2021-01-06T04:45:38.000Z | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD 1000000007
#define all(v) v.begin(),v.end()
#define PB push_back
#define F first
#define S second
int solve(){
ll n,x; cin>>n>>x;
vector< pair< ll , ll > > v(n);
for(ll i=0;i<n;i++){
cin>>v[i].F;
v[i].S = i+1;
}
sort(all(v));
ll i=0,j=n-1;
while(i<j){
if(v[i].F+v[j].F==x){
ll a = min(v[i].S,v[j].S);
ll b = max(v[i].S,v[j].S);
cout<<a<<" "<<b<<endl;
return 0;
}else if(v[i].F+v[j].F>x){
j--;
}else{
i++;
}
}
cout<<"IMPOSSIBLE"<<endl;
return 0;
}
int main(){
ll t=1;
// cin>>t;
while(t--)
solve();
return 0;
} | 14.54386 | 38 | 0.405308 | hardik0899 |
c421c8527b0bdf126b1a2b03027c289b903f9398 | 13,627 | cxx | C++ | test/font_test/font_test.cxx | henne90gen/cgv | 31995e9f09d093f9997980093452a5424d0c1319 | [
"BSD-3-Clause"
] | null | null | null | test/font_test/font_test.cxx | henne90gen/cgv | 31995e9f09d093f9997980093452a5424d0c1319 | [
"BSD-3-Clause"
] | null | null | null | test/font_test/font_test.cxx | henne90gen/cgv | 31995e9f09d093f9997980093452a5424d0c1319 | [
"BSD-3-Clause"
] | null | null | null | #include <cgv/base/node.h>
#include <cgv/base/register.h>
#include <cgv/gui/event_handler.h>
#include <cgv/gui/provider.h>
#include <cgv/gui/key_event.h>
#include <cgv/gui/mouse_event.h>
#include <cgv/utils/file.h>
#include <cgv/utils/dir.h>
#include <cgv/render/drawable.h>
#include <cgv/render/attribute_array_binding.h>
#include <cgv_gl/gl/gl.h>
#include <cgv_gl/rectangle_renderer.h>
#include <cgv/math/ftransform.h>
#include <cgv/media/image/image_writer.h>
#include <cgv/media/color_scale.h>
#include <libs/tt_gl_font/tt_gl_font.h>
// include self reflection helpers of used types (here vec3 & rgb)
#include <libs/cgv_reflect_types/math/fvec.h>
#include <libs/cgv_reflect_types/media/color.h>
class font_test :
public cgv::base::node,
public cgv::render::drawable,
public cgv::base::argument_handler,
public cgv::gui::event_handler,
public cgv::gui::provider
{
protected:
/// helper member to support loading individual truetype files
std::string font_file_name;
/// helper member to support scanning of specific font directories
std::string font_directory;
/// currently chosen font
int font_idx;
/// pointer to current font
cgv::tt_gl_font_ptr font_ptr;
/// font face selector
cgv::media::font::FontFaceAttributes ffa;
/// pointer to current font face
cgv::tt_gl_font_face_ptr font_face_ptr;
/// rasterization size of font
float font_size;
/// whether to use blending during font rendering
bool use_blending;
/// render style for drawing font onto cube
cgv::render::rectangle_render_style rrs;
/// to be drawn text
std::string text;
/// whether to use per character colors when drawing text
bool use_colors;
/// screen location in pixel coordinates
ivec2 pixel_position;
/// subpixel offset that allows to debug font rendering results if texels and pixels are not aligned
vec2 subpixel_offset;
/// whether to show lines
bool show_lines;
/// y-pixel coordinate to start drawing lines
int fst_line;
/// y-pixel offset between successive lines
unsigned line_delta;
/// whether to show cube
bool show_cube;
void render_textured_quads(cgv::render::context& ctx, cgv::render::rectangle_render_style& _rrs,
const std::vector<cgv::render::textured_rectangle>& Q,
const std::vector<rgba>* colors_ptr = 0,
const std::vector<vec3>* translations_ptr = 0,
const std::vector<quat>* rotations_ptr = 0)
{
auto& rr = cgv::render::ref_rectangle_renderer(ctx);
rr.set_render_style(_rrs);
rr.set_textured_rectangle_array(ctx, Q);
font_face_ptr->ref_texture(ctx).enable(ctx);
if (colors_ptr)
rr.set_color_array(ctx, *colors_ptr);
if (translations_ptr)
rr.set_translation_array(ctx, *translations_ptr);
if (rotations_ptr)
rr.set_rotation_array(ctx, *rotations_ptr);
GLboolean blend;
GLenum blend_src, blend_dst, depth;
if (use_blending) {
blend = glIsEnabled(GL_BLEND); glEnable(GL_BLEND);
glGetIntegerv(GL_BLEND_DST, reinterpret_cast<GLint*>(&blend_dst));
glGetIntegerv(GL_BLEND_SRC, reinterpret_cast<GLint*>(&blend_src));
glGetIntegerv(GL_DEPTH_FUNC, reinterpret_cast<GLint*>(&depth));
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthFunc(GL_LEQUAL);
}
rr.render(ctx, 0, Q.size());
if (use_blending) {
if (!blend)
glDisable(GL_BLEND);
glDepthFunc(depth);
glBlendFunc(blend_src, blend_dst);
}
font_face_ptr->ref_texture(ctx).disable(ctx);
}
public:
font_test() : node("font test")
{
font_idx = 0;
ffa = cgv::media::font::FFA_REGULAR;
font_size = 32.0f;
use_blending = true;
on_set(&font_idx); // ensure that font and font face pointers are set
text = "This demo shows how to render text with the tt_gl_font library including <�������>!";
pixel_position = ivec2(100, 100);
use_colors = true;
subpixel_offset = vec2(0.0f);
show_lines = true;
fst_line = 100;
line_delta = 40;
show_cube = true;
rrs.surface_color = rgba(1, 0, 1, 1);
rrs.pixel_blend = 0.0f;
rrs.texture_mode = 1;
rrs.default_depth_offset = -0.0000001f;
rrs.border_color = rgba(0, 0, 0, 0);
rrs.map_color_to_material = cgv::render::CM_COLOR_AND_OPACITY;
rrs.illumination_mode = cgv::render::IM_OFF;
}
void on_set(void* member_ptr)
{
if (member_ptr == &font_file_name)
read_font(font_file_name);
if (member_ptr == &font_directory) {
cgv::scan_fonts(font_directory);
font_idx = 0;
on_set(&font_idx);
post_recreate_gui();
}
if (member_ptr == &ffa)
font_face_ptr = font_ptr->get_font_face(ffa).up_cast<cgv::tt_gl_font_face>();
if (member_ptr == &font_idx) {
font_ptr = cgv::find_font(cgv::get_font_names()[font_idx]);
font_ptr->set_font_size(font_size);
bool first = true;
std::string ffa_enum;
static const char* ffa_names[4] = { "regular","bold","italic","bolditalic" };
for (int _ffa = 0; _ffa < 4; ++_ffa) {
if (font_ptr->supports_font_face(_ffa)) {
if (first)
first = false;
else
ffa_enum += ',';
ffa_enum += ffa_names[_ffa];
}
}
if (find_control(ffa))
find_control(ffa)->set("enums", ffa_enum);
while (!font_ptr->supports_font_face(ffa))
ffa = cgv::media::font::FontFaceAttributes(((int)ffa + 1) % 4);
update_member(&ffa);
font_face_ptr = font_ptr->get_font_face(ffa).up_cast<cgv::tt_gl_font_face>();
}
if (font_ptr) {
if (member_ptr == &font_size) {
font_ptr->set_font_size(font_size);
}
}
update_member(member_ptr);
post_redraw();
}
bool read_font(const std::string& file_name)
{
cgv::tt_gl_font_face_ptr new_font_face_ptr = new cgv::tt_gl_font_face(file_name, font_size);
if (new_font_face_ptr->is_valid()) {
font_face_ptr = new_font_face_ptr;
return true;
}
return false;
}
void handle_args(std::vector<std::string>& args)
{
for (auto a : args) {
if (cgv::utils::file::exists(a)) {
font_file_name = a;
on_set(&font_file_name);
}
else if (cgv::utils::dir::exists(a)) {
font_directory = a;
on_set(&font_directory);
}
}
// clear args vector as all args have been processed
args.clear();
post_redraw();
}
void stream_help(std::ostream& os)
{
os << "font test: toggle use_<B>lending, use_<C>olor, show_<L>ines, select font|size with left,right|up,down" << std::endl;
}
void stream_stats(std::ostream& os)
{
os << "font name = " << (font_ptr ? font_ptr->get_name() : "<empty>") << std::endl;
}
bool handle(cgv::gui::event& e)
{
if (e.get_kind() == cgv::gui::EID_KEY) {
cgv::gui::key_event& ke = reinterpret_cast<cgv::gui::key_event&>(e);
if (ke.get_action() == cgv::gui::KA_RELEASE)
return false;
switch (ke.get_key()) {
case 'L':
show_lines = !show_lines;
on_set(&show_lines);
break;
case 'B':
use_blending = !use_blending;
on_set(&use_blending);
break;
case 'C':
use_colors = !use_colors;
on_set(&use_colors);
break;
case cgv::gui::KEY_Up:
if (ke.get_modifiers() == 0) {
font_size *= 1.2f;
on_set(&font_size);
return true;
}
break;
case cgv::gui::KEY_Down:
if (ke.get_modifiers() == 0) {
font_size /= 1.2f;
on_set(&font_size);
return true;
}
break;
case cgv::gui::KEY_Right:
if (ke.get_modifiers() == 0) {
if (font_idx + 1 < cgv::get_font_names().size()) {
++font_idx;
on_set(&font_idx);
}
return true;
}
break;
case cgv::gui::KEY_Left:
if (ke.get_modifiers() == 0) {
if (font_idx > 0) {
--font_idx;
on_set(&font_idx);
}
return true;
}
break;
}
}
return false;
}
std::string get_type_name() const { return "font_test"; }
bool self_reflect(cgv::reflect::reflection_handler& rh)
{
return
rh.reflect_member("font_idx", font_idx) &&
rh.reflect_member("text", text) &&
rh.reflect_member("use_blending", use_blending) &&
rh.reflect_member("rrs", rrs) &&
rh.reflect_member("font_file_name", font_file_name) &&
rh.reflect_member("font_directory", font_directory) &&
rh.reflect_member("font_size", font_size);
}
bool init(cgv::render::context& ctx)
{
cgv::render::ref_rectangle_renderer(ctx, 1);
return true;
}
void clear(cgv::render::context& ctx)
{
cgv::render::ref_rectangle_renderer(ctx, -1);
}
void draw(cgv::render::context& ctx)
{
if (show_cube) {
// render cube first
auto& surf_prog = ctx.ref_surface_shader_program();
surf_prog.enable(ctx);
ctx.tesselate_unit_cube(true);
surf_prog.disable(ctx);
// then render numbers onto sides
if (font_face_ptr) {
std::vector<cgv::render::textured_rectangle> Q;
vec2 p(0.0f);
box2 R;
std::vector<vec3> positions;
std::vector<quat> rotations;
std::vector<rgba> colors;
for (int i = 0; i < 6; ++i) {
std::string t(1, (char)('1' + i));
font_face_ptr->text_to_quads(p, t, Q);
Q.back().rectangle.translate(-Q.back().rectangle.get_center());
R.add_axis_aligned_box(Q.back().rectangle);
// select z axis and offset as well as other axes
int z_axis = i / 2;
int delta = 2 * (i % 2) - 1;
int x_axis = (z_axis + 1) % 3;
int y_axis = (z_axis + 2) % 3;
// define color
rgba col(0.5f, 0.5f, 0.5f, 1.0f);
col[z_axis] = 0.5f * (delta+1);
colors.push_back(col);
// define position in center of cube face
vec3 pos(0.0f);
pos[z_axis] = (float)delta;
positions.push_back(pos);
// define rotation of x and y axes onto cube face
mat3 rot;
rot.zeros();
rot(x_axis, 0) = 1.0f;
rot(y_axis, 1) = 1.0f;
rot(z_axis, 2) = 1.0f;
rotations.push_back(quat(rot));
}
// scale down quads to fit cube face
float scale = 1.6f / R.get_extent()[R.get_max_extent_coord_index()];
for (auto& q : Q)
q.rectangle.scale(scale);
render_textured_quads(ctx, rrs, Q, &colors, &positions, & rotations);
}
}
ctx.push_pixel_coords();
if (show_lines) {
std::vector<vec3> P;
std::vector<rgb> C;
int y = fst_line;
while (y < int(ctx.get_height())) {
P.push_back(vec3(0.0f, float(y), 0.0f));
C.push_back(rgb(1, 1, 1));
P.push_back(vec3(float(ctx.get_width()), float(y), 0.0f));
C.push_back(rgb(1, 1, 1));
y += line_delta;
}
auto& prog = ctx.ref_default_shader_program();
cgv::render::attribute_array_binding::set_global_attribute_array(ctx, prog.get_position_index(), P);
cgv::render::attribute_array_binding::set_global_attribute_array(ctx, prog.get_color_index(), C);
cgv::render::attribute_array_binding::enable_global_array(ctx, prog.get_position_index());
cgv::render::attribute_array_binding::enable_global_array(ctx, prog.get_color_index());
prog.enable(ctx);
glDrawArrays(GL_LINES, 0, (GLsizei)P.size());
prog.disable(ctx);
cgv::render::attribute_array_binding::disable_global_array(ctx, prog.get_position_index());
cgv::render::attribute_array_binding::disable_global_array(ctx, prog.get_color_index());
}
if (font_face_ptr) {
ctx.mul_modelview_matrix(cgv::math::translate4<float>(subpixel_offset[0], subpixel_offset[1], 0.0f));
// default approach to draw text in single color
if (!use_colors) {
vec2 p = pixel_position;
ctx.set_color(rrs.surface_color);
font_face_ptr->enable(&ctx, font_size);
font_face_ptr->draw_text(p[0], p[1], text);
}
else {
// otherwise convert to textured rectangles
std::vector<cgv::render::textured_rectangle> Q;
vec2 fpix_pos(pixel_position);
font_face_ptr->text_to_quads(fpix_pos, text, Q);
if (!Q.empty()) {
// define color array
std::vector<rgba> C(Q.size());
for (size_t i = 0; i < C.size(); ++i) {
float v = (float)i / (C.size() - 1);
C[i] = cgv::media::color_scale(v, cgv::media::CS_HUE);
}
// render with default rectangle render style
render_textured_quads(ctx, cgv::ref_rectangle_render_style(), Q, &C);
}
}
}
ctx.pop_pixel_coords();
}
void create_gui()
{
add_decorator("font test", "heading", "level=1");
add_gui("font_file_name", font_file_name, "file_name");
add_gui("font_directory", font_directory, "directory");
add_member_control(this, "font", (cgv::type::DummyEnum&)font_idx, "dropdown", cgv::get_font_enum_declaration());
add_member_control(this, "font face", ffa, "dropdown", "enums='regular,bold,italic,bold+italic'");
add_member_control(this, "font_size", font_size, "value_slider", "min=6;max=128;log=true;ticks=true");
add_decorator("text", "heading", "level=2");
add_member_control(this, "use_colors", use_colors, "toggle");
add_member_control(this, "text", text);
add_member_control(this, "default_text_color", rrs.surface_color);
add_gui("pixel_position", pixel_position, "vector", "options='min=0;step=0.01;max=300;ticks=true'");
add_gui("subpixel_offset", subpixel_offset, "vector", "options='min=0;step=0.001;max=1;ticks=true'");
add_decorator("lines", "heading", "level=2");
add_member_control(this, "show_lines", show_lines, "toggle");
add_member_control(this, "fst_line", fst_line, "value_slider", "min=-1;max=128;ticks=true");
add_member_control(this, "line_delta", line_delta, "value_slider", "min=5;max=128;ticks=true");
add_decorator("cube", "heading", "level=2");
add_member_control(this, "show_cube", show_cube, "toggle");
add_member_control(this, "use_blending", use_blending, "toggle");
if (begin_tree_node("rectangle", rrs, true)) {
align("\a");
add_gui("rectangle", rrs);
align("\b");
end_tree_node(rrs);
}
}
};
#include <cgv/base/register.h>
cgv::base::object_registration<font_test> reg_font_test("");
#ifdef CGV_FORCE_STATIC
cgv::base::registration_order_definition ro_def("stereo_view_interactor;font_test");
#endif
| 31.764569 | 125 | 0.676965 | henne90gen |
c422e32063934f810d7ba085a9650364c9f7c1d4 | 1,155 | cpp | C++ | luogu/P3478.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | 1 | 2020-07-24T03:07:08.000Z | 2020-07-24T03:07:08.000Z | luogu/P3478.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | null | null | null | luogu/P3478.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | null | null | null | //
// Created by yangtao on 20-11-27.
//
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
ll h[N], e[N*2], ne[N*2], size[N], dep[N], dp[N];
int n, idx;
void add(int u, int v) {
e[idx] = v, ne[idx] = h[u], h[u] = idx++;
}
void dfs1(int u, int f) {
size[u] = 1, dep[u] = dep[f] + 1;
for(int i = h[u]; ~i; i = ne[i] ) {
int v = e[i];
if(v == f) continue;
dfs1(v, u);
size[u] += size[v];
}
}
void dfs2(int u, int f) {
for(int i = h[u]; ~i ; i = ne[i]) {
int v = e[i];
if(v == f) continue;
dp[v] = dp[u] - size[v] + n - size[v];
dfs2(v, u);
}
}
int main() {
cin >> n;
memset(h, -1 , sizeof(h));
for(int i = 1; i < n; i++) {
int u, v;
scanf("%d%d", &u, &v);
add(u, v), add(v, u);
}
dfs1(1, 0);
for(int i = 1; i <= n; i++) dp[1] += size[i];
dfs2(1, 0);
ll ans = 0, mmax = 0;
for(int i = 1; i <= n; i++) {
if(dp[i] > mmax) {
ans = i, mmax = dp[i];
}
}
cout << ans;
return 0;
}
| 20.625 | 49 | 0.423377 | delphi122 |
c424bb1d9916145c4ecfbcf3106ff97b6794b842 | 809 | cpp | C++ | mp2/main.cpp | Atrifex/ECE-438 | fbf2c3f51291bfa347abaa06f843e2d20d5239f6 | [
"MIT"
] | 2 | 2019-04-25T00:24:55.000Z | 2019-04-25T04:35:05.000Z | mp2/main.cpp | Atrifex/ECE-438 | fbf2c3f51291bfa347abaa06f843e2d20d5239f6 | [
"MIT"
] | null | null | null | mp2/main.cpp | Atrifex/ECE-438 | fbf2c3f51291bfa347abaa06f843e2d20d5239f6 | [
"MIT"
] | 1 | 2020-10-02T21:32:34.000Z | 2020-10-02T21:32:34.000Z |
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include "ls_router.h"
using std::thread;
using std::ref;
void announceToNeighbors(LS_Router & router) {
router.announceToNeighbors();
}
void generateLSP(LS_Router & router) {
router.generateLSP();
}
int main(int argc, char** argv)
{
if(argc != 4) {
fprintf(stderr, "Usage: %s mynodeid initialcostsfile logfile\n\n", argv[0]);
exit(1);
}
// Parse input and initialize router
LS_Router router(atoi(argv[1]), argv[2], argv[3]);
// start announcing
thread announcer(announceToNeighbors, ref(router));
// start generating lsps
thread lspGenerator(generateLSP, ref(router));
// start listening
router.listenForNeighbors();
}
| 19.731707 | 84 | 0.672435 | Atrifex |
c42540e5c27ad1cc5aea128573f1731dc0b40771 | 3,385 | cc | C++ | stig/rpc/msg.cc | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | 5 | 2018-04-24T12:36:50.000Z | 2020-03-25T00:37:17.000Z | stig/rpc/msg.cc | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | null | null | null | stig/rpc/msg.cc | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | 2 | 2018-04-24T12:39:24.000Z | 2020-03-25T00:45:08.000Z | /* <stig/rpc/msg.cc>
Implements <stig/rpc/msg.h>.
Copyright 2010-2014 Tagged
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 <stig/rpc/msg.h>
#include <stdexcept>
#include <io/endian.h>
using namespace std;
using namespace Io;
using namespace Stig::Rpc;
void TMsg::Send(TSafeTransceiver *xver, int sock_fd) {
assert(this);
assert(xver);
/* Measure up our blob. */
size_t block_count, byte_count;
Blob.GetCounts(block_count, byte_count);
block_count += 3;
/* We'll need to send the kind, the request id, and the byte count as well as
the blocks in the blob itself, so order up some iovecs. */
auto
*vecs = xver->GetIoVecs(block_count),
*limit = vecs + block_count;
/* The first iovec holds the kind.
That's just one byte, so we don't need to worry about network byte order. */
vecs->iov_base = &Kind;
vecs->iov_len = sizeof(Kind);
++vecs;
/* The second iovec holds the request id, in NBO. */
auto nbo_req_id = SwapEnds(ReqId);
vecs->iov_base = &nbo_req_id;
vecs->iov_len = sizeof(nbo_req_id);
++vecs;
/* The second iovec holds the number of bytes in the blob, in NBO. */
auto nbo_byte_count = SwapEnds(static_cast<TByteCount>(byte_count));
vecs->iov_base = &nbo_byte_count;
vecs->iov_len = sizeof(nbo_byte_count);
++vecs;
/* The rest of the iovecs hold the blob's data blocks. Fill them in and fire away. */
Blob.InitIoVecs(vecs, limit);
xver->Send(sock_fd);
}
TMsg TMsg::Recv(TBufferPool *buffer_pool, TSafeTransceiver *xver, int sock_fd) {
assert(buffer_pool);
assert(xver);
/* We'll start by receiving a kind, a request id, and the number of bytes in the incoming blob. */
TKind kind;
TReqId req_id;
TByteCount byte_count;
auto *vecs = xver->GetIoVecs(3);
vecs->iov_base = &kind;
vecs->iov_len = sizeof(kind);
++vecs;
vecs->iov_base = &req_id;
vecs->iov_len = sizeof(req_id);
++vecs;
vecs->iov_base = &byte_count;
vecs->iov_len = sizeof(byte_count);
xver->Recv(sock_fd);
/* The request id and the byte count arrived in network byte order, so it's time to do the endian dance. */
req_id = SwapEnds(req_id);
byte_count = SwapEnds(byte_count);
/* Check the kind we receiver to make sure it's valid. */
switch (kind) {
case TKind::Request:
case TKind::NormalReply:
case TKind::ErrorReply: {
break;
}
default: {
throw invalid_argument("Stig RPC message arrived with unknown kind");
}
}
/* Make a buffer space large enough, then receive the blob into it. */
size_t block_count = (byte_count + BlockSize - 1) / BlockSize;
TBlob blob(buffer_pool, byte_count);
vecs = xver->GetIoVecs(block_count);
auto *limit = vecs + block_count;
blob.InitIoVecs(vecs, limit);
xver->Recv(sock_fd);
/* Construct a new message and return it. */
return move(TMsg(kind, req_id, move(blob)));
}
| 32.864078 | 109 | 0.690694 | ctidder |
c4269bf3b0e39b55290bc4a407ffcc9b0cdc5a8c | 641 | cpp | C++ | src/Evel/UdpSocket_WF.cpp | hleclerc/Evel | c607adda555f417dfc9fb4de310c07c48ea3642f | [
"Apache-2.0"
] | null | null | null | src/Evel/UdpSocket_WF.cpp | hleclerc/Evel | c607adda555f417dfc9fb4de310c07c48ea3642f | [
"Apache-2.0"
] | null | null | null | src/Evel/UdpSocket_WF.cpp | hleclerc/Evel | c607adda555f417dfc9fb4de310c07c48ea3642f | [
"Apache-2.0"
] | null | null | null | #include "UdpSocket_WF.h"
namespace Evel {
UdpSocket_WF::~UdpSocket_WF() {
if ( f_close ) f_close( this );
}
void UdpSocket_WF::on_rdy() {
if ( f_rdy ) f_rdy( this );
}
void UdpSocket_WF::parse( const InetAddress &src, char **data, unsigned size ) {
if ( f_parse ) f_parse( this, src, data, size );
}
void *UdpSocket_WF::allocate( size_t inp_buf_size ) {
return f_allocate ? f_allocate( this, inp_buf_size ) : UdpSocket::allocate( inp_buf_size );
}
void UdpSocket_WF::on_bind_error( const char *msg ) {
return f_on_bind_error ? f_on_bind_error( this, msg ) : UdpSocket::on_bind_error( msg );
}
} // namespace Evel
| 24.653846 | 95 | 0.687988 | hleclerc |
c428833922bad37bca68690b5d71003424c6b628 | 1,249 | cpp | C++ | 01-Question_after_WangDao/Chapter_02/2.2/T01.cpp | ysl970629/kaoyan_data_structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | 2 | 2021-03-24T03:29:16.000Z | 2022-03-29T16:34:30.000Z | 01-Question_after_WangDao/Chapter_02/2.2/T01.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | 01-Question_after_WangDao/Chapter_02/2.2/T01.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
using namespace std;
#define INFINITY 9999
typedef int ElemType;
typedef struct {
ElemType *data;
int length;
} SqList;
SqList initList(int arr[], int length) {
SqList L;
L.length = length;
L.data = (ElemType *)malloc(sizeof(ElemType) * L.length);
for (int i = 0; i < length; i++)
L.data[i] = arr[i];
return L;
}
void outPutList(SqList L) {
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
}
bool deleteList(SqList &L, ElemType &e) {
if (L.length == 0)
return false;
ElemType minValue = INFINITY;
int minIndex = -1;
for (int i = 0; i < L.length; i++) {
if (L.data[i] < minValue) {
minValue = L.data[i];
minIndex = i;
}
}
e = minValue;
L.data[minIndex] = L.data[L.length - 1];
L.length--;
return true;
}
void test(int arr1[], int length1) {
SqList L = initList(arr1, length1);
ElemType e;
deleteList(L, e);
cout << e << endl;
outPutList(L);
}
int main() {
ElemType A[] = {3, 4, 5, 0, 1, 2, 6, 7, 8};
int length1 = sizeof(A) / sizeof(int);
test(A, length1);
return 0;
}
// 输出结果:
// 0
// 3 4 5 8 1 2 6 7
| 19.215385 | 61 | 0.536429 | ysl970629 |
c42a24c0464599f37230836540333f75a738d277 | 1,894 | cc | C++ | lib/wam_orderby.cc | fbsamples/wamquery | d772b10adb5ff7979212b0b2d6197c06c4553478 | [
"Apache-2.0"
] | 1 | 2021-09-12T13:28:40.000Z | 2021-09-12T13:28:40.000Z | lib/wam_orderby.cc | fbsamples/wamquery | d772b10adb5ff7979212b0b2d6197c06c4553478 | [
"Apache-2.0"
] | null | null | null | lib/wam_orderby.cc | fbsamples/wamquery | d772b10adb5ff7979212b0b2d6197c06c4553478 | [
"Apache-2.0"
] | 1 | 2021-09-12T12:36:55.000Z | 2021-09-12T12:36:55.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
/* orderby + limit implementation */
#include <algorithm>
#include "wam_orderby.h"
/* array to sort (maybe be partially sort) */
static tuple_t **tuples = NULL;
typedef tuple_t *tuple_p;
static uint64_t size = 0;
void wam_orderby_init(uint64_t input_size)
{
tuples = new tuple_p[input_size];
}
void wam_orderby_free(void)
{
if (!tuples) return;
delete []tuples;
tuples = NULL;
}
void wam_orderby_visit(tuple_t *t)
{
tuples[size++] = t;
}
/* NOTE: the same as wam_query_orderby_compare(a, b) but returns bool instead of
* int 0|1 */
static inline
bool compare_tuple(tuple_t *a, tuple_t *b)
{
return wam_query_orderby_compare(a, b);
}
tuple_t **wam_orderby_function(uint64_t limit)
{
if (limit >= size) // full sort
std::sort(tuples, tuples + size, compare_tuple);
else // partial sort
std::partial_sort(tuples, tuples + limit, tuples + size, compare_tuple);
return tuples;
}
/* NOTE: the same as wam_query_groupby_compare(a, b) but returns bool instead of
* int 0|1 */
static inline
bool compare_groupby_key(tuple_t *a, tuple_t *b)
{
return wam_query_groupby_compare(a, b);
}
tuple_t **wam_orderby_group_key(void)
{
std::sort(tuples, tuples + size, compare_groupby_key);
return tuples;
}
| 21.522727 | 80 | 0.703801 | fbsamples |
c42a95ae09e4e4ec894bc0e23fbad602c769659c | 3,660 | cc | C++ | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_istream/getline/wchar_t/1.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_istream/getline/wchar_t/1.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_istream/getline/wchar_t/1.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // Copyright (C) 2004 Free Software Foundation
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 27.6.1.3 unformatted input functions
#include <istream>
#include <sstream>
#include <testsuite_hooks.h>
void
test02()
{
typedef std::char_traits<wchar_t> traits_type;
bool test __attribute__((unused)) = true;
const wchar_t str_lit01[] = L"\t\t\t sun*ra \n"
L" "
L"and his myth science arkestra present\n"
L" "
L"angles and demons @ play\n"
L" "
L"the nubians of plutonia";
std::wstring str01(str_lit01);
std::wstring strtmp;
std::wstringbuf sbuf_04(str01, std::ios_base::in);
std::wistream is_00(NULL);
std::wistream is_04(&sbuf_04);
std::ios_base::iostate state1, state2, statefail, stateeof;
statefail = std::ios_base::failbit;
stateeof = std::ios_base::eofbit;
wchar_t carray1[400] = L"";
// istream& getline(wchar_t* s, streamsize n, wchar_t delim)
// istream& getline(wchar_t* s, streamsize n)
state1 = is_00.rdstate();
is_00.getline(carray1, 20, L'*');
state2 = is_00.rdstate();
// make sure failbit was set, since we couldn't extract
// from the NULL streambuf...
VERIFY( state1 != state2 );
VERIFY( static_cast<bool>(state2 & statefail) );
VERIFY( is_04.gcount() == 0 );
state1 = is_04.rdstate();
is_04.getline(carray1, 1, L'\t'); // extracts, throws away
state2 = is_04.rdstate();
VERIFY( is_04.gcount() == 1 );
VERIFY( state1 == state2 );
VERIFY( state1 == 0 );
VERIFY( !traits_type::compare(L"", carray1, 1) );
state1 = is_04.rdstate();
is_04.getline(carray1, 20, L'*');
state2 = is_04.rdstate();
VERIFY( is_04.gcount() == 10 );
VERIFY( state1 == state2 );
VERIFY( state1 == 0 );
VERIFY( !traits_type::compare(L"\t\t sun", carray1, 10) );
state1 = is_04.rdstate();
is_04.getline(carray1, 20);
state2 = is_04.rdstate();
VERIFY( is_04.gcount() == 4 );
VERIFY( state1 == state2 );
VERIFY( state1 == 0 );
VERIFY( !traits_type::compare(L"ra ", carray1, 4) );
state1 = is_04.rdstate();
is_04.getline(carray1, 65);
state2 = is_04.rdstate();
VERIFY( is_04.gcount() == 64 );
VERIFY( state1 != state2 );
VERIFY( state2 == statefail );
VERIFY( !traits_type::compare(
L" and his myth science arkestra presen",
carray1, 65) );
is_04.clear();
state1 = is_04.rdstate();
is_04.getline(carray1, 120, L'|');
state2 = is_04.rdstate();
VERIFY( is_04.gcount() == 106 );
VERIFY( state1 != state2 );
VERIFY( state2 == stateeof );
is_04.clear();
state1 = is_04.rdstate();
is_04.getline(carray1, 100, L'|');
state2 = is_04.rdstate();
VERIFY( is_04.gcount() == 0 );
VERIFY( state1 != state2 );
VERIFY( static_cast<bool>(state2 & stateeof) );
VERIFY( static_cast<bool>(state2 & statefail) );
}
int
main()
{
test02();
return 0;
}
| 30.756303 | 79 | 0.639891 | vidkidz |
c42b0f6f5556e70beb86f8f029212fa1a274897d | 5,565 | hpp | C++ | SSCode/SSFeature.hpp | timmyd7777/SSCore | 3a3a6f1408a5e4b37af67c27026269997d7a6216 | [
"IJG",
"FSFAP"
] | 13 | 2020-05-11T06:16:58.000Z | 2022-01-16T00:12:38.000Z | SSCode/SSFeature.hpp | timmyd7777/SSCore | 3a3a6f1408a5e4b37af67c27026269997d7a6216 | [
"IJG",
"FSFAP"
] | 2 | 2020-09-09T17:58:45.000Z | 2020-12-04T23:06:33.000Z | SSCode/SSFeature.hpp | timmyd7777/SSCore | 3a3a6f1408a5e4b37af67c27026269997d7a6216 | [
"IJG",
"FSFAP"
] | 5 | 2020-04-13T02:28:56.000Z | 2021-07-27T07:40:43.000Z | // SSFeature.hpp
// SSCore
//
// Created by Tim DeBenedictis on 11/18/20.
//
// Copyright © 2020 Southern Stars. All rights reserved.
//
// This subclass of SSObject represents planetary surface features.
#ifndef SSFeature_hpp
#define SSFeature_hpp
#include "SSObject.hpp"
#include "SSPlanet.hpp"
#pragma pack ( push, 1 )
// This subclass of SSObject stores basic data for planetary surface features
// from the IAU Gazetteer of Planetary Nomenclature:
// https://planetarynames.wr.usgs.gov/AdvancedSearch
// For details, see https://planetarynames.wr.usgs.gov/Page/Specifics
class SSFeature : public SSObject
{
protected:
// string _name; // feature name; may contain funky UTF8 characters. Stored in SSObject::_names[0].
// string _clean_name; // clean feature name; only contains ASCII characters. Stored in SSObject::_names[1].
string _target; // name of planetary object to which the feature belongs.
string _type_code; // feature type code; see https://planetarynames.wr.usgs.gov/DescriptorTerms
string _origin; // feature origin (short explanation of name)
float _diameter; // diameter in kilometers
float _lat, _lon; // center latitude & longitude in degrees. East and North are positive.
public:
SSFeature ( void );
// accessors
string getName ( void ) { return _names[0]; }
string getCleanName ( void ) { return _names[1]; }
string getTarget ( void ) { return _target; }
string getFeatureTypeCode ( void ) { return _type_code; }
string getOrigin ( void ) { return _origin; }
double getDiameter ( void ) { return _diameter; }
double getLatitude ( void ) { return _lat; }
double getLongitude ( void ) { return _lon; }
// modifiers
void setName ( string name ) { _names[0] = name; }
void setCleanName ( string clean_name ) { _names[1] = clean_name; }
void setTarget ( string target ) { _target = target; }
void setFeatureTypeCode ( string type_code ) { _type_code = type_code; }
void setOrigin ( string origin ) { _origin = origin; }
void setDiameter ( double diameter ) { _diameter = diameter; }
void setLatitude ( double lat ) { _lat = lat; }
void setLongitude ( double lon ) { _lon = lon; }
// imports/exports from/to CSV-format text string
static SSObjectPtr fromCSV ( string csv );
virtual string toCSV ( void );
// computes apparent direction and distance; planet must already have ephemeris computed.
void computeEphemeris ( SSPlanet *pPlanet );
};
// This subclass of SSFeature stores data for cities obtained from:
// http://download.geonames.org/export/dump/cities1000.zip
// For details see http://download.geonames.org/export/dump/readme.txt
class SSCity : public SSFeature
{
protected:
string _country_code; // 2-letter country code
string _admin1_code, _admin1_name; // administrative division 1: 2-letter code & name
string _timezone_name; // time zone name (e.g. "America/Los_Angeles")
float _elevation; // elevation in meters, -1 means unknown
int _population; // population, -1 means unknown
bool _daylight_saving; // whether the city observes daylight saving time
float _timezone_raw_offset; // offset from GMT in hours, independent of daylight saving time; east is positive
public:
SSCity ( void );
// accessors
string getCountryCode ( void ) { return _country_code; }
string getAdmin1Code ( void ) { return _admin1_code; }
string getAdmin1Name ( void ) { return _admin1_name; }
string getTimezoneName ( void ) { return _timezone_name; }
float getElevation ( void ) { return _elevation; }
int getPopulation ( void ) { return _population; }
bool getDaylightSaving ( void ) { return _daylight_saving; }
float getTimezoneRawOffset ( void ) { return _timezone_raw_offset; }
// modifiers
void setCountryCode ( string country_code ) { _country_code = country_code; }
void setAdmin1Code ( string admin1_code ) { _admin1_code = admin1_code; }
void setAdmin1Name ( string admin1_name ) { _admin1_name = admin1_name; }
void setTimezoneName ( string timezone_name ) { _timezone_name = timezone_name; }
void setElevation ( float elevation ) { _elevation = elevation; }
void setPopulation ( int population ) { _population = population; }
void setDaylightSaving ( bool daylight_saving ) { _daylight_saving = daylight_saving; }
void setTimezoneRawOffset ( double timezone_raw_offset ) { _timezone_raw_offset = timezone_raw_offset; }
// imports/exports from/to CSV-format text string
static SSObjectPtr fromCSV ( string csv );
virtual string toCSV ( void );
};
#pragma pack ( pop )
// convenient aliases for pointers to various subclasses of SSFeature
typedef SSFeature *SSFeaturePtr;
typedef SSCity *SSCityPtr;
// These functions downcast a pointer from the SSObject base class to its various SSFeature subclasses.
// They all return null pointers if the input object pointer is not an instance of the expected derived class.
SSFeaturePtr SSGetFeaturePtr ( SSObjectPtr ptr );
SSCityPtr SSGetCityPtr ( SSObjectPtr ptr );
typedef map<string,int> SSPlanetFeatureMap;
int SSMakePlanetFeatureMap ( SSObjectVec &features, SSPlanetFeatureMap &map );
#endif /* SSFeature_hpp */
| 40.919118 | 129 | 0.681941 | timmyd7777 |
c430c3f7a41a594286a0aced1e17298807805390 | 418 | cpp | C++ | contest/AtCoder/abc173/B.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/AtCoder/abc173/B.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/AtCoder/abc173/B.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "string.hpp"
int main() {
int n(in), ac = 0, wa = 0, tle = 0, re = 0;
for (int i = 0; i < n; ++i) {
String s(in);
if (s == "AC") {
++ac;
} else if (s == "WA") {
++wa;
} else if (s == "TLE") {
++tle;
} else {
++re;
}
}
cout << "AC x " << ac << endl;
cout << "WA x " << wa << endl;
cout << "TLE x " << tle << endl;
cout << "RE x " << re << endl;
}
| 19 | 45 | 0.366029 | not522 |
c431093118059ac620713bcb36cf416c81693b5e | 254 | hpp | C++ | src/Modules/Interface/IModuleBuilder.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | 1 | 2021-03-12T13:39:17.000Z | 2021-03-12T13:39:17.000Z | src/Modules/Interface/IModuleBuilder.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | src/Modules/Interface/IModuleBuilder.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | //
// Created by caedus on 04.02.2021.
//
#pragma once
#include "Modules/Interface/IModule.hpp"
namespace nastya::modules {
class IModuleBuilder {
public:
virtual ~IModuleBuilder() = default;
virtual std::unique_ptr<IModule> build() = 0;
};
}
| 15.875 | 49 | 0.692913 | pawel-jarosz |
c43214465609dcb7aad82c3d6fb31cb98b9fa6ef | 1,859 | cpp | C++ | boboleetcode/Play-Leetcode-master/0909-Snakes-and-Ladders/cpp-0909/main.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0909-Snakes-and-Ladders/cpp-0909/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0909-Snakes-and-Ladders/cpp-0909/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/snakes-and-ladders/description/
/// Author : liuyubobobo
/// Time : 2018-09-22
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
/// BFS
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n = board.size();
vector<int> b;
int order = 0;
for(int i = n - 1; i >= 0; i --){
if(order)
reverse(board[i].begin(), board[i].end());
for(int j = 0; j < n; j ++){
if(board[i][j] != -1)
board[i][j] --;
b.push_back(board[i][j]);
}
order = 1 - order;
}
assert(b.size() == n * n);
return bfs(b, 0, n * n - 1);
}
private:
int bfs(const vector<int>& b, int s, int t){
vector<bool> visited(b.size(), false);
queue<pair<int, int>> q;
q.push(make_pair(s, 0));
visited[s] = true;
while(!q.empty()){
int pos = q.front().first;
int step = q.front().second;
q.pop();
if(pos == t)
return step;
for(int i = 1; i <= 6 && pos + i < b.size(); i ++){
int next = pos + i;
if(b[next] != -1)
next = b[next];
if(!visited[next]){
visited[next] = true;
q.push(make_pair(next, step + 1));
}
}
}
return -1;
}
};
int main() {
vector<vector<int>> board1 = {
{-1,1,2,-1},
{2,13,15,-1},
{-1,10,-1,-1},
{-1,6,2,8}
};
cout << Solution().snakesAndLadders(board1) << endl;
// 2
return 0;
} | 22.670732 | 74 | 0.423346 | yaominzh |
c4331b57d588538cff69656332c13bef13a5c624 | 3,031 | hpp | C++ | include/gp/genetic_operations/mutation.hpp | ho-ri1991/genetic-programming | 06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0 | [
"MIT"
] | null | null | null | include/gp/genetic_operations/mutation.hpp | ho-ri1991/genetic-programming | 06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0 | [
"MIT"
] | null | null | null | include/gp/genetic_operations/mutation.hpp | ho-ri1991/genetic-programming | 06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0 | [
"MIT"
] | null | null | null | #ifndef GP_GENETIC_OPERATIONS_MUTATION
#define GP_GENETIC_OPERATIONS_MUTATION
#include <gp/node/node_interface.hpp>
#include <gp/tree/tree.hpp>
#include <gp/tree_operations/tree_operations.hpp>
#include <gp/utility/is_detected.hpp>
#include <cassert>
namespace gp::genetic_operations {
namespace detail {
template <typename RandomTreeGenerator>
using is_match_random_tree_generator_concept =
std::is_invocable_r<
node::NodeInterface::node_instance_type,
RandomTreeGenerator,
const tree::TreeProperty&,
std::size_t
>;
template <typename RandomTreeGenerator>
static constexpr bool is_match_random_tree_generator_concept_v = is_match_random_tree_generator_concept<RandomTreeGenerator>::value;
template <typename NodeSelector>
using is_match_node_selector_concept =
std::is_invocable_r<
const node::NodeInterface&,
NodeSelector,
const node::NodeInterface&
>;
template <typename NodeSelector>
static constexpr bool is_match_node_selector_concept_v = is_match_node_selector_concept<NodeSelector>::value;
}
template <typename RandomTreeGenerator, //concept: node::NodeInterface::node_instance_type operator()(const tree::TreeProperty&, std::size_t), the first argument is property of tree, second is max tree depth
typename NodeSelector //concept: const node::NodeInterface& operator()(const node::NodeInterface&) , the argument is the root node of tree
>
auto mutation(tree::Tree tree,
RandomTreeGenerator& randomTreeGenerator,
NodeSelector& nodeSelector,
std::size_t maxTreeDepth)
-> std::enable_if_t<
std::conjunction_v<
detail::is_match_random_tree_generator_concept<RandomTreeGenerator>,
detail::is_match_node_selector_concept<NodeSelector>
>,
tree::Tree
>
{
const auto& selectedNode = nodeSelector(tree.getRootNode());
auto depth = tree_operations::getDepth(selectedNode);
assert(depth <= maxTreeDepth);
auto subtreeProperty = tree.getTreeProperty();
subtreeProperty.returnType = &selectedNode.getReturnType();
auto newSubtree = randomTreeGenerator(subtreeProperty, maxTreeDepth - depth);
if(selectedNode.hasParent()) {
auto& parent = const_cast<node::NodeInterface&>(selectedNode.getParent());
for(int i = 0; i < parent.getChildNum(); ++i) {
if(parent.hasChild(i) && &parent.getChild(i) == &selectedNode) {
parent.setChild(i, std::move(newSubtree));
return tree;
}
}
return tree;
} else {
return tree::Tree(std::move(tree).getTreeProperty(), std::move(newSubtree));
}
};
}
#endif
| 41.520548 | 211 | 0.633124 | ho-ri1991 |
c436572efbf5f261c84fa7f82e672f10a9ff032f | 310 | cpp | C++ | aql/benchmark/lib_60/class_8.cpp | menify/sandbox | 32166c71044f0d5b414335b2b6559adc571f568c | [
"MIT"
] | null | null | null | aql/benchmark/lib_60/class_8.cpp | menify/sandbox | 32166c71044f0d5b414335b2b6559adc571f568c | [
"MIT"
] | null | null | null | aql/benchmark/lib_60/class_8.cpp | menify/sandbox | 32166c71044f0d5b414335b2b6559adc571f568c | [
"MIT"
] | null | null | null | #include "class_8.h"
#include "class_9.h"
#include "class_3.h"
#include "class_6.h"
#include "class_4.h"
#include "class_7.h"
#include <lib_8/class_1.h>
#include <lib_40/class_5.h>
#include <lib_52/class_4.h>
#include <lib_7/class_3.h>
#include <lib_10/class_9.h>
class_8::class_8() {}
class_8::~class_8() {}
| 20.666667 | 27 | 0.712903 | menify |
c436876c46e9b0354a1ad972f0d59d2e4927cf83 | 1,646 | hpp | C++ | src/vkt/Resample_serial.hpp | szellmann/volk | f8e8755d0e016359e4977934412888830080dd42 | [
"MIT"
] | 1 | 2021-01-20T22:31:07.000Z | 2021-01-20T22:31:07.000Z | src/vkt/Resample_serial.hpp | szellmann/volkit | f8e8755d0e016359e4977934412888830080dd42 | [
"MIT"
] | null | null | null | src/vkt/Resample_serial.hpp | szellmann/volkit | f8e8755d0e016359e4977934412888830080dd42 | [
"MIT"
] | null | null | null | // This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#include <vkt/Resample.hpp>
#include <vkt/StructuredVolume.hpp>
#include "linalg.hpp"
namespace vkt
{
void Resample_serial(
StructuredVolume& dst,
StructuredVolume& src,
Filter filter
)
{
if (dst.getDims() == src.getDims())
{
// In that case don't resample spatially!
Vec3i dims = dst.getDims();
for (int32_t z = 0; z != dims.z; ++z)
{
for (int32_t y = 0; y != dims.y; ++y)
{
for (int32_t x = 0; x != dims.x; ++x)
{
Vec3i index{x,y,z};
dst.setValue(index, src.getValue(index));
}
}
}
}
else
{
Vec3i dstDims = dst.getDims();
Vec3i srcDims = src.getDims();
for (int32_t z = 0; z != dstDims.z; ++z)
{
for (int32_t y = 0; y != dstDims.y; ++y)
{
for (int32_t x = 0; x != dstDims.x; ++x)
{
float srcX = x / float(dstDims.x) * srcDims.x;
float srcY = y / float(dstDims.y) * srcDims.y;
float srcZ = z / float(dstDims.z) * srcDims.z;
float value = src.sampleLinear(srcX, srcY, srcZ);
dst.setValue({x,y,z}, value);
}
}
}
}
}
} // vkt
| 26.983607 | 73 | 0.402795 | szellmann |
c439ec2d3cac849808d08ae87376fbed3236e7c5 | 1,337 | cpp | C++ | luogu/p6198.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | luogu/p6198.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | luogu/p6198.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int n;
int val = 1;
vector<int> arr(1e6+5), ans(1e6+5);
vector<vector<int>> pos(1e6+5, vector<int>());
void slove(int l, int r, int splitNum)
{
/* cout << l << " " << r << endl; */
if(l>r) return;
vector<int> splitPos; //记录分割点
// 二分查端点
int st = lower_bound(pos[splitNum].begin(), pos[splitNum].end(), r) - pos[splitNum].begin();
// splitNum 从r到l 按照val递增赋值
for(int i = min(st, int(pos[splitNum].size()-1)); i >= 0 && pos[splitNum][i] >= l; i--)
{
if(pos[splitNum][i] <= r && arr[pos[splitNum][i]] == splitNum)
{
ans[pos[splitNum][i]] = val++;
splitPos.push_back(pos[splitNum][i]);
}
}
// l r 也可以作为分割点
if(!splitPos.empty() && splitPos.back()!=l) splitPos.push_back(l-1);
if(splitPos.front()!=r) splitPos.insert(splitPos.begin(),r+1);
for(int i = splitPos.size()-2; i >= 0; i--)
{
slove(splitPos[i+1]+1, splitPos[i]-1, splitNum+1);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> arr[i];
if(arr[i] == -1) arr[i] = arr[i-1]+1;
pos[arr[i]].push_back(i);
}
slove(1, n, 1);
for(int i = 1; i <= n; i++)
cout << ans[i] << " ";
cout << endl;
return 0;
}
| 26.215686 | 96 | 0.511593 | freedomDR |
c43ac9c7802269ebb639954548731d12893d3d66 | 1,302 | cc | C++ | DataFormats/CaloTowers/test/CaloTowersDump.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DataFormats/CaloTowers/test/CaloTowersDump.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DataFormats/CaloTowers/test/CaloTowersDump.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/CaloTowers/interface/CaloTowerCollection.h"
#include <iostream>
using namespace std;
/** \class CaloTowersDump
\author J. Mans - Minnesota
*/
class CaloTowersDump : public edm::EDAnalyzer {
public:
explicit CaloTowersDump(edm::ParameterSet const& conf);
virtual void analyze(edm::Event const& e, edm::EventSetup const& c);
};
CaloTowersDump::CaloTowersDump(edm::ParameterSet const& conf) {}
void CaloTowersDump::analyze(edm::Event const& e, edm::EventSetup const& c) {
std::vector<edm::Handle<CaloTowerCollection> > prods;
try {
e.getManyByType(prods);
// cout << "Selected " << hbhe.size() << endl;
std::vector<edm::Handle<CaloTowerCollection> >::iterator i;
for (i = prods.begin(); i != prods.end(); i++) {
const CaloTowerCollection& c = *(*i);
for (CaloTowerCollection::const_iterator j = c.begin(); j != c.end(); j++) {
cout << *j << std::endl;
}
}
} catch (...) {
cout << "No CaloTowers." << endl;
}
}
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(CaloTowersDump);
| 29.590909 | 82 | 0.68126 | ckamtsikis |
c43c81cf2f099d29d0bec5181481cc6203ce1388 | 800 | cpp | C++ | source/game/Main.cpp | AlexKoukoulas2074245K/Genesis | 23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88 | [
"MIT"
] | null | null | null | source/game/Main.cpp | AlexKoukoulas2074245K/Genesis | 23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88 | [
"MIT"
] | null | null | null | source/game/Main.cpp | AlexKoukoulas2074245K/Genesis | 23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88 | [
"MIT"
] | null | null | null | ///------------------------------------------------------------------------------------------------
/// Main.cpp
/// Genesis
///
/// Created by Alex Koukoulas on 19/11/2019.
///------------------------------------------------------------------------------------------------
#include "Game.h"
#include "../engine/GenesisEngine.h"
#if defined(_WIN32) && !defined(NDEBUG)
#include <vld.h>
#endif
///------------------------------------------------------------------------------------------------
int main(int, char**)
{
genesis::GenesisEngine engine;
genesis::GameStartupParameters startupParameters("Genesis", 0.7f);
Game game;
engine.RunGame(startupParameters, game);
}
///------------------------------------------------------------------------------------------------
| 27.586207 | 99 | 0.3325 | AlexKoukoulas2074245K |
c43ebc79b8b575b62f652c1abbdb65988fd33316 | 984 | cpp | C++ | Plugins/Optimizations/Optimizations/AsyncLogFlush.cpp | Jorteck/unified | 834e39fabfe8fdb0b636cf6b4d48b3a78af64c59 | [
"MIT"
] | null | null | null | Plugins/Optimizations/Optimizations/AsyncLogFlush.cpp | Jorteck/unified | 834e39fabfe8fdb0b636cf6b4d48b3a78af64c59 | [
"MIT"
] | null | null | null | Plugins/Optimizations/Optimizations/AsyncLogFlush.cpp | Jorteck/unified | 834e39fabfe8fdb0b636cf6b4d48b3a78af64c59 | [
"MIT"
] | null | null | null | #include "Optimizations/AsyncLogFlush.hpp"
#include "Services/Hooks/Hooks.hpp"
#include "Services/Tasks/Tasks.hpp"
#include "API/Functions.hpp"
#include "API/CExoDebugInternal.hpp"
#include "API/CExoFile.hpp"
namespace Optimizations {
using namespace NWNXLib;
using namespace NWNXLib::API;
NWNXLib::Services::TasksProxy* AsyncLogFlush::s_tasker;
AsyncLogFlush::AsyncLogFlush(Services::HooksProxy* hooker, Services::TasksProxy* tasker)
{
s_tasker = tasker;
hooker->Hook(API::Functions::_ZN17CExoDebugInternal12FlushLogFileEv, (void*)&FlushLogFile_Hook, Hooking::Order::Final);
}
void AsyncLogFlush::FlushLogFile_Hook(CExoDebugInternal* pThis)
{
// Rotating log file, do synchronously
if (pThis->m_bRotateLogFile && ((pThis->m_nCurrentLogSize << 2) > pThis->m_nMaxLogSize))
{
pThis->m_pLogFile->Flush();
return;
}
if (pThis->m_bFilesOpen)
{
s_tasker->QueueOnAsyncThread([pThis](){ pThis->m_pLogFile->Flush(); });
}
}
}
| 26.594595 | 123 | 0.721545 | Jorteck |
c44396e5f9fff08a4c4008c7cbf95202dd6aa77f | 6,498 | cpp | C++ | src/Pegasus/Config/tests/BldMsgBndl/BldMsgBndl.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | src/Pegasus/Config/tests/BldMsgBndl/BldMsgBndl.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | src/Pegasus/Config/tests/BldMsgBndl/BldMsgBndl.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////////
/****************************************************************************
**
** This executable generates output to stdout for a message bundle
** representing the help messages for Config Properties. It can be used
** at any time to generate this text which must be then manually
** inserted into the Server message bundle.
** It generates the message bundle text from the help Strings defined
** in the file src/Pegasus/Config/ConfigPropertyHelp.cpp
**
** Normally not compiled. Compile and use only when the text in the table
** changes.
**
****************************************************************************/
#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/PegasusAssert.h>
#include <Pegasus/Common/Constants.h>
#include <Pegasus/Config/ConfigPropertyHelp.h>
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
static Boolean verbose;
// Creates string of form:
// Config.DefaultPropertyOwner.<propertyName>.DESCRIPTION
String _createKey(const char* propertyName)
{
String rtn = "Config.ConfigPropertyHelp.";
rtn.append("DESCRIPTION_");
rtn.append(propertyName);
return rtn;
}
String _descriptionWithPrefix(const char* description)
{
String rtn = description;
return rtn;
}
static String _fill(Uint32 count)
{
String str;
for (Uint32 i = 0 ; i < count ; i++)
{
str.append(' ');
}
return str;
}
// Indents a String including all
String indentString(
const String& input,
Uint32 leftMargin,
Boolean indentFirstLine )
{
String fill = _fill(leftMargin);
String output;
if (indentFirstLine)
{
output.append(fill);
}
for (Uint32 i = 0 ; i < input.size(); i++ )
{
if (input[i] == '\n')
{
output.append(input[i]);
output.append(fill);
}
else
{
output.append(input[i]);
}
}
return output;
}
int main()
{
verbose = getenv ("PEGASUS_TEST_VERBOSE") ? true : false;
/*
Function to output the full text of all messages in the
configPropertyDescriptionList to a file in a form compatible with
the message bundle format. This is used ONLY as a way to generate
input for the Message bundle rather than to try to manually keep
the bundle and these files in sync.
*/
String out = indentString(
"// ==START_CONFIG_PROPERTY_HELP MSGS==========================\n"
"// Description Messages for ConfigPropertyHelp\n"
"// These messages do not have a number prefix.\n"
"// These msgs are auto-generated by Config/tests/BldMsgBndl\n"
"// and are defined in source file\n"
"// Pegasus/Config/ConfigPropertyOwner.cpp\n"
"// Do NOT translate words or phrases enclosed in single\n"
"// quotes (ex 'required').\n"
"// PLEASE auto-generate this if config property help messages "
" change.\n"
"// ==========================================================\n",
8, true);
out.append("\n");
for (Uint32 i = 0; i < configPropertyDescriptionListSize ; i++)
{
String description = _descriptionWithPrefix(
configPropertyDescriptionList[i].Description);
String fixedDescription;
// Map selected characters to get correct output for the bundle
// /n maps to new line representation in output string, quote
// new line indent, newline to show the \n to the translator
// It also fixes any internalized double quotes so that a \" is output
//
for (Uint32 j = 0; j < description.size(); j++)
{
switch (description[j])
{
case '\n':
fixedDescription.append("\\n\"\n \"");
break;
case '\"':
fixedDescription.append("\\\"");
break;
default:
fixedDescription.append(description[j]);
}
}
// Output data for the pegasusServer_en.txt file for this
// key where key includes config property name.
// Indenting these lines is handled during the mapping to
// fixedDescription.
out.append( " " );
out.append(_createKey(
configPropertyDescriptionList[i].name));
out.append( ":string {\"");
out.append(fixedDescription);
out.append("\"}");
out.append("\n\n");
}
out.append(indentString(
"// ==END_CONFIG_PROPERTY_HELP MSGS "
"DO NOT HAND EDIT THE ABOVE==========",
8, true));
out.append("\n\n");
cout << out;
return 0;
}
| 35.315217 | 80 | 0.58618 | natronkeltner |
c4460696fcf299459176912295c98084eea6094e | 6,149 | cpp | C++ | examples_tests/07.HardwareSkinning/main.cpp | Crisspl/Nabla | 8e2ff2551113b2837513b188a8f16ef70adc9f81 | [
"Apache-2.0"
] | null | null | null | examples_tests/07.HardwareSkinning/main.cpp | Crisspl/Nabla | 8e2ff2551113b2837513b188a8f16ef70adc9f81 | [
"Apache-2.0"
] | 2 | 2021-04-28T21:42:36.000Z | 2021-06-02T22:52:33.000Z | examples_tests/07.HardwareSkinning/main.cpp | Crisspl/Nabla | 8e2ff2551113b2837513b188a8f16ef70adc9f81 | [
"Apache-2.0"
] | 1 | 2021-05-31T20:33:28.000Z | 2021-05-31T20:33:28.000Z | #define _IRR_STATIC_LIB_
#include <irrlicht.h>
#include "../../ext/ScreenShot/ScreenShot.h"
#include "../common/QToQuitEventReceiver.h"
using namespace irr;
using namespace core;
class SimpleCallBack : public video::IShaderConstantSetCallBack
{
int32_t mvpUniformLocation;
int32_t cameraDirUniformLocation;
video::E_SHADER_CONSTANT_TYPE mvpUniformType;
video::E_SHADER_CONSTANT_TYPE cameraDirUniformType;
public:
SimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {}
virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants)
{
for (size_t i = 0; i<constants.size(); i++)
{
if (constants[i].name == "MVP")
{
mvpUniformLocation = constants[i].location;
mvpUniformType = constants[i].type;
}
else if (constants[i].name == "cameraPos")
{
cameraDirUniformLocation = constants[i].location;
cameraDirUniformType = constants[i].type;
}
}
}
virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData)
{
core::vectorSIMDf modelSpaceCamPos;
modelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation());
if (cameraDirUniformLocation != -1)
services->setShaderConstant(&modelSpaceCamPos, cameraDirUniformLocation, cameraDirUniformType, 1);
if (mvpUniformLocation != -1)
services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(), mvpUniformLocation, mvpUniformType, 1);
}
virtual void OnUnsetMaterial() {}
};
int main()
{
// create device with full flexibility over creation parameters
// you can add more parameters if desired, check irr::SIrrlichtCreationParameters
irr::SIrrlichtCreationParameters params;
params.Bits = 24; //may have to set to 32bit for some platforms
params.ZBufferBits = 24; //we'd like 32bit here
params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing
params.WindowSize = dimension2d<uint32_t>(1280, 720);
params.Fullscreen = false;
params.Vsync = false;
params.Doublebuffer = true;
params.Stencilbuffer = false; //! This will not even be a choice soon
IrrlichtDevice* device = createDeviceEx(params);
if (device == 0)
return 1; // could not create selected driver.
video::IVideoDriver* driver = device->getVideoDriver();
SimpleCallBack* cb = new SimpleCallBack();
video::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert",
"", "", "", //! No Geometry or Tessellation Shaders
"../mesh.frag",
3, video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only
cb, //! Our Shader Callback
0); //! No custom user data
cb->drop();
scene::ISceneManager* smgr = device->getSceneManager();
driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
scene::ICameraSceneNode* camera =
smgr->addCameraSceneNodeFPS(0, 100.0f, 0.01f);
camera->setPosition(core::vector3df(-4, 0, 0));
camera->setTarget(core::vector3df(0, 0, 0));
camera->setNearValue(0.01f);
camera->setFarValue(250.0f);
smgr->setActiveCamera(camera);
device->getCursorControl()->setVisible(false);
QToQuitEventReceiver receiver;
device->setEventReceiver(&receiver);
io::IFileSystem* fs = device->getFileSystem();
#define kInstanceSquareSize 10
scene::ISceneNode* instancesToRemove[kInstanceSquareSize*kInstanceSquareSize] = { 0 };
asset::IAssetLoader::SAssetLoadParams lparams;
auto cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*device->getAssetManager()->getAsset("../../media/dwarf.baw", lparams).getContents().begin());
if (cpumesh&&cpumesh->getMeshType() == asset::EMT_ANIMATED_SKINNED)
{
scene::ISkinnedMeshSceneNode* anode = 0;
auto manipulator = device->getAssetManager()->getMeshManipulator();
for (size_t x = 0; x<kInstanceSquareSize; x++)
for (size_t z = 0; z<kInstanceSquareSize; z++)
{
auto duplicate = manipulator->createMeshDuplicate(cpumesh.get());
auto gpumesh = std::move(driver->getGPUObjectsFromAssets(&duplicate.get(), &duplicate.get()+1)->operator[](0u));
instancesToRemove[x + kInstanceSquareSize*z] = anode = smgr->addSkinnedMeshSceneNode(core::smart_refctd_ptr_static_cast<video::IGPUSkinnedMesh>(gpumesh));
anode->setScale(core::vector3df(0.05f));
anode->setPosition(core::vector3df(x, 0.f, z)*4.f);
anode->setAnimationSpeed(18.f*float(x + 1 + (z + 1)*kInstanceSquareSize) / float(kInstanceSquareSize*kInstanceSquareSize));
for (auto i = 0u; i < gpumesh->getMeshBufferCount(); i++)
{
auto& material = gpumesh->getMeshBuffer(i)->getMaterial();
material.MaterialType = newMaterialType;
material.setTexture(3u, core::smart_refctd_ptr<video::ITextureBufferObject>(anode->getBonePoseTBO()));
}
}
}
uint64_t lastFPSTime = 0;
while (device->run() && receiver.keepOpen())
//if (device->isWindowActive())
{
driver->beginScene(true, true, video::SColor(255, 0, 0, 255));
//! This animates (moves) the camera and sets the transforms
//! Also draws the meshbuffer
smgr->drawAll();
driver->endScene();
// display frames per second in window title
uint64_t time = device->getTimer()->getRealTime();
if (time - lastFPSTime > 1000)
{
std::wostringstream str;
str << L"Builtin Nodes Demo - Irrlicht Engine [" << driver->getName() << "] FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn();
device->setWindowCaption(str.str());
lastFPSTime = time;
}
}
for (size_t x = 0; x<kInstanceSquareSize; x++)
for (size_t z = 0; z<kInstanceSquareSize; z++)
instancesToRemove[x + kInstanceSquareSize*z]->remove();
//create a screenshot
{
core::rect<uint32_t> sourceRect(0, 0, params.WindowSize.Width, params.WindowSize.Height);
ext::ScreenShot::dirtyCPUStallingScreenshot(driver, device->getAssetManager(), "screenshot.png", sourceRect, asset::EF_R8G8B8_SRGB);
}
device->drop();
return 0;
}
| 35.959064 | 175 | 0.733615 | Crisspl |
c446fbaec4e11b32e672213929f1c501ec9605f8 | 352 | cpp | C++ | exercises/4.4.2/main.cpp | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | exercises/4.4.2/main.cpp | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | exercises/4.4.2/main.cpp | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | #include "contact.h"
#include "contactlist.h"
#include "contactfactory.h"
#include <QTextStream>
int main(int argc, char *argv[])
{
QTextStream out(stdout);
ContactFactory cf;
ContactList cl;
cf.createRandomContacts(cl, 10);
for (int i = 0; i < cl.count(); ++i) {
Contact c = cl.at(i);
out << c << "\n";
}
};
| 18.526316 | 42 | 0.585227 | PatrickTrentin88 |
c448de0cde57393a668990a66beed745ce0007ac | 3,075 | cpp | C++ | ad_map_access/src/point/BoundingSphereOperation.cpp | woojinjjang/map-1 | d12bb410f03d078a995130b4e671746ace8b6287 | [
"MIT"
] | 61 | 2019-12-19T20:57:24.000Z | 2022-03-29T15:20:51.000Z | ad_map_access/src/point/BoundingSphereOperation.cpp | woojinjjang/map-1 | d12bb410f03d078a995130b4e671746ace8b6287 | [
"MIT"
] | 54 | 2020-04-05T05:32:47.000Z | 2022-03-15T18:42:33.000Z | ad_map_access/src/point/BoundingSphereOperation.cpp | woojinjjang/map-1 | d12bb410f03d078a995130b4e671746ace8b6287 | [
"MIT"
] | 31 | 2019-12-20T07:37:39.000Z | 2022-03-16T13:06:16.000Z | // ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2018-2021 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#include "ad/map/point/BoundingSphereOperation.hpp"
namespace ad {
namespace map {
namespace point {
void expandBounds(point::ECEFPoint &upperBound, point::ECEFPoint &lowerBound, point::ECEFPoint const &point)
{
upperBound.x = std::max(upperBound.x, point.x);
upperBound.y = std::max(upperBound.y, point.y);
upperBound.z = std::max(upperBound.z, point.z);
lowerBound.x = std::min(lowerBound.x, point.x);
lowerBound.y = std::min(lowerBound.y, point.y);
lowerBound.z = std::min(lowerBound.z, point.z);
}
point::BoundingSphere calcBoundingSphere(Geometry const &geometryLeft, Geometry const &geometryRight)
{
point::BoundingSphere boundingSphere;
if (geometryLeft.ecefEdge.empty() && geometryRight.ecefEdge.empty())
{
return boundingSphere;
}
point::ECEFPoint upperBound;
point::ECEFPoint lowerBound;
if (geometryLeft.ecefEdge.empty())
{
upperBound = geometryRight.ecefEdge.front();
}
else
{
upperBound = geometryLeft.ecefEdge.front();
}
lowerBound = upperBound;
for (auto const &point : geometryLeft.ecefEdge)
{
expandBounds(upperBound, lowerBound, point);
}
for (auto const &point : geometryRight.ecefEdge)
{
expandBounds(upperBound, lowerBound, point);
}
point::ECEFPoint const diagonalVector = upperBound - lowerBound;
auto diagonalVectorLength = point::vectorLength(diagonalVector);
boundingSphere.radius = 0.5 * diagonalVectorLength;
boundingSphere.center = lowerBound + 0.5 * diagonalVector;
return boundingSphere;
}
} // namespace point
} // namespace map
} // namespace ad
::ad::map::point::BoundingSphere operator+(::ad::map::point::BoundingSphere const &a,
::ad::map::point::BoundingSphere const &b)
{
::ad::map::point::BoundingSphere result;
::ad::map::point::BoundingSphere const *small;
::ad::map::point::BoundingSphere const *large;
if (a.radius < b.radius)
{
small = &a;
large = &b;
}
else
{
small = &b;
large = &a;
}
auto const fromLargeToSmallCenter = small->center - large->center;
auto const sphereCenterDistance = ::ad::map::point::vectorLength(fromLargeToSmallCenter);
// move the center of the larger sphere in direction of the smaller one
// and increase the larger radius by the moving distance
auto const displacement = 0.5 * (sphereCenterDistance - large->radius + small->radius);
if (displacement <= ::ad::physics::Distance(0.))
{
// small is already within large
result = *large;
}
else if (sphereCenterDistance == ::ad::physics::Distance(0.))
{
// tiny center distance
result = *large;
}
else
{
result.center
= large->center + ::ad::physics::Distance(displacement / sphereCenterDistance) * (fromLargeToSmallCenter);
result.radius = large->radius + displacement;
}
return result;
}
| 28.211009 | 112 | 0.663415 | woojinjjang |
c449c846ca94f3a68d09ce129de727b925a62c83 | 221 | cpp | C++ | Os/MemCommon.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 9,182 | 2017-07-06T15:51:35.000Z | 2022-03-30T11:20:33.000Z | Os/MemCommon.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 719 | 2017-07-14T17:56:01.000Z | 2022-03-31T02:41:35.000Z | Os/MemCommon.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 1,216 | 2017-07-12T15:41:08.000Z | 2022-03-31T21:44:37.000Z | #include <Os/Mem.hpp>
#include <cstring>
namespace Os {
U32 Mem::virtToPhys(U32 virtAddr) {
return virtAddr;
}
U32 Mem::physToVirt(U32 physAddr) {
return physAddr;
}
}
| 13.8125 | 39 | 0.552036 | AlperenCetin0 |
c44a0627e809de0fb6c2b324059d3a75c1dda6ab | 6,723 | cpp | C++ | src/shogun/classifier/FeatureBlockLogisticRegression.cpp | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | src/shogun/classifier/FeatureBlockLogisticRegression.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | src/shogun/classifier/FeatureBlockLogisticRegression.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* 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 3 of the License, or
* (at your option) any later version.
*
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/classifier/FeatureBlockLogisticRegression.h>
#include <shogun/lib/slep/slep_solver.h>
#include <shogun/lib/slep/slep_options.h>
#include <shogun/lib/IndexBlockGroup.h>
#include <shogun/lib/IndexBlockTree.h>
namespace shogun
{
CFeatureBlockLogisticRegression::CFeatureBlockLogisticRegression() :
CLinearMachine()
{
init();
register_parameters();
}
CFeatureBlockLogisticRegression::CFeatureBlockLogisticRegression(
float64_t z, CDotFeatures* train_features,
CBinaryLabels* train_labels, CIndexBlockRelation* feature_relation) :
CLinearMachine()
{
init();
set_feature_relation(feature_relation);
set_z(z);
set_features(train_features);
set_labels(train_labels);
register_parameters();
}
void CFeatureBlockLogisticRegression::init()
{
m_feature_relation=NULL;
m_z=0.0;
m_q=2.0;
m_termination=0;
m_regularization=0;
m_tolerance=1e-3;
m_max_iter=1000;
}
CFeatureBlockLogisticRegression::~CFeatureBlockLogisticRegression()
{
SG_UNREF(m_feature_relation);
}
void CFeatureBlockLogisticRegression::register_parameters()
{
SG_ADD((CSGObject**)&m_feature_relation, "feature_relation", "feature relation", MS_NOT_AVAILABLE);
SG_ADD(&m_z, "z", "regularization coefficient", MS_AVAILABLE);
SG_ADD(&m_q, "q", "q of L1/Lq", MS_AVAILABLE);
SG_ADD(&m_termination, "termination", "termination", MS_NOT_AVAILABLE);
SG_ADD(&m_regularization, "regularization", "regularization", MS_NOT_AVAILABLE);
SG_ADD(&m_tolerance, "tolerance", "tolerance", MS_NOT_AVAILABLE);
SG_ADD(&m_max_iter, "max_iter", "maximum number of iterations", MS_NOT_AVAILABLE);
}
CIndexBlockRelation* CFeatureBlockLogisticRegression::get_feature_relation() const
{
SG_REF(m_feature_relation);
return m_feature_relation;
}
void CFeatureBlockLogisticRegression::set_feature_relation(CIndexBlockRelation* feature_relation)
{
SG_REF(feature_relation);
SG_UNREF(m_feature_relation);
m_feature_relation = feature_relation;
}
int32_t CFeatureBlockLogisticRegression::get_max_iter() const
{
return m_max_iter;
}
int32_t CFeatureBlockLogisticRegression::get_regularization() const
{
return m_regularization;
}
int32_t CFeatureBlockLogisticRegression::get_termination() const
{
return m_termination;
}
float64_t CFeatureBlockLogisticRegression::get_tolerance() const
{
return m_tolerance;
}
float64_t CFeatureBlockLogisticRegression::get_z() const
{
return m_z;
}
float64_t CFeatureBlockLogisticRegression::get_q() const
{
return m_q;
}
void CFeatureBlockLogisticRegression::set_max_iter(int32_t max_iter)
{
ASSERT(max_iter>=0)
m_max_iter = max_iter;
}
void CFeatureBlockLogisticRegression::set_regularization(int32_t regularization)
{
ASSERT(regularization==0 || regularization==1)
m_regularization = regularization;
}
void CFeatureBlockLogisticRegression::set_termination(int32_t termination)
{
ASSERT(termination>=0 && termination<=4)
m_termination = termination;
}
void CFeatureBlockLogisticRegression::set_tolerance(float64_t tolerance)
{
ASSERT(tolerance>0.0)
m_tolerance = tolerance;
}
void CFeatureBlockLogisticRegression::set_z(float64_t z)
{
m_z = z;
}
void CFeatureBlockLogisticRegression::set_q(float64_t q)
{
m_q = q;
}
bool CFeatureBlockLogisticRegression::train_machine(CFeatures* data)
{
if (data && (CDotFeatures*)data)
set_features((CDotFeatures*)data);
ASSERT(features)
ASSERT(m_labels)
int32_t n_vecs = m_labels->get_num_labels();
SGVector<float64_t> y(n_vecs);
for (int32_t i=0; i<n_vecs; i++)
y[i] = ((CBinaryLabels*)m_labels)->get_label(i);
slep_options options = slep_options::default_options();
options.q = m_q;
options.regularization = m_regularization;
options.termination = m_termination;
options.tolerance = m_tolerance;
options.max_iter = m_max_iter;
options.loss = LOGISTIC;
EIndexBlockRelationType relation_type = m_feature_relation->get_relation_type();
switch (relation_type)
{
case GROUP:
{
CIndexBlockGroup* feature_group = (CIndexBlockGroup*)m_feature_relation;
SGVector<index_t> ind = feature_group->get_SLEP_ind();
options.ind = ind.vector;
options.n_feature_blocks = ind.vlen-1;
if (ind[ind.vlen-1] > features->get_dim_feature_space())
SG_ERROR("Group of features covers more features than available\n")
options.gWeight = SG_MALLOC(double, options.n_feature_blocks);
for (int32_t i=0; i<options.n_feature_blocks; i++)
options.gWeight[i] = 1.0;
options.mode = FEATURE_GROUP;
options.loss = LOGISTIC;
options.n_nodes = 0;
slep_result_t result = slep_solver(features, y.vector, m_z, options);
SG_FREE(options.gWeight);
int32_t n_feats = features->get_dim_feature_space();
SGVector<float64_t> new_w(n_feats);
for (int i=0; i<n_feats; i++)
new_w[i] = result.w[i];
set_bias(result.c[0]);
w = new_w;
}
break;
case TREE:
{
CIndexBlockTree* feature_tree = (CIndexBlockTree*)m_feature_relation;
SGVector<float64_t> ind_t = feature_tree->get_SLEP_ind_t();
SGVector<float64_t> G;
if (feature_tree->is_general())
{
G = feature_tree->get_SLEP_G();
options.general = true;
}
options.ind_t = ind_t.vector;
options.G = G.vector;
options.n_nodes = ind_t.vlen/3;
options.n_feature_blocks = ind_t.vlen/3;
options.mode = FEATURE_TREE;
options.loss = LOGISTIC;
slep_result_t result = slep_solver(features, y.vector, m_z, options);
int32_t n_feats = features->get_dim_feature_space();
SGVector<float64_t> new_w(n_feats);
for (int i=0; i<n_feats; i++)
new_w[i] = result.w[i];
set_bias(result.c[0]);
w = new_w;
}
break;
default:
SG_ERROR("Not supported feature relation type\n")
}
return true;
}
float64_t CFeatureBlockLogisticRegression::apply_one(int32_t vec_idx)
{
return CMath::exp(-(features->dense_dot(vec_idx, w.vector, w.vlen) + bias));
}
SGVector<float64_t> CFeatureBlockLogisticRegression::apply_get_outputs(CFeatures* data)
{
if (data)
{
if (!data->has_property(FP_DOT))
SG_ERROR("Specified features are not of type CDotFeatures\n")
set_features((CDotFeatures*) data);
}
if (!features)
return SGVector<float64_t>();
int32_t num=features->get_num_vectors();
ASSERT(num>0)
ASSERT(w.vlen==features->get_dim_feature_space())
float64_t* out=SG_MALLOC(float64_t, num);
features->dense_dot_range(out, 0, num, NULL, w.vector, w.vlen, bias);
for (int32_t i=0; i<num; i++)
out[i] = 2.0/(1.0+CMath::exp(-out[i])) - 1.0;
return SGVector<float64_t>(out,num);
}
}
| 25.660305 | 100 | 0.754425 | srgnuclear |
c44a87df8b1fe729708ce05a2d1d2a0766fff0d8 | 1,587 | cpp | C++ | Source/Controllers/Corsair/CorsairController.cpp | pramberg/DeviceRGB | a2020b2b5accb1fc864c16905c35c352d3e4f39b | [
"MIT"
] | 3 | 2021-08-12T16:13:22.000Z | 2022-02-26T05:54:06.000Z | Source/Controllers/Corsair/CorsairController.cpp | pramberg/DeviceRGB | a2020b2b5accb1fc864c16905c35c352d3e4f39b | [
"MIT"
] | 12 | 2021-08-11T09:00:36.000Z | 2021-11-06T16:04:55.000Z | Source/Controllers/Corsair/CorsairController.cpp | pramberg/DeviceRGB | a2020b2b5accb1fc864c16905c35c352d3e4f39b | [
"MIT"
] | null | null | null | // Copyright(c) 2021 Viktor Pramberg
#include "CorsairController.h"
#include <Interfaces/IPluginManager.h>
#include "CorsairDevice.h"
#include "DeviceRGB.h"
#include <CUESDK.h>
FCorsairController::FCorsairController()
{
const FString BaseDir = IPluginManager::Get().FindPlugin("DeviceRGB")->GetBaseDir();
const FString LibraryPath = FPaths::Combine(*BaseDir, TEXT("Source/ThirdParty/CUESDK/redist/x64/CUESDK.x64_2017.dll"));
SDKHandle = FPlatformProcess::GetDllHandle(*LibraryPath);
}
FCorsairController::~FCorsairController()
{
FPlatformProcess::FreeDllHandle(SDKHandle);
SDKHandle = nullptr;
}
TUniquePtr<FCorsairController> FCorsairController::Construct()
{
auto Controller = TUniquePtr<FCorsairController>(new FCorsairController());
if (!Controller->SDKHandle)
{
return nullptr;
}
CorsairPerformProtocolHandshake();
if (CorsairGetLastError())
{
UE_LOG(LogDeviceRGB, Display, TEXT("Failed to connect to Corsair CUE service."));
return nullptr;
}
for (int32 DeviceIndex = 0; DeviceIndex < CorsairGetDeviceCount(); DeviceIndex++)
{
Controller->AddDevice<FCorsairDevice>(DeviceIndex);
}
return MoveTemp(Controller);
}
void FCorsairController::FlushBuffers()
{
FlushBuffersImpl();
}
void FCorsairController::FlushBuffersImpl()
{
CorsairSetLedsColorsFlushBufferAsync([](void* Context, bool Result, CorsairError Error)
{
if (Error != CE_Success)
{
UE_LOG(LogDeviceRGB, Error, TEXT("Failed to flush Corsair color buffer"));
}
}, nullptr);
}
void FCorsairController::SetEnabled(bool bEnabled)
{
CorsairSetLayerPriority(bEnabled ? 255 : 0);
}
| 24.045455 | 120 | 0.759294 | pramberg |
c44be4f8fba288be41dc23c9d349f72f73b0c8cc | 1,158 | hpp | C++ | include/nornir/external/fastflow/ff/make_unique.hpp | DanieleDeSensi/Nornir | 60587824d6b0a6e61b8fc75bdea37c9fc69199c7 | [
"MIT"
] | 11 | 2020-12-16T22:44:08.000Z | 2022-03-30T00:52:58.000Z | include/nornir/external/fastflow/ff/make_unique.hpp | DanieleDeSensi/Nornir | 60587824d6b0a6e61b8fc75bdea37c9fc69199c7 | [
"MIT"
] | 1 | 2021-04-01T09:07:52.000Z | 2021-07-21T22:10:07.000Z | include/nornir/external/fastflow/ff/make_unique.hpp | DanieleDeSensi/Nornir | 60587824d6b0a6e61b8fc75bdea37c9fc69199c7 | [
"MIT"
] | 3 | 2020-12-21T18:47:43.000Z | 2021-11-20T19:48:45.000Z | #ifndef FF_MAKEUNIQUE_HPP
#define FF_MAKEUNIQUE_HPP
#include <memory>
#include <type_traits>
#include <utility>
#if __cplusplus < 201400L // to check
// C++11 implementation of make_unique
#if (__cplusplus >= 201103L) || (defined __GXX_EXPERIMENTAL_CXX0X__) || (defined(HAS_CXX11_VARIADIC_TEMPLATES))
template <typename T, typename... Args>
std::unique_ptr<T> make_unique_helper(std::false_type, Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <typename T, typename... Args>
std::unique_ptr<T> make_unique_helper(std::true_type, Args&&... args) {
static_assert(std::extent<T>::value == 0,
"make_unique<T[N]>() is forbidden, please use make_unique<T[]>().");
typedef typename std::remove_extent<T>::type U;
return std::unique_ptr<T>(new U[sizeof...(Args)]{std::forward<Args>(args)...});
}
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return make_unique_helper<T>(std::is_array<T>(), std::forward<Args>(args)...);
}
#endif
#else
using std::make_unique;// need to check if only the name is sufficient
#endif
#endif // FF_MAKEUNIQUE_HPP
| 28.243902 | 111 | 0.701209 | DanieleDeSensi |
c44c7f7ed528e1e6acde199cb5f205e7fb51537d | 14,535 | cpp | C++ | Source/Canvas/selectiontransformitem.cpp | erayzesen/turquoise2D | 33bd2e85169bba4c82c388c1619b2de55065eb7b | [
"Zlib"
] | 13 | 2020-05-24T23:52:48.000Z | 2020-12-01T02:43:03.000Z | Source/Canvas/selectiontransformitem.cpp | erayzesen/turquoise2D | 33bd2e85169bba4c82c388c1619b2de55065eb7b | [
"Zlib"
] | 3 | 2020-05-26T22:19:49.000Z | 2020-12-01T09:31:25.000Z | Source/Canvas/selectiontransformitem.cpp | erayzesen/turquoise2D | 33bd2e85169bba4c82c388c1619b2de55065eb7b | [
"Zlib"
] | 3 | 2020-05-26T01:35:20.000Z | 2020-05-26T13:51:07.000Z | #include "selectiontransformitem.h"
SelectionTransformItem::SelectionTransformItem(QList<QGraphicsItem*> _items,GraphicsScene * _scene,PropertiesItem *_propItem)
{
scene=_scene;
items=_items;
//(i) Defining anchor items for scale
rightBottomAnchor=new TransformAnchor(this,TransformTypes::Scale);
leftBottomAnchor=new TransformAnchor(this,TransformTypes::Scale);
rightTopAnchor=new TransformAnchor(this,TransformTypes::Scale);
leftTopAnchor=new TransformAnchor(this,TransformTypes::Scale);
//Defining items container, all items will add to the container.
itemsContainer=new QGraphicsItemGroup;
scene->addItem(itemsContainer);
scene->addItem(this);
rectItem=setRectItem();
this->setZValue(9999999999);
//rectItem->setFlag(QGraphicsItem::ItemStacksBehindParent);
/* (i) Order of creating transform Item; 1-add items 2-add transform tools 3-add rectangle item
*/
this->addItems();
UpdateContainerZOrder();
this->addTransformTools();
this->addToGroup(rectItem);
this->setFlag(QGraphicsItem::ItemIsMovable,true);
this->setFlag(QGraphicsItem::ItemIsFocusable,false);
this->setFlag(QGraphicsItem::ItemIsSelectable,false);
propItem=_propItem;
//Creating new properties item and add properties panel
GraphicsScene* gs=dynamic_cast<GraphicsScene*>(scene);
if(gs!=NULL){
if(propItem==NULL){
propItem=new PropertiesItem(this,gs->propPanel);
gs->propPanel->AddGameProperties(propItem);
}else{
propItem->transformItem=this;
propItem->UpdateTransformProp();
}
}
}
SelectionTransformItem::~SelectionTransformItem()
{
}
void SelectionTransformItem::UpdateContainer()
{
itemsContainer->setTransform(this->transform());
itemsContainer->setPos(this->scenePos());
itemsContainer->setRotation(this->rotation());
}
void SelectionTransformItem::UpdateContainerZOrder()
{
qreal minZOrder=999999999999;
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
minZOrder=selectedGameItem->zValue()<minZOrder ? selectedGameItem->zValue():minZOrder;
}
}
itemsContainer->setZValue(minZOrder);
}
void SelectionTransformItem::updateOrigin()
{
*originPoint=this->scenePos();
}
SelectionTransformRect* SelectionTransformItem::setRectItem()
{
//(i) Defining min max variables with big numbers as default.
float minX=items.count()==0 ? 0:10000000000;
float minY=items.count()==0 ? 0:10000000000;
float maxX=items.count()==0 ? 0:-10000000000;
float maxY=items.count()==0 ? 0:-10000000000;
float aloneItemRot;
if(items.count()==1){
//(i) if the user selected one item,we're getting actual size and defining new rect.
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(0));
QSizeF cgsize=selectedGameItem->actualSize();
minX=selectedGameItem->pos().x()-cgsize.width()/2;
minY=selectedGameItem->pos().y()-cgsize.height()/2;
maxX=selectedGameItem->pos().x()+cgsize.width()/2;
maxY=selectedGameItem->pos().y()+cgsize.height()/2;
aloneItemRot=0;
}else{
//(i) if the user selected multiple item, we're getting actual bounds from the item and checking min-max values
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
QPolygonF itemBounds=selectedGameItem->actualBounds(true);
for(int n=0;n<itemBounds.count();n++){
QPointF p=itemBounds.at(n);
minX=p.x()<minX ? p.x():minX;
minY=p.y()<minY ? p.y():minY;
maxX=p.x()>maxX ? p.x():maxX;
maxY=p.y()>maxY ? p.y():maxY;
}
}
}
}
selectorSize=new QSizeF(maxX-minX,maxY-minY);
//(i) We're creating transformRect according to min-max values in this period.
transformRect=new QRectF(-selectorSize->width()/2,-selectorSize->height()/2,selectorSize->width(),selectorSize->height());
currentRect=transformRect;
SelectionTransformRect *nRectItem=new SelectionTransformRect(this);
// Setting position of transformRect to origin.
nRectItem->setPos(minX+selectorSize->width()/2,minY+selectorSize->height()/2);
originPoint=new QPointF(minX+selectorSize->width()/2,minY+selectorSize->height()/2);
this->setPos(originPoint->x(),originPoint->y());
UpdateContainer();
if(items.count()==1) this->setRotation(aloneItemRot);
return nRectItem;
}
void SelectionTransformItem::addItems()
{
//(i) Adding all items into group.
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
QPointF delta=selectedGameItem->scenePos()-this->scenePos();
itemsContainer->addToGroup(selectedGameItem);
selectedGameItem->setPos(delta.x(),delta.y());
//selectedGameItem->setFlag(QGraphicsItem::ItemStacksBehindParent);
}
}
}
void SelectionTransformItem::dropItems()
{
//(i) Removing all items from group and clearing items array. Calculating the final item size for all items.
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
itemsContainer->removeFromGroup(selectedGameItem);
selectedGameItem->setSelected(false);
QPointF currentScale(selectedGameItem->transform().m11(),selectedGameItem->transform().m22());
QSize originalSize=selectedGameItem->pixmap().size();
QSizeF finalSize=QSizeF(currentScale.x()*originalSize.width(),currentScale.y()*originalSize.height());
QTransform tempTransform=QTransform();
}
}
items.clear();
}
void SelectionTransformItem::addTransformTools()
{
/*(i) Settings anchors for scale and rotate operations.
* If the user selects an item, we're setting the anchor positions to the item's actualBounds
* If the user selects multiple items, we're setting the anchor positions according to the transformItem's boundingRect values.
*/
if(!rectItem)
return;
int rectSize=8;
QPolygonF points(4);
if(items.count()==1){
GameItem *gitem=dynamic_cast<GameItem*>(items.at(0));
if(gitem){
points=gitem->actualBounds(true);
}
}else{
points[0]=QPointF(originPoint->x()-rectItem->boundingRect().width()/2,originPoint->y()-rectItem->boundingRect().height()/2);
points[1]=QPointF(originPoint->x()+rectItem->boundingRect().width()/2,originPoint->y()-rectItem->boundingRect().height()/2);
points[2]=QPointF(originPoint->x()+rectItem->boundingRect().width()/2,originPoint->y()+rectItem->boundingRect().height()/2);
points[3]=QPointF(originPoint->x()-rectItem->boundingRect().width()/2,originPoint->y()+rectItem->boundingRect().height()/2);
}
leftTopAnchor->setPos(points.at(0));
leftTopAnchor->setZValue(100000000);
leftTopAnchor->UpdateDeltaFromOrigin();
this->addToGroup(leftTopAnchor);
rightTopAnchor->setPos(points.at(1));
rightTopAnchor->setZValue(100000000);
rightTopAnchor->UpdateDeltaFromOrigin();
this->addToGroup(rightTopAnchor);
rightBottomAnchor->setPos(points.at(2));
rightBottomAnchor->setZValue(100000000);
rightBottomAnchor->UpdateDeltaFromOrigin();
this->addToGroup(rightBottomAnchor);
leftBottomAnchor->setPos(points.at(3));
leftBottomAnchor->setZValue(100000000);
leftBottomAnchor->UpdateDeltaFromOrigin();
this->addToGroup(leftBottomAnchor);
TransformAnchor *originAnchor=new TransformAnchor(this,TransformTypes::Origin);
originAnchor->setPos(this->originPoint->x(),this->originPoint->y());
this->addToGroup(originAnchor);
}
bool SelectionTransformItem::checkScaleCursor(QGraphicsSceneMouseEvent *mouseEvent)
{
/* (i) Checking if mouse position is in the scale anchor and setting application cursor.*/
bool tmp=false;
QGraphicsItem *mouseOverItem=scene->itemAt(mouseEvent->scenePos(),QTransform());
if(mouseOverItem){
TransformAnchor *overedAnchor=dynamic_cast<TransformAnchor*>(mouseOverItem);
if(overedAnchor){
QPointF go=overedAnchor->transformGroup->scenePos(); // Group Origin
QPointF tp=overedAnchor->scenePos();
if((tp.x()>go.x() && tp.y()>go.y()) || (tp.x()<go.x() && tp.y()<go.y())){
scene->view->setMouseCursor(QCursor(Qt::SizeFDiagCursor));
tmp=true;
}else if((tp.x()<go.x() && tp.y()>go.y()) || (tp.x()>go.x() && tp.y()<go.y())){
scene->view->setMouseCursor(QCursor(Qt::SizeBDiagCursor));
tmp=true;
}
}
}
return tmp;
}
bool SelectionTransformItem::checkRotateCursor(QGraphicsSceneMouseEvent *mouseEvent)
{
/*(i) Checking if mouse position distance between enough for rotate transform.
* And setting cursor, calculating cursor angle according to the between the origin and mousePosition.
*/
bool tmp=false;
bool cond1=this->rightBottomAnchor->checkRotationDistance(mouseEvent->scenePos());
bool cond2=this->leftBottomAnchor->checkRotationDistance(mouseEvent->scenePos());
bool cond3=this->leftTopAnchor->checkRotationDistance(mouseEvent->scenePos());
bool cond4=this->rightTopAnchor->checkRotationDistance(mouseEvent->scenePos());
if(cond1 || cond2 || cond3 || cond4){
QPixmap cursor(":/mouseIcons/rotate_mouse_cursor.png");
float angle=MathOperations::vectorToAngle(mouseEvent->scenePos(),*this->originPoint);
angle=qRadiansToDegrees(angle);
QTransform trans;
trans.rotate(angle-90);
cursor=cursor.transformed(trans,Qt::SmoothTransformation);
//qDebug()<<angle;
QCursor nCursor(cursor);
scene->view->setMouseCursor(nCursor);
tmp=true;
}
return tmp;
}
void SelectionTransformItem::updateLastRotation()
{
//(i) We need lastRotation variable because calculating delta rotation except old rotation. Delta rotation=lastRotation+resultAngle
lastRotation=this->rotation();
}
bool SelectionTransformItem::checkTransformCursor(QGraphicsSceneMouseEvent *mouseEvent)
{
//(i) Checking if the mouse position is over the transformitem. If it's true, we're setting mouse cursor as arrow.
bool tmp=false;
QGraphicsItem *mouseOverItem=scene->itemAt(mouseEvent->scenePos(),QTransform());
if(mouseOverItem){
SelectionTransformRect *overedTransformItem=dynamic_cast<SelectionTransformRect*>(mouseOverItem);
if(overedTransformItem){
scene->view->setMouseCursor(QCursor(Qt::ArrowCursor));
tmp=true;
}
}
return tmp;
}
void SelectionTransformItem::rotateTransform(QPointF p1, QPointF p2)
{
/* Calculating the angle between p1 and p2.
* p1 for begin angle (clicked mouse position)
* p2 for current angle (moving mouse position)
* Result angle is the endAngle-beginAngle. Because we need rotate according to the clicked point angle.
* Delta rotation is how many degree rotated item except the default rotation angle.
*/
float beginAngle=MathOperations::vectorToAngle(*this->originPoint,p1);
float endAngle=MathOperations::vectorToAngle(*this->originPoint,p2);
//qDebug()<<"begin: "<<beginAngle<<" end: "<<endAngle;
float resultAngle=endAngle-beginAngle;
resultAngle=qRadiansToDegrees(resultAngle);
//qDebug()<<"result: "<<resultAngle;
rotateTransform(resultAngle);
}
void SelectionTransformItem::rotateTransform(float angle)
{
deltaRotation=lastRotation+angle;
//reducing digits
deltaRotation=qRound(deltaRotation*100);
deltaRotation/=100;
this->setRotation(deltaRotation);
applyRotations();
this->UpdateContainer();
}
void SelectionTransformItem::UpdateBounds()
{
//(i) We need update the selectable area according to the current scale.
float w=transformRect->width()*this->transform().m11();
float h=transformRect->height()*this->transform().m22();
currentRect=new QRectF(-w/2,-h/2,w,h);
}
void SelectionTransformItem::applyRotations()
{
/* (i) Setting new rotation values of game items.
* We're using tempRotate for that. tempRotate is the angle before transform operation.
* We're adding delta rotation to the tempRotate value of item for set current item's rotation value.
*/
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
selectedGameItem->rotate=selectedGameItem->tempRotate+deltaRotation;
}
}
}
void SelectionTransformItem::applyScales()
{
/* (i) Setting new scale values of game items.
* We're using tempScale for that. tempScale is the scale value of item before transform operation.
* We're crossing tempScale values and transformItem current scale values for calculating new item's scale.
*/
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
selectedGameItem->scale.setWidth(selectedGameItem->tempScale.width()*(this->transform().m11()));
selectedGameItem->scale.setHeight(selectedGameItem->tempScale.height()*(this->transform().m22()));
}
}
}
void SelectionTransformItem::rePrepareItems()
{
/*(i) We didn't use that function. We didn't need that for current version.
* This function re-prepare game items for transformations.
*/
for(int i=0;i<items.count();i++){
GameItem *selectedGameItem=dynamic_cast<GameItem*>(items.at(i));
if(selectedGameItem){
selectedGameItem->prepareTransform();
}
}
}
void SelectionTransformItem::updateAnchorTransforms(QPolygonF points)
{
}
void SelectionTransformItem::setNewScale(QPointF newScale,bool digitFilter)
{
//Setting scale with new value (we convert two-digit number)
QPointF filtScale=digitFilter==true ? MathOperations::setDigitFloat(newScale):newScale;
QTransform trans;
trans.scale(filtScale.x(),filtScale.y());
this->setTransform(trans);
this->applyScales();
this->UpdateBounds();
this->propItem->UpdateTransformProp();
this->UpdateContainer();
}
| 38.76 | 135 | 0.684692 | erayzesen |
c44f77c396cd96c4c1070d239e652530745ad88b | 470 | hpp | C++ | src/systems/EntityTestSystem.hpp | gabriellanzer/Ravine-ECS | f96467508cd22d4f4b9230b6c5502da201869449 | [
"MIT"
] | 7 | 2019-09-10T10:22:52.000Z | 2021-11-23T02:54:10.000Z | src/systems/EntityTestSystem.hpp | gabriellanzer/Ravine-ECS | f96467508cd22d4f4b9230b6c5502da201869449 | [
"MIT"
] | null | null | null | src/systems/EntityTestSystem.hpp | gabriellanzer/Ravine-ECS | f96467508cd22d4f4b9230b6c5502da201869449 | [
"MIT"
] | null | null | null | #ifndef ENTITYTESTSYSTEM_HPP
#define ENTITYTESTSYSTEM_HPP
#include "components/Position.h"
#include "ravine/ecs.h"
#include "ravine/ecs/Entity.hpp"
using namespace rv;
class EntityTestSystem : public BaseSystem<EntityProxy, Position>
{
void update(double deltaTime, int32_t size, EntityProxy* const e, Position* const p) final
{
for (int32_t i = 0; i < size; i++)
{
fprintf(stdout, "|Ent(%u)|Pos(%.3f,%.3f)", e[i].entityId, p[i].x, p[i].y);
}
}
};
#endif | 22.380952 | 91 | 0.695745 | gabriellanzer |
c450fac68fa8df9625a6f1af5e900b7cee05546e | 424 | cpp | C++ | tests/src/string_ifind.cpp | scaryrawr/mtl | eea8e9c6662b613dc5098a2cb442a7b1522bf8f0 | [
"MIT"
] | null | null | null | tests/src/string_ifind.cpp | scaryrawr/mtl | eea8e9c6662b613dc5098a2cb442a7b1522bf8f0 | [
"MIT"
] | null | null | null | tests/src/string_ifind.cpp | scaryrawr/mtl | eea8e9c6662b613dc5098a2cb442a7b1522bf8f0 | [
"MIT"
] | null | null | null | #include <mtl/string.hpp>
#include <gtest/gtest.h>
TEST(StringIFind, RawString)
{
const char *str{"Hello World"};
ASSERT_EQ(mtl::string::ifind(str, "world"), 6);
}
TEST(StringIFind, BasicString)
{
std::string str{"Hello World"};
ASSERT_EQ(mtl::string::ifind(str, "world"), 6);
}
TEST(StringIFind, StringView)
{
std::string_view str{"Hello World"};
ASSERT_EQ(mtl::string::ifind(str, "world"), 6);
} | 21.2 | 51 | 0.658019 | scaryrawr |