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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
74db8bc40a132f317512b5305d8ad5d8edeba284 | 2,616 | cpp | C++ | Melone/Src/Melone/Renderer/BufferObj.cpp | Nightskies/Melone | eb735a97fa1416c1feffecaefb479d30ce6e21e2 | [
"MIT"
] | null | null | null | Melone/Src/Melone/Renderer/BufferObj.cpp | Nightskies/Melone | eb735a97fa1416c1feffecaefb479d30ce6e21e2 | [
"MIT"
] | null | null | null | Melone/Src/Melone/Renderer/BufferObj.cpp | Nightskies/Melone | eb735a97fa1416c1feffecaefb479d30ce6e21e2 | [
"MIT"
] | null | null | null | #include "mlpch.h"
#include "BufferObj.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLBufferObj.h"
namespace Melone
{
VBOElement::VBOElement(ShaderDataType elType, std::string elName, bool elNormalized)
:
type(elType),
name(std::move(elName)),
size(ShaderDataTypeSize(elType)),
normalized(elNormalized)
{}
unsigned int VBOElement::getComponentCount(void) const
{
switch (type)
{
case Melone::ShaderDataType::Float:
return 1;
case Melone::ShaderDataType::Float2:
return 2;
case Melone::ShaderDataType::Float3:
return 3;
case Melone::ShaderDataType::Float4:
return 4;
case Melone::ShaderDataType::Mat3:
return 9;
case Melone::ShaderDataType::Mat4:
return 16;
case Melone::ShaderDataType::Int:
return 1;
case Melone::ShaderDataType::Int2:
return 2;
case Melone::ShaderDataType::Int3:
return 3;
case Melone::ShaderDataType::Int4:
return 4;
case Melone::ShaderDataType::Bool:
return 1;
default:
MELONE_CORE_ASSERT(false, "Unknown shader data type");
return 0;
}
}
VBOLayout::VBOLayout(std::initializer_list<VBOElement> el)
:
mElements(std::move(el))
{
calculateOffsetAndStride();
}
void VBOLayout::calculateOffsetAndStride(void)
{
unsigned int offset = 0;
mStride = 0;
for (auto& el : mElements)
{
el.offset = offset;
offset += el.size;
mStride += el.size;
}
}
std::shared_ptr<VBO> VBO::create(unsigned int size)
{
switch (Renderer::getAPI())
{
case RendererAPI::API::Undefined:
MELONE_CORE_ASSERT(false, "RendererAPI is undefined");
return nullptr;
case RendererAPI::API::OpenGL:
return std::make_shared<OpenGLVBO>(size);
default:
MELONE_CORE_ASSERT(false, "Unknown renderer api");
return nullptr;
}
}
std::shared_ptr<VBO> VBO::create(float* vertices, unsigned int size)
{
switch (Renderer::getAPI())
{
case RendererAPI::API::Undefined:
MELONE_CORE_ASSERT(false, "RendererAPI is undefined");
return nullptr;
case RendererAPI::API::OpenGL:
return std::make_shared<OpenGLVBO>(vertices, size);
default:
MELONE_CORE_ASSERT(false, "Unknown renderer api");
return nullptr;
}
}
std::shared_ptr<IBO> IBO::create(unsigned int* indices, unsigned int count)
{
switch (Renderer::getAPI())
{
case RendererAPI::API::Undefined:
MELONE_CORE_ASSERT(false, "RendererAPI is undefined");
return nullptr;
case RendererAPI::API::OpenGL:
return std::make_shared<OpenGLIBO>(indices, count);
default:
MELONE_CORE_ASSERT(false, "Unknown renderer api");
return nullptr;
}
}
} | 21.8 | 85 | 0.689985 | Nightskies |
74ddd42c331ae4ae26f5b34afaba95046ccbfe55 | 4,899 | cc | C++ | chrome/browser/ui/gtk/download/download_item_drag.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | chrome/browser/ui/gtk/download/download_item_drag.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | chrome/browser/ui/gtk/download/download_item_drag.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/gtk/download/download_item_drag.h"
#include "base/files/file_path.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/download/drag_download_item.h"
#include "content/public/browser/download_item.h"
#include "net/base/net_util.h"
#include "ui/base/dragdrop/gtk_dnd_util.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
using content::DownloadItem;
namespace {
const int kDownloadItemCodeMask = ui::TEXT_URI_LIST | ui::CHROME_NAMED_URL;
const GdkDragAction kDownloadItemDragAction = GDK_ACTION_COPY;
} // namespace
// Stores metadata for a drag & drop operation.
class DownloadItemDrag::DragData {
public:
// Constructs a DragData object based on the current state of |item|.
explicit DragData(const DownloadItem* item);
// Sets up a drag source and connects |drag_data| to 'drag-data-get' on
// |widget|. If |icon| is non-NULL it will be used as the drag icon. The
// object pointed to by |drag_data| will be deleted when the signal is
// disconnected.
static void AttachToWidget(scoped_ptr<DragData> drag_data,
GtkWidget* widget,
gfx::Image* icon);
// 'drag-data-get' signal handler.
CHROMEGTK_CALLBACK_4(DragData, void, OnDragDataGet, GdkDragContext*,
GtkSelectionData*, guint, guint);
private:
// GClosureNotify handler for destroying a DragData object. |data| is assumed
// to be a DragData*.
static void OnDestroy(gpointer data, GClosure* closure);
GURL url_;
base::string16 display_name_;
};
DownloadItemDrag::DragData::DragData(const DownloadItem* item)
: url_(net::FilePathToFileURL(item->GetTargetFilePath())),
display_name_(item->GetFileNameToReportUser().LossyDisplayName()) {
DCHECK_EQ(DownloadItem::COMPLETE, item->GetState());
}
// static
void DownloadItemDrag::DragData::AttachToWidget(scoped_ptr<DragData> drag_data,
GtkWidget* widget,
gfx::Image* icon) {
gtk_drag_source_set(
widget, GDK_BUTTON1_MASK, NULL, 0, kDownloadItemDragAction);
ui::SetSourceTargetListFromCodeMask(widget, kDownloadItemCodeMask);
// Disconnect previous signal handlers, if any.
g_signal_handlers_disconnect_matched(
widget,
G_SIGNAL_MATCH_FUNC,
0,
0,
NULL,
reinterpret_cast<gpointer>(&OnDragDataGetThunk),
NULL);
// Connect new signal handlers.
g_signal_connect_data(widget,
"drag-data-get",
G_CALLBACK(&OnDragDataGetThunk),
reinterpret_cast<gpointer>(drag_data.release()),
&OnDestroy,
static_cast<GConnectFlags>(0));
if (icon)
gtk_drag_source_set_icon_pixbuf(widget, icon->ToGdkPixbuf());
}
void DownloadItemDrag::DragData::OnDragDataGet(GtkWidget* widget,
GdkDragContext* context,
GtkSelectionData* selection_data,
guint target_type,
guint time) {
ui::WriteURLWithName(selection_data, url_, display_name_, target_type);
}
// static
void DownloadItemDrag::DragData::OnDestroy(gpointer data, GClosure* closure) {
DragData* drag_data = reinterpret_cast<DragData*>(data);
delete drag_data;
}
// DownloadItemDrag ------------------------------------------------------------
// static
void DownloadItemDrag::SetSource(GtkWidget* widget,
const DownloadItem* item,
gfx::Image* icon) {
scoped_ptr<DragData> drag_data(new DragData(item));
DragData::AttachToWidget(drag_data.Pass(), widget, icon);
}
DownloadItemDrag::DownloadItemDrag(const DownloadItem* item, gfx::Image* icon)
: CustomDrag(icon, kDownloadItemCodeMask, kDownloadItemDragAction),
drag_data_(new DragData(item)) {}
DownloadItemDrag::~DownloadItemDrag() {}
void DownloadItemDrag::OnDragDataGet(GtkWidget* widget,
GdkDragContext* context,
GtkSelectionData* selection_data,
guint target_type,
guint time) {
drag_data_->OnDragDataGet(widget, context, selection_data, target_type, time);
}
void DragDownloadItem(const content::DownloadItem* download,
gfx::Image* icon,
gfx::NativeView view) {
// This starts the drag process, the lifetime of this object is tied to the
// system drag.
new DownloadItemDrag(download, icon);
}
| 36.834586 | 80 | 0.636252 | nagineni |
74e3b25f2b47de23ec1355fc2c6b5dafdd6baaa1 | 1,070 | cpp | C++ | docs/assets/examples/try.cpp | IohannRabeson/lexy | 881beb56f030e8f4761514e70cb50d809ac4ad17 | [
"BSL-1.0"
] | null | null | null | docs/assets/examples/try.cpp | IohannRabeson/lexy | 881beb56f030e8f4761514e70cb50d809ac4ad17 | [
"BSL-1.0"
] | null | null | null | docs/assets/examples/try.cpp | IohannRabeson/lexy | 881beb56f030e8f4761514e70cb50d809ac4ad17 | [
"BSL-1.0"
] | null | null | null | #include <optional>
#include <lexy/callback.hpp>
#include <lexy/dsl.hpp>
#include <lexy/input/string_input.hpp>
#include <lexy/parse.hpp>
#include <lexy_ext/cfile.hpp>
#include <lexy_ext/report_error.hpp>
namespace dsl = lexy::dsl;
//{
struct version
{
std::optional<int> major, minor, patch;
};
struct production
{
static constexpr auto rule = [] {
// If we don't have an integer, recover by producing nullopt.
auto number = dsl::try_(dsl::integer<int>(dsl::digits<>), dsl::nullopt);
auto dot = dsl::try_(dsl::period);
return number + dot + number + dot + number;
}();
static constexpr auto value = lexy::construct<version>;
};
//}
int main()
{
auto input = lexy_ext::read_file<>(stdin);
auto result = lexy::parse<production>(input, lexy_ext::report_error);
if (!result.has_value())
return 1;
auto [major, minor, patch] = result.value();
std::printf("The value is: %d.%d.%d\n", major.value_or(0), minor.value_or(0),
patch.value_or(0));
return result ? 0 : 1;
}
| 24.318182 | 81 | 0.629907 | IohannRabeson |
74e47a7337eb25b058a9e4d072d7e4445832140e | 3,868 | cpp | C++ | libs/GameUI/controllers/NineSlicer.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | 3 | 2019-10-27T22:32:44.000Z | 2020-05-21T04:00:46.000Z | libs/GameUI/controllers/NineSlicer.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | null | null | null | libs/GameUI/controllers/NineSlicer.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | null | null | null | #include "stdafx.h"
#include "NineSlicer.h"
#include "GameUI/ContainerManager.h"
#include "GameUI/Container.h"
#include "GameUI/UIContext.h"
#include "RFType/CreateClassInfoDefinition.h"
#include "core_math/Lerp.h"
RFTYPE_CREATE_META( RF::ui::controller::NineSlicer )
{
RFTYPE_META().BaseClass<RF::ui::controller::InstancedController>();
RFTYPE_REGISTER_BY_QUALIFIED_NAME( RF::ui::controller::NineSlicer );
}
namespace RF::ui::controller {
///////////////////////////////////////////////////////////////////////////////
NineSlicer::NineSlicer()
{
for( bool& b : mSliceEnabled )
{
b = true;
}
}
NineSlicer::NineSlicer( bool const ( &sliceEnabled )[9] )
{
for( size_t i = 0; i < 9; i++ )
{
mSliceEnabled[i] = sliceEnabled[i];
}
}
ContainerID NineSlicer::GetChildContainerID( size_t sliceIndex ) const
{
return mContainers.at( sliceIndex );
}
void NineSlicer::CreateChildContainer( ContainerManager& manager, size_t sliceIndex )
{
CreateChildContainerInternal( manager, GetMutableContainer( manager, mParentContainerID ), sliceIndex );
}
void NineSlicer::DestroyChildContainer( ContainerManager& manager, size_t sliceIndex )
{
ContainerID& id = mContainers.at( sliceIndex );
if( id != kInvalidContainerID )
{
DestroyContainer( manager, id );
id = kInvalidContainerID;
mSliceEnabled[sliceIndex] = false;
}
else
{
RF_ASSERT( mSliceEnabled[sliceIndex] == false );
}
}
void NineSlicer::OnInstanceAssign( UIContext& context, Container& container )
{
mParentContainerID = container.mContainerID;
m0 = CreateAnchor( context.GetMutableContainerManager(), container );
m33 = CreateAnchor( context.GetMutableContainerManager(), container );
m66 = CreateAnchor( context.GetMutableContainerManager(), container );
m100 = CreateAnchor( context.GetMutableContainerManager(), container );
for( size_t i = 0; i < 9; i++ )
{
if( mSliceEnabled[i] == false )
{
mContainers[i] = kInvalidContainerID;
continue;
}
CreateChildContainerInternal( context.GetMutableContainerManager(), container, i );
}
}
void NineSlicer::OnAABBRecalc( UIContext& context, Container& container )
{
gfx::ppu::AABB const& aabb = container.mAABB;
gfx::ppu::CoordElem const x0 = aabb.Left();
gfx::ppu::CoordElem const x100 = aabb.Right();
gfx::ppu::CoordElem const x33 = math::Lerp( x0, x100, 1.f / 3.f );
gfx::ppu::CoordElem const x66 = math::Lerp( x0, x100, 2.f / 3.f );
gfx::ppu::CoordElem const y0 = aabb.Top();
gfx::ppu::CoordElem const y100 = aabb.Bottom();
gfx::ppu::CoordElem const y33 = math::Lerp( y0, y100, 1.f / 3.f );
gfx::ppu::CoordElem const y66 = math::Lerp( y0, y100, 2.f / 3.f );
MoveAnchor( context.GetMutableContainerManager(), m0, { x0, y0 } );
MoveAnchor( context.GetMutableContainerManager(), m33, { x33, y33 } );
MoveAnchor( context.GetMutableContainerManager(), m66, { x66, y66 } );
MoveAnchor( context.GetMutableContainerManager(), m100, { x100, y100 } );
}
///////////////////////////////////////////////////////////////////////////////
void NineSlicer::CreateChildContainerInternal( ContainerManager& manager, Container& container, size_t sliceIndex )
{
ContainerID& id = mContainers.at( sliceIndex );
if( id != kInvalidContainerID )
{
RF_DBGFAIL_MSG( "Container already exists" );
return;
}
AnchorID top;
AnchorID bottom;
if( sliceIndex < 3 )
{
top = m0;
bottom = m33;
}
else if( sliceIndex < 6 )
{
top = m33;
bottom = m66;
}
else
{
top = m66;
bottom = m100;
}
AnchorID left;
AnchorID right;
size_t const column = sliceIndex % 3;
if( column == 0 )
{
left = m0;
right = m33;
}
else if( column == 1 )
{
left = m33;
right = m66;
}
else
{
left = m66;
right = m100;
}
id = Controller::CreateChildContainer( manager, container, left, right, top, bottom );
}
///////////////////////////////////////////////////////////////////////////////
}
| 23.301205 | 115 | 0.65486 | max-delta |
74e4b1a8bf02b4a4a9d3056df3816ee1be31bef0 | 4,952 | cpp | C++ | source/rfid/source/rfid.cpp | hyphaproject/hyphaplugins | b41b396392c5546e3c2802bfc34213c5da04fdf4 | [
"MIT"
] | null | null | null | source/rfid/source/rfid.cpp | hyphaproject/hyphaplugins | b41b396392c5546e3c2802bfc34213c5da04fdf4 | [
"MIT"
] | 1 | 2017-02-18T10:51:07.000Z | 2017-02-18T10:51:07.000Z | source/rfid/source/rfid.cpp | hyphaproject/hyphaplugins | b41b396392c5546e3c2802bfc34213c5da04fdf4 | [
"MIT"
] | null | null | null | // Copyright (c) 2015-2016 Hypha
#include "hyphaplugins/rfid/rfid.h"
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <Poco/ClassLibrary.h>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QProcess>
#include <QtSerialPort/QSerialPortInfo>
using namespace hypha::plugin;
using namespace hypha::plugin::rfid;
void RFID::doWork() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// read card reader data
char buf[1024];
if (read_until(fd, buf, '\n') == 0) {
}
QString uid(buf);
uid = uid.remove(QRegExp("[ \\n\\t\\r]"));
if (uid.isEmpty() || uid.length() < 5) return;
// create json string with card id;
QJsonDocument document_out;
QJsonObject object_out;
QJsonArray devices =
QJsonArray::fromStringList(uid.split('\n', QString::SkipEmptyParts));
object_out.insert("source", QJsonValue(QString::fromStdString(getId())));
object_out.insert("devices", devices);
object_out.insert("devicetype", QJsonValue("rfid"));
document_out.setObject(object_out);
qDebug(uid.toStdString().c_str());
sendMessage(document_out.toJson().data());
std::this_thread::sleep_for(std::chrono::seconds(2));
}
void RFID::setup() {
struct termios toptions;
port.setPort(QSerialPortInfo::availablePorts().at(0));
QProcess process;
if (process.execute("stty -F /dev/ttyACM0 9600 -parenb -parodd cs8 -hupcl "
"-cstopb cread clocal -crtscts "
"-ignbrk -brkint -ignpar -parmrk inpck -istrip -inlcr "
"-igncr -icrnl -ixon -ixoff "
"-iuclc -ixany -imaxbel -iutf8 "
"-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill "
"-ofdel nl0 cr0 tab0 bs0 vt0 ff0 "
"-isig -icanon -iexten -echo -echoe -echok -echonl "
"-noflsh -xcase -tostop -echoprt "
"-echoctl -echoke ")) {
qDebug("tty options set");
}
port.setBaudRate(QSerialPort::Baud9600);
port.setParity(QSerialPort::NoParity);
port.setFlowControl(QSerialPort::NoFlowControl);
port.setDataBits(QSerialPort::Data8);
if (port.open(QIODevice::ReadWrite)) {
port.write("BEEP");
}
port.close();
// TODO: QSerialPort not working atm
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY);
std::this_thread::sleep_for(std::chrono::seconds(2));
tcgetattr(fd, &toptions);
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
toptions.c_lflag |= ICANON;
tcsetattr(fd, TCSANOW, &toptions);
beep();
beep();
beep();
}
int RFID::read_until(int fd, char *buf, char until) {
char b[1];
int i = 0;
do {
int n = read(fd, b, 1); // read a char at a time
if (n == -1) return -1; // couldn't read
if (n == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
buf[i] = b[0];
i++;
} while (b[0] != until);
buf[i] = 0; // null terminate the string
return 0;
}
std::string RFID::communicate(std::string UNUSED(message)) {
return getStatusMessage();
}
void RFID::loadConfig(std::string UNUSED(json)) {}
std::string RFID::getConfig() { return "{}"; }
hypha::plugin::HyphaPlugin *RFID::getInstance(std::string id) {
RFID *instance = new RFID();
instance->setId(id);
return instance;
}
void RFID::receiveMessage(std::string message) {
if (message.length() > 0) {
bool red = false;
bool green = false;
bool yellow = false;
bool door = false;
QJsonDocument document = QJsonDocument::fromJson(message.c_str());
QJsonObject object = document.object();
if (object.contains("beep")) {
beep();
}
if (object.contains("door")) {
door = object.value("door").toBool();
setDoor(door);
}
if (object.contains("red") || object.contains("green") ||
object.contains("yellow")) {
if (object.contains("red")) {
red = object.value("red").toBool();
}
if (object.contains("green")) {
green = object.value("green").toBool();
}
if (object.contains("yellow")) {
yellow = object.value("yellow").toBool();
}
setRGY(red, green, yellow);
}
}
}
void RFID::beep() { write(fd, "BEEP\n", 5); }
void RFID::setDoor(bool open) {
write(fd, open ? "DOOR_OPEN\n" : "DOOR_CLOSE\n", open ? 10 : 11);
}
void RFID::setRGY(bool red, bool green, bool yellow) {
write(fd, red ? "RED_ON\n" : "RED_OFF\n", red ? 7 : 8);
write(fd, green ? "GREEN_ON\n" : "GREEN_OFF\n", green ? 9 : 10);
write(fd, yellow ? "YELLOW_ON\n" : "YELLOW_OFF\n", yellow ? 10 : 11);
}
POCO_BEGIN_MANIFEST(HyphaPlugin)
POCO_EXPORT_CLASS(RFID)
POCO_END_MANIFEST
| 27.977401 | 77 | 0.624394 | hyphaproject |
74e516de859434b99d93ddcf03e82c71281ded97 | 504 | hh | C++ | Option/SquareDance/squaredance.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | Option/SquareDance/squaredance.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | Option/SquareDance/squaredance.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../option.hh"
#include "../OdoWalkTo/odowalkto.hh"
#include "../../MotionModule/WalkModule/walkmodule.hh"
namespace bold
{
class SquareDance : public Option
{
public:
SquareDance(std::string const& id, std::shared_ptr<WalkModule> walkModule);
OptionVector runPolicy() override;
private:
enum Stage
{
FORWARD,
RIGHT,
BACKWARD,
LEFT,
RESTART
};
Stage d_stage;
std::shared_ptr<OdoWalkTo> d_odoWalkTo;
};
}
| 16.258065 | 79 | 0.636905 | drewnoakes |
74e6f87843e903caabf0b62cb8af5d5cd1fea570 | 1,829 | hpp | C++ | libs/fnd/compare/include/bksge/fnd/compare/compare_three_way.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/compare/include/bksge/fnd/compare/compare_three_way.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/compare/include/bksge/fnd/compare/compare_three_way.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file compare_three_way.hpp
*
* @brief compare_three_way の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_COMPARE_COMPARE_THREE_WAY_HPP
#define BKSGE_FND_COMPARE_COMPARE_THREE_WAY_HPP
#include <bksge/fnd/compare/config.hpp>
#if defined(BKSGE_HAS_STD_COMPARE) && defined(BKSGE_HAS_CXX20_THREE_WAY_COMPARISON)
#if defined(BKSGE_USE_STD_COMPARE)
#include <compare>
namespace bksge
{
using std::compare_three_way;
} // namespace bksge
#else // defined(BKSGE_USE_STD_COMPARE)
#include <bksge/fnd/compare/detail/builtin_ptr_three_way.hpp>
#include <bksge/fnd/compare/concepts/three_way_comparable_with.hpp>
#include <bksge/fnd/config.hpp>
#include <type_traits> // is_constant_evaluated
#include <cstdint>
#include <utility>
namespace bksge
{
struct compare_three_way
{
template <typename T, typename U>
requires bksge::three_way_comparable_with<T, U> || detail::builtin_ptr_three_way<T, U>
constexpr auto operator()(T&& t, U&& u) const
noexcept(noexcept(std::declval<T>() <=> std::declval<U>()))
{
if constexpr (detail::builtin_ptr_three_way<T, U>)
{
auto pt = static_cast<void const volatile*>(t);
auto pu = static_cast<void const volatile*>(u);
#if defined(__cpp_lib_is_constant_evaluated) && __cpp_lib_is_constant_evaluated >= 201811
if (std::is_constant_evaluated())
{
return pt <=> pu;
}
#endif
auto it = reinterpret_cast<std::uintptr_t>(pt);
auto iu = reinterpret_cast<std::uintptr_t>(pu);
return it <=> iu;
}
else
{
return static_cast<T&&>(t) <=> static_cast<U&&>(u);
}
}
using is_transparent = void;
};
} // namespace bksge
#endif // defined(BKSGE_USE_STD_COMPARE)
#endif // defined(BKSGE_HAS_CXX20_THREE_WAY_COMPARISON)
#endif // BKSGE_FND_COMPARE_COMPARE_THREE_WAY_HPP
| 23.753247 | 90 | 0.708037 | myoukaku |
d55df69f1911e31ef3e8cd409cb73c42ebd35b99 | 1,288 | hpp | C++ | lib/arbimath/bigint/VectorUtil.hpp | waegemans/arbimath | d3408b6b75762bdb276b8d9cec6de54ebae913d0 | [
"MIT"
] | null | null | null | lib/arbimath/bigint/VectorUtil.hpp | waegemans/arbimath | d3408b6b75762bdb276b8d9cec6de54ebae913d0 | [
"MIT"
] | null | null | null | lib/arbimath/bigint/VectorUtil.hpp | waegemans/arbimath | d3408b6b75762bdb276b8d9cec6de54ebae913d0 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <string_view>
#include <vector>
namespace arbimath::vector_util {
/// add two vectors with given signs together and return resulting sign and magnitude
std::pair<bool, std::vector<uint64_t>> add(bool lhs_sign, const std::vector<uint64_t>& lhs, bool rhs_sign, const std::vector<uint64_t>& rhs);
/// subtract two vectors with given signs together and return resulting sign and magnitude
std::pair<bool, std::vector<uint64_t>> sub(bool lhs_sign, const std::vector<uint64_t>& lhs, bool rhs_sign, const std::vector<uint64_t>& rhs);
/// add two vectors together and returns the result
std::vector<uint64_t> addMagnitude(const std::vector<uint64_t>& lhs, const std::vector<uint64_t>& rhs);
/// subs two vectors together and returns the result. lhs must be larger then rhs
std::vector<uint64_t> subMagnitude(const std::vector<uint64_t>& lhs, const std::vector<uint64_t>& rhs);
/// converts an hex string without prefix to
std::vector<uint64_t> fromHexStringView(std::string_view stringView);
/// check if lhs is smaller then rhs
bool less(const std::vector<uint64_t>& lhs, const std::vector<uint64_t>& rhs);
bool hasLeadingZeros(const std::vector<uint64_t>& x);
void removeLeadingZeros(std::vector<uint64_t>& x);
} // namespace arbimath::vector_util
| 49.538462 | 141 | 0.763199 | waegemans |
d56022d6b0104b3fc55d7884289eb77b00de5581 | 10,572 | cpp | C++ | src/my_renderer.cpp | ldm0/my_soft_renderer | 25935e3e2ae1d8f0e7411ecc4b1abe6a60bd4497 | [
"WTFPL"
] | null | null | null | src/my_renderer.cpp | ldm0/my_soft_renderer | 25935e3e2ae1d8f0e7411ecc4b1abe6a60bd4497 | [
"WTFPL"
] | null | null | null | src/my_renderer.cpp | ldm0/my_soft_renderer | 25935e3e2ae1d8f0e7411ecc4b1abe6a60bd4497 | [
"WTFPL"
] | null | null | null | #include"my_renderer.h"
#include"my_graphic.h"
#include"my_obj_loader/my_obj_loader.h"
#include"SCG/scg.h"
#include<Windows.h>
#include<tchar.h>
#include<math.h>
Renderer::Renderer()
:draw_mode(DRAW_MESH),
yaw_pitch_roll({0}),
camera_position({0}),
back_buffer(0),
z_buffer(0),
v_buffer(0),
c_buffer(0),
mesh(0),
/*
texture_width(0),
texture_height(0),
texture(0),
*/
//window_exit(false),
alloc(0),
drop(0)
{
}
Renderer::~Renderer()
{
if (mesh) {
drop(v_buffer);
drop(c_buffer);
}
mesh = NULL;
}
void Renderer::v_shading(void)
{
if (draw_mode == DRAW_MESH)
return;
unsigned numf = mesh->num_f;
for (unsigned i = 0; i < numf; ++i) {
//float brightness = 0.1;
c_buffer[i].x = 0xff0000ff;
c_buffer[i].y = 0x00ff00ff;
c_buffer[i].z = 0x0000ffff;
}
}
void Renderer::projection(void)
{
unsigned numv = mesh->num_v;
for (unsigned i = 0; i < numv; ++i) {
f4 tmp_v = {
mesh->v_buffer[i].x,
mesh->v_buffer[i].y,
mesh->v_buffer[i].z,
1.f
};
tmp_v = view_space(&tmp_v, &camera_position, &yaw_pitch_roll);
v_buffer[i].x = tmp_v.x;
v_buffer[i].y = tmp_v.y;
v_buffer[i].z = tmp_v.z;
}
}
void Renderer::clipping(void)
{
// do nothing
}
void Renderer::screen_mapping(void)
{
int width = scg_window_width;
int height = scg_window_height;
unsigned numv = mesh->num_v;
for (unsigned i = 0; i < numv; ++i) {
float scale = fminf((float)width, (float)height);
v_buffer[i].x = v_buffer[i].x * scale + .5f * width;
// Negative sign for origin at top-left corner
v_buffer[i].y = -v_buffer[i].y * scale + .5f * height;
}
}
void Renderer::draw_line(f3 a, f3 b)
{
int width = scg_window_width;
int height = scg_window_height;
// z buffer is not needed when drawing line
float a_b_x = a.x - b.x;
float a_b_y = a.y - b.y;
float a_b_z = a.z - b.z;
unsigned line_color = 0x00ffffff;
if (fabsf(a_b_x) < fabsf(a_b_y)) {
int top = (int)clampf(fminf(a.y, b.y), 0, (float)height);
int bottom = (int)clampf(fmaxf(a.y, b.y), 0, (float)height);
for (int y = top; y < bottom; ++y) {
float depth = 1 / (a.z - a_b_z * (a.y - y) / a_b_y);
int x = (int)((b.x * (a.y - (float)y) + a.x * ((float)y - b.y)) / a_b_y);
if (x >= 0 && x < width) {
if (depth >= z_buffer[x + y * width]) {
z_buffer[x + y * width] = depth;
back_buffer[x + y * width] = line_color;
}
}
}
} else {
int left = (int)clampf(fminf(a.x, b.x), 0, (float)width);
int right = (int)clampf(fmaxf(a.x, b.x), 0, (float)width);
for (int x = left; x < right; ++x) {
float depth = 1 / (a.z - a_b_z * (a.x - x) / a_b_x);
int y = (int)((b.y * (a.x - (float)x) + a.y * ((float)x - b.x)) / a_b_x);
if (y >= 0 && y < height) {
if (depth >= z_buffer[x + y * width]) {
z_buffer[x + y * width] = depth;
back_buffer[x + y * width] = line_color;
}
}
}
}
}
void Renderer::rasterization(void)
{
int width = scg_window_width;
int height = scg_window_height;
unsigned numf = mesh->num_f;
for (unsigned i = 0; i < numf; ++i) {
u3 triangle = {
mesh->f_buffer[i].v1,
mesh->f_buffer[i].v2,
mesh->f_buffer[i].v3,
};
f3 a = v_buffer[triangle.x - 1];
f3 b = v_buffer[triangle.y - 1];
f3 c = v_buffer[triangle.z - 1];
if (draw_mode != DRAW_MESH) {
// Draw color
float window_height_f = (float)height;
float window_width_f = (float)width;
// get scan area
float left_f = clampf(fminf(fminf(a.x, b.x), c.x), 0.f, window_width_f);
float right_f = clampf(fmaxf(fmaxf(a.x, b.x), c.x), 0.f, window_width_f);
float top_f = clampf(fminf(fminf(a.y, b.y), c.y), 0.f, window_height_f);
float bottom_f = clampf(fmaxf(fmaxf(a.y, b.y), c.y), 0.f, window_height_f);
int left = (int)(left_f + .5f);
int right = (int)(right_f + .5f);
int top = (int)(top_f + .5f);
int bottom = (int)(bottom_f + .5f);
float b_c_y = (b.y - c.y);
float c_a_y = (c.y - a.y);
float a_b_y = (a.y - b.y);
int a_color_r = c_buffer[i].x >> 24;
int a_color_g = 0xff & (c_buffer[i].x >> 16);
int a_color_b = 0xff & (c_buffer[i].x >> 8);
int b_color_r = c_buffer[i].y >> 24;
int b_color_g = 0xff & (c_buffer[i].y >> 16);
int b_color_b = 0xff & (c_buffer[i].y >> 8);
int c_color_r = c_buffer[i].z >> 24;
int c_color_g = 0xff & (c_buffer[i].z >> 16);
int c_color_b = 0xff & (c_buffer[i].z >> 8);
float b_a_z = b.z - a.z;
float c_a_z = c.z - a.z;
// Coordinate transform
// Build two vector
f2 b_a_position;
b_a_position.x = b.x - a.x;
b_a_position.y = -a_b_y;
float length1 = sqrtf(b_a_position.x * b_a_position.x + b_a_position.y * b_a_position.y);
b_a_position.x /= length1;
b_a_position.y /= length1;
f2 c_a_position;
c_a_position.x = c.x - a.x;
c_a_position.y = c_a_y;
float length2 = sqrtf(c_a_position.x * c_a_position.x + c_a_position.y * c_a_position.y);
c_a_position.x /= length2;
c_a_position.y /= length2;
// Build transform
float determinant = b_a_position.x * c_a_position.y - b_a_position.y * c_a_position.x;
mat2x2 inv_coord_transform;
inv_coord_transform.m[0][0] = c_a_position.y / determinant;
inv_coord_transform.m[0][1] = -b_a_position.y / determinant;
inv_coord_transform.m[1][0] = -c_a_position.x / determinant;
inv_coord_transform.m[1][1] = b_a_position.x / determinant;
float tmp = b_c_y * a.x + c_a_y * b.x + a_b_y * c.x;
for (unsigned y = top; y < bottom; ++y) {
for (unsigned x = left; x < right; ++x) {
float x_f = (float)x;
float y_f = (float)y;
float side0 = b_c_y * x_f
+ (c.y - y_f) * b.x
+ (y_f - b.y) * c.x;
float side1 = (y_f - c.y) * a.x
+ c_a_y * x_f
+ (a.y - y_f) * c.x;
float side2 = (b.y - y_f) * a.x
+ (y_f - a.y) * b.x
+ a_b_y * x_f;
// the point is same side with another triangle point in each in 3 side
bool draw = (tmp * side0 >= -0.f) && (tmp * side1 >= -0.f) && (tmp * side2 >= -0.f);
if (!draw)
continue;
float u = ((x_f - a.x) * inv_coord_transform.m[0][0] + (y_f - a.y) * inv_coord_transform.m[1][0]) / length1;
float v = ((x_f - a.x) * inv_coord_transform.m[0][1] + (y_f - a.y) * inv_coord_transform.m[1][1]) / length2;
// Depth
float pixel_depth = 1 / (a.z + u * b_a_z + v * c_a_z);
if (pixel_depth > z_buffer[x + y * width]) {
z_buffer[x + y * width] = pixel_depth;
float tmp = 1 - u - v;
unsigned pixel_color_r = (unsigned)(tmp * a_color_r + u * b_color_r + v * c_color_r);
unsigned pixel_color_g = (unsigned)(tmp * a_color_g + u * b_color_g + v * c_color_g);
unsigned pixel_color_b = (unsigned)(tmp * a_color_b + u * b_color_b + v * c_color_b);
unsigned pixel_color = (unsigned)((pixel_color_r << 24) | (pixel_color_g << 16) | (pixel_color_b << 8));
back_buffer[x + y * width] = pixel_color >> 8;
}
}
}
}
if (draw_mode != DRAW_COLOR) {
// Draw mesh
draw_line(a, b);
draw_line(b, c);
draw_line(c, a);
}
}
}
Renderer& Renderer::get(void)
{
static Renderer instance;
return instance;
}
void Renderer::set_allocator(void *(*_malloc)(size_t), void (*_free)(void *))
{
this->alloc = _malloc;
this->drop = _free;
}
int Renderer::create_window(int width, int height, const TCHAR* title, WNDPROC event_process)
{
width = width;
height = height;
if (scg_create_window(width, height, title, event_process))
return -1;
back_buffer = scg_back_buffer;
// create depth buffer with the same width and height
z_buffer = (float *)alloc(width * height * sizeof(float));
if (!z_buffer)
return -1;
return 0;
}
void Renderer::close_window(void)
{
if (z_buffer)
drop(z_buffer);
z_buffer = NULL;
scg_close_window();
}
void Renderer::refresh(void)
{
scg_refresh();
}
void Renderer::clear(void)
{
int width = scg_window_width;
int height = scg_window_height;
#define block_size 32
#define block_color 0x7f
for (unsigned y = 0; y < height; ++y) {
for (unsigned x = 0; x < width; ++x) {
unsigned b_color = (((x / block_size) % 2) ^ ((y / block_size) % 2)) * block_color;
back_buffer[x + y * width] = b_color << 16 | b_color << 8 | b_color;
z_buffer[x + y * width] = 0.f;
}
}
#undef block_color
#undef block_size
}
int Renderer::load_mesh(const my_obj_elements *_mesh)
{
mesh = _mesh;
if (v_buffer)
drop(v_buffer);
v_buffer = (f3 *)alloc(_mesh->num_v * sizeof(f3));
if (!v_buffer)
return -1;
if (c_buffer)
drop(c_buffer);
c_buffer = (u3 *)alloc(_mesh->num_f * sizeof(u3));
if (!c_buffer)
return -1;
return 0;
}
/*
void Renderer::load_texture(unsigned width, unsigned height, const unsigned *tex)
{
texture_width = width;
texture_height = height;
texture = tex;
}
*/
void Renderer::draw(void)
{
v_shading();
projection();
clipping();
screen_mapping();
rasterization();
}
| 31.094118 | 128 | 0.507283 | ldm0 |
d563264bda1fff474227fb01bd6d7c5b06b1045c | 12,379 | cc | C++ | content/renderer/accessibility/ax_image_stopwords.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/accessibility/ax_image_stopwords.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/accessibility/ax_image_stopwords.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "base/containers/flat_set.h"
#include "base/i18n/case_conversion.h"
#include "base/i18n/char_iterator.h"
#include "base/no_destructor.h"
#include "base/stl_util.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "content/renderer/accessibility/ax_image_stopwords.h"
#include "third_party/icu/source/common/unicode/uchar.h"
namespace content {
namespace {
// List of image stopwords for all languages. See ax_image_stopwords.h
// for information about how image stopwords are defined and how they're
// used.
//
// The stopwords are encoded here as a single long string delimited by
// newlines. This is much more efficient than an array of strings, which
// in practice takes ~6x more storage in the resulting binary.
//
// Current size as of June 2020:
// 369 unique words
// 2542 bytes uncompressed
// 1127 bytes gzipped
const char kImageStopwordsUtf8[] = {
//
// Language-independent stopwords.
//
"com\n"
"edu\n"
"http\n"
"https\n"
"www\n"
//
// English.
//
// General English stopwords.
"and\n"
"are\n"
"for\n"
"from\n"
"how\n"
"online\n"
"our\n"
"the\n"
"this\n"
"with\n"
"you\n"
"your\n"
// English image-specific stopwords.
"art\n"
"avatar\n"
"background\n"
"backgrounds\n"
"black\n"
"download\n"
"drawing\n"
"drawings\n"
"free\n"
"gif\n"
"icon\n"
"icons\n"
"illustration\n"
"illustrations\n"
"image\n"
"images\n"
"jpeg\n"
"jpg\n"
"logo\n"
"logos\n"
"meme\n"
"memes\n"
"photo\n"
"photos\n"
"picture\n"
"pictures\n"
"png\n"
"stock\n"
"transparent\n"
"vector\n"
"vectors\n"
"video\n"
"videos\n"
"wallpaper\n"
"wallpapers\n"
"white\n"
// Alt text from may images starts with "Image may contain".
"may\n"
"contain\n"
// Many images on the web have the alt text "Highlights info row."
"highlights\n"
"info\n"
"row\n"
// Google Photos images are labeled as "portrait" or "landscape".
"portrait\n"
"landscape\n"
// Reddit says "post image".
"post\n"
// Months and month abbreviations. Often used as part of the date/time
// when a photograph was taken.
"january\n"
"jan\n"
"february\n"
"feb\n"
"march\n"
"mar\n"
"april\n"
"apr\n"
"may\n"
"june\n"
"jun\n"
"july\n"
"jul\n"
"august\n"
"aug\n"
"september\n"
"sep\n"
"october\n"
"oct"
"november"
"nov\n"
"december\n"
"dec\n"
// Days of the week.
"monday\n"
"mon\n"
"tuesday\n"
"tue\n"
"wednesday\n"
"wed\n"
"thursday\n"
"thu\n"
"friday\n"
"fri\n"
"saturday\n"
"sat\n"
"sunday\n"
"sun\n"
//
// French
//
// General French stopwords.
"les\n" // the
"pour\n" // for
"des\n" // of the
"sur\n" // on
"avec\n" // with
"une\n" // one
"dans\n" // in
"est\n" // is
"plus\n" // more
"par\n" // by
"vous\n" // you
"pas\n" // not
"qui\n" // who
"aux\n" // to the
"son\n" // his/her/its
"nous\n" // we
"voir\n" // see
// French Image stopwords.
"noir\n" // black
"blanc\n" // white
"dessin\n" // drawing
"font\n" // background
"peinture\n" // painting
// Months.
"janvier\n"
"janv\n"
"février\n"
"févr\n"
"mars\n"
"avril\n"
"mai\n"
"juin\n"
"juillet\n"
"juil\n"
"août\n"
"septembre\n"
"sept\n"
"octobre\n"
"oct\n"
"novembre\n"
"nov\n"
"décembre\n"
"déc\n"
// Days of the week.
"lundi\n"
"lun\n"
"mardi\n"
"mar\n"
"mercredi\n"
"mer\n"
"jeudi\n"
"jeu\n"
"vendredi\n"
"ven\n"
"samedi\n"
"sam\n"
"dimanche\n"
"dim\n"
//
// Italian
//
"con\n" // with
"per\n" // through, by
"non\n" // not
"come\n" // as
"più\n" // more
"dal\n" // da + il
"dallo\n" // da + lo
"dai\n" // da + i
"dagli\n" // da + gli
"dall\n" // da + l'
"dagl\n" // da + gll'
"dalla\n" // da + la
"dalle\n" // da + le
"del\n" // di + il
"dello\n" // di + lo
"dei\n" // di + i
"degli\n" // di + gli
"dell\n" // di + l'
"degl\n" // di + gl'
"della\n" // di + la
"delle\n" // di + le
"nel\n" // in + el
"nello\n" // in + lo
"nei\n" // in + i
"negli\n" // in + gli
"nell\n" // in + l'
"negl\n" // in + gl'
"nella\n" // in + la
"nelle\n" // in + le
"sul\n" // su + il
"sullo\n" // su + lo
"sui\n" // su + i
"sugli\n" // su + gli
"sull\n" // su + l'
"sugl\n" // su + gl'
"sulla\n" // su + la
"sulle\n" // su + le
// Images
"arte\n"
"immagini\n"
"illustrazione\n"
"fotografia\n"
"icona\n"
"bianca\n" // white
"bianco\n" // white
"nera\n" // black
"nero\n" // black
"contenere\n" // contain (image may contain...)
// Months.
"gennaio\n"
"genn\n"
"febbraio\n"
"febbr\n"
"marzo\n"
"mar\n"
"aprile\n"
"apr\n"
"maggio\n"
"magg\n"
"giugno\n"
"luglio\n"
"agosto\n"
"settembre\n"
"sett\n"
"ottobre\n"
"ott\n"
"novembre\n"
"nov\n"
"dicembre\n"
"dic\n"
// Weekdays.
"lunedì\n"
"lun\n"
"martedì\n"
"mar\n"
"mercoledì\n"
"mer\n"
"giovedì\n"
"gio\n"
"venerdì\n"
"ven\n"
"sabato\n"
"sab\n"
"domenica\n"
"dom\n"
//
// German
//
// General German stopwords.
"und\n" // and
"mit\n" // with
"für\n" // for
"der\n" // the
"die\n" // the
"von\n" // of, from
"auf\n" // on
"das\n" // the
"aus\n" // out of
"ist\n" // is
"ein\n" // one
"eine\n" // one
"sie\n" // they, she
"den\n" // the
"zum\n" // zu + dem
"zur\n" // zu + der
"bei\n" // by
"des\n" // the
"sprüche\n" // claims (to be)
"oder\n" // or
// German Image stopwords.
"bild\n" // picture
"bilder\n" // pictures
"foto\n" // photo
"schwarz\n" // black
"weiß\n" // white
// Months.
"januar\n"
"jan\n"
"jän\n"
"februar\n"
"feb\n"
"märz\n"
"april\n"
"apr\n"
"mai\n"
"juni\n"
"juli\n"
"august\n"
"aug\n"
"september\n"
"sept\n"
"oktober\n"
"okt\n"
"november\n"
"nov\n"
"dezember\n"
"dez\n"
// Weekdays.
"montag\n"
"dienstag\n"
"mittwoch\n"
"donnerstag\n"
"freitag\n"
"samstag\n"
"sonntag\n"
//
// Spanish
//
// General Spanish stopwords.
"con\n" // with
"para\n" // by
"del\n" // of the
"que\n" // that
"los\n" // the
"las\n" // the
"una\n" // one
"por\n" // for
"más\n" // more
"como\n" // how
// Spanish image stopwords.
"dibujos\n" // drawings
"imagen\n" // images
"arte\n" // art
"fondo\n" // background
"fondos\n" // backgrounds
"diseño\n" // design
"ilustración\n" // illustration
"imagenes\n" // images
"blanca\n" // white
"blanco\n" // white
"negra\n" // black
"negro\n" // black
// Months.
"enero\n"
"febrero\n"
"feb\n"
"marzo\n"
"abril\n"
"abr\n"
"mayo\n"
"junio\n"
"jun\n"
"julio\n"
"jul\n"
"agosto\n"
"septiembre\n"
"sept\n"
"set\n"
"octubre\n"
"oct\n"
"noviembre\n"
"nov\n"
"diciembre\n"
"dic\n"
// Weekdays. Weekday abbreviations in Spanish are two-letters which
// don't need to be listed here (anything less than 3 letters is
// considered a stopword already).
"lunes\n"
"martes\n"
"miércoles\n"
"jueves\n"
"viernes\n"
"sábado\n"
"domingo\n"
//
// Hindi
//
// General Hindi stopwords.
"में\n" // in
"लिए\n" // for
"नहीं\n" // no
"एक\n" // one
"साथ\n" // with
"दिया\n" // gave
"किया\n" // did
"रहे\n" // are
"सकता\n" // can
"इस\n" // this
"शामिल\n" // include
"तारीख\n" // the date
// Hindi image stopwords.
"चित्र\n" // picture
"वीडियो\n" // video
// Months
"जनवरी\n"
"फरवरी\n"
"मार्च\n"
"अप्रैल\n"
"मई\n"
"जून\n"
"जुलाई\n"
"अगस्त\n"
"सितंबर\n"
"अक्टूबर\n"
"नवंबर\n"
"दिसंबर\n"
// Weekdays.
"सोमवार\n"
"मंगलवार\n"
"बुधवार\n"
"बृहस्पतिवार\n"
"शुक्रवार\n"
"शनिवार\n"
"रविवार\n"};
} // namespace
// static
AXImageStopwords& AXImageStopwords::GetInstance() {
static base::NoDestructor<AXImageStopwords> instance;
return *instance;
}
AXImageStopwords::AXImageStopwords() {
// Parse the newline-delimited stopwords from kImageStopwordsUtf8 and store
// them as a flat_set of type StringPiece. This is very memory-efficient
// because it avoids ever needing to copy any of the strings; each StringPiece
// is just a pointer into kImageStopwordsUtf8 and flat_set acts like a set but
// basically just does a binary search.
std::vector<base::StringPiece> stopwords =
base::SplitStringPiece(kImageStopwordsUtf8, "\n", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
// It's inefficient to add things to a flat_set one at a time. Copy them
// all over at once.
stopword_set_ = stopwords;
}
AXImageStopwords::~AXImageStopwords() = default;
bool AXImageStopwords::IsImageStopword(const char* word_utf8) const {
base::string16 word_utf16 = base::UTF8ToUTF16(word_utf8);
// It's not really meaningful, but since short words are stopwords, for
// simplicity we define the empty string to be a stopword too.
if (word_utf16.empty())
return true;
// Canonicalize case, this is like "ToLower" for many languages but
// works independently of the current locale.
word_utf16 = base::i18n::FoldCase(word_utf16);
// Count the number of distinct codepoints from a supported unicode block.
base::i18n::UTF16CharIterator iter(&word_utf16);
int supported_count = 0;
int total_count = 0;
while (!iter.end()) {
total_count++;
int32_t codepoint = iter.get();
UBlockCode block_code = ublock_getCode(codepoint);
switch (block_code) {
case UBLOCK_BASIC_LATIN:
case UBLOCK_LATIN_1_SUPPLEMENT:
case UBLOCK_LATIN_EXTENDED_A:
case UBLOCK_DEVANAGARI:
supported_count++;
break;
default:
break;
}
iter.Advance();
}
// Treat any string of 2 or fewer characters in any of these unicode
// blocks as a stopword. Of course, there are rare exceptions, but they're
// acceptable for this heuristic. All that means is that we won't count
// those words when trying to determine if the alt text for an image
// has meaningful text or not. The odds are good that a 1 or 2 character
// word is not meaningful.
//
// Note: this assumption might not be valid for some unicode blocks,
// like Chinese. That's why the heuristic only applies to certain unicode
// blocks where we believe this to be a reasonable assumption.
//
// Note that in Devanagari (the script used for the Hindi language, among
// others) a word sometimes looks like a single character (one glyph) but it's
// actually two or more unicode codepoints (consonants and vowels that are
// joined together), which is why this heuristic still works. Anything with
// two or fewer unicode codepoints is an extremely short word.
if (supported_count == total_count && total_count <= 2)
return true;
return base::Contains(stopword_set_, base::UTF16ToUTF8(word_utf16));
}
} // namespace content
| 21.491319 | 80 | 0.535019 | mghgroup |
d56516faccc981829754f0ca17328d8b7da8aeb1 | 874 | cpp | C++ | proCpp/main.cpp | varpeti/Suli | f0309306ed65454f70fbd67c8084aa2c2e085296 | [
"Unlicense"
] | 1 | 2020-10-21T09:54:22.000Z | 2020-10-21T09:54:22.000Z | proCpp/main.cpp | varpeti/Suli2 | 6cd0c98e5d725846116aa29936314e113ae7923e | [
"Unlicense"
] | null | null | null | proCpp/main.cpp | varpeti/Suli2 | 6cd0c98e5d725846116aa29936314e113ae7923e | [
"Unlicense"
] | null | null | null | #include <iostream>
struct A
{
};
struct B1
{
int a1;
int a2;
};
struct B2
{
char a1;
char a2;
};
struct B3
{
int a1;
char a2;
};
struct B4
{
char a1;
int a2;
};
struct CSI
{
char c;
short s;
int i;
};
struct CIS
{
char c;
int i;
short s;
};
//DIAMOND
struct teto
{
int t;
};
struct jobb : public teto
{
int j;
};
struct bal : public teto
{
int b;
};
struct alja : virtual public jobb, bal
{
int a;
};
int main()
{
std::cout << sizeof(A) << "\n";
std::cout << sizeof(B1) << "\n";
std::cout << sizeof(B2) << "\n";
std::cout << sizeof(B3) << "\n";
std::cout << sizeof(B4) << "\n";
std::cout << sizeof(CSI) << "\n";
std::cout << sizeof(CIS) << "\n";
alja a;
a.bal::t=9;
a.jobb::t=8;
a.j=7;
a.b=6;
a.a=5;
getchar();
return 0;
} | 10.045977 | 38 | 0.467963 | varpeti |
d566ad3414da5e2734bc6bdbdcba704762d21ec0 | 7,269 | hpp | C++ | deps/boost/include/boost/gil/extension/numeric/pixel_numeric_operations.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 80 | 2021-09-07T12:44:32.000Z | 2022-03-29T01:22:19.000Z | deps/boost/include/boost/gil/extension/numeric/pixel_numeric_operations.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 2 | 2021-12-23T02:49:42.000Z | 2022-02-15T05:28:24.000Z | deps/boost/include/boost/gil/extension/numeric/pixel_numeric_operations.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 25 | 2021-09-14T06:24:25.000Z | 2022-03-20T06:55:07.000Z | //
// Copyright 2005-2007 Adobe Systems Incorporated
//
// 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 BOOST_GIL_EXTENSION_NUMERIC_PIXEL_NUMERIC_OPERATIONS_HPP
#define BOOST_GIL_EXTENSION_NUMERIC_PIXEL_NUMERIC_OPERATIONS_HPP
#include <boost/gil/extension/numeric/channel_numeric_operations.hpp>
#include <boost/gil/color_base_algorithm.hpp>
#include <boost/gil/pixel.hpp>
namespace boost { namespace gil {
// Function objects and utilities for pixel-wise numeric operations.
//
// List of currently defined functors:
// pixel_plus_t (+)
// pixel_minus_t (-)
// pixel_multiplies_scalar_t (*)
// pixel_divides_scalar_t (/)
// pixel_halves_t (/=2),
// pixel_zeros_t (=0)
// pixel_assigns_t (=)
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise addition of two pixels.
/// \tparam PixelRef1 - models PixelConcept
/// \tparam PixelRef2 - models PixelConcept
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef1, typename PixelRef2, typename PixelResult>
struct pixel_plus_t
{
auto operator()(PixelRef1 const& p1, PixelRef2 const& p2) const -> PixelResult
{
PixelResult result;
static_transform(p1, p2, result,
channel_plus_t
<
typename channel_type<PixelRef1>::type,
typename channel_type<PixelRef2>::type,
typename channel_type<PixelResult>::type
>());
return result;
}
};
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise subtraction of two pixels.
/// \tparam PixelRef1 - models PixelConcept
/// \tparam PixelRef2 - models PixelConcept
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef1, typename PixelRef2, typename PixelResult>
struct pixel_minus_t
{
auto operator()(PixelRef1 const& p1, PixelRef2 const& p2) const -> PixelResult
{
PixelResult result;
static_transform(p1, p2, result,
channel_minus_t
<
typename channel_type<PixelRef1>::type,
typename channel_type<PixelRef2>::type,
typename channel_type<PixelResult>::type
>());
return result;
}
};
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise multiplication of pixel elements by scalar.
/// \tparam PixelRef - models PixelConcept
/// \tparam Scalar - models a scalar type
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef, typename Scalar, typename PixelResult>
struct pixel_multiplies_scalar_t
{
auto operator()(PixelRef const& p, Scalar const& s) const -> PixelResult
{
PixelResult result;
static_transform(p, result,
std::bind(
channel_multiplies_scalar_t<typename channel_type<PixelRef>::type,
Scalar,
typename channel_type<PixelResult>::type>(),
std::placeholders::_1, s));
return result;
}
};
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise multiplication of two pixels.
/// \tparam PixelRef1 - models PixelConcept
/// \tparam PixelRef1 - models PixelConcept
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef1, typename PixelRef2, typename PixelResult>
struct pixel_multiply_t
{
auto operator()(PixelRef1 const& p1, PixelRef2 const& p2) const -> PixelResult
{
PixelResult result;
static_transform(p1, p2, result,
channel_multiplies_t
<
typename channel_type<PixelRef1>::type,
typename channel_type<PixelRef2>::type,
typename channel_type<PixelResult>::type
>());
return result;
}
};
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise division of pixel elements by scalar.
/// \tparam PixelRef - models PixelConcept
/// \tparam Scalar - models a scalar type
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef, typename Scalar, typename PixelResult>
struct pixel_divides_scalar_t
{
auto operator()(PixelRef const& p, Scalar const& s) const -> PixelResult
{
PixelResult result;
static_transform(p, result,
std::bind(channel_divides_scalar_t<typename channel_type<PixelRef>::type,
Scalar,
typename channel_type<PixelResult>::type>(),
std::placeholders::_1, s));
return result;
}
};
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise division of two pixels.
/// \tparam PixelRef1 - models PixelConcept
/// \tparam PixelRef1 - models PixelConcept
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef1, typename PixelRef2, typename PixelResult>
struct pixel_divide_t
{
auto operator()(PixelRef1 const& p1, PixelRef2 const& p2) const -> PixelResult
{
PixelResult result;
static_transform(p1, p2, result,
channel_divides_t
<
typename channel_type<PixelRef1>::type,
typename channel_type<PixelRef2>::type,
typename channel_type<PixelResult>::type
>());
return result;
}
};
/// \ingroup PixelNumericOperations
/// \brief Performs channel-wise division by 2
/// \tparam PixelRef - models PixelConcept
template <typename PixelRef>
struct pixel_halves_t
{
auto operator()(PixelRef& p) const -> PixelRef&
{
static_for_each(p, channel_halves_t<typename channel_type<PixelRef>::type>());
return p;
}
};
/// \ingroup PixelNumericOperations
/// \brief Sets pixel elements to zero (for whatever zero means)
/// \tparam PixelRef - models PixelConcept
template <typename PixelRef>
struct pixel_zeros_t
{
auto operator()(PixelRef& p) const -> PixelRef&
{
static_for_each(p, channel_zeros_t<typename channel_type<PixelRef>::type>());
return p;
}
};
/// \brief Sets pixel elements to zero (for whatever zero means)
/// \tparam Pixel - models PixelConcept
template <typename Pixel>
void zero_channels(Pixel& p)
{
static_for_each(p, channel_zeros_t<typename channel_type<Pixel>::type>());
}
/// \ingroup PixelNumericOperations
/// \brief Casts and assigns a pixel to another
///
/// A generic implementation for casting and assigning a pixel to another.
/// User should specialize it for better performance.
///
/// \tparam PixelRef - models PixelConcept
/// \tparam PixelResult - models PixelValueConcept
template <typename PixelRef, typename PixelResult>
struct pixel_assigns_t
{
auto operator()(PixelRef const& src, PixelResult& dst) const -> PixelResult
{
static_for_each(src, dst,
channel_assigns_t
<
typename channel_type<PixelRef>::type,
typename channel_type<PixelResult>::type
>());
return dst;
}
};
}} // namespace boost::gil
#endif
| 33.344037 | 87 | 0.6591 | kindlychung |
d56700b5b805739edea709fd4eda59ecbd9decce | 259 | cpp | C++ | src/08_evaluation_step1.cpp | pbouamriou/tuto_mpl | 6c159662d50277f5bb4eda3038b394fb99501e3c | [
"MIT"
] | null | null | null | src/08_evaluation_step1.cpp | pbouamriou/tuto_mpl | 6c159662d50277f5bb4eda3038b394fb99501e3c | [
"MIT"
] | null | null | null | src/08_evaluation_step1.cpp | pbouamriou/tuto_mpl | 6c159662d50277f5bb4eda3038b394fb99501e3c | [
"MIT"
] | null | null | null | #include <iostream>
class X;
#if (__cplusplus < 201103L)
template<typename T>
struct Ptr {
typedef T* type;
};
#else
template<typename T>
struct Ptr {
using type = T*;
};
#endif
int main() {
std::cout << sizeof(Ptr<X>::type) << std::endl;
} | 11.26087 | 51 | 0.6139 | pbouamriou |
d567478d935bd4ceca756a92aa3b9b6980ab0f96 | 3,425 | cpp | C++ | functorch/csrc/BatchRulesPooling.cpp | laurencer/functorch | 1bc4093b09f7a69606ff3fd2e6c76ffd55d4ac13 | [
"BSD-3-Clause"
] | null | null | null | functorch/csrc/BatchRulesPooling.cpp | laurencer/functorch | 1bc4093b09f7a69606ff3fd2e6c76ffd55d4ac13 | [
"BSD-3-Clause"
] | null | null | null | functorch/csrc/BatchRulesPooling.cpp | laurencer/functorch | 1bc4093b09f7a69606ff3fd2e6c76ffd55d4ac13 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <functorch/csrc/BatchRulesHelper.h>
#include <functorch/csrc/PlumbingHelper.h>
#include <functorch/csrc/BatchedFallback.h>
#include <ATen/core/dispatch/Dispatcher.h>
namespace at { namespace functorch {
std::tuple<Tensor,optional<int64_t>> adaptive_avg_pool2d_batch_rule(
const Tensor& tensor, optional<int64_t> batch_dim, IntArrayRef output_size) {
auto batch_size = tensor.size(*batch_dim);
auto tensor_ = reshape_dim_into(*batch_dim, 0, tensor);
auto result = at::adaptive_avg_pool2d(tensor_, output_size);
return std::make_tuple( reshape_dim_outof(0, batch_size, result), 0 );
}
std::tuple<Tensor,int64_t> max_pool2d_with_indices_backward_batch_rule(
const Tensor & grad_output, optional<int64_t> grad_output_bdim,
const Tensor & self, optional<int64_t> self_bdim,
IntArrayRef kernel_size, IntArrayRef stride, IntArrayRef padding,
IntArrayRef dilation, bool ceil_mode,
const Tensor & indices, optional<int64_t> indices_bdim) {
TORCH_INTERNAL_ASSERT(grad_output_bdim && self_bdim && indices_bdim);
auto bdim_size = self.size(*self_bdim);
auto grad_output_ = reshape_dim_into(*grad_output_bdim, 0, grad_output);
auto self_ = reshape_dim_into(*self_bdim, 0, self);
auto indices_ = reshape_dim_into(*indices_bdim, 0, indices);
auto result = at::max_pool2d_with_indices_backward(
grad_output_, self_, kernel_size, stride, padding, dilation, ceil_mode,
indices_);
result = reshape_dim_outof(0, bdim_size, result);
return std::make_tuple(result, 0);
}
Tensor max_pool2d_with_indices_backward_plumbing(const Tensor & grad_output, const Tensor & self, IntArrayRef kernel_size, IntArrayRef stride, IntArrayRef padding, IntArrayRef dilation, bool ceil_mode, const Tensor & indices) {
auto maybe_layer = maybeCurrentDynamicLayer();
TORCH_INTERNAL_ASSERT(maybe_layer.has_value());
int64_t cur_level = maybe_layer->layerId();
Tensor grad_output_value;
optional<int64_t> grad_output_bdim;
std::tie(grad_output_value, grad_output_bdim) = unwrapTensorAtLevel(grad_output, cur_level);
Tensor self_value;
optional<int64_t> self_bdim;
std::tie(self_value, self_bdim) = unwrapTensorAtLevel(self, cur_level);
Tensor indices_value;
optional<int64_t> indices_bdim;
std::tie(indices_value, indices_bdim) = unwrapTensorAtLevel(indices, cur_level);
if (self_bdim && grad_output_bdim && indices_bdim) {
c10::impl::ExcludeDispatchKeyGuard guard(kBatchedKey);
auto result = max_pool2d_with_indices_backward_batch_rule(
grad_output_value, grad_output_bdim,
self_value, self_bdim,
kernel_size, stride, padding, dilation, ceil_mode,
indices_value, indices_bdim);
return makeBatched(std::get<0>(result), std::get<1>(result), cur_level);
}
static auto op = c10::Dispatcher::singleton()
.findSchemaOrThrow("aten::max_pool2d_with_indices_backward", "");
return slow_fallback<Tensor>(op, { grad_output, self, kernel_size, stride, padding, dilation, ceil_mode, indices });
}
TORCH_LIBRARY_IMPL(aten, FT_BATCHED_KEY, m) {
VMAP_SUPPORT("adaptive_avg_pool2d", adaptive_avg_pool2d_batch_rule);
m.impl("max_pool2d_with_indices_backward", max_pool2d_with_indices_backward_plumbing);
}
}}
| 42.8125 | 227 | 0.769343 | laurencer |
d56a9fada4449e73cfde2571a9dc7d1d58539527 | 658 | cpp | C++ | sw4261.cpp | sjnov11/SW-expert-academy | b7040017f2f8ff037aee40a5024284aaad1e50f9 | [
"MIT"
] | 1 | 2022-02-21T09:11:15.000Z | 2022-02-21T09:11:15.000Z | sw4261.cpp | sjnov11/SW-expert-academy | b7040017f2f8ff037aee40a5024284aaad1e50f9 | [
"MIT"
] | null | null | null | sw4261.cpp | sjnov11/SW-expert-academy | b7040017f2f8ff037aee40a5024284aaad1e50f9 | [
"MIT"
] | 1 | 2019-07-03T10:12:55.000Z | 2019-07-03T10:12:55.000Z | #include <iostream>
#include <string>
#include <vector>
using namespace std;
char keypad[26] = { '2','2','2',
'3','3','3',
'4','4','4',
'5','5','5',
'6','6','6',
'7','7','7','7',
'8','8','8',
'9','9','9','9' };
int main() {
int T;
cin >> T;
for (int tc = 1; tc <= T; tc++) {
string S;
int N;
cin >> S >> N;
int answer = 0;
for (int i = 0; i < N; i++) {
string word;
cin >> word;
bool flag = true;
for (int j = 0; j < word.size(); j++) {
if (S[j] != keypad[word[j] - 'a']) {
flag = false;
break;
}
}
if (flag) answer++;
}
cout << "#" << tc << " " << answer << "\n";
}
} | 18.277778 | 45 | 0.401216 | sjnov11 |
d56b89cdd5548e447982f8b8feee1ba5ffc681a2 | 750 | cpp | C++ | src/nasty.cpp | IlyaGusev/tgcontest | 8945b9f6d1527ca21920998e86a8ecc1ebfdf526 | [
"Apache-2.0"
] | 91 | 2020-01-05T11:46:12.000Z | 2022-03-28T04:50:12.000Z | src/nasty.cpp | IlyaGusev/tgcontest | 8945b9f6d1527ca21920998e86a8ecc1ebfdf526 | [
"Apache-2.0"
] | 1 | 2020-07-10T11:32:47.000Z | 2020-08-05T20:57:10.000Z | src/nasty.cpp | IlyaGusev/tgcontest | 8945b9f6d1527ca21920998e86a8ecc1ebfdf526 | [
"Apache-2.0"
] | 33 | 2020-01-14T17:37:14.000Z | 2022-03-12T15:28:01.000Z | #include "nasty.h"
bool ComputeDocumentNasty(const TDbDocument& document) {
if ((document.Language == tg::LN_EN) && (document.Title.size() < 16)) {
return true;
}
if ((document.Language == tg::LN_RU) && (document.Title.size() < 30)) {
return true;
}
unsigned char lastSymb = document.Title.back();
if (lastSymb == 0x21 || lastSymb == 0x3f || lastSymb == 0x2e || lastSymb == 0x20) {
return true; // !?. and space
}
unsigned char firstSymb = document.Title.front();
if (firstSymb == 0x22 || firstSymb == 0xab) {
return true; // "«
}
if (std::count(document.Title.begin(), document.Title.end(), 0x20) < 2) {
return true; // 3 words min
}
return false;
}
| 26.785714 | 88 | 0.573333 | IlyaGusev |
d56d0d9dcc415e166f57e43916555271bef08c1d | 10,535 | cxx | C++ | Src/Projects/box_Spring/boxSpring_box.cxx | Mikkelbf/OpenMoBu | c57c41a0908ad7734d48642549758271d11263b8 | [
"BSD-3-Clause"
] | 53 | 2018-04-21T14:16:46.000Z | 2022-03-19T11:27:37.000Z | Src/Projects/box_Spring/boxSpring_box.cxx | Mikkelbf/OpenMoBu | c57c41a0908ad7734d48642549758271d11263b8 | [
"BSD-3-Clause"
] | 6 | 2019-06-05T16:37:29.000Z | 2021-09-20T07:17:03.000Z | Src/Projects/box_Spring/boxSpring_box.cxx | Mikkelbf/OpenMoBu | c57c41a0908ad7734d48642549758271d11263b8 | [
"BSD-3-Clause"
] | 10 | 2019-02-22T18:43:59.000Z | 2021-09-02T18:53:37.000Z |
/////////////////////////////////////////////////////////////////////////////////////////
//
// boxSpring_box.cxx
//
// Sergei <Neill3d> Solokhin 2014-2018
//
// GitHub page - https://github.com/Neill3d/OpenMoBu
// Licensed under The "New" BSD License - https ://github.com/Neill3d/OpenMoBu/blob/master/LICENSE
//
/////////////////////////////////////////////////////////////////////////////////////////
/** \file boxSpring_box.cxx
*/
//--- Class declaration
#include <math.h>
#include "boxSpring_box.h"
//--- Registration defines
#define BOXSPRING__CLASS BOXSPRING__CLASSNAME
#define BOXSPRING__NAME BOXSPRING__CLASSSTR
#define BOXSPRING__LOCATION "Neill3d"
#define BOXSPRING__LABEL "Spring"
#define BOXSPRING__DESC "spring controller"
//--- implementation and registration
FBBoxImplementation ( BOXSPRING__CLASS ); // Box class name
FBRegisterBox ( BOXSPRING__NAME, // Unique name to register box.
BOXSPRING__CLASS, // Box class name
BOXSPRING__LOCATION, // Box location ('plugins')
BOXSPRING__LABEL, // Box label (name of box to display)
BOXSPRING__DESC, // Box long description.
FB_DEFAULT_SDK_ICON ); // Icon filename (default=Open Reality icon)
/************************************************
* Creation
************************************************/
bool CBoxSpring::FBCreate()
{
lastLocalTimeDouble = lastSystemTimeDouble = 0.0;
mOldPos[0] = mOldPos[1] = mOldPos[2] = 0.0;
mCurrentPos[0] = mCurrentPos[1] = mCurrentPos[2] = 0.0;
mVel[0] = mVel[1] = mVel[2] = 0.0;
mDeltaTimeDouble = 0.0;
mReset = false;
//printf( "spring box here!\n" );
if( FBBox::FBCreate() )
{
// Input Nodes
mStiffnessNode = AnimationNodeInCreate ( 0, "Stiff", ANIMATIONNODE_TYPE_NUMBER );
mDampingNode = AnimationNodeInCreate ( 1, "Damp", ANIMATIONNODE_TYPE_NUMBER );
mFrictionNode = AnimationNodeInCreate ( 2, "Friction", ANIMATIONNODE_TYPE_NUMBER );
mLengthNode = AnimationNodeInCreate ( 3, "Length", ANIMATIONNODE_TYPE_NUMBER );
mMassNode = AnimationNodeInCreate ( 4, "Mass", ANIMATIONNODE_TYPE_NUMBER );
mPosNode = AnimationNodeInCreate ( 5, "Pos", ANIMATIONNODE_TYPE_VECTOR );
mTimedt = AnimationNodeInCreate ( 6, "EvalSteps", ANIMATIONNODE_TYPE_INTEGER );
mZeroFrame = AnimationNodeInCreate ( 7, "ZeroFrame", ANIMATIONNODE_TYPE_INTEGER );
mRealTime = AnimationNodeInCreate ( 8, "RealTime", ANIMATIONNODE_TYPE_BOOL );
// Output Node
mResultNode = AnimationNodeOutCreate( 9, "Result", ANIMATIONNODE_TYPE_VECTOR );
return true;
}
return false;
}
/************************************************
* Destruction.
************************************************/
void CBoxSpring::FBDestroy()
{
FBBox::FBDestroy();
}
/************************************************
* Real-time engine evaluation
************************************************/
void VectorSet( float a, float b, float c, FBVector3d &v )
{
v[0] = a;
v[1] = b;
v[2] = c;
}
void VectorAdd( const FBVector3d &a, const FBVector3d &b, FBVector3d &c )
{
c[0] = a[0] + b[0];
c[1] = a[1] + b[1];
c[2] = a[2] + b[2];
}
void VectorSub( const FBVector3d &a, const FBVector3d &b, FBVector3d &c )
{
c[0] = a[0] - b[0];
c[1] = a[1] - b[1];
c[2] = a[2] - b[2];
}
void VectorMul( const FBVector3d &a, const FBVector3d &b, FBVector3d &c )
{
c[0] = a[0] * b[0];
c[1] = a[1] * b[1];
c[2] = a[2] * b[2];
}
void VectorMul( const FBVector3d &a, float scale, FBVector3d &c )
{
c[0] = a[0] * scale;
c[1] = a[1] * scale;
c[2] = a[2] * scale;
}
void VectorDiv( const FBVector3d &a, float scale, FBVector3d &c )
{
c[0] = a[0] / scale;
c[1] = a[1] / scale;
c[2] = a[2] / scale;
}
float VectorLength( const FBVector3d &a )
{
return sqrt( a[0]*a[0] + a[1]*a[1] + a[2]*a[2] );
}
void VectorNorm( FBVector3d &v )
{
float len = VectorLength( v );
if (len > 0)
{
v[0] /= len;
v[1] /= len;
v[2] /= len;
}
}
float VectorDot( const FBVector3d &a, FBVector3d &b )
{
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
}
struct SpringSettings
{
double length;
double friction;
double mass;
double stiffness;
double damping;
SpringSettings(const double _length, const double _friction, const double _mass, const double _stiffness, const double _damping)
: length(_length)
, friction(_friction)
, mass(_mass)
, stiffness(_stiffness)
, damping(_damping)
{}
};
bool CalculateSpring( const double dt, const FBVector3d &lV, const FBVector3d &mPos, const FBVector3d &mOldPos, const SpringSettings &settings, FBVector3d &mVel, FBVector3d &outPos )
{
FBVector3d lForce, lR;
FBVector3d px1, px2, pv1, pv2, dx, dv; // position & velocity
double m, r, value; // vector length
// position
px1 = lV;
px2 = mOldPos;
VectorSub( px1, px2, dx );
// velocity
VectorSub( lV, mOldPos, pv1 );
pv2 = mVel;
VectorSub( pv1, pv2, dv );
// force
r = settings.length;
m = VectorLength( dx );
if (m == 0.0) m = 0.0001;
lForce = dx;
VectorNorm( lForce );
value = (settings.stiffness*(m-r)+settings.damping*(VectorDot(dv, dx)/m));
//value = lS*(m-r);
VectorMul( lForce, value, lForce );
VectorDiv( lForce, settings.mass, lForce );
// add friction
lR = mVel;
if (m > 1.0f)
VectorMul( lR, -settings.friction, lR );
else
VectorMul( lR, -settings.friction, lR );
VectorAdd( lForce, lR, lForce );
VectorAdd( mVel, lForce, mVel ); // Change in velocity is added to the velocity.
// The change is proportinal with the acceleration (force / m) and change in time
VectorMul( mVel, dt, lR ); // Change in position is added to the position.
VectorAdd( mOldPos, mVel, outPos ); // Change in position is velocity times the change in time
/*
//
// damping
//
VectorSub( lV, mPos, lR );
VectorMul( lR, 0.5, lR );
double dt = (lTime - lastTimeDouble) * 10;
VectorMul( lR, dt, lR );
VectorAdd( mPos, lR, mPos );
lR = mPos;
*/
return true;
}
bool CBoxSpring::AnimationNodeNotify( FBAnimationNode *pAnimationNode, FBEvaluateInfo *pEvaluateInfo )
{
double lS, lD, lM, lFriction, lLength, lTimeDt, lZeroFrame, lRealTime;
FBVector3d lInputPos, lR, lVel, lHold, lForce;
bool lStatus[9];
FBTime lEvaluationTime, lLocalTime;
// Read connector in values
lStatus[0] = mStiffnessNode ->ReadData( &lS, pEvaluateInfo );
lStatus[1] = mMassNode ->ReadData( &lM, pEvaluateInfo );
lStatus[2] = mPosNode ->ReadData( &lInputPos[0], pEvaluateInfo );
lStatus[3] = mFrictionNode ->ReadData( &lFriction, pEvaluateInfo );
lStatus[4] = mLengthNode ->ReadData( &lLength, pEvaluateInfo );
lStatus[5] = mDampingNode ->ReadData( &lD, pEvaluateInfo );
lStatus[6] = mTimedt ->ReadData( &lTimeDt, pEvaluateInfo );
lStatus[7] = mZeroFrame ->ReadData( &lZeroFrame, pEvaluateInfo );
lStatus[8] = mRealTime ->ReadData( &lRealTime, pEvaluateInfo );
// Set default values if no input connection.
if( !lStatus[0] )
{
lS = 1.25;
}
if( !lStatus[1] )
{
lM = 2.0;
}
if( !lStatus[2] )
{
VectorSet( 0.0, 0.0, 0.0, lInputPos );
}
if( !lStatus[3] )
{
lFriction = 0.15;
}
if( !lStatus[4] )
{
lLength = 0.0;
}
if( !lStatus[5] )
{
lD = 0.1;
}
if (!lStatus[6]) lTimeDt = 30.0;
if (!lStatus[7]) lZeroFrame = 0.0;
if (!lStatus[8]) lRealTime = 1.0;
const double resetLimit = 20.0;
// Get the current evaluation time, indicating if recording.
#ifdef OLD_FBEVALUATE_LOCALTIME
// Get the current evaluation time, indicating if recording.
if( lRealTime > 0.0 )
{
lEvaluationTime = FBSystem().SystemTime;
mDeltaTimeDouble += lEvaluationTime.GetSecondDouble() - lastSystemTimeDouble;
if (mDeltaTimeDouble > resetLimit)
{
lastSystemTimeDouble = lEvaluationTime.GetSecondDouble();
mDeltaTimeDouble = 0.0;
mReset = true;
}
}
else
{
lEvaluationTime = pEvaluateInfo->GetLocalStart();
mDeltaTimeDouble += lEvaluationTime.GetSecondDouble() - lastLocalTimeDouble;
if (mDeltaTimeDouble > resetLimit || lEvaluationTime.GetFrame() == (int)lZeroFrame)
{
lastLocalTimeDouble = lEvaluationTime.GetSecondDouble();
mDeltaTimeDouble = 0.0;
mReset = true;
}
}
lLocalTime = pEvaluateInfo->GetLocalStart();
#else
// Get the current evaluation time, indicating if recording.
if( lRealTime > 0.0 )
{
lEvaluationTime = pEvaluateInfo->GetSystemTime();
mDeltaTimeDouble += lEvaluationTime.GetSecondDouble() - lastSystemTimeDouble;
if (mDeltaTimeDouble > resetLimit)
{
lastSystemTimeDouble = lEvaluationTime.GetSecondDouble();
mDeltaTimeDouble = 0.0;
mReset = true;
}
}
else
{
lEvaluationTime = pEvaluateInfo->GetLocalTime();
mDeltaTimeDouble += lEvaluationTime.GetSecondDouble() - lastLocalTimeDouble;
if (mDeltaTimeDouble > resetLimit || lEvaluationTime.GetFrame() == (int)lZeroFrame)
{
lastLocalTimeDouble = lEvaluationTime.GetSecondDouble();
mDeltaTimeDouble = 0.0;
mReset = true;
}
}
lLocalTime = pEvaluateInfo->GetLocalTime();
#endif
if ( mReset )
{
VectorSet( 0.0, 0.0, 0.0, mVel );
mCurrentPos = lInputPos; // at start mass pos and input pos is equal
lR = lInputPos;
mOldPos = lInputPos;
mReset = false;
}
else
{
if (lTimeDt == 0.0) lTimeDt = 30.0;
else
if (lTimeDt < 0.0) lTimeDt = fabsl(lTimeDt);
if (lTimeDt > 200.0) lTimeDt = 200.0;
const double dt = 1.0 / lTimeDt;
SpringSettings settings(lLength, lFriction, lM, lS, lD);
lHold = lInputPos;
//printf( "delta time double - %.2f\n", (float) mDeltaTimeDouble );
while( mDeltaTimeDouble > dt )
{
//printf( "vel length - %.2f\n", (float)FBLength( FBTVector(mVel[0], mVel[1], mVel[2], 0.0) ) );
CalculateSpring( dt, lInputPos, mCurrentPos, mOldPos, settings, mVel, mCurrentPos );
mDeltaTimeDouble -= dt;
}
lR = mCurrentPos;
mOldPos = mCurrentPos;
}
if( lRealTime > 0.0 )
{
lastSystemTimeDouble = lEvaluationTime.GetSecondDouble();
}
else
{
lastLocalTimeDouble = lEvaluationTime.GetSecondDouble();
}
// Write result out to connector.
mResultNode->WriteData( &lR[0], pEvaluateInfo );
return true;
}
/************************************************
* FBX Storage.
************************************************/
bool CBoxSpring::FbxStore( FBFbxObject *pFbxObject, kFbxObjectStore pStoreWhat )
{
/*
* Store box parameters.
*/
return true;
}
/************************************************
* FBX Retrieval.
************************************************/
bool CBoxSpring::FbxRetrieve(FBFbxObject *pFbxObject, kFbxObjectStore pStoreWhat )
{
/*
* Retrieve box parameters.
*/
return true;
} | 25.203349 | 182 | 0.625914 | Mikkelbf |
d56da687f54879debee3aa016e468bdf7c357561 | 7,864 | cpp | C++ | sparta/test/Argos/DatabaseDump/Database_dumper.cpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/test/Argos/DatabaseDump/Database_dumper.cpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/test/Argos/DatabaseDump/Database_dumper.cpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | #include "sparta/argos/Reader.hpp"
#include "sparta/argos/PipelineDataCallback.hpp"
#include "sparta/utils/SpartaAssert.hpp"
#include "sparta/utils/SpartaTester.hpp"
#include <iomanip>
#include <unordered_map>
#include <functional>
#include <unistd.h>
/**
* \file Database_dumper.cpp
* \brief dump an argos database to a human readable format.
* Instructions, run ./ArgosDumper <path+database prefix>
* the database prefix should be the same prefix passed to the simulator when creating the database
* example
* ./ArgosDumper ../../fiat/data_ > out.csv
*
* I recommend dumping the output to an *.csv file. Then in open office you can set the file to
* recognize spaces as new columns. If you do this, then you will have a nice output formatted table
* that should be a little easier to read/manipulate using sort functionality and what not in office.
*/
namespace sparta
{
namespace argos
{
class DumpCallback : public PipelineDataCallback
{
bool merge_transactions = false;
bool sort_by_end_time = false;
std::unordered_map<uint16_t, std::shared_ptr<transaction_t> > continued_transactions;
std::vector<std::string> output_buffer;
// Returns whether the given transaction is split across a heartbeat
bool isContinued(transaction_t *t)
{
return (t->flags & CONTINUE_FLAG) != 0;
}
// Prints a transaction to output_buffer
// This is used for the default sort mode (by transaction ID) when merging transactions
template<typename T>
void printToBuf(T* t, void(*print_func)(T*, std::ostream &))
{
std::stringstream sstr;
uint64_t trans_id = t->transaction_ID;
print_func(t, sstr);
if(output_buffer.size() <= trans_id)
{
output_buffer.resize(trans_id + 1);
}
output_buffer[trans_id] = sstr.str();
}
template<typename T>
void genericTransactionHandler(T* t, void(*print_func)(T*, std::ostream &))
{
// If there's no merging, then we can just print the transaction and be done
if(!merge_transactions)
{
print_func(t, std::cout);
return;
}
uint16_t loc_id = t->location_ID;
std::stringstream sstr;
// This transaction has already been encountered and is split across a heartbeat boundary
if(continued_transactions.count(loc_id))
{
// Update the saved transaction with the latest end time
std::shared_ptr<T> cont_trans = std::static_pointer_cast<T>(continued_transactions.at(loc_id));
cont_trans->time_End = t->time_End;
// If this transaction isn't continued, then it's the last one in the chain. So, we can print it and delete the entry.
if(!isContinued(t))
{
if(!sort_by_end_time)
{
// This will be out of order with respect to transaction ID, so print it to the buffer instead of stdout
printToBuf<T>(cont_trans.get(), print_func);
}
else
{
// We're sorting by end time, so we can just print directly to stdout
print_func(cont_trans.get(), std::cout);
}
continued_transactions.erase(loc_id);
}
}
else
{
// This is the first part of a transaction that has been split across a heartbeat boundary
if(isContinued(t))
{
continued_transactions[loc_id] = std::make_shared<T>(*t);
}
// This transaction isn't split at all
else
{
if(!sort_by_end_time)
{
// This will be out of order with respect to transaction ID, so print it to the buffer instead of stdout
printToBuf<T>(t, print_func);
}
else
{
// We're sorting by end time, so we can just print directly to stdout
print_func(t, std::cout);
}
}
}
}
static void printInst(instruction_t *t, std::ostream & sout)
{
sout << std::setbase(10);
sout << "*instruction* " << t->transaction_ID << " @ " << t->location_ID << " start: " << t->time_Start << " end: "<<t->time_End;
sout << " opcode: " << std::setbase(16) << std::showbase << t->operation_Code << " vaddr: " << t->virtual_ADR;
sout << " real_addr: " << t->real_ADR << std::endl;
}
virtual void foundInstRecord(instruction_t*t)
{
genericTransactionHandler<instruction_t>(t, &printInst);
}
static void printMemOp(memoryoperation_t *t, std::ostream & sout)
{
sout << std::setbase(10);
sout << "*memop* " << t->transaction_ID << " @ " << t->location_ID << " start: " << t->time_Start << " end: "<<t->time_End;
sout << std::setbase(16) << std::showbase << " vaddr: " << t->virtual_ADR;
sout << " real_addr: " << t->real_ADR << std::endl;
}
virtual void foundMemRecord(memoryoperation_t*t)
{
genericTransactionHandler<memoryoperation_t>(t, printMemOp);
}
static void printPairOp(pair_t * , std::ostream & ){
}
virtual void foundPairRecord(pair_t * t){
genericTransactionHandler<pair_t>(t, printPairOp);
}
static void printAnnotation(annotation_t* , std::ostream & )
{
}
virtual void foundAnnotationRecord(annotation_t*t)
{
genericTransactionHandler<annotation_t>(t, printAnnotation);
}
public:
// Sets merge/sort flags
void setFlags(bool merge, bool sort)
{
merge_transactions = merge;
sort_by_end_time = sort;
}
// Print the sorted buffer to stdout
void flushBuffer()
{
for(auto & s : output_buffer)
{
std::cout << s;
}
}
};
}//namespace sparta
}//namespace argos
void usage()
{
std::cerr << "Usage: ArgosDumper [-h] [-m] [-s] argos_db_prefix" << std::endl
<< "Options:" << std::endl
<< "\t-h\t\tPrint usage info" << std::endl
<< "\t-m\t\tMerge transactions that were split by a heartbeat interval" << std::endl
<< "\t-s\t\tSort output by transaction end time" << std:: endl;
}
int main(int argc, char ** argv)
{
sparta::argos::DumpCallback cb;
std::string db_path = "db_pipeout/pipeout";
if (argc > 1) {
db_path = argv[1];
}
bool merge_transactions = false;
bool sort_by_end_time = true;
cb.setFlags(merge_transactions, sort_by_end_time);
sparta::argos::Reader reader(db_path, &cb);
// Get data
reader.getWindow(reader.getCycleFirst(), reader.getCycleLast());
// If we're sorting by transaction ID, then we need to flush the buffer
// In non-merging mode, sorting by transaction ID and end time should be identical
if(merge_transactions && !sort_by_end_time)
{
cb.flushBuffer();
}
std::cout << "range: [" << reader.getCycleFirst() << ", " << reader.getCycleLast() << "]" << std::endl;
// Check indices
std::cout << "Checking indices:" << std::endl;
reader.dumpIndexTransactions();
}
| 34.491228 | 141 | 0.552009 | knute-sifive |
d570dc97b50454ae5075e488d7719a090bfd1215 | 5,791 | cpp | C++ | src/engine/entity/src/scripting/nodes/script_logic_gates.cpp | amrezzd/halley | 5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4 | [
"Apache-2.0"
] | null | null | null | src/engine/entity/src/scripting/nodes/script_logic_gates.cpp | amrezzd/halley | 5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4 | [
"Apache-2.0"
] | null | null | null | src/engine/entity/src/scripting/nodes/script_logic_gates.cpp | amrezzd/halley | 5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4 | [
"Apache-2.0"
] | null | null | null | #include "script_logic_gates.h"
using namespace Halley;
String ScriptLogicGateAnd::getShortDescription(const World& world, const ScriptGraphNode& node, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
auto b = getConnectedNodeName(world, node, graph, 1);
return addParentheses(std::move(a)) + " AND " + addParentheses(std::move(b));
}
gsl::span<const IScriptNodeType::PinType> ScriptLogicGateAnd::getPinConfiguration(const ScriptGraphNode& node) const
{
using ET = ScriptNodeElementType;
using PD = ScriptNodePinDirection;
const static auto data = std::array<PinType, 3>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
return data;
}
std::pair<String, Vector<ColourOverride>> ScriptLogicGateAnd::getNodeDescription(const ScriptGraphNode& node, const World& world, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
auto b = getConnectedNodeName(world, node, graph, 1);
ColourStringBuilder result;
result.append("True if ");
result.append(addParentheses(std::move(a)), Colour4f(0.97f, 0.35f, 0.35f));
result.append(" AND ");
result.append(addParentheses(std::move(b)), Colour4f(0.97f, 0.35f, 0.35f));
return result.moveResults();
}
ConfigNode ScriptLogicGateAnd::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
const bool value = readDataPin(environment, node, 0).asBool(false) && readDataPin(environment, node, 1).asBool(false);
return ConfigNode(value);
}
String ScriptLogicGateOr::getShortDescription(const World& world, const ScriptGraphNode& node, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
auto b = getConnectedNodeName(world, node, graph, 1);
return addParentheses(std::move(a)) + " OR " + addParentheses(std::move(b));
}
gsl::span<const IScriptNodeType::PinType> ScriptLogicGateOr::getPinConfiguration(const ScriptGraphNode& node) const
{
using ET = ScriptNodeElementType;
using PD = ScriptNodePinDirection;
const static auto data = std::array<PinType, 3>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
return data;
}
std::pair<String, Vector<ColourOverride>> ScriptLogicGateOr::getNodeDescription(const ScriptGraphNode& node, const World& world, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
auto b = getConnectedNodeName(world, node, graph, 1);
ColourStringBuilder result;
result.append("True if ");
result.append(addParentheses(std::move(a)), Colour4f(0.97f, 0.35f, 0.35f));
result.append(" OR ");
result.append(addParentheses(std::move(b)), Colour4f(0.97f, 0.35f, 0.35f));
return result.moveResults();
}
ConfigNode ScriptLogicGateOr::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
const bool value = readDataPin(environment, node, 0).asBool(false) || readDataPin(environment, node, 1).asBool(false);
return ConfigNode(value);
}
String ScriptLogicGateXor::getShortDescription(const World& world, const ScriptGraphNode& node, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
auto b = getConnectedNodeName(world, node, graph, 1);
return addParentheses(std::move(a)) + " XOR " + addParentheses(std::move(b));
}
gsl::span<const IScriptNodeType::PinType> ScriptLogicGateXor::getPinConfiguration(const ScriptGraphNode& node) const
{
using ET = ScriptNodeElementType;
using PD = ScriptNodePinDirection;
const static auto data = std::array<PinType, 3>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
return data;
}
std::pair<String, Vector<ColourOverride>> ScriptLogicGateXor::getNodeDescription(const ScriptGraphNode& node, const World& world, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
auto b = getConnectedNodeName(world, node, graph, 1);
ColourStringBuilder result;
result.append("True if ");
result.append(addParentheses(std::move(a)), Colour4f(0.97f, 0.35f, 0.35f));
result.append(" XOR ");
result.append(addParentheses(std::move(b)), Colour4f(0.97f, 0.35f, 0.35f));
return result.moveResults();
}
ConfigNode ScriptLogicGateXor::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
const bool value = (readDataPin(environment, node, 0).asBool(false) ^ readDataPin(environment, node, 1).asBool(false)) != 0;
return ConfigNode(value);
}
String ScriptLogicGateNot::getShortDescription(const World& world, const ScriptGraphNode& node, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
return "NOT " + addParentheses(std::move(a));
}
gsl::span<const IScriptNodeType::PinType> ScriptLogicGateNot::getPinConfiguration(const ScriptGraphNode& node) const
{
using ET = ScriptNodeElementType;
using PD = ScriptNodePinDirection;
const static auto data = std::array<PinType, 2>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
return data;
}
std::pair<String, Vector<ColourOverride>> ScriptLogicGateNot::getNodeDescription(const ScriptGraphNode& node, const World& world, const ScriptGraph& graph) const
{
auto a = getConnectedNodeName(world, node, graph, 0);
ColourStringBuilder result;
result.append("True if NOT ");
result.append(addParentheses(std::move(a)), Colour4f(0.97f, 0.35f, 0.35f));
return result.moveResults();
}
ConfigNode ScriptLogicGateNot::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
const bool value = !readDataPin(environment, node, 0).asBool(false);
return ConfigNode(value);
}
| 42.896296 | 169 | 0.756346 | amrezzd |
d573bc75a0042247c0b732f147440ff8edfefe5b | 8,243 | cpp | C++ | src/main.cpp | ysono/CarND-T3P1-Path-Planning | 1df4812381f51c22c35d46c9ae06a7a3f1eb68cb | [
"MIT"
] | null | null | null | src/main.cpp | ysono/CarND-T3P1-Path-Planning | 1df4812381f51c22c35d46c9ae06a7a3f1eb68cb | [
"MIT"
] | null | null | null | src/main.cpp | ysono/CarND-T3P1-Path-Planning | 1df4812381f51c22c35d46c9ae06a7a3f1eb68cb | [
"MIT"
] | null | null | null | #include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <tuple>
#include <vector>
#include <functional>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
#include "support.h"
using std::cout;
using std::endl;
using std::string;
using std::vector;
using nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y)
{
int prev_wp = -1;
while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) ))
{
prev_wp++;
}
int wp2 = (prev_wp+1)%maps_x.size();
double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s-maps_s[prev_wp]);
double seg_x = maps_x[prev_wp]+seg_s*cos(heading);
double seg_y = maps_y[prev_wp]+seg_s*sin(heading);
double perp_heading = heading-pi()/2;
double x = seg_x + d*cos(perp_heading);
double y = seg_y + d*sin(perp_heading);
return {x,y};
}
int main(int argc, char* argv[]) {
PP_DEBUG = argc >= 2 && strcmp(argv[1], "--debug") == 0;
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
std::ifstream in_map_(map_file_.c_str(), std::ifstream::in);
string line;
while (getline(in_map_, line)) {
std::istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
std::function<vector<double>(double, double)> sd_to_xy =
[&map_waypoints_s, &map_waypoints_x, &map_waypoints_y]
(double s, double d) {
return getXY(s, d, map_waypoints_s, map_waypoints_x, map_waypoints_y);
};
FSM fsm {KEEP_LANE, 1, SPEED_LIMIT};
// A requried property of the previously planned path that's not retained and
// provided by the simulator.
double end_path_speed = 0;
h.onMessage(
[&fsm, &end_path_speed, &sd_to_xy]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
Telemetry telemetry;
// Main car's localization Data
telemetry.now_x = j[1]["x"];
telemetry.now_y = j[1]["y"];
telemetry.now_s = j[1]["s"];
telemetry.now_d = j[1]["d"];
double now_yaw = j[1]["yaw"]; // deg
telemetry.now_yaw = deg2rad(now_yaw); // rad
telemetry.now_speed = j[1]["speed"]; // keep all speed vars as mph
// Previous path data given to the Planner
vector<double> future_path_x = j[1]["previous_path_x"];
vector<double> future_path_y = j[1]["previous_path_y"];
telemetry.future_path_x = future_path_x;
telemetry.future_path_y = future_path_y;
telemetry.future_path_size = future_path_x.size();
telemetry.future_path_duration = PATH_INTERVAL * telemetry.future_path_size;
// Previous path's end s and d values
telemetry.future_s = j[1]["end_path_s"];
telemetry.future_d = j[1]["end_path_d"];
telemetry.future_speed = end_path_speed;
// Sensor Fusion Data, a list of all other cars on the same side of the road.
vector<vector<double> > now_obstacles = j[1]["sensor_fusion"];
telemetry.now_obstacles = now_obstacles;
////// End of unravelling telemtry data //////
if (PP_DEBUG) {
cout << "======" << endl << fsm;
}
vector<double> next_path_x, next_path_y;
if (telemetry.future_path_size >= NUM_OUTPUT_PATH_POINTS) {
if (PP_DEBUG) {
cout << "no need to generate path points" << endl;
}
} else {
if (telemetry.future_path_size == 0) {
telemetry.future_s = telemetry.now_s;
telemetry.future_d = telemetry.now_d;
}
fsm = iterate_fsm(fsm, telemetry);
// For all modes, adjust acceleration only.
// We're using the same speed for all path points to be added.
// Although it would be more effective to use different speeds for
// points to be added, in practice it should make little difference
// becuase we rarely have to generate more than 1 to 3 points.
if (end_path_speed < fsm.target_speed) {
end_path_speed += DEFAULT_ACCEL;
} else {
end_path_speed -= DEFAULT_ACCEL;
}
std::tie(next_path_x, next_path_y) = generate_path(
fsm.target_lane, end_path_speed, telemetry, sd_to_xy);
}
////// Finished generating path //////
json msgJson;
msgJson["next_x"] = next_path_x;
msgJson["next_y"] = next_path_y;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
//this_thread::sleep_for(chrono::milliseconds(1000));
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| 32.07393 | 131 | 0.582798 | ysono |
d575ed33c151f988d5b6bfdbec60ddfe488f3891 | 213 | cpp | C++ | src/var/ConstString.cpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 2 | 2016-05-21T03:09:19.000Z | 2016-08-27T03:40:51.000Z | src/var/ConstString.cpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 75 | 2017-10-08T22:21:19.000Z | 2020-03-30T21:13:20.000Z | src/var/ConstString.cpp | StratifyLabs/StratifyLib | 975a5c25a84296fd0dec64fe4dc579cf7027abe6 | [
"MIT"
] | 5 | 2018-03-27T16:44:09.000Z | 2020-07-08T16:45:55.000Z | /*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#include "var/ConstString.hpp"
#include "var/Data.hpp"
using namespace var;
u32 sapi_const_string_unused;
| 17.75 | 100 | 0.737089 | bander9289 |
d5769fbb96776119150f0b2c8f036ee364fbad0e | 3,707 | cc | C++ | RAVL2/Audio/Features/testAudioFeatures.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Audio/Features/testAudioFeatures.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Audio/Features/testAudioFeatures.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2003, OmniPerception Ltd.
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//! rcsid="$Id: testAudioFeatures.cc 5240 2005-12-06 17:16:50Z plugger $"
//! lib=RavlAudioFeatures
//! docentry="Ravl.API.Audio.Feature Extraction"
//! userlevel=Develop
//! author="Charles Galambos"
//! file="Ravl/Audio/Features/testAudioFeatures.cc"
#include "Ravl/Audio/MelSpectrum.hh"
#include "Ravl/Audio/MelCepstrum.hh"
#include "Ravl/Audio/FeatureMFCC.hh"
#include "Ravl/Audio/VectorDelta012.hh"
#include "Ravl/Stream.hh"
#include "Ravl/SArray1dIter.hh"
#include "Ravl/StdConst.hh"
#include "Ravl/DP/ListIO.hh"
#include "Ravl/Random.hh"
using namespace RavlAudioN;
int testMelSpectrum();
int testMelCepstrum();
int testFeatureMFCC();
int testVectorDelta012();
int main() {
int ln;
if((ln = testMelSpectrum()) != 0) {
cerr << "Test failed line " << ln << "\n";
return 1;
}
if((ln = testMelCepstrum()) != 0) {
cerr << "Test failed line " << ln << "\n";
return 1;
}
if((ln = testFeatureMFCC()) != 0) {
cerr << "Test failed line " << ln << "\n";
return 1;
}
if((ln = testVectorDelta012()) != 0) {
cerr << "Test failed line " << ln << "\n";
return 1;
}
return 0;
}
int testMelSpectrum() {
int specSize = 512;
RealRangeC freqRange(133.333,6855.4976);
MelSpectrumC mel(16000,specSize,freqRange,40);
//: Check Lin2Mel & Mel2Lin.
for(RealT t = 10;t < 2000;t += 10) {
RealT v = mel.Lin2Mel(mel.Mel2Lin(t));
if(Abs(v - t) > 0.001) {
cerr << "v=" << v << " t=" << t << "\n";
return __LINE__;
}
}
// Test response to flat spectrum.
SArray1dC<RealT> spec(specSize);
spec.Fill(1);
SArray1dC<RealT> melspec = mel.Apply(spec);
//cerr << "Mel=" << melspec << "\n";
// Should be unit spectrum.
for(SArray1dIterC<RealT> it(melspec);it;it++)
if(Abs(*it - 1) > 0.01) return __LINE__;
return 0;
}
int testMelCepstrum() {
MelCepstrumC cep(13,40);
SArray1dC<RealT> spec(40);
RealT i = 0;
for(SArray1dIterC<RealT> it(spec);it;it++,i++) {
*it = Cos(i * RavlConstN::pi / 20) * 100 + 101;
cerr << " " << *it ;
}
cerr << "\n";
SArray1dC<RealT> cspec = cep.Apply(spec);
cerr << "Cepstrum=" << cspec << "\n";
return 0;
}
int testFeatureMFCC() {
cerr << "testFeatureMFCC(), Called. \n";
cerr.precision(2);
for(int i = 0;i < 3;i++) {
DListC<Int16T> list;
FeatureMFCCC fextract(16000);
switch(i) {
case 0: {
cerr << "Sine wave.\n";
for(int i= 0;i < 32000;i++)
list.InsLast(Round(Sin(i *(200 / RavlConstN::pi)) * 32000));
} break;
case 1: {
cerr << "Noise.\n";
for(int i= 0;i < 32000;i++)
list.InsLast((RandomInt() % 64000)-32000);
} break;
case 2: {
cerr << "Zero.\n";
for(int i= 0;i < 32000;i++)
list.InsLast(0);
} break;
}
DPISListC<Int16T> ip(list);
fextract.Input() = ip;
VectorC v1;
for(int i = 0;i < 20;i++) {
fextract.Get(v1);
for(SArray1dIterC<RealT> it(v1);it;it++)
if(*it < 0.001)
*it = 0;
cerr << "v1=" << v1 << "\n";
}
}
return 0;
}
int testVectorDelta012() {
cerr << "testVectorDelta012(), Called. \n";
VectorDelta012C vecDelta(3);
for(int i = 0;i < 10;i++) {
VectorC vec(3);
vec[0] = 1;
vec[1] = i;
vec[2] = Sqr(i);
VectorC delta = vecDelta.Apply(vec);
if(delta.Size() != (vec.Size() * 3))
return __LINE__;
cerr << delta << "\n";
}
return 0;
}
| 24.071429 | 74 | 0.586728 | isuhao |
d57789c51db7859511e6e61ceb723422b33327ee | 10,500 | cpp | C++ | PS_Fgen_FW/Screens/ScreenPS.cpp | M1S2/PS_Fgen_FW | 3fca0e33487b95cd1a5b4c2e9ea0d4f9f7a4dd97 | [
"MIT"
] | null | null | null | PS_Fgen_FW/Screens/ScreenPS.cpp | M1S2/PS_Fgen_FW | 3fca0e33487b95cd1a5b4c2e9ea0d4f9f7a4dd97 | [
"MIT"
] | 11 | 2021-06-08T13:08:46.000Z | 2021-12-11T13:50:54.000Z | PS_Fgen_FW/Screens/ScreenPS.cpp | M1S2/PS_Fgen_FW | 3fca0e33487b95cd1a5b4c2e9ea0d4f9f7a4dd97 | [
"MIT"
] | 1 | 2021-06-25T12:26:36.000Z | 2021-06-25T12:26:36.000Z | /*
* ScreenPS.cpp
* Created: 07.11.2020 13:09:35
* Author: Markus Scheich
*/
#include "../Device.h"
#ifdef PS_SUBSYSTEM_ENABLED
ContainerList list_PS(SCREEN_TAB_WIDTH, 0, 240 - SCREEN_TAB_WIDTH, 64);
#define PS_COLUMN1_POSX SCREEN_TAB_WIDTH + 5
#define PS_COLUMN2_POSX PS_COLUMN1_POSX + 83
#define PS_COLUMN3_POSX PS_COLUMN2_POSX + 57
#define PS_ROW1_POSY 25
#define PS_ROW2_POSY PS_ROW1_POSY + 20
void PSProtectionsClear(void* controlContext);
void PSProtectionsClearedOK(void* controlContext);
// ***** Power Supply Overview page *****
ContainerPage page_PSOverview;
Icon ico_PSOverview(SCREEN_TAB_WIDTH + 5, 3, icon_supplyDC_width, icon_supplyDC_height, icon_supplyDC_bits);
Label<15> lbl_PSOverview_caption(SCREEN_TAB_WIDTH + 25, 5, "PowerSupply");
Icon ico_PSOverviewVoltage(PS_COLUMN1_POSX, PS_ROW1_POSY - 2, icon_voltage_width, icon_voltage_height, icon_voltage_bits);
NumericControl<float> numCtrl_PSOverviewVoltage(PS_COLUMN1_POSX + icon_voltage_width + 3, PS_ROW1_POSY, &Device.PsChannel.Voltage.Val, "V", PS_MIN_VOLTAGE, PS_MAX_VOLTAGE, 3, &Device.PsChannel, &PS_Channel::PSVoltageChanged);
Icon ico_PSOverviewEnabled(PS_COLUMN2_POSX, PS_ROW1_POSY - 2, icon_OnOff_width, icon_OnOff_height, icon_OnOff_bits);
BoolControl boolCtrl_PSOverviewEnabled(PS_COLUMN2_POSX + icon_OnOff_width + 3, PS_ROW1_POSY, &Device.PsChannel.Enabled.Val, &Device.PsChannel, &PS_Channel::PSEnabledChanged);
Icon ico_PSOverviewCurrent(PS_COLUMN1_POSX, PS_ROW2_POSY - 2, icon_current_width, icon_current_height, icon_current_bits);
NumericControl<float> numCtrl_PSOverviewCurrent(PS_COLUMN1_POSX + icon_current_width + 3, PS_ROW2_POSY, &Device.PsChannel.Current.Val, "A", PS_MIN_CURRENT, PS_MAX_CURRENT, 3, &Device.PsChannel, &PS_Channel::PSCurrentChanged);
Icon ico_PSOverviewRegMode(PS_COLUMN2_POSX, PS_ROW2_POSY - 2, icon_pin_width, icon_pin_height, icon_pin_bits);
EnumControl<volatile PsRegulationModes_t> enumCtrl_PSOverviewRegMode(PS_COLUMN2_POSX + icon_pin_width + 3, PS_ROW2_POSY, &Device.PsChannel.RegulationMode, PsRegulationModesNames, NUM_PS_REG_MODE_ELEMENTS, &Device.PsChannel, &PS_Channel::PSRegulationModeChanged);
NumericIndicator<volatile float, 10> numInd_PsOverviewVoltage(PS_COLUMN3_POSX, 18, &Device.PsChannel.MeasuredVoltage, "V", PS_MAX_VOLTAGE, 3);
NumericIndicator<volatile float, 10> numInd_PsOverviewCurrent(PS_COLUMN3_POSX, 28, &Device.PsChannel.MeasuredCurrent, "A", PS_MAX_CURRENT, 3);
NumericIndicator<volatile float, 10> numInd_PsOverviewPower(PS_COLUMN3_POSX, 38, &Device.PsChannel.MeasuredPower, "W", PS_MAX_VOLTAGE * PS_MAX_CURRENT, 3);
EnumIndicator<volatile PsStates_t> enumInd_PsOverviewState(PS_COLUMN3_POSX + 4, 48, &Device.PsChannel.PsState, PsStatesNames, NUM_PS_STATE_ELEMENTS);
// ***** Power Supply Protection OVP page *****
ContainerPage page_PSProtectionOVP;
Icon ico_PSProtection(40, 3, icon_protection_width, icon_protection_height, icon_protection_bits);
Label<5> lbl_PSProtectionOVP_caption(60, 5, "OVP");
Icon ico_PSProtectionOVPLevel(PS_COLUMN1_POSX, PS_ROW1_POSY - 2, icon_level_width, icon_level_height, icon_level_bits);
NumericControl<uint8_t> numCtrl_PSProtectionOVPLevel(PS_COLUMN1_POSX + icon_level_width + 3, PS_ROW1_POSY, &Device.PsChannel.OvpLevel.Val, "%%", PS_MIN_OVP_LEVEL_PERCENTAGE, PS_MAX_OVP_LEVEL_PERCENTAGE, 0, &Device.PsChannel, &PS_Channel::PSOvpLevelChanged);
Icon ico_PSProtectionOVPState(PS_COLUMN2_POSX, PS_ROW1_POSY - 2, icon_OnOff_width, icon_OnOff_height, icon_OnOff_bits);
BoolControl boolCtrl_PSProtectionOVPState(PS_COLUMN2_POSX + icon_OnOff_width + 3, PS_ROW1_POSY, &Device.PsChannel.OvpState.Val, &Device.PsChannel, &PS_Channel::PSOvpStateChanged);
Icon ico_PSProtectionOVPDelay(PS_COLUMN1_POSX, PS_ROW2_POSY - 2, icon_delay_width, icon_delay_height, icon_delay_bits);
NumericControl<float> numCtrl_PSProtectionOVPDelay(PS_COLUMN1_POSX + icon_delay_width + 3, PS_ROW2_POSY, &Device.PsChannel.OvpDelay.Val, "s", PS_MIN_OVP_DELAY, PS_MAX_OVP_DELAY, 3, &Device.PsChannel, &PS_Channel::PSOvpDelayChanged);
ButtonControl<6> button_PSProtectionOVPClear(PS_COLUMN2_POSX, PS_ROW2_POSY, DEFAULT_UI_ELEMENT_WIDTH, DEFAULT_UI_ELEMENT_HEIGHT, "Clear", &Device.PsChannel, &PSProtectionsClear);
// ***** Power Supply Protection OCP page *****
ContainerPage page_PSProtectionOCP;
Label<5> lbl_PSProtectionOCP_caption(60, 5, "OCP");
Icon ico_PSProtectionOCPLevel(PS_COLUMN1_POSX, PS_ROW1_POSY - 2, icon_level_width, icon_level_height, icon_level_bits);
NumericControl<uint8_t> numCtrl_PSProtectionOCPLevel(PS_COLUMN1_POSX + icon_level_width + 3, PS_ROW1_POSY, &Device.PsChannel.OcpLevel.Val, "%%", PS_MIN_OCP_LEVEL_PERCENTAGE, PS_MAX_OCP_LEVEL_PERCENTAGE, 0, &Device.PsChannel, &PS_Channel::PSOcpLevelChanged);
Icon ico_PSProtectionOCPState(PS_COLUMN2_POSX, PS_ROW1_POSY - 2, icon_OnOff_width, icon_OnOff_height, icon_OnOff_bits);
BoolControl boolCtrl_PSProtectionOCPState(PS_COLUMN2_POSX + icon_OnOff_width + 3, PS_ROW1_POSY, &Device.PsChannel.OcpState.Val, &Device.PsChannel, &PS_Channel::PSOcpStateChanged);
Icon ico_PSProtectionOCPDelay(PS_COLUMN1_POSX, PS_ROW2_POSY - 2, icon_delay_width, icon_delay_height, icon_delay_bits);
NumericControl<float> numCtrl_PSProtectionOCPDelay(PS_COLUMN1_POSX + icon_delay_width + 3, PS_ROW2_POSY, &Device.PsChannel.OcpDelay.Val, "s", PS_MIN_OCP_DELAY, PS_MAX_OCP_DELAY, 3, &Device.PsChannel, &PS_Channel::PSOcpDelayChanged);
ButtonControl<6> button_PSProtectionOCPClear(PS_COLUMN2_POSX, PS_ROW2_POSY, DEFAULT_UI_ELEMENT_WIDTH, DEFAULT_UI_ELEMENT_HEIGHT, "Clear", &Device.PsChannel, &PSProtectionsClear);
// ***** Power Supply Protection OPP page *****
ContainerPage page_PSProtectionOPP;
Label<5> lbl_PSProtectionOPP_caption(60, 5, "OPP");
Icon ico_PSProtectionOPPLevel(PS_COLUMN1_POSX, PS_ROW1_POSY - 2, icon_level_width, icon_level_height, icon_level_bits);
NumericControl<float> numCtrl_PSProtectionOPPLevel(PS_COLUMN1_POSX + icon_level_width + 3, PS_ROW1_POSY, &Device.PsChannel.OppLevel.Val, "W", PS_MIN_OPP_LEVEL, PS_MAX_OPP_LEVEL, 3, &Device.PsChannel, &PS_Channel::PSOppLevelChanged);
Icon ico_PSProtectionOPPState(PS_COLUMN2_POSX, PS_ROW1_POSY - 2, icon_OnOff_width, icon_OnOff_height, icon_OnOff_bits);
BoolControl boolCtrl_PSProtectionOPPState(PS_COLUMN2_POSX + icon_OnOff_width + 3, PS_ROW1_POSY, &Device.PsChannel.OppState.Val, &Device.PsChannel, &PS_Channel::PSOppStateChanged);
Icon ico_PSProtectionOPPDelay(PS_COLUMN1_POSX, PS_ROW2_POSY - 2, icon_delay_width, icon_delay_height, icon_delay_bits);
NumericControl<float> numCtrl_PSProtectionOPPDelay(PS_COLUMN1_POSX + icon_delay_width + 3, PS_ROW2_POSY, &Device.PsChannel.OppDelay.Val, "s", PS_MIN_OPP_DELAY, PS_MAX_OPP_DELAY, 3, &Device.PsChannel, &PS_Channel::PSOppDelayChanged);
ButtonControl<6> button_PSProtectionOPPClear(PS_COLUMN2_POSX, PS_ROW2_POSY, DEFAULT_UI_ELEMENT_WIDTH, DEFAULT_UI_ELEMENT_HEIGHT, "Clear", &Device.PsChannel, &PSProtectionsClear);
MessageDialog<25> msg_protectionsCleared(0, 0, 240, 64, "Protections Cleared.", MSG_INFO, MSG_BTN_OK, NULL, &PSProtectionsClearedOK);
void PSProtectionsClear(void* controlContext)
{
Device.PsChannel.ClearProtections();
Device.ScreenManager.UiManager.ChangeVisualTreeRoot(&msg_protectionsCleared);
}
void PSProtectionsClearedOK(void* controlContext)
{
Device.ScreenManager.ShowUiMainPage();
}
UIElement* uiBuildScreenPS()
{
enumCtrl_PSOverviewRegMode.Width = 39;
numCtrl_PSOverviewVoltage.CurrentDigitPosition = -1; // select the 0.1 V digit.
numCtrl_PSOverviewCurrent.CurrentDigitPosition = -1; // select the 0.1 A digit.
page_PSOverview.AddItem(&ico_PSOverview);
page_PSOverview.AddItem(&lbl_PSOverview_caption);
page_PSOverview.AddItem(&ico_PSOverviewVoltage);
page_PSOverview.AddItem(&numCtrl_PSOverviewVoltage);
page_PSOverview.AddItem(&ico_PSOverviewEnabled);
page_PSOverview.AddItem(&boolCtrl_PSOverviewEnabled);
page_PSOverview.AddItem(&ico_PSOverviewCurrent);
page_PSOverview.AddItem(&numCtrl_PSOverviewCurrent);
page_PSOverview.AddItem(&ico_PSOverviewRegMode);
page_PSOverview.AddItem(&enumCtrl_PSOverviewRegMode);
page_PSOverview.AddItem(&numInd_PsOverviewVoltage);
page_PSOverview.AddItem(&numInd_PsOverviewCurrent);
page_PSOverview.AddItem(&numInd_PsOverviewPower);
page_PSOverview.AddItem(&enumInd_PsOverviewState);
page_PSOverview.InitItems();
numCtrl_PSProtectionOVPDelay.CurrentDigitPosition = -1; // select the 0.1 s digit.
page_PSProtectionOVP.AddItem(&ico_PSProtection);
page_PSProtectionOVP.AddItem(&lbl_PSProtectionOVP_caption);
page_PSProtectionOVP.AddItem(&ico_PSProtectionOVPLevel);
page_PSProtectionOVP.AddItem(&numCtrl_PSProtectionOVPLevel);
page_PSProtectionOVP.AddItem(&ico_PSProtectionOVPState);
page_PSProtectionOVP.AddItem(&boolCtrl_PSProtectionOVPState);
page_PSProtectionOVP.AddItem(&ico_PSProtectionOVPDelay);
page_PSProtectionOVP.AddItem(&numCtrl_PSProtectionOVPDelay);
page_PSProtectionOVP.AddItem(&button_PSProtectionOVPClear);
page_PSProtectionOVP.InitItems();
numCtrl_PSProtectionOCPDelay.CurrentDigitPosition = -1; // select the 0.1 s digit.
page_PSProtectionOCP.AddItem(&ico_PSProtection);
page_PSProtectionOCP.AddItem(&lbl_PSProtectionOCP_caption);
page_PSProtectionOCP.AddItem(&ico_PSProtectionOCPLevel);
page_PSProtectionOCP.AddItem(&numCtrl_PSProtectionOCPLevel);
page_PSProtectionOCP.AddItem(&ico_PSProtectionOCPState);
page_PSProtectionOCP.AddItem(&boolCtrl_PSProtectionOCPState);
page_PSProtectionOCP.AddItem(&ico_PSProtectionOCPDelay);
page_PSProtectionOCP.AddItem(&numCtrl_PSProtectionOCPDelay);
page_PSProtectionOCP.AddItem(&button_PSProtectionOCPClear);
page_PSProtectionOCP.InitItems();
numCtrl_PSProtectionOPPLevel.CurrentDigitPosition = -1; // select the 0.1 s digit.
numCtrl_PSProtectionOPPDelay.CurrentDigitPosition = -1; // select the 0.1 s digit.
page_PSProtectionOPP.AddItem(&ico_PSProtection);
page_PSProtectionOPP.AddItem(&lbl_PSProtectionOPP_caption);
page_PSProtectionOPP.AddItem(&ico_PSProtectionOPPLevel);
page_PSProtectionOPP.AddItem(&numCtrl_PSProtectionOPPLevel);
page_PSProtectionOPP.AddItem(&ico_PSProtectionOPPState);
page_PSProtectionOPP.AddItem(&boolCtrl_PSProtectionOPPState);
page_PSProtectionOPP.AddItem(&ico_PSProtectionOPPDelay);
page_PSProtectionOPP.AddItem(&numCtrl_PSProtectionOPPDelay);
page_PSProtectionOPP.AddItem(&button_PSProtectionOPPClear);
page_PSProtectionOPP.InitItems();
list_PS.AddItem(&page_PSOverview);
list_PS.AddItem(&page_PSProtectionOVP);
list_PS.AddItem(&page_PSProtectionOCP);
list_PS.AddItem(&page_PSProtectionOPP);
return &list_PS;
}
#endif /* PS_SUBSYSTEM_ENABLED */ | 66.037736 | 262 | 0.836381 | M1S2 |
d5798e8ed05db34d8c8fb29f13fb7b0c66f3eb67 | 3,748 | cpp | C++ | AIEngine/src/path/navmesh/polytope/PolytopePlaneSurface.cpp | petitg1987/urchinEngine | a14a57ac49a19237d748d2eafc7c2a38a45b95d6 | [
"BSL-1.0"
] | 18 | 2020-06-12T00:04:46.000Z | 2022-01-11T14:56:19.000Z | AIEngine/src/path/navmesh/polytope/PolytopePlaneSurface.cpp | petitg1987/urchinEngine | a14a57ac49a19237d748d2eafc7c2a38a45b95d6 | [
"BSL-1.0"
] | null | null | null | AIEngine/src/path/navmesh/polytope/PolytopePlaneSurface.cpp | petitg1987/urchinEngine | a14a57ac49a19237d748d2eafc7c2a38a45b95d6 | [
"BSL-1.0"
] | 6 | 2020-08-16T15:58:41.000Z | 2022-03-05T13:17:50.000Z | #include <algorithm>
#include <path/navmesh/polytope/PolytopePlaneSurface.h>
namespace urchin {
/**
* @param ccwPoints Points of the plane which must be coplanar and counter clockwise oriented
*/
PolytopePlaneSurface::PolytopePlaneSurface(std::vector<Point3<float>> ccwPoints, bool isSlopeWalkable) :
ccwPoints(std::move(ccwPoints)),
isSlopeWalkable(isSlopeWalkable) {
Vector3<float> v1 = this->ccwPoints[0].vector(this->ccwPoints[2]);
Vector3<float> v2 = this->ccwPoints[1].vector(this->ccwPoints[0]);
normal = v1.crossProduct(v2).normalize();
buildOutlineCwPoints();
buildAABBox();
}
/**
* @param ccwPoints Points of the plane which must be coplanar and counter clockwise oriented
*/
PolytopePlaneSurface::PolytopePlaneSurface(std::vector<Point3<float>> ccwPoints, const Vector3<float>& normal, bool isSlopeWalkable) :
ccwPoints(std::move(ccwPoints)),
normal(normal),
isSlopeWalkable(isSlopeWalkable) {
buildOutlineCwPoints();
buildAABBox();
}
void PolytopePlaneSurface::buildOutlineCwPoints() {
outlineCwPoints.reserve(ccwPoints.size());
for (auto it = ccwPoints.rbegin(); it != ccwPoints.rend(); ++it) {
outlineCwPoints.emplace_back(Point2<float>(it->X, -it->Z));
}
}
void PolytopePlaneSurface::buildAABBox() {
aabbox = AABBox<float>(ccwPoints);
}
bool PolytopePlaneSurface::isWalkable() const {
return isWalkableCandidate() && isSlopeWalkable;
}
Rectangle<float> PolytopePlaneSurface::computeXZRectangle() const {
Point2<float> minPoint(std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
Point2<float> maxPoint(-std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());
for (const auto& point : ccwPoints) {
minPoint.X = minPoint.X > point.X ? point.X : minPoint.X;
minPoint.Y = minPoint.Y > -point.Z ? -point.Z : minPoint.Y;
maxPoint.X = maxPoint.X < point.X ? point.X : minPoint.X;
maxPoint.Y = maxPoint.Y < -point.Z ? -point.Z : minPoint.Y;
}
return Rectangle<float>(minPoint, maxPoint);
}
const AABBox<float>& PolytopePlaneSurface::getAABBox() const {
return aabbox;
}
const std::vector<Point2<float>>& PolytopePlaneSurface::getOutlineCwPoints() const {
return outlineCwPoints;
}
Plane<float> PolytopePlaneSurface::getPlane(const Rectangle<float>&) const {
return Plane<float>(ccwPoints[0], ccwPoints[1], ccwPoints[2]);
}
const std::vector<CSGPolygon<float>>& PolytopePlaneSurface::getSelfObstacles() const {
return selfObstacles;
}
/**
* Return point on un-expanded surface
*/
Point3<float> PolytopePlaneSurface::computeRealPoint(const Point2<float>& point, const NavMeshAgent& agent) const {
Point3<float> pointOnExpandedSurface(point.X, 0.0, -point.Y);
float shortestFaceDistance = normal.dotProduct(pointOnExpandedSurface.vector(ccwPoints[0]));
pointOnExpandedSurface.Y += shortestFaceDistance / normal.Y;
float reduceDistance = - agent.computeExpandDistance(normal);
return pointOnExpandedSurface.translate(normal * reduceDistance);
}
const std::shared_ptr<const NavTopography>& PolytopePlaneSurface::getNavTopography() const {
return nullNavTopography; //no topography for flat surface
}
const std::vector<Point3<float>>& PolytopePlaneSurface::getCcwPoints() const {
return ccwPoints;
}
const Vector3<float>& PolytopePlaneSurface::getNormal() const {
return normal;
}
}
| 36.745098 | 138 | 0.661686 | petitg1987 |
d581ed3bd62df2d3380dd0e9caa4e20aad775550 | 7,728 | cpp | C++ | tests/xtd.core.unit_tests/src/xtd/diagnostics/trace_listener.cpp | BaderEddineOuaich/xtd | 6f28634c7949a541d183879d2de18d824ec3c8b1 | [
"MIT"
] | 1 | 2022-02-25T16:53:06.000Z | 2022-02-25T16:53:06.000Z | tests/xtd.core.unit_tests/src/xtd/diagnostics/trace_listener.cpp | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | tests/xtd.core.unit_tests/src/xtd/diagnostics/trace_listener.cpp | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | #define TRACE
#include <xtd/diagnostics/trace_listener.h>
#include <xtd/xtd.tunit>
#include <sstream>
using namespace xtd::diagnostics;
using namespace xtd::tunit;
namespace unit_tests {
class test_class_(test_trace_listener) {
class unit_test_trace_listener : public trace_listener {
public:
unit_test_trace_listener() = default;
xtd::ustring result() const {return string_stream.str();}
void close() override {}
void flush() override {}
using trace_listener::write;
void write(const xtd::ustring& message) override {
if (need_indent())
write_indent();
string_stream << message;
}
using trace_listener::write_line;
void write_line(const xtd::ustring& message) override {
write(message);
string_stream << std::endl;
need_indent(true);
}
using trace_listener::need_indent;
private:
std::stringstream string_stream;
};
public:
void test_method_(new_trace_listener) {
unit_test_trace_listener trace_listener;
assert::are_equal(0U, trace_listener.indent_level(), csf_);
assert::are_equal(4U, trace_listener.indent_size(), csf_);
assert::is_false(trace_listener.is_thread_safe(), csf_);
assert::is_empty(trace_listener.name(), csf_);
assert::is_true(trace_listener.need_indent(), csf_);
assert::are_equal(trace_options::none, trace_listener.trace_output_options(), csf_);
assert::is_empty(trace_listener.result(), csf_);
}
void test_method_(indent_level) {
unit_test_trace_listener trace_listener;
trace_listener.indent_level(5);
assert::are_equal(5U, trace_listener.indent_level(), csf_);
}
void test_method_(indent_size) {
unit_test_trace_listener trace_listener;
trace_listener.indent_size(8);
assert::are_equal(8U, trace_listener.indent_size(), csf_);
}
void test_method_(name) {
unit_test_trace_listener trace_listener;
trace_listener.name("test_omplementation");
assert::are_equal("test_omplementation", trace_listener.name(), csf_);
}
void test_method_(need_indent) {
unit_test_trace_listener trace_listener;
trace_listener.need_indent(false);
assert::is_false(trace_listener.need_indent(), csf_);
}
void test_method_(trace_output_options) {
unit_test_trace_listener trace_listener;
trace_listener.trace_output_options(trace_options::process_id | trace_options::callstack);
assert::are_equal(trace_options::process_id | trace_options::callstack, trace_listener.trace_output_options(), csf_);
}
void test_method_(fail_message) {
unit_test_trace_listener trace_listener;
trace_listener.fail("invalid_argument");
assert::are_equal("Fail: invalid_argument\n", trace_listener.result(), csf_);
}
void test_method_(fail_detail_message) {
unit_test_trace_listener trace_listener;
trace_listener.fail("invalid_argument", "Pointer is null");
assert::are_equal("Fail: invalid_argument Pointer is null\n", trace_listener.result(), csf_);
}
void test_method_(trace_data_with_string) {
unit_test_trace_listener trace_listener;
trace_listener.trace_data(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1, "information");
assert::are_equal("source error: 1 : information\n", trace_listener.result(), csf_);
}
void test_method_(trace_data_with_int) {
unit_test_trace_listener trace_listener;
trace_listener.trace_data(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1, 42);
assert::are_equal("source error: 1 : 42\n", trace_listener.result(), csf_);
}
void test_method_(trace_data_with_string_aarray) {
unit_test_trace_listener trace_listener;
trace_listener.trace_data(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1, std::vector<xtd::ustring> {"one", "two"});
assert::are_equal("source error: 1 : one, two\n", trace_listener.result(), csf_);
}
void test_method_(trace_data_with_string_args) {
unit_test_trace_listener trace_listener;
trace_listener.trace_data(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1, "one", "two");
assert::are_equal("source error: 1 : one, two\n", trace_listener.result(), csf_);
}
void test_method_(trace_event) {
unit_test_trace_listener trace_listener;
trace_listener.trace_event(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1);
assert::are_equal("source error: 1\n", trace_listener.result(), csf_);
}
void test_method_(trace_event_with_string) {
unit_test_trace_listener trace_listener;
trace_listener.trace_event(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1, "information");
assert::are_equal("source error: 1 : information\n", trace_listener.result(), csf_);
}
void test_method_(trace_event_with_format) {
unit_test_trace_listener trace_listener;
trace_listener.trace_event(xtd::diagnostics::trace_event_cache(), "source", xtd::diagnostics::trace_event_type::error, 1, "informations {}, {}", 42, "84");
assert::are_equal("source error: 1 : informations 42, 84\n", trace_listener.result(), csf_);
}
void test_method_(trace_transfer) {
unit_test_trace_listener trace_listener;
trace_listener.trace_transfer(xtd::diagnostics::trace_event_cache(), "source", 1, "message", "10203040-5060-7080-90a0-b0c0d0e0f001");
assert::are_equal("source transfer: 1 : message, related_activity_id=10203040-5060-7080-90a0-b0c0d0e0f001\n", trace_listener.result(), csf_);
}
void test_method_(write_string) {
unit_test_trace_listener trace_listener;
trace_listener.write("string");
assert::are_equal("string", trace_listener.result(), csf_);
}
void test_method_(write_int) {
unit_test_trace_listener trace_listener;
trace_listener.write(42);
assert::are_equal("42", trace_listener.result(), csf_);
}
void test_method_(write_line_string) {
unit_test_trace_listener trace_listener;
trace_listener.write_line("string");
assert::are_equal("string\n", trace_listener.result(), csf_);
}
void test_method_(write_line_int) {
unit_test_trace_listener trace_listener;
trace_listener.write_line(42);
assert::are_equal("42\n", trace_listener.result(), csf_);
}
void test_method_(write_stream_string) {
unit_test_trace_listener trace_listener;
trace_listener << "string";
assert::are_equal("string\n", trace_listener.result(), csf_);
}
void test_method_(write_stream_int) {
unit_test_trace_listener trace_listener;
trace_listener << 42;
assert::are_equal("42\n", trace_listener.result(), csf_);
}
void test_method_(write_string_with_one_indent_level) {
unit_test_trace_listener trace_listener;
trace_listener.indent_level(1);
trace_listener << "string";
assert::are_equal(" string\n", trace_listener.result(), csf_);
}
void test_method_(write_string_with_two_indent_level) {
unit_test_trace_listener trace_listener;
trace_listener.indent_size(8);
trace_listener.indent_level(2);
trace_listener << "string";
assert::are_equal(" string\n", trace_listener.result(), csf_);
}
};
}
| 40.041451 | 169 | 0.698499 | BaderEddineOuaich |
d584eb9d7aa75522aec97277674321061b90fbed | 5,296 | cpp | C++ | src/resource_provider/daemon.cpp | j143/mesos | a85a22baa32f66ecaa13c4602a195d57f6abf9be | [
"Apache-2.0"
] | null | null | null | src/resource_provider/daemon.cpp | j143/mesos | a85a22baa32f66ecaa13c4602a195d57f6abf9be | [
"Apache-2.0"
] | null | null | null | src/resource_provider/daemon.cpp | j143/mesos | a85a22baa32f66ecaa13c4602a195d57f6abf9be | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "resource_provider/daemon.hpp"
#include <utility>
#include <vector>
#include <glog/logging.h>
#include <process/id.hpp>
#include <process/process.hpp>
#include <stout/foreach.hpp>
#include <stout/json.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/protobuf.hpp>
#include <stout/try.hpp>
#include "resource_provider/local.hpp"
using std::list;
using std::string;
using std::vector;
using process::Owned;
using process::Process;
using process::ProcessBase;
using process::spawn;
using process::terminate;
using process::wait;
namespace mesos {
namespace internal {
class LocalResourceProviderDaemonProcess
: public Process<LocalResourceProviderDaemonProcess>
{
public:
LocalResourceProviderDaemonProcess(
const process::http::URL& _url,
const string& _workDir,
const Option<string>& _configDir)
: ProcessBase(process::ID::generate("local-resource-provider-daemon")),
url(_url),
workDir(_workDir),
configDir(_configDir) {}
protected:
void initialize() override;
private:
struct Provider
{
Provider(const ResourceProviderInfo& _info,
Owned<LocalResourceProvider> _provider)
: info(_info),
provider(std::move(_provider)) {}
const ResourceProviderInfo info;
const Owned<LocalResourceProvider> provider;
};
Try<Nothing> load(const string& path);
const process::http::URL url;
const string workDir;
const Option<string> configDir;
vector<Provider> providers;
};
void LocalResourceProviderDaemonProcess::initialize()
{
if (configDir.isNone()) {
return;
}
Try<list<string>> entries = os::ls(configDir.get());
if (entries.isError()) {
LOG(ERROR) << "Unable to list the resource provider directory '"
<< configDir.get() << "': " << entries.error();
}
foreach (const string& entry, entries.get()) {
const string path = path::join(configDir.get(), entry);
if (os::stat::isdir(path)) {
continue;
}
Try<Nothing> loading = load(path);
if (loading.isError()) {
LOG(ERROR) << "Failed to load resource provider config '"
<< path << "': " << loading.error();
continue;
}
}
}
Try<Nothing> LocalResourceProviderDaemonProcess::load(const string& path)
{
Try<string> read = os::read(path);
if (read.isError()) {
return Error("Failed to read the config file: " + read.error());
}
Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get());
if (json.isError()) {
return Error("Failed to parse the JSON config: " + json.error());
}
Try<ResourceProviderInfo> info =
::protobuf::parse<ResourceProviderInfo>(json.get());
if (info.isError()) {
return Error("Not a valid resource provider config: " + info.error());
}
// Ensure that ('type', 'name') pair is unique.
foreach (const Provider& provider, providers) {
if (info->type() == provider.info.type() &&
info->name() == provider.info.name()) {
return Error(
"Multiple resource providers with type '" + info->type() +
"' and name '" + info->name() + "'");
}
}
Try<Owned<LocalResourceProvider>> provider =
LocalResourceProvider::create(url, info.get());
if (provider.isError()) {
return Error(
"Failed to create resource provider with type '" + info->type() +
"' and name '" + info->name() + "'");
}
providers.emplace_back(info.get(), provider.get());
return Nothing();
}
Try<Owned<LocalResourceProviderDaemon>> LocalResourceProviderDaemon::create(
const process::http::URL& url,
const slave::Flags& flags)
{
// We require that the config directory exists to create a daemon.
Option<string> configDir = flags.resource_provider_config_dir;
if (configDir.isSome() && !os::exists(configDir.get())) {
return Error("Config directory '" + configDir.get() + "' does not exist");
}
return new LocalResourceProviderDaemon(
url,
flags.work_dir,
configDir);
}
LocalResourceProviderDaemon::LocalResourceProviderDaemon(
const process::http::URL& url,
const string& workDir,
const Option<string>& configDir)
: process(new LocalResourceProviderDaemonProcess(url, workDir, configDir))
{
spawn(CHECK_NOTNULL(process.get()));
}
LocalResourceProviderDaemon::~LocalResourceProviderDaemon()
{
terminate(process.get());
wait(process.get());
}
} // namespace internal {
} // namespace mesos {
| 26.613065 | 78 | 0.681647 | j143 |
d58560131eba6481eb625704b88a018347147c65 | 14,252 | cpp | C++ | legacy/gnupg/agent/divert-scd.cpp | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 224 | 2017-10-29T09:48:00.000Z | 2021-07-21T10:27:14.000Z | legacy/gnupg/agent/divert-scd.cpp | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 66 | 2017-10-29T16:17:55.000Z | 2020-11-30T18:53:40.000Z | legacy/gnupg/agent/divert-scd.cpp | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 22 | 2017-10-29T19:55:45.000Z | 2020-01-04T13:25:50.000Z | /* divert-scd.c - divert operations to the scdaemon
* Copyright (C) 2002, 2003, 2009 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <config.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "agent.h"
#include "../common/sexp-parse.h"
static int ask_for_card(ctrl_t ctrl, const unsigned char *shadow_info,
char **r_kid) {
int rc, i;
char *serialno;
int no_card = 0;
char *desc;
char *want_sn, *want_kid, *want_sn_disp;
int len;
*r_kid = NULL;
rc = parse_shadow_info(shadow_info, &want_sn, &want_kid, NULL);
if (rc) return rc;
want_sn_disp = xtrystrdup(want_sn);
if (!want_sn_disp) {
rc = gpg_error_from_syserror();
xfree(want_sn);
xfree(want_kid);
return rc;
}
len = strlen(want_sn_disp);
if (len == 32 && !strncmp(want_sn_disp, "D27600012401", 12)) {
/* This is an OpenPGP card - reformat */
memmove(want_sn_disp, want_sn_disp + 16, 4);
want_sn_disp[4] = ' ';
memmove(want_sn_disp + 5, want_sn_disp + 20, 8);
want_sn_disp[13] = 0;
} else if (len == 20 && want_sn_disp[19] == '0') {
/* We assume that a 20 byte serial number is a standard one
* which has the property to have a zero in the last nibble (Due
* to BCD representation). We don't display this '0' because it
* may confuse the user. */
want_sn_disp[19] = 0;
}
for (;;) {
rc = agent_card_serialno(ctrl, &serialno, want_sn);
if (!rc) {
log_debug("detected card with S/N %s\n", serialno);
i = strcmp(serialno, want_sn);
xfree(serialno);
serialno = NULL;
if (!i) {
xfree(want_sn_disp);
xfree(want_sn);
*r_kid = want_kid;
return 0; /* yes, we have the correct card */
}
} else if (rc == GPG_ERR_ENODEV) {
log_debug("no device present\n");
rc = 0;
no_card = 1;
} else if (rc == GPG_ERR_CARD_NOT_PRESENT) {
log_debug("no card present\n");
rc = 0;
no_card = 2;
} else {
log_error("error accessing card: %s\n", gpg_strerror(rc));
}
if (!rc) {
if (asprintf(&desc,
"%s:%%0A%%0A"
" %s",
no_card ? L_("Please insert the card with serial number")
: L_("Please remove the current card and "
"insert the one with serial number"),
want_sn_disp) < 0) {
rc = gpg_error_from_syserror();
} else {
rc = agent_get_confirmation(ctrl, desc, NULL, NULL, 0);
if (rc == GPG_ERR_NO_PIN_ENTRY) rc = GPG_ERR_CARD_NOT_PRESENT;
xfree(desc);
}
}
if (rc) {
xfree(want_sn_disp);
xfree(want_sn);
xfree(want_kid);
return rc;
}
}
}
/* Put the DIGEST into an DER encoded container and return it in R_VAL. */
static int encode_md_for_card(const unsigned char *digest, size_t digestlen,
int algo, unsigned char **r_val, size_t *r_len) {
unsigned char *frame;
unsigned char asn[100];
size_t asnlen;
*r_val = NULL;
*r_len = 0;
asnlen = DIM(asn);
if (!algo || gcry_md_test_algo(algo)) return GPG_ERR_DIGEST_ALGO;
if (gcry_md_algo_info(algo, GCRYCTL_GET_ASNOID, asn, &asnlen)) {
log_error("no object identifier for algo %d\n", algo);
return GPG_ERR_INTERNAL;
}
frame = (unsigned char *)xtrymalloc(asnlen + digestlen);
if (!frame) return gpg_error_from_syserror();
memcpy(frame, asn, asnlen);
memcpy(frame + asnlen, digest, digestlen);
if (DBG_CRYPTO) log_printhex("encoded hash:", frame, asnlen + digestlen);
*r_val = frame;
*r_len = asnlen + digestlen;
return 0;
}
/* Return true if STRING ends in "%0A". */
static int has_percent0A_suffix(const char *string) {
size_t n;
return (string && (n = strlen(string)) >= 3 &&
!strcmp(string + n - 3, "%0A"));
}
/* Callback used to ask for the PIN which should be set into BUF. The
buf has been allocated by the caller and is of size MAXBUF which
includes the terminating null. The function should return an UTF-8
string with the passphrase, the buffer may optionally be padded
with arbitrary characters.
If DESC_TEXT is not NULL it can be used as further informtion shown
atop of the INFO message.
INFO gets displayed as part of a generic string. However if the
first character of INFO is a vertical bar all up to the next
verical bar are considered flags and only everything after the
second vertical bar gets displayed as the full prompt.
Flags:
'N' = New PIN, this requests a second prompt to repeat the
PIN. If the PIN is not correctly repeated it starts from
all over.
'A' = The PIN is an Admin PIN, SO-PIN or alike.
'P' = The PIN is a PUK (Personal Unblocking Key).
'R' = The PIN is a Reset Code.
Example:
"|AN|Please enter the new security officer's PIN"
The text "Please ..." will get displayed and the flags 'A' and 'N'
are considered.
*/
static int getpin_cb(void *opaque, const char *desc_text, const char *info,
char *buf, size_t maxbuf) {
struct pin_entry_info_s *pi;
int rc;
ctrl_t ctrl = (ctrl_t)opaque;
const char *ends, *s;
int any_flags = 0;
int newpin = 0;
int resetcode = 0;
int is_puk = 0;
const char *again_text = NULL;
const char *prompt = "PIN";
if (buf && maxbuf < 2) return GPG_ERR_INV_VALUE;
/* Parse the flags. */
if (info && *info == '|' && (ends = strchr(info + 1, '|'))) {
for (s = info + 1; s < ends; s++) {
if (*s == 'A')
prompt = L_("Admin PIN");
else if (*s == 'P') {
/* TRANSLATORS: A PUK is the Personal Unblocking Code
used to unblock a PIN. */
prompt = L_("PUK");
is_puk = 1;
} else if (*s == 'N')
newpin = 1;
else if (*s == 'R') {
prompt = L_("Reset Code");
resetcode = 1;
}
}
info = ends + 1;
any_flags = 1;
} else if (info && *info == '|')
log_debug("pin_cb called without proper PIN info hack\n");
/* If BUF has been passed as NULL, we are in pinpad mode: The
callback opens the popup and immediately returns. */
if (!buf) {
if (maxbuf == 0) /* Close the pinentry. */
{
agent_popup_message_stop(ctrl);
rc = 0;
} else if (maxbuf == 1) /* Open the pinentry. */
{
if (info) {
char *desc, *desc2;
if (asprintf(&desc, L_("%s%%0A%%0AUse the reader's pinpad for input."),
info) < 0)
rc = gpg_error_from_syserror();
else {
/* Prepend DESC_TEXT to INFO. */
if (desc_text)
desc2 = strconcat(
desc_text, has_percent0A_suffix(desc_text) ? "%0A" : "%0A%0A",
desc, NULL);
else
desc2 = NULL;
rc = agent_popup_message_start(ctrl, desc2 ? desc2 : desc, NULL);
xfree(desc2);
xfree(desc);
}
} else
rc = agent_popup_message_start(ctrl, desc_text, NULL);
} else
rc = GPG_ERR_INV_VALUE;
return rc;
}
/* FIXME: keep PI and TRIES in OPAQUE. Frankly this is a whole
mess because we should call the card's verify function from the
pinentry check pin CB. */
again:
pi = (pin_entry_info_s *)gcry_calloc_secure(1, sizeof(*pi) + maxbuf + 10);
if (!pi) return gpg_error_from_syserror();
pi->max_length = maxbuf - 1;
pi->min_digits = 0; /* we want a real passphrase */
pi->max_digits = 16;
pi->max_tries = 3;
if (any_flags) {
{
char *desc2;
if (desc_text)
desc2 = strconcat(desc_text,
has_percent0A_suffix(desc_text) ? "%0A" : "%0A%0A",
info, NULL);
else
desc2 = NULL;
rc = agent_askpin(ctrl, desc2 ? desc2 : info, prompt, again_text, pi,
NULL, (cache_mode_t)(0));
xfree(desc2);
}
again_text = NULL;
if (!rc && newpin) {
struct pin_entry_info_s *pi2;
pi2 =
(pin_entry_info_s *)gcry_calloc_secure(1, sizeof(*pi) + maxbuf + 10);
if (!pi2) {
rc = gpg_error_from_syserror();
xfree(pi);
return rc;
}
pi2->max_length = maxbuf - 1;
pi2->min_digits = 0;
pi2->max_digits = 16;
pi2->max_tries = 1;
rc = agent_askpin(ctrl, (resetcode ? L_("Repeat this Reset Code")
: is_puk ? L_("Repeat this PUK")
: L_("Repeat this PIN")),
prompt, NULL, pi2, NULL, (cache_mode_t)0);
if (!rc && strcmp(pi->pin, pi2->pin)) {
again_text =
(resetcode ? L_("Reset Code not correctly repeated; try again")
: is_puk ? L_("PUK not correctly repeated; try again")
: L_("PIN not correctly repeated; try again"));
xfree(pi2);
xfree(pi);
goto again;
}
xfree(pi2);
}
} else {
char *desc, *desc2;
if (asprintf(&desc, L_("Please enter the PIN%s%s%s to unlock the card"),
info ? " (" : "", info ? info : "", info ? ")" : "") < 0)
desc = NULL;
if (desc_text)
desc2 = strconcat(desc_text,
has_percent0A_suffix(desc_text) ? "%0A" : "%0A%0A",
desc, NULL);
else
desc2 = NULL;
rc = agent_askpin(ctrl, desc2 ? desc2 : desc ? desc : info, prompt, NULL,
pi, NULL, (cache_mode_t)(0));
xfree(desc2);
xfree(desc);
}
if (!rc) {
strncpy(buf, pi->pin, maxbuf - 1);
buf[maxbuf - 1] = 0;
}
xfree(pi);
return rc;
}
/* This function is used when a sign operation has been diverted to a
* smartcard. DESC_TEXT is the original text for a prompt has send by
* gpg to gpg-agent.
*
* FIXME: Explain the other args. */
int divert_pksign(ctrl_t ctrl, const char *desc_text,
const unsigned char *digest, size_t digestlen, int algo,
const unsigned char *shadow_info, unsigned char **r_sig,
size_t *r_siglen) {
int rc;
char *kid;
size_t siglen;
unsigned char *sigval = NULL;
(void)desc_text;
rc = ask_for_card(ctrl, shadow_info, &kid);
if (rc) return rc;
if (algo == MD_USER_TLS_MD5SHA1) {
int save = ctrl->use_auth_call;
ctrl->use_auth_call = 1;
rc = agent_card_pksign(ctrl, kid, getpin_cb, ctrl, NULL, algo, digest,
digestlen, &sigval, &siglen);
ctrl->use_auth_call = save;
} else {
unsigned char *data;
size_t ndata;
rc = encode_md_for_card(digest, digestlen, algo, &data, &ndata);
if (!rc) {
rc = agent_card_pksign(ctrl, kid, getpin_cb, ctrl, NULL, algo, data,
ndata, &sigval, &siglen);
xfree(data);
}
}
if (!rc) {
*r_sig = sigval;
*r_siglen = siglen;
}
xfree(kid);
return rc;
}
/* Decrypt the value given asn an S-expression in CIPHER using the
key identified by SHADOW_INFO and return the plaintext in an
allocated buffer in R_BUF. The padding information is stored at
R_PADDING with -1 for not known. */
int divert_pkdecrypt(ctrl_t ctrl, const char *desc_text,
const unsigned char *cipher,
const unsigned char *shadow_info, char **r_buf,
size_t *r_len, int *r_padding) {
int rc;
char *kid;
const unsigned char *s;
size_t n;
const unsigned char *ciphertext;
size_t ciphertextlen;
char *plaintext;
size_t plaintextlen;
(void)desc_text;
*r_padding = -1;
s = cipher;
if (*s != '(') return GPG_ERR_INV_SEXP;
s++;
n = snext(&s);
if (!n) return GPG_ERR_INV_SEXP;
if (!smatch(&s, n, "enc-val")) return GPG_ERR_UNKNOWN_SEXP;
if (*s != '(') return GPG_ERR_UNKNOWN_SEXP;
s++;
n = snext(&s);
if (!n) return GPG_ERR_INV_SEXP;
if (smatch(&s, n, "rsa")) {
if (*s != '(') return GPG_ERR_UNKNOWN_SEXP;
s++;
n = snext(&s);
if (!n) return GPG_ERR_INV_SEXP;
if (!smatch(&s, n, "a")) return GPG_ERR_UNKNOWN_SEXP;
n = snext(&s);
} else if (smatch(&s, n, "ecdh")) {
if (*s != '(') return GPG_ERR_UNKNOWN_SEXP;
s++;
n = snext(&s);
if (!n) return GPG_ERR_INV_SEXP;
if (smatch(&s, n, "s")) {
n = snext(&s);
s += n;
if (*s++ != ')') return GPG_ERR_INV_SEXP;
if (*s++ != '(') return GPG_ERR_UNKNOWN_SEXP;
n = snext(&s);
if (!n) return GPG_ERR_INV_SEXP;
}
if (!smatch(&s, n, "e")) return GPG_ERR_UNKNOWN_SEXP;
n = snext(&s);
} else
return GPG_ERR_UNSUPPORTED_ALGORITHM;
if (!n) return GPG_ERR_UNKNOWN_SEXP;
ciphertext = s;
ciphertextlen = n;
rc = ask_for_card(ctrl, shadow_info, &kid);
if (rc) return rc;
rc =
agent_card_pkdecrypt(ctrl, kid, getpin_cb, ctrl, NULL, ciphertext,
ciphertextlen, &plaintext, &plaintextlen, r_padding);
if (!rc) {
*r_buf = plaintext;
*r_len = plaintextlen;
}
xfree(kid);
return rc;
}
int divert_writekey(ctrl_t ctrl, int force, const char *serialno,
const char *id, const char *keydata, size_t keydatalen) {
return agent_card_writekey(ctrl, force, serialno, id, keydata, keydatalen,
getpin_cb, ctrl);
}
int divert_generic_cmd(ctrl_t ctrl, const char *cmdline, void *assuan_context) {
return agent_card_scd(ctrl, cmdline, getpin_cb, ctrl, assuan_context);
}
| 30.518201 | 80 | 0.586865 | mehrdad-shokri |
d586f35a84d344c5c59774ecc4363eecd344167c | 5,634 | cc | C++ | m.heap/swe9416.cc | kimminki10/algorithms2 | 5d3b2d970dbc88169108632ce0d234bf74446316 | [
"MIT"
] | null | null | null | m.heap/swe9416.cc | kimminki10/algorithms2 | 5d3b2d970dbc88169108632ce0d234bf74446316 | [
"MIT"
] | null | null | null | m.heap/swe9416.cc | kimminki10/algorithms2 | 5d3b2d970dbc88169108632ce0d234bf74446316 | [
"MIT"
] | null | null | null | #ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <ctime>
/////
struct post {
int like=0;
int uid=-1;
int timestamp;
} posts[100'005];
int postCnt = 0;
int following[1'003][1'003];
int fidx[1'003];
int userNum;
void init(int N) {
userNum = N;
postCnt = 0;
for (int i = 0; i <= N; i++) {
following[i][0] = i;
fidx[i] = 1;
}
}
void follow(int uID1, int uID2, int timestamp) {
int fi = fidx[uID1]++;
following[uID1][fi] = uID2;
}
void makePost(int uID, int pID, int timestamp) {
postCnt++;
post &p = posts[pID];
p.like = 0; p.uid = uID; p.timestamp = timestamp;
}
void like(int pID, int timestamp) {
posts[pID].like++;
}
bool isFollow(int uID, int puid) {
int fl = fidx[uID];
for (int i = 0; i < fl; i++) {
if (following[uID][i] == puid) {
return true;
}
}
return false;
}
void getFeed(int uID, int timestamp, int pIDList[]) {
int topten[11];
int tidx = 0;
for (int pid = postCnt; pid >= 1; pid--) {
post p = posts[pid];
if (!isFollow(uID, p.uid)) { continue; }
if (timestamp - p.timestamp > 1000) {
if (tidx >= 10) { break; }
topten[tidx++] = pid;
if (tidx >= 10) { break; }
continue;
}
int cur = 0;
for (; cur < tidx; cur++) {
int tid = topten[cur];
if (posts[tid].like < posts[pid].like) {
for (int i = tidx; i >= cur+1; i--) {
topten[i] = topten[i-1];
}
break;
}
}
topten[cur] = pid; tidx++;
if (tidx > 10) { tidx = 10; }
}
for (int i = 0; i < 10; i++) {
pIDList[i] = topten[i];
}
}
/////
static int mSeed;
static int pseudo_rand(void) {
mSeed = mSeed * 431345 + 2531999;
return mSeed & 0x7FFFFFFF;
}
static int follow_status[1005][1005];
static int answer_score;
static int n; // n >= 2 && n <= 1000
static int end_timestamp;
static int follow_ratio; // follow_ratio >= 1 && follow_ratio <= 10000
static int make_ratio; // make_ratio >= 1 && make_ratio <= 10000
static int like_ratio; // like_ratio >= 1 && like_ratio <= 10000
static int get_feed_ratio; // get_feed_ratio >= 1 && get_feed_ratio <= 10000
static int post_arr[200000];
static int total_post_cnt;
static int min_post_cnt;
static bool run() {
int uId1, uId2, pId, pIdList[10], ans_pIdList[10], rand_val;
bool ret = true;
scanf("%d%d%d%d%d%d%d", &mSeed, &n, &end_timestamp, &follow_ratio,
&make_ratio, &like_ratio, &get_feed_ratio);
init(n);
for (int uId1 = 1; uId1 <= n; uId1++) {
follow_status[uId1][uId1] = 1;
int m = n / 10 + 1;
if (m > 10) m = 10;
for (int i = 0; i < m; i++) {
uId2 = uId1;
while (follow_status[uId1][uId2] == 1) {
uId2 = pseudo_rand() % n + 1;
}
follow(uId1, uId2, 1);
follow_status[uId1][uId2] = 1;
}
}
min_post_cnt = total_post_cnt = 1;
for (int timestamp = 1; timestamp <= end_timestamp; timestamp++) {
rand_val = pseudo_rand() % 10000;
if (rand_val < follow_ratio) {
uId1 = pseudo_rand() % n + 1;
uId2 = pseudo_rand() % n + 1;
int lim = 0;
while (follow_status[uId1][uId2] == 1 || uId1 == uId2) {
uId2 = pseudo_rand() % n + 1;
lim++;
if (lim >= 5) break;
}
if (follow_status[uId1][uId2] == 0) {
follow(uId1, uId2, timestamp);
follow_status[uId1][uId2] = 1;
}
}
rand_val = pseudo_rand() % 10000;
if (rand_val < make_ratio) {
uId1 = pseudo_rand() % n + 1;
post_arr[total_post_cnt] = timestamp;
makePost(uId1, total_post_cnt, timestamp);
total_post_cnt += 1;
}
rand_val = pseudo_rand() % 10000;
if (rand_val < like_ratio && total_post_cnt - min_post_cnt > 0) {
while (post_arr[min_post_cnt] < timestamp - 1000 &&
min_post_cnt < total_post_cnt)
min_post_cnt++;
if (total_post_cnt != min_post_cnt) {
pId = pseudo_rand() % (total_post_cnt - min_post_cnt) +
min_post_cnt;
like(pId, timestamp);
}
}
rand_val = pseudo_rand() % 10000;
if (rand_val < get_feed_ratio && total_post_cnt > 0) {
uId1 = pseudo_rand() % n + 1;
getFeed(uId1, timestamp, pIdList);
for (int i = 0; i < 10; i++) {
scanf("%d", ans_pIdList + i);
}
for (int i = 0; i < 10; i++) {
if (ans_pIdList[i] == 0) break;
if (ans_pIdList[i] != pIdList[i]) {
ret = false;
}
}
}
}
return ret;
}
int main() {
clock_t start, end;
freopen("../input.txt", "r", stdin);
setbuf(stdout, NULL);
int tc;
start = clock();
scanf("%d%d", &tc, &answer_score);
for (int t = 1; t <= tc; t++) {
int score;
for (int i = 0; i < 1005; i++)
for (int j = 0; j < 1005; j++) follow_status[i][j] = 0;
if (run())
score = answer_score;
else
score = 0;
printf("#%d %d\n", t, score);
}
end = clock();
printf("time: %lf sec\n", (double)(end-start) / CLOCKS_PER_SEC);
return 0;
} | 26.450704 | 77 | 0.49219 | kimminki10 |
d587565617377a489d461c0dabadcd937e65b083 | 1,706 | cpp | C++ | part7/Task7.3/Task7.3/sort.cpp | Matvey1703/Homework | 4599a5a5a1bdaeb819eee13a6233c72ce544c179 | [
"Apache-2.0"
] | 1 | 2020-09-30T17:17:41.000Z | 2020-09-30T17:17:41.000Z | part7/Task7.3/Task7.3/sort.cpp | Matvey1703/Homework | 4599a5a5a1bdaeb819eee13a6233c72ce544c179 | [
"Apache-2.0"
] | null | null | null | part7/Task7.3/Task7.3/sort.cpp | Matvey1703/Homework | 4599a5a5a1bdaeb819eee13a6233c72ce544c179 | [
"Apache-2.0"
] | null | null | null | #include <string.h>
#include "sort.h"
bool less(ListElement* element1, ListElement* element2, bool byPhone)
{
if (byPhone)
{
return strcmp(fieldPhone(element1), fieldPhone(element2)) < 0;
}
else
{
return strcmp(fieldName(element1), fieldName(element2)) < 0;
}
}
void mergeSort(List* list, ListElement* head, ListElement* tail, bool byPhone)
{
if (head == tail || isEmpty(list))
{
return;
}
ListElement* leftDelimetr = head;
ListElement* rightDelimetr = tail;
while (shiftNext(leftDelimetr) != rightDelimetr && shiftNext(leftDelimetr) != shiftPrev(rightDelimetr))
{
leftDelimetr = shiftNext(leftDelimetr);
rightDelimetr = shiftPrev(rightDelimetr);
}
if (shiftNext(leftDelimetr) == shiftPrev(rightDelimetr))
{
leftDelimetr = shiftNext(leftDelimetr);
}
mergeSort(list, head, leftDelimetr, byPhone);
mergeSort(list, rightDelimetr, tail, byPhone);
List* bufferList = create();
ListElement* leftHelper = head;
ListElement* rightHelper = rightDelimetr;
while (leftHelper != rightDelimetr || rightHelper != shiftNext(tail))
{
if ((rightHelper == shiftNext(tail) || less(leftHelper, rightHelper, byPhone)) && leftHelper != rightDelimetr)
{
addElement(fieldName(leftHelper), fieldPhone(leftHelper), bufferList);
leftHelper = shiftNext(leftHelper);
}
else
{
addElement(fieldName(rightHelper), fieldPhone(rightHelper), bufferList);
rightHelper = shiftNext(rightHelper);
}
}
ListElement* bufferHelper = headPointer(bufferList);
ListElement* listHelper = head;
while (bufferHelper != nullptr)
{
copyFields(&listHelper, &bufferHelper);
listHelper = shiftNext(listHelper);
bufferHelper = shiftNext(bufferHelper);
}
deleteList(bufferList);
} | 25.848485 | 112 | 0.727433 | Matvey1703 |
d5886db1acc5531017a2656266bcc819a55ee107 | 16,472 | cc | C++ | thirdparty/google/type/timeofday.pb.cc | kobeya/GVA-demo | 41a57bfff01ab0de2f56ddcd7611514e550472ff | [
"Apache-2.0"
] | 2 | 2019-03-29T07:20:43.000Z | 2019-08-13T04:47:27.000Z | thirdparty/google/type/timeofday.pb.cc | kobeya/GVA-demo | 41a57bfff01ab0de2f56ddcd7611514e550472ff | [
"Apache-2.0"
] | null | null | null | thirdparty/google/type/timeofday.pb.cc | kobeya/GVA-demo | 41a57bfff01ab0de2f56ddcd7611514e550472ff | [
"Apache-2.0"
] | 1 | 2019-08-09T05:26:50.000Z | 2019-08-09T05:26:50.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/timeofday.proto
#include "google/type/timeofday.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace google {
namespace type {
class TimeOfDayDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TimeOfDay>
_instance;
} _TimeOfDay_default_instance_;
} // namespace type
} // namespace google
namespace protobuf_google_2ftype_2ftimeofday_2eproto {
static void InitDefaultsTimeOfDay() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::type::_TimeOfDay_default_instance_;
new (ptr) ::google::type::TimeOfDay();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::type::TimeOfDay::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_TimeOfDay =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimeOfDay}, {}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_TimeOfDay.base);
}
::google::protobuf::Metadata file_level_metadata[1];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::type::TimeOfDay, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::type::TimeOfDay, hours_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::type::TimeOfDay, minutes_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::type::TimeOfDay, seconds_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::type::TimeOfDay, nanos_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::type::TimeOfDay)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::type::_TimeOfDay_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"google/type/timeofday.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\033google/type/timeofday.proto\022\013google.ty"
"pe\"K\n\tTimeOfDay\022\r\n\005hours\030\001 \001(\005\022\017\n\007minute"
"s\030\002 \001(\005\022\017\n\007seconds\030\003 \001(\005\022\r\n\005nanos\030\004 \001(\005B"
"i\n\017com.google.typeB\016TimeOfDayProtoP\001Z>go"
"ogle.golang.org/genproto/googleapis/type"
"/timeofday;timeofday\242\002\003GTPb\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 234);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/type/timeofday.proto", &protobuf_RegisterTypes);
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_google_2ftype_2ftimeofday_2eproto
namespace google {
namespace type {
// ===================================================================
void TimeOfDay::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TimeOfDay::kHoursFieldNumber;
const int TimeOfDay::kMinutesFieldNumber;
const int TimeOfDay::kSecondsFieldNumber;
const int TimeOfDay::kNanosFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TimeOfDay::TimeOfDay()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_google_2ftype_2ftimeofday_2eproto::scc_info_TimeOfDay.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.type.TimeOfDay)
}
TimeOfDay::TimeOfDay(const TimeOfDay& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&hours_, &from.hours_,
static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&hours_)) + sizeof(nanos_));
// @@protoc_insertion_point(copy_constructor:google.type.TimeOfDay)
}
void TimeOfDay::SharedCtor() {
::memset(&hours_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&hours_)) + sizeof(nanos_));
}
TimeOfDay::~TimeOfDay() {
// @@protoc_insertion_point(destructor:google.type.TimeOfDay)
SharedDtor();
}
void TimeOfDay::SharedDtor() {
}
void TimeOfDay::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* TimeOfDay::descriptor() {
::protobuf_google_2ftype_2ftimeofday_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2ftype_2ftimeofday_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const TimeOfDay& TimeOfDay::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_google_2ftype_2ftimeofday_2eproto::scc_info_TimeOfDay.base);
return *internal_default_instance();
}
void TimeOfDay::Clear() {
// @@protoc_insertion_point(message_clear_start:google.type.TimeOfDay)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&hours_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&hours_)) + sizeof(nanos_));
_internal_metadata_.Clear();
}
bool TimeOfDay::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.type.TimeOfDay)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 hours = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &hours_)));
} else {
goto handle_unusual;
}
break;
}
// int32 minutes = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &minutes_)));
} else {
goto handle_unusual;
}
break;
}
// int32 seconds = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &seconds_)));
} else {
goto handle_unusual;
}
break;
}
// int32 nanos = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &nanos_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.type.TimeOfDay)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.type.TimeOfDay)
return false;
#undef DO_
}
void TimeOfDay::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.type.TimeOfDay)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 hours = 1;
if (this->hours() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->hours(), output);
}
// int32 minutes = 2;
if (this->minutes() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->minutes(), output);
}
// int32 seconds = 3;
if (this->seconds() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->seconds(), output);
}
// int32 nanos = 4;
if (this->nanos() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->nanos(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:google.type.TimeOfDay)
}
::google::protobuf::uint8* TimeOfDay::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.type.TimeOfDay)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 hours = 1;
if (this->hours() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->hours(), target);
}
// int32 minutes = 2;
if (this->minutes() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->minutes(), target);
}
// int32 seconds = 3;
if (this->seconds() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->seconds(), target);
}
// int32 nanos = 4;
if (this->nanos() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->nanos(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.type.TimeOfDay)
return target;
}
size_t TimeOfDay::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.type.TimeOfDay)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// int32 hours = 1;
if (this->hours() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->hours());
}
// int32 minutes = 2;
if (this->minutes() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->minutes());
}
// int32 seconds = 3;
if (this->seconds() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->seconds());
}
// int32 nanos = 4;
if (this->nanos() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->nanos());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TimeOfDay::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.type.TimeOfDay)
GOOGLE_DCHECK_NE(&from, this);
const TimeOfDay* source =
::google::protobuf::internal::DynamicCastToGenerated<const TimeOfDay>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.type.TimeOfDay)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.type.TimeOfDay)
MergeFrom(*source);
}
}
void TimeOfDay::MergeFrom(const TimeOfDay& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.type.TimeOfDay)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.hours() != 0) {
set_hours(from.hours());
}
if (from.minutes() != 0) {
set_minutes(from.minutes());
}
if (from.seconds() != 0) {
set_seconds(from.seconds());
}
if (from.nanos() != 0) {
set_nanos(from.nanos());
}
}
void TimeOfDay::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.type.TimeOfDay)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TimeOfDay::CopyFrom(const TimeOfDay& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.type.TimeOfDay)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TimeOfDay::IsInitialized() const {
return true;
}
void TimeOfDay::Swap(TimeOfDay* other) {
if (other == this) return;
InternalSwap(other);
}
void TimeOfDay::InternalSwap(TimeOfDay* other) {
using std::swap;
swap(hours_, other->hours_);
swap(minutes_, other->minutes_);
swap(seconds_, other->seconds_);
swap(nanos_, other->nanos_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata TimeOfDay::GetMetadata() const {
protobuf_google_2ftype_2ftimeofday_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2ftype_2ftimeofday_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace type
} // namespace google
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::type::TimeOfDay* Arena::CreateMaybeMessage< ::google::type::TimeOfDay >(Arena* arena) {
return Arena::CreateInternal< ::google::type::TimeOfDay >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| 35.196581 | 168 | 0.700461 | kobeya |
d58a2f10f14324ec23e0876804b175d73a858784 | 60 | cpp | C++ | csapex_core_plugins/src/core/collection_node.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_core_plugins/src/core/collection_node.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_core_plugins/src/core/collection_node.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z | /// HEADER
#include <csapex_core_plugins/collection_node.h>
| 20 | 48 | 0.8 | AdrianZw |
d58a5f894af4fb13f69479b9d8f5ee9cebf12ea2 | 331 | cpp | C++ | Ch 14/14.49_Book_test.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 14/14.49_Book_test.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 14/14.49_Book_test.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | #include"14.49_Book.h"
int main()
{
Book book1(1, "cpp primer 5th", "Lippman", "2013", 76);
Book book2 = book1;
Book book3(book1);
Book book4 = Book(std::cin);
if (book2)
book2 = book4;
std::cout << book2 << std::endl;
auto flag = static_cast<bool>(book2);
std::cout << std::boolalpha << flag << std::endl;
return 0;
} | 20.6875 | 56 | 0.625378 | Felon03 |
d58bcf14935c2268b4c9657f6a672f7e34dbcb33 | 5,463 | cpp | C++ | glasscore/tests/traveltime_unittest.cpp | jpatton-USGS/neic-glass3 | 52ab2eabd5d5d97c9d74f44c462aec7e88e51899 | [
"CC0-1.0"
] | 9 | 2019-02-18T09:08:43.000Z | 2021-08-25T13:59:15.000Z | glasscore/tests/traveltime_unittest.cpp | jpatton-USGS/neic-glass3 | 52ab2eabd5d5d97c9d74f44c462aec7e88e51899 | [
"CC0-1.0"
] | 65 | 2017-12-06T16:01:11.000Z | 2021-06-10T15:24:23.000Z | glasscore/tests/traveltime_unittest.cpp | jpatton-USGS/neic-glass3 | 52ab2eabd5d5d97c9d74f44c462aec7e88e51899 | [
"CC0-1.0"
] | 7 | 2017-12-04T20:21:28.000Z | 2021-12-01T15:59:40.000Z | #include <gtest/gtest.h>
#include <string>
#include <logger.h>
#include "TravelTime.h"
#define TESTPATH "testdata"
#define PHASE "P"
#define PHASEFILENAME "P.trv"
#define NDISTANCES 720
#define MINDIST 0.0
#define MAXDIST 180.0
#define NDEPTHS 160
#define MINDEPTH 0.0
#define MAXDEPTH 800.0
#define LATITUDE 0.0
#define LONGITUDE 0.0
#define DEPTH 50.0
#define DISTANCE 50.0
#define DELTATIME 529.2172
#define GEOTIME 529.217199
#define TIME2 169.71368
#define BILINEAR 529.217200
// tests to see if the traveltime can be constructed
TEST(TravelTimeTest, Construction) {
glass3::util::Logger::disable();
// construct a traveltime
traveltime::CTravelTime traveltime;
// m_iNumDistances
ASSERT_EQ(0, traveltime.m_iNumDistances)<< "m_iNumDistances Check";
// m_dMinimumDistance
ASSERT_EQ(0, traveltime.m_dMinimumDistance)<< "m_dMinimumDistance Check";
// m_dMaximumDistance
ASSERT_EQ(0, traveltime.m_dMaximumDistance)<< "m_dMaximumDistance Check";
// m_iNumDepths
ASSERT_EQ(0, traveltime.m_iNumDepths)<< "m_iNumDepths Check";
// m_dMinimumDepth
ASSERT_EQ(0, traveltime.m_dMinimumDepth)<< "m_dMinimumDepth Check";
// m_dMaximumDepth
ASSERT_EQ(0, traveltime.m_dMaximumDepth)<< "m_dMaximumDepth Check";
// dDepth
ASSERT_EQ(0, traveltime.m_dDepth)<< "Depth Check";
// dDelta
ASSERT_EQ(0, traveltime.m_dDelta)<< "Delta Check";
// pointers
ASSERT_EQ(NULL, traveltime. m_pTravelTimeArray)<< "pTravelTimeArray null";
}
// tests to see if the traveltime can be setup
TEST(TravelTimeTest, Setup) {
glass3::util::Logger::disable();
std::string phasefile = "./" + std::string(TESTPATH) + "/"
+ std::string(PHASEFILENAME);
std::string phasename = std::string(PHASE);
// construct a traveltime
traveltime::CTravelTime traveltime;
// setup
traveltime.setup(phasename, phasefile);
// phase name
ASSERT_STREQ(traveltime.m_sPhase.c_str(), phasename.c_str());
// m_iNumDistances
ASSERT_EQ(NDISTANCES, traveltime.m_iNumDistances)<< "m_iNumDistances Check";
// m_dMinimumDistance
ASSERT_NEAR(MINDIST, traveltime.m_dMinimumDistance, .001)<< "m_dMinimumDistance Check";
// m_dMaximumDistance
ASSERT_NEAR(MAXDIST, traveltime.m_dMaximumDistance, .001)<< "m_dMaximumDistance Check";
// m_iNumDepths
ASSERT_EQ(NDEPTHS, traveltime.m_iNumDepths)<< "m_iNumDepths Check";
// m_dMinimumDepth
ASSERT_NEAR(MINDEPTH, traveltime.m_dMinimumDepth, .001)<< "m_dMinimumDepth Check";
// m_dMaximumDepth
ASSERT_NEAR(MAXDEPTH, traveltime.m_dMaximumDepth, .001)<< "m_dMaximumDepth Check";
// dDepth
ASSERT_EQ(0, traveltime.m_dDepth)<< "Depth Check";
// dDelta
ASSERT_EQ(0, traveltime.m_dDelta)<< "Delta Check";
// pointers
ASSERT_TRUE(NULL != traveltime. m_pTravelTimeArray)<< "pTravelTimeArray not "
"null";
}
// tests the time warp copy constructor
TEST(TravelTimeTest, Copy) {
glass3::util::Logger::disable();
std::string phasefile = "./" + std::string(TESTPATH) + "/"
+ std::string(PHASEFILENAME);
std::string phasename = std::string(PHASE);
// construct a second traveltime
traveltime::CTravelTime traveltime2;
// setup
traveltime2.setup(phasename, phasefile);
// set origin
traveltime2.setTTOrigin(LATITUDE, LONGITUDE, DEPTH);
// copy
traveltime::CTravelTime traveltime1(traveltime2);
// phase name
ASSERT_STREQ(traveltime1.m_sPhase.c_str(), phasename.c_str());
// m_iNumDistances
ASSERT_EQ(NDISTANCES, traveltime1.m_iNumDistances)<< "m_iNumDistances Check";
// m_dMinimumDistance
ASSERT_NEAR(MINDIST, traveltime1.m_dMinimumDistance, .001)<< "m_dMinimumDistance Check";
// m_dMaximumDistance
ASSERT_NEAR(MAXDIST, traveltime1.m_dMaximumDistance, .001)<< "m_dMaximumDistance Check";
// m_iNumDepths
ASSERT_EQ(NDEPTHS, traveltime1.m_iNumDepths)<< "m_iNumDepths Check";
// m_dMinimumDepth
ASSERT_NEAR(MINDEPTH, traveltime1.m_dMinimumDepth, .001)<< "m_dMinimumDepth Check";
// m_dMaximumDepth
ASSERT_NEAR(MAXDEPTH, traveltime1.m_dMaximumDepth, .001)<< "m_dMaximumDepth Check";
// dDepth
ASSERT_NEAR(DEPTH, traveltime1.m_dDepth, 0.001)<< "Depth Check";
// dDelta
ASSERT_EQ(0, traveltime1.m_dDelta)<< "Delta Check";
// pointers
ASSERT_TRUE(NULL != traveltime1. m_pTravelTimeArray)<< "pTravelTimeArray not "
"null";
}
// tests traveltime operations
TEST(TravelTimeTest, Operations) {
glass3::util::Logger::disable();
std::string phasefile = "./" + std::string(TESTPATH) + "/"
+ std::string(PHASEFILENAME);
std::string phasename = std::string(PHASE);
// construct a traveltime
traveltime::CTravelTime traveltime;
// setup
traveltime.setup(phasename, phasefile);
// set origin
traveltime.setTTOrigin(LATITUDE, LONGITUDE, DEPTH);
// T(delta)
ASSERT_NEAR(DELTATIME, traveltime.T(DISTANCE), 0.001)<< "T(delta) Check";
// dDepth
ASSERT_NEAR(DEPTH, traveltime.m_dDepth, 0.001)<< "Depth Check";
// dDelta
ASSERT_NEAR(DISTANCE, traveltime.m_dDelta, 0.001)<< "Delta Check";
glass3::util::Geo testGeo;
testGeo.setGeographic(LATITUDE, LONGITUDE + DISTANCE, DEPTH);
// T(geo)
ASSERT_NEAR(GEOTIME, traveltime.T(&testGeo), 0.001)<< "T(geo) Check";
// dDepth
ASSERT_NEAR(DEPTH, traveltime.m_dDepth, 0.001)<< "Depth Check";
// dDelta
ASSERT_NEAR(DISTANCE, traveltime.m_dDelta, 0.001)<< "Delta Check";
// T(delta, distance)
ASSERT_NEAR(TIME2, traveltime.T(DISTANCE,DEPTH), 0.001)<< "T(delta, distance) Check"; // NOLINT
// bilinear
// ASSERT_NEAR(BILINEAR, traveltime.bilinear(DISTANCE,DEPTH), 0.001)<< "bilinear Check"; // NOLINT
}
| 26.391304 | 99 | 0.739154 | jpatton-USGS |
d58c5bb8038d50c0f658b79b6fcce571f4f5af83 | 4,353 | cpp | C++ | libs/img/src/CImage_SSE2.cpp | mrliujie/mrpt-learning-code | 7b41a9501fc35c36580c93bc1499f5a36d26c216 | [
"BSD-3-Clause"
] | 2 | 2020-04-21T08:51:21.000Z | 2022-03-21T10:47:52.000Z | libs/img/src/CImage_SSE2.cpp | qifengl/mrpt | 979a458792273a86ec5ab105e0cd6c963c65ea73 | [
"BSD-3-Clause"
] | null | null | null | libs/img/src/CImage_SSE2.cpp | qifengl/mrpt | 979a458792273a86ec5ab105e0cd6c963c65ea73 | [
"BSD-3-Clause"
] | null | null | null | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "img-precomp.h" // Precompiled headers
#if MRPT_HAS_SSE2
// ---------------------------------------------------------------------------
// This file contains the SSE2 optimized functions for mrpt::img::CImage
// See the sources and the doxygen documentation page "sse_optimizations" for
// more details.
//
// Some functions here are derived from sources in libcvd, released
// under BSD. https://www.edwardrosten.com/cvd/
//
// ---------------------------------------------------------------------------
#include <mrpt/img/CImage.h>
#include <mrpt/core/SSE_types.h>
#include <mrpt/core/SSE_macros.h>
#include "CImage_SSEx.h"
/** \addtogroup sse_optimizations
* SSE optimized functions
* @{
*/
/** Subsample each 2x2 pixel block into 1x1 pixel, taking the first pixel &
* ignoring the other 3
* - <b>Input format:</b> uint8_t, 1 channel
* - <b>Output format:</b> uint8_t, 1 channel
* - <b>Preconditions:</b> in & out aligned to 16bytes, w = k*16 (w=width in
* pixels), widthStep=w*1
* - <b>Notes:</b>
* - <b>Requires:</b> SSE2
* - <b>Invoked from:</b> mrpt::img::CImage::scaleHalf()
*/
void image_SSE2_scale_half_1c8u(const uint8_t* in, uint8_t* out, int w, int h)
{
alignas(32) const unsigned long long mask[2] = {0x00FF00FF00FF00FFull,
0x00FF00FF00FF00FFull};
const __m128i m = _mm_load_si128((const __m128i*)mask);
int sw = w >> 4;
int sh = h >> 1;
for (int i = 0; i < sh; i++)
{
for (int j = 0; j < sw; j++)
{
const __m128i here_sampled =
_mm_and_si128(_mm_load_si128((const __m128i*)in), m);
_mm_storel_epi64(
(__m128i*)out, _mm_packus_epi16(here_sampled, here_sampled));
in += 16;
out += 8;
}
in += w;
}
}
/** Average each 2x2 pixels into 1x1 pixel (arithmetic average)
* - <b>Input format:</b> uint8_t, 1 channel
* - <b>Output format:</b> uint8_t, 1 channel
* - <b>Preconditions:</b> in & out aligned to 16bytes, w = k*16 (w=width in
* pixels), widthStep=w*1
* - <b>Notes:</b>
* - <b>Requires:</b> SSE2
* - <b>Invoked from:</b> mrpt::img::CImage::scaleHalfSmooth()
*/
void image_SSE2_scale_half_smooth_1c8u(
const uint8_t* in, uint8_t* out, int w, int h)
{
alignas(MRPT_MAX_ALIGN_BYTES) const unsigned long long mask[2] = {
0x00FF00FF00FF00FFull, 0x00FF00FF00FF00FFull};
const uint8_t* nextRow = in + w;
__m128i m = _mm_load_si128((const __m128i*)mask);
int sw = w >> 4;
int sh = h >> 1;
for (int i = 0; i < sh; i++)
{
for (int j = 0; j < sw; j++)
{
__m128i here = _mm_load_si128((const __m128i*)in);
__m128i next = _mm_load_si128((const __m128i*)nextRow);
here = _mm_avg_epu8(here, next);
next = _mm_and_si128(_mm_srli_si128(here, 1), m);
here = _mm_and_si128(here, m);
here = _mm_avg_epu16(here, next);
_mm_storel_epi64((__m128i*)out, _mm_packus_epi16(here, here));
in += 16;
nextRow += 16;
out += 8;
}
in += w;
nextRow += w;
}
}
/** KLT score at a given point of a grayscale image.
* - <b>Requires:</b> SSE2
* - <b>Invoked from:</b> mrpt::img::CImage::KLT_response()
*
* This function is not manually optimized for SSE2 but templatized for
* different
* window sizes such as the compiler can optimize automatically for that
* size.
*
* Only for the most common window sizes this templates are instantiated
* (W=[2-16] and W=32 ),
* falling back to
* a generic implementation otherwise. The next figure shows the performance
* (time for
* KLT_response() to compute the score for one single pixel) for different
* window sizes.
*
* <img src="KLT_response_performance_SSE2.png" >
*
*/
float KLT_response_optimized();
// TODO:
// Sum of absolute differences: Use _mm_sad_epu8
/** @} */
#endif // end if MRPT_HAS_SSE2
| 32.244444 | 80 | 0.587641 | mrliujie |
d58db4da106d35a0d66213533072b97444540af1 | 1,055 | cpp | C++ | edc127.cpp | EDI9029/FC22 | 79dab09646b1f2e08ae0da1f385d48e5c8a9b09f | [
"MIT"
] | null | null | null | edc127.cpp | EDI9029/FC22 | 79dab09646b1f2e08ae0da1f385d48e5c8a9b09f | [
"MIT"
] | null | null | null | edc127.cpp | EDI9029/FC22 | 79dab09646b1f2e08ae0da1f385d48e5c8a9b09f | [
"MIT"
] | null | null | null | //Cooperation of EDB1 P.129//
//Edward 1,17,2022 //
/***************************************************************/
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i,j,n,m,a,b,cur,book[101]={0},e[101][101];
int que[10001],head,tail;
scanf("%d %d",&n,&m);
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
if(i==j){
e[i][j]=0;
}
else{
e[i][j]=99999999;
}
}
}
for(i=1;i<=m;i++){
scanf("%d %d",&a,&b);
e[a][b]=1;
e[b][a]=1;
}
head=1;
tail=1;
que[tail]=1;
tail++;
book[1]=1;
while(head<tail){
cur=que[head];
for(i=1;i<=n;i++){
if(e[cur][i]==1 && book[i]==0){
que[tail]=i;
tail++;
book[i]=1;
}
if(tail>n){
break;
}
}
head++;
}
for(i=1;i<tail;i++){
printf("%d",que[i]);
}
system("pause");
return 0;
} | 17.881356 | 65 | 0.320379 | EDI9029 |
d58e1febf3666d86f044d16eb601ec4990b95836 | 2,307 | cpp | C++ | CLRDump/CLRDump.cpp | isabella232/CLRExplorer | 8c81c894f115337c0121b5856ab6ab6823c7e164 | [
"MIT"
] | 105 | 2020-01-04T18:36:38.000Z | 2022-01-28T17:27:03.000Z | CLRDump/CLRDump.cpp | isabella232/CLRExplorer | 8c81c894f115337c0121b5856ab6ab6823c7e164 | [
"MIT"
] | 1 | 2020-04-16T09:46:34.000Z | 2020-04-16T09:56:03.000Z | CLRDump/CLRDump.cpp | isabella232/CLRExplorer | 8c81c894f115337c0121b5856ab6ab6823c7e164 | [
"MIT"
] | 14 | 2020-01-05T06:06:07.000Z | 2021-12-03T09:13:22.000Z | #include "pch.h"
#include "..\CLRDiag\DataTarget.h"
CComModule _Module;
void DumpAppDomainsAndAssemblies(DataTarget* dt) {
auto domains = dt->EnumAppDomains();
for (auto& ad : domains) {
printf("AppDomain: %ws (0x%p) (assemblies: %u)\n", (PCWSTR)ad.Name, (void*)ad.AppDomainPtr, ad.AssemblyCount);
for (auto& asminfo : dt->EnumAssemblies(ad)) {
printf("\t%ws (0x%p)\n", (PCWSTR)asminfo.Name, (void*)asminfo.AssemblyPtr);
}
}
}
void DumpThreadPool(DataTarget* dt) {
auto data = dt->GetThreadPoolData();
}
void DumpModules(DataTarget* dt, bool includeMethodTables) {
for (auto& m : dt->EnumModules()) {
printf("Module 0x%p Asm: 0x%p ID: 0x%p Index: %llu IL: 0x%p\n", (void*)m.Address, (void*)m.Assembly, (void*)m.dwModuleID, m.dwModuleIndex, (void*)m.ilBase);
if (includeMethodTables) {
auto mts = dt->EnumMethodTables(m.Address);
for (auto& mt : mts)
printf("Index: %u %ws Size: %d Ifaces: %u Methods: %u Virt: %u\n", mt.Index, (PCWSTR)mt.Name, mt.BaseSize, mt.wNumInterfaces, mt.wNumMethods, mt.wNumVirtuals);
}
}
}
void DumpThreads(DataTarget* dt) {
for (auto& data : dt->EnumThreads(false)) {
printf("MID: %2d OSID: %5u TEB: 0x%p State: 0x%X\n", data.corThreadId, data.osThreadId, (void*)data.teb, data.state);
}
}
void DumpHandles(DataTarget* dt) {
}
void DumpSyncBlocks(DataTarget* dt) {
auto sbs = dt->EnumSyncBlocks(false);
}
void DumpObjects(DataTarget* dt) {
//auto objects = dt->EnumObjects();
//printf("%zu objects\n", objects.size());
}
int main(int argc, const char* argv[]) {
if (argc < 2) {
printf("Usage: CLRDump <pid>\n");
return 0;
}
::CoInitialize(nullptr);
// auto dt = DataTarget::FromProcessId(atoi(argv[1]));
#ifdef _WIN64
auto dt = DataTarget::FromDumpFile(L"c:\\temp\\Snagit32.exe_191231_181145.dmp");
#else
auto dt = DataTarget::FromDumpFile(L"c:\\temp\\HlpViewer.exe_191231_122702.dmp");
#endif
if (dt == nullptr) {
printf("Error connecting to target\n");
return 1;
}
bool suspended = dt->Suspend();
if(!suspended)
printf("Failed to suspend process\n");
//DumpObjects(dt.get());
//DumpAppDomainsAndAssemblies(dt.get());
//DumpThreadPool(dt.get());
//DumpThreads(dt.get());
//DumpModules(dt.get(), true);
//DumpHandles(dt.get());
//DumpSyncBlocks(dt.get());
if(suspended)
dt->Resume();
return 0;
}
| 26.825581 | 163 | 0.671868 | isabella232 |
d5907501442b4aa0ba40b22f93327a99866432c2 | 32,515 | hpp | C++ | core/injector/application_injector.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | core/injector/application_injector.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | core/injector/application_injector.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_CORE_INJECTOR_APPLICATION_INJECTOR_HPP
#define KAGOME_CORE_INJECTOR_APPLICATION_INJECTOR_HPP
#include <boost/di.hpp>
#include <boost/di/extension/scopes/shared.hpp>
#include <libp2p/injector/host_injector.hpp>
#include <libp2p/peer/peer_info.hpp>
#include "api/service/api_service.hpp"
#include "api/service/author/author_jrpc_processor.hpp"
#include "api/service/author/impl/author_api_impl.hpp"
#include "api/service/chain/chain_jrpc_processor.hpp"
#include "api/service/chain/impl/chain_api_impl.hpp"
#include "api/service/state/impl/state_api_impl.hpp"
#include "api/service/state/state_jrpc_processor.hpp"
#include "api/service/system/impl/system_api_impl.hpp"
#include "api/service/system/system_jrpc_processor.hpp"
#include "api/transport/impl/http/http_listener_impl.hpp"
#include "api/transport/impl/http/http_session.hpp"
#include "api/transport/impl/ws/ws_listener_impl.hpp"
#include "api/transport/impl/ws/ws_session.hpp"
#include "api/transport/rpc_thread_pool.hpp"
#include "application/impl/app_state_manager_impl.hpp"
#include "application/impl/configuration_storage_impl.hpp"
#include "authorship/impl/block_builder_factory_impl.hpp"
#include "authorship/impl/block_builder_impl.hpp"
#include "authorship/impl/proposer_impl.hpp"
#include "blockchain/impl/block_tree_impl.hpp"
#include "blockchain/impl/key_value_block_header_repository.hpp"
#include "blockchain/impl/key_value_block_storage.hpp"
#include "blockchain/impl/storage_util.hpp"
#include "boost/di/extension/injections/extensible_injector.hpp"
#include "clock/impl/basic_waitable_timer.hpp"
#include "clock/impl/clock_impl.hpp"
#include "common/outcome_throw.hpp"
#include "consensus/authority/authority_manager.hpp"
#include "consensus/authority/authority_update_observer.hpp"
#include "consensus/authority/impl/authority_manager_impl.hpp"
#include "consensus/babe/babe_lottery.hpp"
#include "consensus/babe/common.hpp"
#include "consensus/babe/impl/babe_lottery_impl.hpp"
#include "consensus/babe/impl/babe_synchronizer_impl.hpp"
#include "consensus/babe/impl/epoch_storage_impl.hpp"
#include "consensus/grandpa/finalization_observer.hpp"
#include "consensus/grandpa/impl/environment_impl.hpp"
#include "consensus/grandpa/impl/finalization_composite.hpp"
#include "consensus/grandpa/impl/vote_crypto_provider_impl.hpp"
#include "consensus/grandpa/structs.hpp"
#include "consensus/grandpa/vote_graph.hpp"
#include "consensus/grandpa/vote_tracker.hpp"
#include "consensus/validation/babe_block_validator.hpp"
#include "crypto/bip39/impl/bip39_provider_impl.hpp"
#include "crypto/crypto_store/crypto_store_impl.hpp"
#include "crypto/ed25519/ed25519_provider_impl.hpp"
#include "crypto/hasher/hasher_impl.hpp"
#include "crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp"
#include "crypto/random_generator/boost_generator.hpp"
#include "crypto/secp256k1/secp256k1_provider_impl.hpp"
#include "crypto/sr25519/sr25519_provider_impl.hpp"
#include "crypto/vrf/vrf_provider_impl.hpp"
#include "extensions/impl/extension_factory_impl.hpp"
#include "network/impl/dummy_sync_protocol_client.hpp"
#include "network/impl/extrinsic_observer_impl.hpp"
#include "network/impl/gossiper_broadcast.hpp"
#include "network/impl/remote_sync_protocol_client.hpp"
#include "network/impl/router_libp2p.hpp"
#include "network/impl/sync_protocol_observer_impl.hpp"
#include "network/sync_protocol_client.hpp"
#include "network/sync_protocol_observer.hpp"
#include "network/types/sync_clients_set.hpp"
#include "outcome/outcome.hpp"
#include "runtime/binaryen/module/wasm_module_factory_impl.hpp"
#include "runtime/binaryen/module/wasm_module_impl.hpp"
#include "runtime/binaryen/runtime_api/babe_api_impl.hpp"
#include "runtime/binaryen/runtime_api/block_builder_impl.hpp"
#include "runtime/binaryen/runtime_api/core_factory_impl.hpp"
#include "runtime/binaryen/runtime_api/core_impl.hpp"
#include "runtime/binaryen/runtime_api/grandpa_api_impl.hpp"
#include "runtime/binaryen/runtime_api/metadata_impl.hpp"
#include "runtime/binaryen/runtime_api/offchain_worker_impl.hpp"
#include "runtime/binaryen/runtime_api/parachain_host_impl.hpp"
#include "runtime/binaryen/runtime_api/tagged_transaction_queue_impl.hpp"
#include "runtime/common/storage_wasm_provider.hpp"
#include "runtime/common/trie_storage_provider_impl.hpp"
#include "storage/changes_trie/impl/storage_changes_tracker_impl.hpp"
#include "storage/leveldb/leveldb.hpp"
#include "storage/predefined_keys.hpp"
#include "storage/trie/impl/trie_storage_backend_impl.hpp"
#include "storage/trie/impl/trie_storage_impl.hpp"
#include "storage/trie/polkadot_trie/polkadot_node.hpp"
#include "storage/trie/polkadot_trie/polkadot_trie_factory_impl.hpp"
#include "storage/trie/serialization/polkadot_codec.hpp"
#include "storage/trie/serialization/trie_serializer_impl.hpp"
#include "transaction_pool/impl/pool_moderator_impl.hpp"
#include "transaction_pool/impl/transaction_pool_impl.hpp"
namespace kagome::injector {
namespace di = boost::di;
template <typename C>
auto useConfig(C c) {
return boost::di::bind<std::decay_t<C>>().template to(
std::move(c))[boost::di::override];
}
template <class T>
using sptr = std::shared_ptr<T>;
template <class T>
using uptr = std::unique_ptr<T>;
template <typename Injector>
sptr<network::PeerList> get_boot_nodes(const Injector &injector) {
static auto initialized =
boost::optional<sptr<network::PeerList>>(boost::none);
if (initialized) {
return initialized.value();
}
auto &cfg = injector.template create<application::ConfigurationStorage &>();
initialized = std::make_shared<network::PeerList>(cfg.getBootNodes());
return initialized.value();
}
template <typename Injector>
sptr<api::ApiService> get_jrpc_api_service(const Injector &injector) {
static auto initialized =
boost::optional<sptr<api::ApiService>>(boost::none);
if (initialized) {
return initialized.value();
}
using SubscriptionEnginePtr = std::shared_ptr<
subscription::SubscriptionEngine<common::Buffer,
std::shared_ptr<api::Session>,
common::Buffer,
primitives::BlockHash>>;
auto subscription_engine =
injector.template create<SubscriptionEnginePtr>();
auto app_state_manager =
injector
.template create<std::shared_ptr<application::AppStateManager>>();
auto rpc_thread_pool =
injector.template create<std::shared_ptr<api::RpcThreadPool>>();
std::vector<std::shared_ptr<api::Listener>> listeners{
injector.template create<std::shared_ptr<api::HttpListenerImpl>>(),
injector.template create<std::shared_ptr<api::WsListenerImpl>>(),
};
auto server = injector.template create<std::shared_ptr<api::JRpcServer>>();
std::vector<std::shared_ptr<api::JRpcProcessor>> processors{
injector
.template create<std::shared_ptr<api::state::StateJrpcProcessor>>(),
injector.template create<
std::shared_ptr<api::author::AuthorJRpcProcessor>>(),
injector
.template create<std::shared_ptr<api::chain::ChainJrpcProcessor>>(),
injector.template create<
std::shared_ptr<api::system::SystemJrpcProcessor>>()};
initialized =
std::make_shared<api::ApiService>(std::move(app_state_manager),
std::move(rpc_thread_pool),
std::move(listeners),
std::move(server),
processors,
std::move(subscription_engine));
auto state_api = injector.template create<std::shared_ptr<api::StateApi>>();
state_api->setApiService(initialized.value());
return initialized.value();
}
// jrpc api listener (over HTTP) getter
template <typename Injector>
sptr<api::HttpListenerImpl> get_jrpc_api_http_listener(
const Injector &injector,
const boost::asio::ip::tcp::endpoint &endpoint) {
static auto initialized =
boost::optional<sptr<api::HttpListenerImpl>>(boost::none);
if (initialized) {
return initialized.value();
}
auto app_state_manager =
injector.template create<sptr<application::AppStateManager>>();
auto context = injector.template create<sptr<api::RpcContext>>();
api::HttpListenerImpl::Configuration listener_config;
listener_config.endpoint = endpoint;
auto &&http_session_config =
injector.template create<api::HttpSession::Configuration>();
initialized = std::make_shared<api::HttpListenerImpl>(
app_state_manager, context, listener_config, http_session_config);
return initialized.value();
}
// jrpc api listener (over Websockets) getter
template <typename Injector>
sptr<api::WsListenerImpl> get_jrpc_api_ws_listener(
const Injector &injector,
const boost::asio::ip::tcp::endpoint &endpoint) {
static auto initialized =
boost::optional<sptr<api::WsListenerImpl>>(boost::none);
if (initialized) {
return initialized.value();
}
auto app_state_manager =
injector.template create<sptr<application::AppStateManager>>();
auto context = injector.template create<sptr<api::RpcContext>>();
api::WsListenerImpl::Configuration listener_config;
listener_config.endpoint = endpoint;
auto &&ws_session_config =
injector.template create<api::WsSession::Configuration>();
initialized = std::make_shared<api::WsListenerImpl>(
app_state_manager, context, listener_config, ws_session_config);
return initialized.value();
}
// block storage getter
template <typename Injector>
sptr<blockchain::BlockStorage> get_block_storage(const Injector &injector) {
static auto initialized =
boost::optional<sptr<blockchain::BlockStorage>>(boost::none);
if (initialized) {
return initialized.value();
}
auto &&hasher = injector.template create<sptr<crypto::Hasher>>();
const auto &db = injector.template create<sptr<storage::BufferStorage>>();
const auto &trie_storage =
injector.template create<sptr<storage::trie::TrieStorage>>();
auto storage = blockchain::KeyValueBlockStorage::create(
trie_storage->getRootHash(),
db,
hasher,
[&db, &injector](const primitives::Block &genesis_block) {
// handle genesis initialization, which happens when there is not
// authorities and last completed round in the storage
if (not db->get(storage::kAuthoritySetKey)) {
// insert authorities
auto grandpa_api =
injector.template create<sptr<runtime::GrandpaApi>>();
const auto &weighted_authorities_res = grandpa_api->authorities(
primitives::BlockId(primitives::BlockNumber{0}));
BOOST_ASSERT_MSG(weighted_authorities_res,
"grandpa_api_->authorities failed");
const auto &weighted_authorities = weighted_authorities_res.value();
for (const auto authority : weighted_authorities) {
spdlog::info("Grandpa authority: {}", authority.id.id.toHex());
}
consensus::grandpa::VoterSet voters{0};
for (const auto &weighted_authority : weighted_authorities) {
voters.insert(weighted_authority.id.id,
weighted_authority.weight);
spdlog::debug("Added to grandpa authorities: {}, weight: {}",
weighted_authority.id.id.toHex(),
weighted_authority.weight);
}
BOOST_ASSERT_MSG(voters.size() != 0, "Grandpa voters are empty");
auto authorities_put_res =
db->put(storage::kAuthoritySetKey,
common::Buffer(scale::encode(voters).value()));
if (not authorities_put_res) {
BOOST_ASSERT_MSG(false, "Could not insert authorities");
std::exit(1);
}
}
});
if (storage.has_error()) {
common::raise(storage.error());
}
initialized = storage.value();
return initialized.value();
}
// block tree getter
template <typename Injector>
sptr<blockchain::BlockTree> get_block_tree(const Injector &injector) {
static auto initialized =
boost::optional<sptr<blockchain::BlockTree>>(boost::none);
if (initialized) {
return initialized.value();
}
auto header_repo =
injector.template create<sptr<blockchain::BlockHeaderRepository>>();
auto &&storage = injector.template create<sptr<blockchain::BlockStorage>>();
auto last_finalized_block_res = storage->getLastFinalizedBlockHash();
const auto block_id =
last_finalized_block_res.has_value()
? primitives::BlockId{last_finalized_block_res.value()}
: primitives::BlockId{0};
auto &&extrinsic_observer =
injector.template create<sptr<network::ExtrinsicObserver>>();
auto &&hasher = injector.template create<sptr<crypto::Hasher>>();
auto &&tree =
blockchain::BlockTreeImpl::create(std::move(header_repo),
storage,
block_id,
std::move(extrinsic_observer),
std::move(hasher));
if (!tree) {
common::raise(tree.error());
}
initialized = tree.value();
return initialized.value();
}
template <typename Injector>
sptr<extensions::ExtensionFactoryImpl> get_extension_factory(
const Injector &injector) {
static auto initialized =
boost::optional<sptr<extensions::ExtensionFactoryImpl>>(boost::none);
if (initialized) {
return initialized.value();
}
auto tracker =
injector.template create<sptr<storage::changes_trie::ChangesTracker>>();
auto sr25519_provider =
injector.template create<sptr<crypto::SR25519Provider>>();
auto ed25519_provider =
injector.template create<sptr<crypto::ED25519Provider>>();
auto secp256k1_provider =
injector.template create<sptr<crypto::Secp256k1Provider>>();
auto hasher = injector.template create<sptr<crypto::Hasher>>();
auto crypto_store = injector.template create<sptr<crypto::CryptoStore>>();
auto bip39_provider =
injector.template create<sptr<crypto::Bip39Provider>>();
auto core_factory_method =
[&injector](sptr<runtime::WasmProvider> wasm_provider) {
auto core_factory =
injector.template create<sptr<runtime::CoreFactory>>();
return core_factory->createWithCode(wasm_provider);
};
initialized =
std::make_shared<extensions::ExtensionFactoryImpl>(tracker,
sr25519_provider,
ed25519_provider,
secp256k1_provider,
hasher,
crypto_store,
bip39_provider,
core_factory_method);
return initialized.value();
}
template <typename Injector>
sptr<storage::trie::TrieStorageBackendImpl> get_trie_storage_backend(
const Injector &injector) {
static auto initialized =
boost::optional<sptr<storage::trie::TrieStorageBackendImpl>>(
boost::none);
if (initialized) {
return initialized.value();
}
auto storage = injector.template create<sptr<storage::BufferStorage>>();
using blockchain::prefix::TRIE_NODE;
auto backend = std::make_shared<storage::trie::TrieStorageBackendImpl>(
storage, common::Buffer{TRIE_NODE});
initialized = backend;
return backend;
}
template <typename Injector>
sptr<storage::trie::TrieStorageImpl> get_trie_storage_impl(
const Injector &injector) {
static auto initialized =
boost::optional<sptr<storage::trie::TrieStorageImpl>>(boost::none);
if (initialized) {
return initialized.value();
}
auto factory =
injector.template create<sptr<storage::trie::PolkadotTrieFactory>>();
auto codec = injector.template create<sptr<storage::trie::Codec>>();
auto serializer =
injector.template create<sptr<storage::trie::TrieSerializer>>();
auto tracker =
injector.template create<sptr<storage::changes_trie::ChangesTracker>>();
auto trie_storage_res = storage::trie::TrieStorageImpl::createEmpty(
factory, codec, serializer, tracker);
if (!trie_storage_res) {
common::raise(trie_storage_res.error());
}
sptr<storage::trie::TrieStorageImpl> trie_storage =
std::move(trie_storage_res.value());
initialized = trie_storage;
return trie_storage;
}
template <typename Injector>
sptr<storage::trie::TrieStorage> get_trie_storage(const Injector &injector) {
static auto initialized =
boost::optional<sptr<storage::trie::TrieStorage>>(boost::none);
if (initialized) {
return initialized.value();
}
auto configuration_storage =
injector.template create<sptr<application::ConfigurationStorage>>();
const auto &genesis_raw_configs = configuration_storage->getGenesis();
auto trie_storage =
injector.template create<sptr<storage::trie::TrieStorageImpl>>();
auto batch = trie_storage->getPersistentBatch();
if (not batch) {
common::raise(batch.error());
}
for (const auto &[key, val] : genesis_raw_configs) {
spdlog::debug(
"Key: {}, Val: {}", key.toHex(), val.toHex().substr(0, 200));
if (auto res = batch.value()->put(key, val); not res) {
common::raise(res.error());
}
}
if (auto res = batch.value()->commit(); not res) {
common::raise(res.error());
}
initialized = trie_storage;
return trie_storage;
}
// level db getter
template <typename Injector>
sptr<storage::BufferStorage> get_level_db(std::string_view leveldb_path,
const Injector &injector) {
static auto initialized =
boost::optional<sptr<storage::BufferStorage>>(boost::none);
if (initialized) {
return initialized.value();
}
auto options = leveldb::Options{};
options.create_if_missing = true;
auto db = storage::LevelDB::create(leveldb_path, options);
if (!db) {
common::raise(db.error());
}
initialized = db.value();
return initialized.value();
};
// configuration storage getter
template <typename Injector>
std::shared_ptr<application::ConfigurationStorage> get_configuration_storage(
std::string_view genesis_path, const Injector &injector) {
static auto initialized =
boost::optional<sptr<application::ConfigurationStorage>>(boost::none);
if (initialized) {
return initialized.value();
}
auto config_storage_res = application::ConfigurationStorageImpl::create(
std::string(genesis_path));
if (config_storage_res.has_error()) {
common::raise(config_storage_res.error());
}
initialized = config_storage_res.value();
return config_storage_res.value();
};
template <typename Injector>
sptr<network::SyncClientsSet> get_sync_clients_set(const Injector &injector) {
static auto initialized =
boost::optional<sptr<network::SyncClientsSet>>(boost::none);
if (initialized) {
return initialized.value();
}
auto configuration_storage =
injector.template create<sptr<application::ConfigurationStorage>>();
auto peer_infos = configuration_storage->getBootNodes().peers;
auto host = injector.template create<sptr<libp2p::Host>>();
auto block_tree = injector.template create<sptr<blockchain::BlockTree>>();
auto block_header_repository =
injector.template create<sptr<blockchain::BlockHeaderRepository>>();
auto res = std::make_shared<network::SyncClientsSet>();
auto ¤t_peer_info =
injector.template create<network::OwnPeerInfo &>();
for (auto &peer_info : peer_infos) {
spdlog::debug("Added peer with id: {}", peer_info.id.toBase58());
if (peer_info.id != current_peer_info.id) {
res->clients.emplace_back(
std::make_shared<network::RemoteSyncProtocolClient>(
*host, std::move(peer_info)));
} else {
res->clients.emplace_back(
std::make_shared<network::DummySyncProtocolClient>());
}
}
std::reverse(res->clients.begin(), res->clients.end());
initialized = res;
return res;
}
template <typename Injector>
sptr<primitives::BabeConfiguration> get_babe_configuration(
const Injector &injector) {
static auto initialized =
boost::optional<sptr<primitives::BabeConfiguration>>(boost::none);
if (initialized) {
return *initialized;
}
auto babe_api = injector.template create<sptr<runtime::BabeApi>>();
auto configuration_res = babe_api->configuration();
if (not configuration_res) {
common::raise(configuration_res.error());
}
auto config = configuration_res.value();
for (const auto &authority : config.genesis_authorities) {
spdlog::debug("Babe authority: {}", authority.id.id.toHex());
}
config.leadership_rate.first *= 3;
initialized = std::make_shared<primitives::BabeConfiguration>(config);
return *initialized;
};
template <class Injector>
sptr<crypto::CryptoStore> get_crypto_store(std::string_view keystore_path,
const Injector &injector) {
static auto initialized =
boost::optional<sptr<crypto::CryptoStore>>(boost::none);
if (initialized) {
return *initialized;
}
auto ed25519_provider =
injector.template create<sptr<crypto::ED25519Provider>>();
auto sr25519_provider =
injector.template create<sptr<crypto::SR25519Provider>>();
auto secp256k1_provider =
injector.template create<sptr<crypto::Secp256k1Provider>>();
auto bip39_provider =
injector.template create<sptr<crypto::Bip39Provider>>();
auto random_generator = injector.template create<sptr<crypto::CSPRNG>>();
auto crypto_store =
std::make_shared<crypto::CryptoStoreImpl>(std::move(ed25519_provider),
std::move(sr25519_provider),
std::move(secp256k1_provider),
std::move(bip39_provider),
std::move(random_generator));
boost::filesystem::path path = std::string(keystore_path);
if (auto &&res = crypto_store->initialize(path); res) {
common::raise(res.error());
}
initialized = crypto_store;
return *initialized;
}
template <class Injector>
sptr<consensus::grandpa::FinalizationObserver> get_finalization_observer(
const Injector &injector) {
static auto instance = boost::optional<
std::shared_ptr<consensus::grandpa::FinalizationObserver>>(boost::none);
if (instance) {
return *instance;
}
instance = std::make_shared<consensus::grandpa::FinalizationComposite>(
injector.template create<
std::shared_ptr<authority::AuthorityManagerImpl>>());
return *instance;
}
template <typename... Ts>
auto makeApplicationInjector(
const std::string &genesis_path,
const std::string &leveldb_path,
const boost::asio::ip::tcp::endpoint &rpc_http_endpoint,
const boost::asio::ip::tcp::endpoint &rpc_ws_endpoint,
Ts &&... args) {
using namespace boost; // NOLINT;
// default values for configurations
api::RpcThreadPool::Configuration rpc_thread_pool_config{};
api::HttpSession::Configuration http_config{};
api::WsSession::Configuration ws_config{};
transaction_pool::PoolModeratorImpl::Params pool_moderator_config{};
transaction_pool::TransactionPool::Limits tp_pool_limits{};
return di::make_injector(
// bind configs
injector::useConfig(rpc_thread_pool_config),
injector::useConfig(http_config),
injector::useConfig(ws_config),
injector::useConfig(pool_moderator_config),
injector::useConfig(tp_pool_limits),
// inherit host injector
libp2p::injector::makeHostInjector(
// FIXME(xDimon): https://github.com/soramitsu/kagome/issues/495
// Uncomment after issue will be resolved
// libp2p::injector::useSecurityAdaptors<
// libp2p::security::Secio>()[di::override]
),
// bind boot nodes
di::bind<network::PeerList>.to(
[](auto const &inj) { return get_boot_nodes(inj); }),
di::bind<application::AppStateManager>.template to<application::AppStateManagerImpl>(),
// bind io_context: 1 per injector
di::bind<::boost::asio::io_context>.in(
di::extension::shared)[boost::di::override],
// bind interfaces
di::bind<api::HttpListenerImpl>.to(
[rpc_http_endpoint](const auto &injector) {
return get_jrpc_api_http_listener(injector, rpc_http_endpoint);
}),
di::bind<api::WsListenerImpl>.to(
[rpc_ws_endpoint](const auto &injector) {
return get_jrpc_api_ws_listener(injector, rpc_ws_endpoint);
}),
di::bind<api::AuthorApi>.template to<api::AuthorApiImpl>(),
di::bind<api::ChainApi>.template to<api::ChainApiImpl>(),
di::bind<api::StateApi>.template to<api::StateApiImpl>(),
di::bind<api::SystemApi>.template to<api::SystemApiImpl>(),
di::bind<api::ApiService>.to([](const auto &injector) {
return get_jrpc_api_service(injector);
}),
di::bind<api::JRpcServer>.template to<api::JRpcServerImpl>(),
di::bind<authorship::Proposer>.template to<authorship::ProposerImpl>(),
di::bind<authorship::BlockBuilder>.template to<authorship::BlockBuilderImpl>(),
di::bind<authorship::BlockBuilderFactory>.template to<authorship::BlockBuilderFactoryImpl>(),
di::bind<storage::BufferStorage>.to(
[leveldb_path](const auto &injector) {
return get_level_db(leveldb_path, injector);
}),
di::bind<blockchain::BlockStorage>.to(
[](const auto &injector) { return get_block_storage(injector); }),
di::bind<blockchain::BlockTree>.to(
[](auto const &inj) { return get_block_tree(inj); }),
di::bind<blockchain::BlockHeaderRepository>.template to<blockchain::KeyValueBlockHeaderRepository>(),
di::bind<clock::SystemClock>.template to<clock::SystemClockImpl>(),
di::bind<clock::SteadyClock>.template to<clock::SteadyClockImpl>(),
di::bind<clock::Timer>.template to<clock::BasicWaitableTimer>(),
di::bind<primitives::BabeConfiguration>.to([](auto const &injector) {
return get_babe_configuration(injector);
}),
di::bind<consensus::BabeSynchronizer>.template to<consensus::BabeSynchronizerImpl>(),
di::bind<consensus::grandpa::Environment>.template to<consensus::grandpa::EnvironmentImpl>(),
di::bind<consensus::grandpa::VoteCryptoProvider>.template to<consensus::grandpa::VoteCryptoProviderImpl>(),
di::bind<consensus::EpochStorage>.template to<consensus::EpochStorageImpl>(),
di::bind<consensus::BlockValidator>.template to<consensus::BabeBlockValidator>(),
di::bind<crypto::ED25519Provider>.template to<crypto::ED25519ProviderImpl>(),
di::bind<crypto::Hasher>.template to<crypto::HasherImpl>(),
di::bind<crypto::SR25519Provider>.template to<crypto::SR25519ProviderImpl>(),
di::bind<crypto::VRFProvider>.template to<crypto::VRFProviderImpl>(),
di::bind<crypto::Bip39Provider>.template to<crypto::Bip39ProviderImpl>(),
di::bind<crypto::Pbkdf2Provider>.template to<crypto::Pbkdf2ProviderImpl>(),
di::bind<crypto::Secp256k1Provider>.template to<crypto::Secp256k1ProviderImpl>(),
di::bind<crypto::CryptoStore>.template to<crypto::CryptoStoreImpl>(),
di::bind<extensions::ExtensionFactory>.template to(
[](auto const &injector) {
return get_extension_factory(injector);
}),
di::bind<network::Router>.template to<network::RouterLibp2p>(),
di::bind<consensus::BabeGossiper>.template to<network::GossiperBroadcast>(),
di::bind<consensus::grandpa::Gossiper>.template to<network::GossiperBroadcast>(),
di::bind<network::Gossiper>.template to<network::GossiperBroadcast>(),
di::bind<network::SyncClientsSet>.to([](auto const &injector) {
return get_sync_clients_set(injector);
}),
di::bind<network::SyncProtocolObserver>.template to<network::SyncProtocolObserverImpl>(),
di::bind<runtime::binaryen::WasmModule>.template to<runtime::binaryen::WasmModuleImpl>(),
di::bind<runtime::binaryen::WasmModuleFactory>.template to<runtime::binaryen::WasmModuleFactoryImpl>(),
di::bind<runtime::CoreFactory>.template to<runtime::binaryen::CoreFactoryImpl>(),
di::bind<runtime::TaggedTransactionQueue>.template to<runtime::binaryen::TaggedTransactionQueueImpl>(),
di::bind<runtime::ParachainHost>.template to<runtime::binaryen::ParachainHostImpl>(),
di::bind<runtime::OffchainWorker>.template to<runtime::binaryen::OffchainWorkerImpl>(),
di::bind<runtime::Metadata>.template to<runtime::binaryen::MetadataImpl>(),
di::bind<runtime::GrandpaApi>.template to<runtime::binaryen::GrandpaApiImpl>(),
di::bind<runtime::Core>.template to<runtime::binaryen::CoreImpl>(),
di::bind<runtime::BabeApi>.template to<runtime::binaryen::BabeApiImpl>(),
di::bind<runtime::BlockBuilder>.template to<runtime::binaryen::BlockBuilderImpl>(),
di::bind<runtime::TrieStorageProvider>.template to<runtime::TrieStorageProviderImpl>(),
di::bind<transaction_pool::TransactionPool>.template to<transaction_pool::TransactionPoolImpl>(),
di::bind<transaction_pool::PoolModerator>.template to<transaction_pool::PoolModeratorImpl>(),
di::bind<storage::changes_trie::ChangesTracker>.template to<storage::changes_trie::StorageChangesTrackerImpl>(),
di::bind<storage::trie::TrieStorageBackend>.to(
[](auto const &inj) { return get_trie_storage_backend(inj); }),
di::bind<storage::trie::TrieStorageImpl>.to(
[](auto const &inj) { return get_trie_storage_impl(inj); }),
di::bind<storage::trie::TrieStorage>.to(
[](auto const &inj) { return get_trie_storage(inj); }),
di::bind<storage::trie::PolkadotTrieFactory>.template to<storage::trie::PolkadotTrieFactoryImpl>(),
di::bind<storage::trie::Codec>.template to<storage::trie::PolkadotCodec>(),
di::bind<storage::trie::TrieSerializer>.template to<storage::trie::TrieSerializerImpl>(),
di::bind<runtime::WasmProvider>.template to<runtime::StorageWasmProvider>(),
di::bind<application::ConfigurationStorage>.to(
[genesis_path](const auto &injector) {
return get_configuration_storage(genesis_path, injector);
}),
di::bind<network::ExtrinsicObserver>.template to<network::ExtrinsicObserverImpl>(),
di::bind<network::ExtrinsicGossiper>.template to<network::GossiperBroadcast>(),
di::bind<authority::AuthorityUpdateObserver>.template to<authority::AuthorityManagerImpl>(),
di::bind<authority::AuthorityManager>.template to<authority::AuthorityManagerImpl>(),
di::bind<consensus::grandpa::FinalizationObserver>.to(
[](auto const &inj) { return get_finalization_observer(inj); }),
// user-defined overrides...
std::forward<decltype(args)>(args)...);
}
} // namespace kagome::injector
#endif // KAGOME_CORE_INJECTOR_APPLICATION_INJECTOR_HPP
| 43.998647 | 120 | 0.673658 | FlorianFranzen |
d594616cadf9861adc32438c5dc7e2cd09c48072 | 713 | cc | C++ | table/raw_table_test.cc | SZ-NPE/SLM-DB | aa3abdac29a7806344e7b219fda7396085cc5dd2 | [
"BSD-3-Clause"
] | 17 | 2019-11-18T07:02:23.000Z | 2021-12-30T10:15:08.000Z | table/raw_table_test.cc | SZ-NPE/SLM-DB | aa3abdac29a7806344e7b219fda7396085cc5dd2 | [
"BSD-3-Clause"
] | null | null | null | table/raw_table_test.cc | SZ-NPE/SLM-DB | aa3abdac29a7806344e7b219fda7396085cc5dd2 | [
"BSD-3-Clause"
] | 18 | 2019-11-21T14:08:50.000Z | 2022-03-17T07:46:16.000Z | #include "leveldb/env.h"
#include "util/testharness.h"
#include "raw_block_builder.h"
uint64_t clflush_cnt = 0;
uint64_t WRITE_LATENCY_IN_NS = 1000;
namespace leveldb {
class RAW_TABLE {
};
TEST(RAW_TABLE, Blocks) {
Options options;
RawBlockBuilder builder(&options);
for (int i = 0; i < 20; i++) {
std::string key = "key";
key.append(std::to_string(i));
std::string value = "value";
value.append(std::to_string(i));
builder.Add(Slice(key), Slice(value));
}
Slice result = builder.Finish();
char size[32];
memcpy(size, result.data(), 32);
ASSERT_EQ(std::stoi(size), result.size()-32);
//printf("%s", result.data());
};
}
int main() {
leveldb::test::RunAllTests();
}
| 19.805556 | 47 | 0.649369 | SZ-NPE |
d5953bec284bc2944f0f5da6301931a1ede0683a | 297 | cpp | C++ | dependencies/faucmix-src/src/stream.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | dependencies/faucmix-src/src/stream.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | dependencies/faucmix-src/src/stream.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | #include "stream.hpp"
void * pcmstream::generateframe(SDL_AudioSpec * spec, unsigned int len, emitterinfo * info)
{}
bool pcmstream::isplaying()
{}
bool pcmstream::ready()
{}
Uint16 pcmstream::channels()
{}
void pcmstream::fire(emitterinfo * info)
{}
void pcmstream::cease(emitterinfo * info)
{}
| 19.8 | 91 | 0.727273 | wareya |
d5978aa2e91b2fedd8890a321292114f39635b26 | 1,211 | cpp | C++ | SumofLeftLeaves/SumofLeftLeaves.cpp | sbchong/LeetCode | 933c7d85519b473f48050b24465aaaba94eede8c | [
"Apache-2.0"
] | null | null | null | SumofLeftLeaves/SumofLeftLeaves.cpp | sbchong/LeetCode | 933c7d85519b473f48050b24465aaaba94eede8c | [
"Apache-2.0"
] | null | null | null | SumofLeftLeaves/SumofLeftLeaves.cpp | sbchong/LeetCode | 933c7d85519b473f48050b24465aaaba94eede8c | [
"Apache-2.0"
] | 1 | 2020-07-29T14:36:51.000Z | 2020-07-29T14:36:51.000Z | // SumofLeftLeaves.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
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) {}
};
int sumOfLeftLeavesL(TreeNode* root) {
if (!root)return 0;
int result = 0;
if (root->left && !root->left->left && !root->left->right)
result += root->left->val;
result += sumOfLeftLeavesL(root->left);
result += sumOfLeftLeavesL(root->right);
return result;
}
int main()
{
std::cout << "_______________start_______________\n\n";
TreeNode tree = { 1, &TreeNode(2,&TreeNode(4),&TreeNode(5)), &TreeNode(3) };
std::cout << "\t" << sumOfLeftLeavesL(&tree) << std::endl;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| 27.522727 | 90 | 0.605285 | sbchong |
d5990f4be26649b13bfe75497021fd1e9240b32b | 703 | hpp | C++ | include/alibabacloud/event_bridge_util.hpp | alibabacloud-sdk-cpp/eventbridge-util | 3d679f81a6ce1f55bd1f22c757e9999c31ac5c1a | [
"Apache-2.0"
] | 6 | 2020-09-10T06:40:24.000Z | 2022-02-09T06:06:11.000Z | include/alibabacloud/event_bridge_util.hpp | alibabacloud-sdk-cpp/eventbridge-util | 3d679f81a6ce1f55bd1f22c757e9999c31ac5c1a | [
"Apache-2.0"
] | 69 | 2020-09-14T08:07:44.000Z | 2022-01-27T09:05:09.000Z | include/alibabacloud/event_bridge_util.hpp | alibabacloud-sdk-cpp/eventbridge-util | 3d679f81a6ce1f55bd1f22c757e9999c31ac5c1a | [
"Apache-2.0"
] | 10 | 2020-09-11T07:54:03.000Z | 2022-03-11T06:08:35.000Z | // This file is auto-generated, don't edit it. Thanks.
#ifndef ALIBABACLOUD_EVENTBRIDGEUTIL_H_
#define ALIBABACLOUD_EVENTBRIDGEUTIL_H_
#include <boost/any.hpp>
#include <darabonba/core.hpp>
#include <iostream>
using namespace std;
namespace Alibabacloud_EventBridgeUtil {
class Client {
public:
static string getStringToSign(shared_ptr<Darabonba::Request> request);
static string getSignature(shared_ptr<string> stringToSign,
shared_ptr<string> secret);
static boost::any serialize(const shared_ptr<void> &events);
static bool startWith(shared_ptr<string> origin, shared_ptr<string> prefix);
Client(){};
};
} // namespace Alibabacloud_EventBridgeUtil
#endif
| 27.038462 | 78 | 0.758179 | alibabacloud-sdk-cpp |
d5994f3f875732e31d34e3915cf7c6eed4d66520 | 257 | cpp | C++ | tutorials/cplusplus.com#1.0#1/programstructure/functions/recursivity/source1.cpp | officialrafsan/CppDroid | 5fb2cc7750fea53b1ea6ff47b5094da6e95e9224 | [
"MIT"
] | null | null | null | tutorials/cplusplus.com#1.0#1/programstructure/functions/recursivity/source1.cpp | officialrafsan/CppDroid | 5fb2cc7750fea53b1ea6ff47b5094da6e95e9224 | [
"MIT"
] | null | null | null | tutorials/cplusplus.com#1.0#1/programstructure/functions/recursivity/source1.cpp | officialrafsan/CppDroid | 5fb2cc7750fea53b1ea6ff47b5094da6e95e9224 | [
"MIT"
] | null | null | null | // factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}
int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
} | 14.277778 | 49 | 0.59144 | officialrafsan |
d59ab9d935963753331d357c5a80320501f64718 | 26 | cpp | C++ | src/orderparameters/SimpleVector.cpp | seanmarks/indus | a25012d79d5cb94986a3210a0c7f21b6d427ce5b | [
"MIT"
] | 6 | 2019-01-14T16:03:19.000Z | 2021-06-28T06:10:33.000Z | src/orderparameters/SimpleVector.cpp | seanmarks/indus | a25012d79d5cb94986a3210a0c7f21b6d427ce5b | [
"MIT"
] | 3 | 2020-01-25T21:46:15.000Z | 2021-08-17T15:31:53.000Z | src/orderparameters/SimpleVector.cpp | seanmarks/indus | a25012d79d5cb94986a3210a0c7f21b6d427ce5b | [
"MIT"
] | 2 | 2021-01-29T16:53:19.000Z | 2021-10-29T19:05:08.000Z | #include "SimpleVector.h"
| 13 | 25 | 0.769231 | seanmarks |
d59d130e1ef442f594761521f1b721a3b9f0822e | 1,793 | hpp | C++ | blast/include/connect/ncbi_service_cxx.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/connect/ncbi_service_cxx.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/connect/ncbi_service_cxx.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | #ifndef CONNECT___NCBI_SERVICE_CXX__HPP
#define CONNECT___NCBI_SERVICE_CXX__HPP
/* $Id: ncbi_service_cxx.hpp 605392 2020-04-10 02:19:46Z lavr $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Anton Lavrentiev
*
* File description:
* @file ncbi_service_cxx.hpp
* Backward-compatible forwarding header for <connect/ncbi_service.hpp>
*
* @warning *** Use <connect/ncbi_service.hpp> directly instead! ***
*
* @warning OBSOLESCENT -- WILL BE DELETED SOON -- DO NOT USE!!
*
*/
#include <connect/ncbi_service.hpp>
#endif // CONNECT___NCBI_SERVICE_CXX__HPP
| 39.844444 | 78 | 0.666481 | mycolab |
d59f1497dd708f9dec3713a85ee5fbafa18c14c8 | 870 | cpp | C++ | src/config.cpp | s-viour/wing | 5635cabaaf614672e5d6ee2d4dd617d74198c30a | [
"MIT"
] | null | null | null | src/config.cpp | s-viour/wing | 5635cabaaf614672e5d6ee2d4dd617d74198c30a | [
"MIT"
] | 8 | 2021-11-24T04:16:07.000Z | 2021-12-21T05:18:43.000Z | src/config.cpp | s-viour/wing | 5635cabaaf614672e5d6ee2d4dd617d74198c30a | [
"MIT"
] | null | null | null | #include <fstream>
#include <toml++/toml.h>
#include <wing/config.h>
using namespace wing;
wing::project_config wing::load_config(const fs::path& path) {
auto table = toml::parse_file(path.string());
auto name = table["name"].value<std::string>();
//auto project_type = table["type"].value<std::string>();
//auto vcpkg_dir = table["vcpkg_dir"].value<std::string>();
auto table_dependencies = table["dependencies"].as_array();
if (!name || !table_dependencies) {
throw wing::config_error("missing required values or has malformed values");
}
std::vector<dependency> dependencies;
for (auto& table_dep : *table_dependencies) {
auto dep = dependency {
.name = table_dep.value<std::string>().value(),
};
dependencies.push_back(dep);
}
return project_config {
.name = name.value(),
.dependencies = dependencies
};
} | 28.064516 | 80 | 0.673563 | s-viour |
d5a044c8ebf812759d6f63595d5c18c9a9305350 | 3,778 | hpp | C++ | drape_frontend/animation/interpolators.hpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | drape_frontend/animation/interpolators.hpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | drape_frontend/animation/interpolators.hpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "geometry/screenbase.hpp"
namespace df
{
class Interpolator
{
public:
Interpolator(double duration, double delay = 0);
virtual ~Interpolator() = default;
virtual void Advance(double elapsedSeconds);
virtual void Finish();
bool IsActive() const;
void SetActive(bool active);
bool IsFinished() const;
void SetMaxDuration(double maxDuration);
void SetMinDuration(double minDuration);
double GetDuration() const;
protected:
double GetT() const;
double GetElapsedTime() const;
private:
double m_elapsedTime;
double m_duration;
double m_delay;
bool m_isActive;
};
class PositionInterpolator: public Interpolator
{
using TBase = Interpolator;
public:
PositionInterpolator();
PositionInterpolator(double duration, double delay,
m2::PointD const & startPosition, m2::PointD const & endPosition);
PositionInterpolator(m2::PointD const & startPosition, m2::PointD const & endPosition,
ScreenBase const & convertor);
PositionInterpolator(double delay,
m2::PointD const & startPosition, m2::PointD const & endPosition,
ScreenBase const & convertor);
PositionInterpolator(m2::PointD const & startPosition, m2::PointD const & endPosition,
m2::RectD const & viewportRect, double scale);
PositionInterpolator(double delay,
m2::PointD const & startPosition, m2::PointD const & endPosition,
m2::RectD const & viewportRect, double scale);
static double GetMoveDuration(double globalDistance, m2::RectD const & viewportRect, double scale);
static double GetMoveDuration(m2::PointD const & startPosition, m2::PointD const & endPosition,
m2::RectD const & viewportRect, double scale);
static double GetMoveDuration(m2::PointD const & startPosition, m2::PointD const & endPosition,
ScreenBase const & convertor);
// Interpolator overrides:
void Advance(double elapsedSeconds) override;
void Finish() override;
m2::PointD GetPosition() const { return m_position; }
m2::PointD GetTargetPosition() const { return m_endPosition; }
private:
m2::PointD m_startPosition;
m2::PointD m_endPosition;
m2::PointD m_position;
};
class ScaleInterpolator: public Interpolator
{
using TBase = Interpolator;
public:
ScaleInterpolator();
ScaleInterpolator(double startScale, double endScale, bool isAutoZoom);
ScaleInterpolator(double delay, double startScale, double endScale, bool isAutoZoom);
static double GetScaleDuration(double startScale, double endScale, bool isAutoZoom);
// Interpolator overrides:
void Advance(double elapsedSeconds) override;
void Finish() override;
double GetScale() const { return m_scale; }
double GetStartScale() const { return m_startScale; }
double GetTargetScale() const { return m_endScale; }
private:
double m_startScale;
double m_endScale;
double m_scale;
};
class AngleInterpolator: public Interpolator
{
using TBase = Interpolator;
public:
AngleInterpolator();
AngleInterpolator(double startAngle, double endAngle);
AngleInterpolator(double delay, double startAngle, double endAngle);
AngleInterpolator(double delay, double duration, double startAngle, double endAngle);
static double GetRotateDuration(double startAngle, double endAngle);
// Interpolator overrides:
void Advance(double elapsedSeconds) override;
void Finish() override;
double GetAngle() const { return m_angle; }
double GetStartAngle() const { return m_startAngle; }
double GetTargetAngle() const { return m_endAngle; }
private:
double m_startAngle;
double m_endAngle;
double m_angle;
};
} // namespace df
| 28.621212 | 101 | 0.718105 | Dushistov |
d5a226af657bab8d3df81322c9ab69c0df7938ee | 822 | cpp | C++ | filters/VesselFilterByBranchingMode.cpp | lfmc/VItA | f7f6c80a09f49cd0d1cca7e6657f18889d95b719 | [
"Apache-2.0"
] | 4 | 2021-05-10T12:38:16.000Z | 2022-02-12T23:31:53.000Z | filters/VesselFilterByBranchingMode.cpp | lfmc/VItA | f7f6c80a09f49cd0d1cca7e6657f18889d95b719 | [
"Apache-2.0"
] | 3 | 2021-01-14T21:37:08.000Z | 2021-03-04T23:02:20.000Z | filters/VesselFilterByBranchingMode.cpp | lfmc/VItA | f7f6c80a09f49cd0d1cca7e6657f18889d95b719 | [
"Apache-2.0"
] | 4 | 2020-09-11T14:47:26.000Z | 2021-11-08T22:45:32.000Z | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright 2020 Gonzalo Maso Talou */
/*
* VesselFilterByBranchingMode.cpp
*
* Created on: 22/05/2019
* Author: Gonzalo D. Maso Talou
*/
#include "VesselFilterByBranchingMode.h"
VesselFilterByBranchingMode::VesselFilterByBranchingMode(AbstractVascularElement::BRANCHING_MODE mode) : AbstractVesselFilter() {
this->mode = mode;
}
VesselFilterByBranchingMode::~VesselFilterByBranchingMode(){
// TODO Auto-generated destructor stub
}
vector<SingleVessel*> VesselFilterByBranchingMode::apply(vector<SingleVessel*> vessels){
vector<SingleVessel*> filteredVessels;
for (std::vector<SingleVessel *>::iterator it = vessels.begin(); it != vessels.end(); ++it) {
if( (*it)->branchingMode == mode){
filteredVessels.push_back(*it);
}
}
return filteredVessels;
}
| 28.344828 | 129 | 0.743309 | lfmc |
d5a2763217737ff12de1bcb0180800368f88c870 | 12,005 | cxx | C++ | Modules/Visualization/MonteverdiGui/src/mvdLayerStackController.cxx | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | Modules/Visualization/MonteverdiGui/src/mvdLayerStackController.cxx | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | Modules/Visualization/MonteverdiGui/src/mvdLayerStackController.cxx | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "mvdLayerStackController.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAbstractLayerModel.h"
#include "mvdFilenameInterface.h"
#include "mvdStackedLayerModel.h"
#include "mvdLayerStackItemModel.h"
#include "mvdLayerStackWidget.h"
namespace mvd
{
/*
TRANSLATOR mvd::LayerStackController
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
LayerStackController
::LayerStackController( LayerStackWidget * widget, QObject * p ) :
AbstractModelController( widget, p )
{
}
/*******************************************************************************/
LayerStackController
::~LayerStackController()
{
}
/*******************************************************************************/
void
LayerStackController
::ClearWidget()
{
}
/*******************************************************************************/
void
LayerStackController
::Connect( AbstractModel * model )
{
assert( model==qobject_cast< StackedLayerModel * >( model ) );
QObject::connect(
model,
SIGNAL( CurrentChanged( size_t ) ),
// to:
this,
SLOT( OnStackedLayerCurrentChanged( size_t ) )
);
QObject::connect(
model,
SIGNAL( ContentChanged() ),
// to:
this,
SLOT( OnStackedLayerContentChanged() )
);
QObject::connect(
model,
SIGNAL( ContentReset() ),
// to:
this,
SLOT( OnStackedLayerContentReset() )
);
LayerStackWidget * widget = GetWidget< LayerStackWidget >();
assert( widget!=NULL );
assert( widget->GetItemModel()!=NULL );
widget->GetItemModel()->SetStack(
qobject_cast< StackedLayerModel * >( model )
);
QObject::connect(
widget,
SIGNAL( SelectionChanged( int ) ),
// to:
this,
SLOT( OnSelectionChanged( int ) )
);
QObject::connect(
widget,
SIGNAL( ProjectionButtonClicked() ),
// to:
this,
SLOT( OnProjectionButtonClicked() )
);
//bugfix for layer deletion
QObject::connect(
widget,
SIGNAL( LayerDeletingWidget( unsigned int ) ),
// to:
model,
SLOT( Deleting( unsigned int ) )
);
QObject::connect(
widget,
SIGNAL( TopButtonClicked() ),
// to:
model,
SLOT( MoveCurrentToTop() )
);
QObject::connect(
widget,
SIGNAL( BottomButtonClicked() ),
// to:
model,
SLOT( MoveCurrentToBottom() )
);
QObject::connect(
widget,
SIGNAL( UpButtonClicked() ),
// to:
model,
SLOT( RaiseCurrent() )
);
QObject::connect(
widget,
SIGNAL( DownButtonClicked() ),
// to:
model,
SLOT( LowerCurrent() )
);
QObject::connect(
widget,
SIGNAL( DeleteLayerRequested() ),
// to:
model,
SLOT( DeleteCurrent() )
);
QObject::connect(
widget,
SIGNAL( DeleteAllLayersRequested() ),
// to:
model,
SLOT( Clear() )
);
QObject::connect(
widget,
SIGNAL( CopyLayerRequested( const AbstractLayerModel * ) ),
// to:
this,
SLOT( OnCopyLayerRequested( const AbstractLayerModel * ) )
);
QObject::connect(
widget,
SIGNAL( RotateLayersRequested( int ) ),
// to:
model,
SLOT( RotateLayers( int ) )
);
QObject::connect(
widget,
SIGNAL( ApplyButtonClicked() ),
// to:
this,
SIGNAL( ApplyAllRequested() )
);
QObject::connect(
widget,
SIGNAL( ResetEffectsButtonClicked() ),
// to:
this,
SIGNAL( ResetEffectsRequested() )
);
}
/*******************************************************************************/
void
LayerStackController
::Disconnect( AbstractModel * model )
{
// assert( model==qobject_cast< StackedLayerModel * >( model ) );
QObject::disconnect(
model,
SIGNAL( CurrentChanged( size_t ) ),
// from:deletin
this,
SLOT( OnStackedLayerCurrentChanged( size_t ) )
);
QObject::disconnect(
model,
SIGNAL( ContentChanged() ),
// from:
this,
SLOT( OnStackedLayerContentChanged() )
);
QObject::disconnect(
model,
SIGNAL( ContentReset() ),
// from:
this,
SLOT( OnStackedLayerContentReset() )
);
LayerStackWidget * widget = GetWidget< LayerStackWidget >();
assert( widget!=NULL );
assert( widget->GetItemModel()!=NULL );
widget->GetItemModel()->SetStack( NULL );
QObject::disconnect(
widget,
SIGNAL( SelectionChanged( int ) ),
// from:
this,
SLOT( OnSelectionChanged( int ) )
);
QObject::disconnect(
widget,
SIGNAL( ProjectionButtonClicked() ),
// from:
this,
SLOT( OnProjectionButtonClicked() )
);
//Bugfix for layer deletion
QObject::disconnect(
widget,
SIGNAL( LayerDeletingWidget( unsigned int ) ),
// to:
model,
SLOT( Deleting( unsigned int ) )
);
QObject::disconnect(
widget,
SIGNAL( TopButtonClicked() ),
// from:
model,
SLOT( MoveCurrentToTop() )
);
QObject::disconnect(
widget,
SIGNAL( BottomButtonClicked() ),
// from:
model,
SLOT( MoveCurrentToBottom() )
);
QObject::disconnect(
widget,
SIGNAL( UpButtonClicked() ),
// from:
model,
SLOT( RaiseCurrent() )
);
QObject::disconnect(
widget,
SIGNAL( DownButtonClicked() ),
// from:
model,
SLOT( LowerCurrent() )
);
QObject::disconnect(
widget,
SIGNAL( DeleteLayerRequested() ),
// from:
model,
SLOT( DeleteCurrent() )
);
QObject::disconnect(
widget,
SIGNAL( DeleteAllLayersRequested() ),
// from:
model,
SLOT( Clear() )
);
QObject::disconnect(
widget,
SIGNAL( CopyLayerRequested( const AbstractLayerModel * ) ),
// from:
this,
SLOT( OnCopyLayerRequested( const AbstractLayerModel * ) )
);
QObject::disconnect(
widget,
SIGNAL( RotateLayersRequested( int ) ),
// from:
model,
SLOT( RotateLayers( int ) )
);
QObject::disconnect(
widget,
SIGNAL( ApplyButtonClicked() ),
// to:
this,
SIGNAL( ApplyAllRequested() )
);
QObject::disconnect(
widget,
SIGNAL( ResetEffectsButtonClicked() ),
// to:
this,
SIGNAL( ResetEffectsRequested() )
);
}
/*******************************************************************************/
void
LayerStackController
::virtual_ResetWidget( bool )
{
}
/*******************************************************************************/
void
LayerStackController
::UpdateButtonsState()
{
assert( GetModel()==GetModel< StackedLayerModel >() );
StackedLayerModel * model = GetModel< StackedLayerModel >();
assert( model!=NULL );
assert( GetWidget()==GetWidget< LayerStackWidget >() );
LayerStackWidget * widget = GetWidget< LayerStackWidget >();
assert( widget!=NULL );
{
size_t unk = 0;
size_t gcs = 0;
model->CountSRT( unk, gcs, gcs, gcs );
widget->SetProjectionEnabled( unk==0 && !model->IsEmpty() );
}
widget->SetDeleteEnabled( !model->IsEmpty() );
widget->SetReloadEnabled( !model->IsEmpty() );
widget->SetMoveEnabled( model->GetCount()>1 );
widget->SetApplyEnabled( model->GetCount()>1 );
widget->SetResetEffectsEnabled( !model->IsEmpty() );
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
LayerStackController
::OnCopyLayerRequested( const AbstractLayerModel * layer )
{
// qDebug() << this << "::OnCopyLayerRequested(" << layer << ")";
assert( layer!=NULL );
const FilenameInterface * interface =
dynamic_cast< const FilenameInterface * >( layer );
if( interface==NULL )
return;
assert( qApp!=NULL );
assert( qApp->clipboard()!=NULL );
assert( qApp->clipboard()->mimeData()!=NULL );
QList< QUrl > urls;
urls << QUrl::fromLocalFile( interface->GetFilename() );
qDebug() << "URLs:" << urls;
QMimeData * mimeData = new QMimeData();
mimeData->setUrls( urls );
mimeData->setText( interface->GetFilename() );
qApp->clipboard()->setMimeData( mimeData );
}
/*******************************************************************************/
void
LayerStackController
::OnCurrentChanged( int index )
{
// qDebug() << this << "::OnCurrentChanged(" << index << ")";
assert( GetModel()==GetModel< StackedLayerModel >() );
StackedLayerModel * model = GetModel< StackedLayerModel >();
assert( model!=NULL );
model->SetCurrent( index );
}
/*******************************************************************************/
void
LayerStackController
::OnProjectionButtonClicked()
{
// qDebug() << this << "::OnProjectionButtonClicked()";
assert( GetModel()==GetModel< StackedLayerModel >() );
StackedLayerModel * model = GetModel< StackedLayerModel >();
assert( model!=NULL );
model->SetReference( model->GetCurrentIndex() );
}
/*******************************************************************************/
void
LayerStackController
::OnSelectionChanged( int index )
{
// qDebug() << this << "::OnSelectionChanged(" << index << ")";
assert( GetModel()==GetModel< StackedLayerModel >() );
StackedLayerModel * model = GetModel< StackedLayerModel >();
assert( model!=NULL );
model->SetCurrent( index );
}
/*******************************************************************************/
void
LayerStackController
::OnStackedLayerCurrentChanged( size_t index )
{
// qDebug() << this << "::OnStackedLayerCurrentChanged(" << index << ")";
LayerStackWidget * widget = GetWidget< LayerStackWidget >();
assert( widget!=NULL );
assert( widget->GetItemModel()!=NULL );
bool prevSignalsBlocked = widget->blockSignals( true );
{
widget->SetCurrent( index );
}
widget->blockSignals( prevSignalsBlocked );
}
/*******************************************************************************/
void
LayerStackController
::OnStackedLayerContentChanged()
{
// qDebug() << this << "::OnStackedLayerContentChanged()";
UpdateButtonsState();
}
/*******************************************************************************/
void
LayerStackController
::OnStackedLayerContentReset()
{
// qDebug() << this << "::OnStackedLayerContentChanged()";
UpdateButtonsState();
}
} // end namespace 'mvd'
| 21.946984 | 81 | 0.547272 | xcorail |
d5a5b44c7e83d6443db3a8a761edd675e65ca5e8 | 1,779 | hpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_cdp_cfg.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_cdp_cfg.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_cdp_cfg.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_IOS_XR_CDP_CFG_
#define _CISCO_IOS_XR_CDP_CFG_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_cdp_cfg {
class Cdp : public ydk::Entity
{
public:
Cdp();
~Cdp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
ydk::YLeaf timer; //type: uint32
ydk::YLeaf advertise_v1_only; //type: empty
ydk::YLeaf enable; //type: boolean
ydk::YLeaf hold_time; //type: uint32
ydk::YLeaf log_adjacency; //type: empty
}; // Cdp
}
}
#endif /* _CISCO_IOS_XR_CDP_CFG_ */
| 37.0625 | 162 | 0.697021 | CiscoDevNet |
d5a91f47fb10019fe2401979688879374980da79 | 3,862 | cpp | C++ | oomact/src/error-terms/ErrorTermWheelsZ.cpp | OnyxBlack7/oomact | 5ae5fbbaddaf58e2fc24adaabedf711619934ac9 | [
"BSD-3-Clause"
] | 21 | 2017-06-19T13:57:59.000Z | 2022-02-20T02:40:58.000Z | oomact/src/error-terms/ErrorTermWheelsZ.cpp | OnyxBlack7/oomact | 5ae5fbbaddaf58e2fc24adaabedf711619934ac9 | [
"BSD-3-Clause"
] | 19 | 2017-05-10T09:11:25.000Z | 2019-03-11T16:41:36.000Z | oomact/src/error-terms/ErrorTermWheelsZ.cpp | OnyxBlack7/oomact | 5ae5fbbaddaf58e2fc24adaabedf711619934ac9 | [
"BSD-3-Clause"
] | 11 | 2017-06-19T13:39:12.000Z | 2022-03-16T19:53:27.000Z | /******************************************************************************
* Copyright (C) 2013 by Jerome Maye *
* jerome.maye@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the Lesser GNU General Public License as published by*
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* Lesser GNU General Public License for more details. *
* *
* You should have received a copy of the Lesser GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "aslam/calibration/error-terms/ErrorTermWheelsZ.h"
#include <Eigen/Dense>
using namespace aslam::backend;
namespace aslam {
namespace calibration {
/******************************************************************************/
/* Constructors and Destructor */
/******************************************************************************/
ErrorTermWheelsZ::ErrorTermWheelsZ(const aslam::backend::EuclideanExpression& v_w_mwl,
const aslam::backend::EuclideanExpression& v_w_mwr,
const Covariance& sigma2_vert_vel) :
_v_w_mwl(v_w_mwl),
_v_w_mwr(v_w_mwr),
_sigma2_vert_vel(sigma2_vert_vel) {
setInvR(_sigma2_vert_vel.inverse());
DesignVariable::set_t dv;
_v_w_mwl.getDesignVariables(dv);
_v_w_mwr.getDesignVariables(dv);
setDesignVariablesIterator(dv.begin(), dv.end());
}
ErrorTermWheelsZ::ErrorTermWheelsZ(const ErrorTermWheelsZ& other) :
ErrorTermFs<1>(other),
_v_w_mwl(other. _v_w_mwl),
_v_w_mwr(other. _v_w_mwr),
_sigma2_vert_vel(other._sigma2_vert_vel){
}
ErrorTermWheelsZ& ErrorTermWheelsZ::operator =
(const ErrorTermWheelsZ& other) {
if (this != &other) {
ErrorTermFs<1>::operator=(other);
_v_w_mwl = other._v_w_mwl;
_v_w_mwr = other._v_w_mwr;
_sigma2_vert_vel = other._sigma2_vert_vel;
}
return *this;
}
ErrorTermWheelsZ::~ErrorTermWheelsZ() {
}
/******************************************************************************/
/* Methods */
/******************************************************************************/
double ErrorTermWheelsZ::evaluateErrorImplementation() {
error_t error;
const double vzl = _v_w_mwl.toEuclidean()(2);
const double vzr = _v_w_mwr.toEuclidean()(2);
error(0) = vzl + vzr;
setError(error);
return evaluateChiSquaredError();
}
void ErrorTermWheelsZ::evaluateJacobiansImplementation(JacobianContainer&
jacobians) {
Eigen::Matrix<double, 1, 3> Jl = Eigen::Matrix<double, 1, 3>::Zero();
Eigen::Matrix<double, 1, 3> Jr = Eigen::Matrix<double, 1, 3>::Zero();
Jl(2) = 1.0;
Jr(2) = 1.0;
_v_w_mwl.evaluateJacobians(jacobians, Jl);
_v_w_mwr.evaluateJacobians(jacobians,Jr);
}
}
}
| 40.229167 | 88 | 0.483687 | OnyxBlack7 |
d5a946cc94e66be572493e51068c73954c65d9d7 | 2,269 | cpp | C++ | solutions/LeetCode/C++/203.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/203.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/203.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 24 ms submission
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
Solution()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
ListNode* removeElements(ListNode* head, int val) {
while(head != nullptr and head->val == val)
{
auto hn = head->next;
//delete head;
head = hn;
}
if(head == nullptr)
{
return nullptr;
}
auto temp = head;
while(head->next != nullptr)
{
while(head->next != nullptr and (head->next->val != val))
{
head = head->next;
}
if(head->next == nullptr)
{
break;
}
auto nextnext = head->next->next;
//delete head->next;
head->next = nextnext;
}
return temp;
}
};
__________________________________________________________________________________________________
sample 10968 kb submission
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static const auto speedup =[]() {std::ios::sync_with_stdio(false); std::cin.tie(NULL); return 0;}();
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(!head)
return head;
ListNode* dummy = new ListNode(-1), *itr, *prev;
dummy -> next = head;
prev = dummy;
itr = prev -> next;
while(itr) {
if(itr -> val == val) {
prev -> next = itr -> next;
itr = prev -> next;
}
else {
prev = prev -> next;
itr = prev -> next;
}
}
return dummy -> next;
}
};
__________________________________________________________________________________________________
| 25.494382 | 100 | 0.513001 | timxor |
d5ab9a5c3f340e937334126b63c44eb538318e5b | 4,933 | cpp | C++ | 3.7.0/clang-tools-extra-3.7.0.src/clang-modernize/LoopConvert/StmtAncestor.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 3 | 2016-02-10T14:18:40.000Z | 2018-02-05T03:15:56.000Z | 3.7.0/clang-tools-extra-3.7.0.src/clang-modernize/LoopConvert/StmtAncestor.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 1 | 2016-02-10T15:40:03.000Z | 2016-02-10T15:40:03.000Z | 3.7.0/clang-tools-extra-3.7.0.src/clang-modernize/LoopConvert/StmtAncestor.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | null | null | null | //===-- LoopConvert/StmtAncestor.cpp - AST property visitors --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains the definitions of several RecursiveASTVisitors
/// used to build and check data structures used in loop migration.
///
//===----------------------------------------------------------------------===//
#include "StmtAncestor.h"
using namespace clang;
/// \brief Tracks a stack of parent statements during traversal.
///
/// All this really does is inject push_back() before running
/// RecursiveASTVisitor::TraverseStmt() and pop_back() afterwards. The Stmt atop
/// the stack is the parent of the current statement (NULL for the topmost
/// statement).
bool StmtAncestorASTVisitor::TraverseStmt(Stmt *Statement) {
StmtAncestors.insert(std::make_pair(Statement, StmtStack.back()));
StmtStack.push_back(Statement);
RecursiveASTVisitor<StmtAncestorASTVisitor>::TraverseStmt(Statement);
StmtStack.pop_back();
return true;
}
/// \brief Keep track of the DeclStmt associated with each VarDecl.
///
/// Combined with StmtAncestors, this provides roughly the same information as
/// Scope, as we can map a VarDecl to its DeclStmt, then walk up the parent tree
/// using StmtAncestors.
bool StmtAncestorASTVisitor::VisitDeclStmt(DeclStmt *Decls) {
for (DeclStmt::const_decl_iterator I = Decls->decl_begin(),
E = Decls->decl_end(); I != E; ++I)
if (const VarDecl *V = dyn_cast<VarDecl>(*I))
DeclParents.insert(std::make_pair(V, Decls));
return true;
}
/// \brief record the DeclRefExpr as part of the parent expression.
bool ComponentFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
Components.push_back(E);
return true;
}
/// \brief record the MemberExpr as part of the parent expression.
bool ComponentFinderASTVisitor::VisitMemberExpr(MemberExpr *Member) {
Components.push_back(Member);
return true;
}
/// \brief Forward any DeclRefExprs to a check on the referenced variable
/// declaration.
bool DependencyFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *DeclRef) {
if (VarDecl *V = dyn_cast_or_null<VarDecl>(DeclRef->getDecl()))
return VisitVarDecl(V);
return true;
}
/// \brief Determine if any this variable is declared inside the ContainingStmt.
bool DependencyFinderASTVisitor::VisitVarDecl(VarDecl *V) {
const Stmt *Curr = DeclParents->lookup(V);
// First, see if the variable was declared within an inner scope of the loop.
while (Curr != nullptr) {
if (Curr == ContainingStmt) {
DependsOnInsideVariable = true;
return false;
}
Curr = StmtParents->lookup(Curr);
}
// Next, check if the variable was removed from existence by an earlier
// iteration.
for (ReplacedVarsMap::const_iterator I = ReplacedVars->begin(),
E = ReplacedVars->end(); I != E; ++I)
if ((*I).second == V) {
DependsOnInsideVariable = true;
return false;
}
return true;
}
/// \brief If we already created a variable for TheLoop, check to make sure
/// that the name was not already taken.
bool DeclFinderASTVisitor::VisitForStmt(ForStmt *TheLoop) {
StmtGeneratedVarNameMap::const_iterator I = GeneratedDecls->find(TheLoop);
if (I != GeneratedDecls->end() && I->second == Name) {
Found = true;
return false;
}
return true;
}
/// \brief If any named declaration within the AST subtree has the same name,
/// then consider Name already taken.
bool DeclFinderASTVisitor::VisitNamedDecl(NamedDecl *D) {
const IdentifierInfo *Ident = D->getIdentifier();
if (Ident && Ident->getName() == Name) {
Found = true;
return false;
}
return true;
}
/// \brief Forward any declaration references to the actual check on the
/// referenced declaration.
bool DeclFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *DeclRef) {
if (NamedDecl *D = dyn_cast<NamedDecl>(DeclRef->getDecl()))
return VisitNamedDecl(D);
return true;
}
/// \brief If the new variable name conflicts with any type used in the loop,
/// then we mark that variable name as taken.
bool DeclFinderASTVisitor::VisitTypeLoc(TypeLoc TL) {
QualType QType = TL.getType();
// Check if our name conflicts with a type, to handle for typedefs.
if (QType.getAsString() == Name) {
Found = true;
return false;
}
// Check for base type conflicts. For example, when a struct is being
// referenced in the body of the loop, the above getAsString() will return the
// whole type (ex. "struct s"), but will be caught here.
if (const IdentifierInfo *Ident = QType.getBaseTypeIdentifier()) {
if (Ident->getName() == Name) {
Found = true;
return false;
}
}
return true;
}
| 34.985816 | 80 | 0.676667 | androm3da |
d5abff91677d3a21ba2d351f9751df7cdbc0e86f | 400 | cpp | C++ | src/entity.cpp | kindanoob/pong | 92f649e5d9f2286509ea5f8738097f0fc26e3a8f | [
"MIT"
] | null | null | null | src/entity.cpp | kindanoob/pong | 92f649e5d9f2286509ea5f8738097f0fc26e3a8f | [
"MIT"
] | null | null | null | src/entity.cpp | kindanoob/pong | 92f649e5d9f2286509ea5f8738097f0fc26e3a8f | [
"MIT"
] | null | null | null | #include "entity.h"
Entity::Entity(const sf::Texture &texture, const std::string &name,
int x, int y, double dx, double dy, int w, int h, int row, int col):
name_(name), h_(h), w_(w), x_(x), y_(y), dx_(dx), dy_(dy), texture_(texture) {
sprite_.setTexture(texture);
sprite_.setTextureRect(sf::IntRect(col * w, row * h, w, h));
rect_ = sf::FloatRect(x, y, w, h);
}
| 36.363636 | 87 | 0.5975 | kindanoob |
d5ae8ea566582c9532eb9478088711d6e106ec27 | 9,263 | cpp | C++ | service/regalloc-fast/LiveInterval.cpp | kami-lang/madex-redex | 90ae1bc46c6e20a0aed2c128183b9f289cecee34 | [
"MIT"
] | null | null | null | service/regalloc-fast/LiveInterval.cpp | kami-lang/madex-redex | 90ae1bc46c6e20a0aed2c128183b9f289cecee34 | [
"MIT"
] | null | null | null | service/regalloc-fast/LiveInterval.cpp | kami-lang/madex-redex | 90ae1bc46c6e20a0aed2c128183b9f289cecee34 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "LiveInterval.h"
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include "DexUtil.h"
#include "LinearScan.h"
namespace fastregalloc {
LiveIntervals init_live_intervals(
cfg::ControlFlowGraph& cfg,
std::vector<LiveIntervalPoint>* live_interval_points) {
LiveIntervals live_intervals;
VRegAliveInsns vreg_alive_insns;
auto add_live_range = [&vreg_alive_insns](const auto& vreg_block_range) {
for (auto& [vreg, range] : vreg_block_range) {
vreg_alive_insns[vreg].push_back(range);
}
};
LivenessFixpointIterator liveness_fixpoint_iter(cfg);
liveness_fixpoint_iter.run({});
std::unordered_map<cfg::Block*, std::unordered_set<vreg_t>>
check_cast_throw_targets_vregs;
for (cfg::Block* block : cfg.blocks()) {
add_live_range(get_live_range_in_block(
liveness_fixpoint_iter, block, &check_cast_throw_targets_vregs));
}
for (auto& [block, vregs] : check_cast_throw_targets_vregs) {
add_live_range(get_check_cast_throw_targets_live_range(
liveness_fixpoint_iter, block, vregs));
}
// number the instructions to get sortable live intervals
LiveIntervalPointIndices indices;
auto add_lip = [&indices, live_interval_points](const auto& lip) {
auto success = indices.emplace(lip, indices.size()).second;
always_assert(success);
live_interval_points->push_back(lip);
};
auto ordered_blocks = get_ordered_blocks(cfg, liveness_fixpoint_iter);
for (auto block : ordered_blocks) {
for (auto& mie : InstructionIterable(block)) {
add_lip(LiveIntervalPoint::get(mie.insn));
}
if (cfg.get_succ_edge_if(
block, [](cfg::Edge* e) { return e->type() != cfg::EDGE_GHOST; })) {
// Any block with continuing control-flow could have a live-out registers,
// and thus we allocate a block-end point for it.
add_lip(LiveIntervalPoint::get_block_end(block));
}
}
for (const auto& [vreg, ranges] : vreg_alive_insns) {
auto [start_point, end_point] = calculate_live_interval(ranges, indices);
live_intervals.push_back(VRegLiveInterval{start_point, end_point, vreg});
}
std::sort(live_intervals.begin(), live_intervals.end());
return live_intervals;
}
IntervalEndPoints calculate_live_interval(
const std::vector<RangeInBlock>& ranges,
const LiveIntervalPointIndices& indices) {
always_assert(!indices.empty());
uint32_t max_index = indices.size() - 1;
uint32_t interval_start = max_index;
uint32_t interval_end = 0;
for (auto& range : ranges) {
always_assert(!range.first.is_missing());
auto range_start = indices.at(range.first);
interval_start = std::min(interval_start, range_start);
// if there is deadcode (def no use), we assume the live interval lasts
// until end of code
if (range.second.is_missing()) {
interval_end = max_index;
} else {
auto range_end = indices.at(range.second);
interval_end = std::max(interval_end, range_end);
}
}
redex_assert(interval_start <= interval_end);
return std::make_pair(interval_start, interval_end);
}
VRegAliveRangeInBlock get_live_range_in_block(
const LivenessFixpointIterator& fixpoint_iter,
cfg::Block* block,
std::unordered_map<cfg::Block*, std::unordered_set<vreg_t>>*
check_cast_throw_targets_vregs) {
VRegAliveRangeInBlock vreg_block_range;
LivenessDomain live_in = fixpoint_iter.get_live_in_vars_at(block);
LivenessDomain live_out = fixpoint_iter.get_live_out_vars_at(block);
LiveIntervalPoint first = LiveIntervalPoint::get_block_begin(block);
for (auto vreg : live_in.elements()) {
auto range = std::make_pair(first, LiveIntervalPoint::get());
bool emplaced = vreg_block_range.emplace(vreg, range).second;
always_assert(emplaced);
}
auto ii = InstructionIterable(block);
for (auto it = ii.begin(); it != ii.end(); it++) {
auto insn = it->insn;
if (!insn->has_dest()) {
continue;
}
vreg_t vreg = insn->dest();
auto next = std::next(it) == ii.end()
? LiveIntervalPoint::get_block_end(block)
: LiveIntervalPoint::get(std::next(it)->insn);
auto range = std::make_pair(next, LiveIntervalPoint::get());
vreg_block_range.emplace(vreg, range);
// emplace might silently fail if we already had an entry
if (insn->opcode() != IOPCODE_MOVE_RESULT_PSEUDO_OBJECT) {
continue;
}
auto& cfg = block->cfg();
auto primary_insn_it = cfg.primary_instruction_of_move_result(
block->to_cfg_instruction_iterator(it.unwrap()));
if (primary_insn_it->insn->opcode() != OPCODE_CHECK_CAST) {
continue;
}
// We need to remember for all catch handlers which check-cast
// move-result-pseudo-object dest registers should be kept alive to
// deal with a special quirk of our check-cast instruction lowering.
auto src_block = primary_insn_it.block();
for (auto e : cfg.get_succ_edges_of_type(src_block, cfg::EDGE_THROW)) {
(*check_cast_throw_targets_vregs)[e->target()].insert(vreg);
}
}
LiveIntervalPoint last = LiveIntervalPoint::get_block_end(block);
for (auto vreg : live_out.elements()) {
vreg_block_range.at(vreg).second = last;
}
for (auto it = block->rbegin(); it != block->rend(); ++it) {
if (it->type != MFLOW_OPCODE) continue;
auto insn = it->insn;
for (vreg_t vreg : insn->srcs()) {
auto it2 = vreg_block_range.find(vreg);
if (it2 != vreg_block_range.end() && it2->second.second.is_missing()) {
it2->second.second = LiveIntervalPoint::get(insn);
}
}
}
return vreg_block_range;
}
VRegAliveRangeInBlock get_check_cast_throw_targets_live_range(
const LivenessFixpointIterator& fixpoint_iter,
cfg::Block* block,
const std::unordered_set<vreg_t>& vregs) {
VRegAliveRangeInBlock vreg_block_range;
LivenessDomain live_in = fixpoint_iter.get_live_in_vars_at(block);
auto elements = live_in.elements();
for (auto vreg : vregs) {
if (!elements.contains(vreg)) {
LiveIntervalPoint first = LiveIntervalPoint::get_block_begin(block);
auto range = std::make_pair(first, first);
bool emplaced = vreg_block_range.emplace(vreg, range).second;
always_assert(emplaced);
}
}
return vreg_block_range;
}
std::vector<cfg::Block*> get_ordered_blocks(
cfg::ControlFlowGraph& cfg,
const LivenessFixpointIterator& liveness_fixpoint_iter) {
// For each block, compute distance (in number of blocks) from exit-block.
std::unordered_map<cfg::Block*, size_t> block_depths;
std::queue<std::pair<cfg::Block*, size_t>> work_queue;
work_queue.emplace(cfg.exit_block(), 1);
while (!work_queue.empty()) {
auto [block, depth] = work_queue.front();
work_queue.pop();
if (!block_depths.emplace(block, depth).second) {
continue;
}
for (auto e : block->preds()) {
work_queue.emplace(e->src(), depth + 1);
}
}
// Compute (maximum) depth (in number of blocks, from exit-block) of each
// assigned register
std::unordered_map<vreg_t, size_t> vreg_defs_depths;
for (auto block : cfg.blocks()) {
for (auto& mie : InstructionIterable(block)) {
if (mie.insn->has_dest()) {
auto& depth = vreg_defs_depths[mie.insn->dest()];
depth = std::max(depth, block_depths.at(block));
}
}
}
// For each block, compute the maximum distance (in number of blocks, from
// exit-block) over all live-in registers
std::unordered_map<cfg::Block*, size_t> live_in_def_depths;
for (cfg::Block* block : cfg.blocks()) {
auto live_in = liveness_fixpoint_iter.get_live_in_vars_at(block);
size_t depth = 0;
for (auto vreg : live_in.elements()) {
auto vreg_defs_depth = vreg_defs_depths.at(vreg);
depth = std::max(depth, vreg_defs_depth);
}
live_in_def_depths.emplace(block, depth);
}
// Collect blocks by doing a post-order traversal, processing predecessors in
// their live-in-def-depths order, smallest depths goes last
std::unordered_set<cfg::Block*> visited;
std::vector<cfg::Block*> ordered_blocks;
std::function<void(cfg::Block*)> visit;
visit = [&](cfg::Block* block) {
if (!visited.insert(block).second) {
return;
}
std::vector<cfg::Block*> pred_blocks;
for (auto e : block->preds()) {
pred_blocks.push_back(e->src());
}
// We might have duplicates, but that's okay.
std::sort(pred_blocks.begin(),
pred_blocks.end(),
[&live_in_def_depths](cfg::Block* a, cfg::Block* b) {
auto a_depth = live_in_def_depths.at(a);
auto b_depth = live_in_def_depths.at(b);
if (a_depth != b_depth) {
return a_depth > b_depth;
}
return a->id() < b->id();
});
for (auto pred_block : pred_blocks) {
visit(pred_block);
}
ordered_blocks.push_back(block);
};
visit(cfg.exit_block());
always_assert(ordered_blocks.size() == cfg.blocks().size());
return ordered_blocks;
}
} // namespace fastregalloc
| 36.042802 | 80 | 0.6825 | kami-lang |
d5b065ce873965a55b1cd8e420a4184959f289b9 | 989 | cc | C++ | test/tensorflow_link_test.cc | WuJoel2020/aom | 65e6b6954c45c1b12883942b14d1988da377e0cd | [
"BSD-2-Clause"
] | null | null | null | test/tensorflow_link_test.cc | WuJoel2020/aom | 65e6b6954c45c1b12883942b14d1988da377e0cd | [
"BSD-2-Clause"
] | null | null | null | test/tensorflow_link_test.cc | WuJoel2020/aom | 65e6b6954c45c1b12883942b14d1988da377e0cd | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2019, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
// example.cpp
#include <stdio.h>
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/public/session.h"
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
class TensorflowLinkTest : public ::testing::Test {};
TEST_F(TensorflowLinkTest, TestTensorflowFunctionCalls) {
tensorflow::Session *session;
tensorflow::Status status =
NewSession(tensorflow::SessionOptions(), &session);
EXPECT_TRUE(status.ok());
}
| 32.966667 | 78 | 0.752275 | WuJoel2020 |
d5b10a97dd242b49178e0c5fe220607ba20daef3 | 7,119 | cpp | C++ | src/libtsduck/dtv/descriptors/tsISDBTerrestrialDeliverySystemDescriptor.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | 1 | 2019-04-23T21:16:00.000Z | 2019-04-23T21:16:00.000Z | src/libtsduck/dtv/descriptors/tsISDBTerrestrialDeliverySystemDescriptor.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | src/libtsduck/dtv/descriptors/tsISDBTerrestrialDeliverySystemDescriptor.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
#include "tsISDBTerrestrialDeliverySystemDescriptor.h"
#include "tsDescriptor.h"
#include "tsNames.h"
#include "tsTablesDisplay.h"
#include "tsPSIRepository.h"
#include "tsPSIBuffer.h"
#include "tsDuckContext.h"
#include "tsxmlElement.h"
TSDUCK_SOURCE;
#define MY_XML_NAME u"ISDB_terrestrial_delivery_system_descriptor"
#define MY_CLASS ts::ISDBTerrestrialDeliverySystemDescriptor
#define MY_DID ts::DID_ISDB_TERRES_DELIV
#define MY_PDS ts::PDS_ISDB
#define MY_STD ts::Standards::ISDB
TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Private(MY_DID, MY_PDS), MY_XML_NAME, MY_CLASS::DisplayDescriptor);
//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------
ts::ISDBTerrestrialDeliverySystemDescriptor::ISDBTerrestrialDeliverySystemDescriptor() :
AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),
area_code(0),
guard_interval(0),
transmission_mode(0),
frequencies()
{
}
void ts::ISDBTerrestrialDeliverySystemDescriptor::clearContent()
{
area_code = 0;
guard_interval = 0;
transmission_mode = 0;
frequencies.clear();
}
ts::ISDBTerrestrialDeliverySystemDescriptor::ISDBTerrestrialDeliverySystemDescriptor(DuckContext& duck, const Descriptor& desc) :
ISDBTerrestrialDeliverySystemDescriptor()
{
deserialize(duck, desc);
}
//----------------------------------------------------------------------------
// Serialization
//----------------------------------------------------------------------------
void ts::ISDBTerrestrialDeliverySystemDescriptor::serializePayload(PSIBuffer& buf) const
{
buf.putBits(area_code, 12);
buf.putBits(guard_interval, 2);
buf.putBits(transmission_mode, 2);
for (auto it = frequencies.begin(); it != frequencies.end(); ++it) {
buf.putUInt16(HzToBin(*it));
}
}
//----------------------------------------------------------------------------
// Deserialization
//----------------------------------------------------------------------------
void ts::ISDBTerrestrialDeliverySystemDescriptor::deserializePayload(PSIBuffer& buf)
{
buf.getBits(area_code, 12);
buf.getBits(guard_interval, 2);
buf.getBits(transmission_mode, 2);
while (buf.canRead()) {
frequencies.push_back(BinToHz(buf.getUInt16()));
}
}
//----------------------------------------------------------------------------
// Enumerations in XML data.
//----------------------------------------------------------------------------
namespace {
const ts::Enumeration GuardIntervalNames({
{u"1/32", 0},
{u"1/16", 1},
{u"1/8", 2},
{u"1/4", 3},
});
const ts::Enumeration TransmissionModeNames({
{u"2k", 0},
{u"mode1", 0},
{u"4k", 1},
{u"mode2", 1},
{u"8k", 2},
{u"mode3", 2},
{u"undefined", 3},
});
}
//----------------------------------------------------------------------------
// Static method to display a descriptor.
//----------------------------------------------------------------------------
void ts::ISDBTerrestrialDeliverySystemDescriptor::DisplayDescriptor(TablesDisplay& disp, PSIBuffer& buf, const UString& margin, DID did, TID tid, PDS pds)
{
if (buf.canReadBytes(2)) {
disp << margin << UString::Format(u"Area code: 0x%3X (%<d)", {buf.getBits<uint16_t>(12)}) << std::endl;
const uint8_t guard = buf.getBits<uint8_t>(2);
const uint8_t mode = buf.getBits<uint8_t>(2);
disp << margin << UString::Format(u"Guard interval: %d (%s)", {guard, GuardIntervalNames.name(guard)}) << std::endl;
disp << margin << UString::Format(u"Transmission mode: %d (%s)", {mode, TransmissionModeNames.name(mode)}) << std::endl;
}
while (buf.canReadBytes(2)) {
disp << margin << UString::Format(u"Frequency: %'d Hz", {BinToHz(buf.getUInt16())}) << std::endl;
}
}
//----------------------------------------------------------------------------
// XML serialization
//----------------------------------------------------------------------------
void ts::ISDBTerrestrialDeliverySystemDescriptor::buildXML(DuckContext& duck, xml::Element* root) const
{
root->setIntAttribute(u"area_code", area_code, true);
root->setEnumAttribute(GuardIntervalNames, u"guard_interval", guard_interval);
root->setEnumAttribute(TransmissionModeNames, u"transmission_mode", transmission_mode);
for (auto it = frequencies.begin(); it != frequencies.end(); ++it) {
root->addElement(u"frequency")->setIntAttribute(u"value", *it, false);
}
}
//----------------------------------------------------------------------------
// XML deserialization
//----------------------------------------------------------------------------
bool ts::ISDBTerrestrialDeliverySystemDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element)
{
xml::ElementVector xfreq;
bool ok =
element->getIntAttribute(area_code, u"area_code", true, 0, 0, 0x0FFF) &&
element->getIntEnumAttribute(guard_interval, GuardIntervalNames, u"guard_interval", true) &&
element->getIntEnumAttribute(transmission_mode, TransmissionModeNames, u"transmission_mode", true) &&
element->getChildren(xfreq, u"frequency", 0, 126);
for (auto it = xfreq.begin(); ok && it != xfreq.end(); ++it) {
uint64_t f = 0;
ok = (*it)->getIntAttribute(f, u"value", true);
frequencies.push_back(f);
}
return ok;
}
| 38.690217 | 154 | 0.577047 | cedinu |
d5b213a071d857111b195a3e77dcef995569d648 | 15,209 | cpp | C++ | src/CDataList.cpp | colinw7/CDataList | d38705c8049aaf5d5045636427c9df7a3cb020db | [
"MIT"
] | 1 | 2021-12-23T02:24:03.000Z | 2021-12-23T02:24:03.000Z | src/CDataList.cpp | colinw7/CDataList | d38705c8049aaf5d5045636427c9df7a3cb020db | [
"MIT"
] | null | null | null | src/CDataList.cpp | colinw7/CDataList | d38705c8049aaf5d5045636427c9df7a3cb020db | [
"MIT"
] | null | null | null | #include <CDataList.h>
#include <CStrUtil.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <cfloat>
#include <cmath>
#include <vector>
void usage(int rc=1) {
std::cerr << "Usage: CDataList " <<
"[-h] [-s[dfiscCb]] [-n] [-t] [-o <off>] [-l <len> ] [--|<filename>]" << std::endl;
exit(rc);
}
int
main(int argc, char **argv)
{
if (argc < 2)
usage(1);
CDataList dataList;
std::string filename;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
if (strcmp(argv[i], "-n") == 0)
dataList.setNumber(true);
else if (strncmp(argv[i], "-s", 2) == 0) {
std::string str(&argv[i][2]);
std::vector<std::string> fields;
CStrUtil::addFields(str, fields, ":");
for (const auto &f : fields) {
int show1 = 0;
int len = f.size();
for (auto j = 0; j < len; ++j) {
switch (f[j]) {
case 'd': show1 |= int(CDataList::Show::Double ); break;
case 'f': show1 |= int(CDataList::Show::Float ); break;
case 'i': show1 |= int(CDataList::Show::Integer); break;
case 's': show1 |= int(CDataList::Show::Short ); break;
case 'c': show1 |= int(CDataList::Show::Char ); break;
case 'C': show1 |= int(CDataList::Show::Chars ); break;
case 'b': show1 |= int(CDataList::Show::Byte ); break;
default : break;
}
}
if (show1 == 0)
show1 = int(CDataList::Show::All);
dataList.addShow(show1);
}
}
else if (strcmp(argv[i], "-o") == 0) {
if (i < argc - 1)
dataList.setOffset(atoi(argv[++i]));
}
else if (strcmp(argv[i], "-l") == 0) {
if (i < argc - 1)
dataList.setLength(atoi(argv[++i]));
}
else if (strcmp(argv[i], "-t") == 0) {
dataList.setTitle(true);
}
else if (strcmp(argv[i], "-r") == 0) {
dataList.setRepeat(true);
}
else if (strcmp(argv[i], "-j") == 0) {
dataList.setJoin(true);
}
else if (strcmp(argv[i], "-w") == 0) {
if (i < argc - 1)
dataList.setWidth(atoi(argv[++i]));
}
else if (strcmp(argv[i], "-h") == 0) {
usage(0);
}
else if (strncmp(argv[i], "--", 2) == 0) {
filename = "-";
}
else {
std::cerr << "Invalid Option '" << argv[i] << "'" << std::endl;
usage(1);
}
}
else if (filename == "") {
filename = argv[i];
}
else {
std::cerr << "Invalid Argument '" << argv[i] << "'" << std::endl;
usage(1);
}
}
if (filename == "") {
std::cerr << "No files specified" << std::endl;
usage(1);
}
//---
if (! dataList.init(filename))
exit(1);
//---
dataList.showData();
exit(0);
}
CDataList::
CDataList()
{
}
CDataList::
~CDataList()
{
if (fp_ && fp_ != stdin)
fclose(fp_);
}
bool
CDataList::
init(const std::string &filename)
{
if (filename != "-") {
fp_ = fopen(filename.c_str(), "r");
if (! fp_) {
std::cerr << "Can't open file '" << filename << "'" << std::endl;
return false;
}
}
else
fp_ = stdin;
//---
if (showSet_.empty()) {
showSet_.push_back(int(Show::All));
showAnd_ = uint(Show::All);
showOr_ = uint(Show::All);
}
return true;
}
void
CDataList::
showData()
{
size_ = showSize(showOr_);
//---
n_ = 1;
if (title_)
showTitle();
if (isRepeat()) {
while (true) {
if (! showSet())
break;
}
}
else {
showSet();
int show = showSet_[showSet_.size() - 1];
showAll(show);
}
if (isSingleShow(Show::Char)) {
if (n_ > 0 && ((n_ % width()) != 0))
printf("\n");
}
}
void
CDataList::
showTitle()
{
// display title
if (isNumber()) printf(" ");
if (! isSingleShow(Show::Double ) && hasShowDouble ()) printf(" Double " );
if (! isSingleShow(Show::Float ) && hasShowFloat ()) printf(" Float " );
if (! isSingleShow(Show::Integer) && hasShowInteger()) printf(" Integer " );
if (! isSingleShow(Show::Short) && hasShowShort()) {
if (size_ >= 4)
printf(" Short1 Short2 ");
else
printf(" Short ");
}
if (! isSingleShow(Show::Byte) && hasShowByte()) {
if (size_ >= 4)
printf(" B1 B2 B3 B4 ");
else if (size_ >= 2)
printf(" B1 B2 ");
else
printf(" B1 ");
}
if (! isSingleShow(Show::Char) && hasShowChar()) {
if (size_ >= 4)
printf(" C1 C2 C3 C4 ");
else if (size_ >= 2)
printf(" C1 C2 ");
else
printf(" C1 ");
}
if (! isSingleShow(Show::Chars) && hasShowChars()) printf("Char ");
if (! isSingleShow(Show::Double) && ! isSingleShow(Show::Float) &&
! isSingleShow(Show::Integer) && ! isSingleShow(Show::Short) &&
! isSingleShow(Show::Byte) && ! isSingleShow(Show::Char ) &&
! isSingleShow(Show::Chars))
printf("\n");
if (isNumber()) printf(" ");
if (! isSingleShow(Show::Double) && hasShowDouble ()) printf("---------------- " );
if (! isSingleShow(Show::Float) && hasShowFloat ()) printf("---------------- " );
if (! isSingleShow(Show::Integer) && hasShowInteger()) printf("---------------- " );
if (! isSingleShow(Show::Short) && hasShowShort()) {
if (size_ >= 4)
printf(" ------ ------ ");
else
printf(" ------ ");
}
if (! isSingleShow(Show::Byte) && hasShowByte()) {
if (size_ >= 4)
printf(" -- -- -- -- ");
else if (size_ >= 2)
printf(" -- -- ");
else
printf(" -- ");
}
if (! isSingleShow(Show::Char) && hasShowChar()) {
if (size_ >= 4)
printf(" -- -- -- -- ");
else if (size_ >= 2)
printf(" -- -- ");
else
printf(" -- ");
}
if (! isSingleShow(Show::Chars) && hasShowChars()) printf("---- ");
if (! isSingleShow(Show::Double) && ! isSingleShow(Show::Float) &&
! isSingleShow(Show::Integer) && ! isSingleShow(Show::Short) &&
! isSingleShow(Show::Byte) && ! isSingleShow(Show::Char ) &&
! isSingleShow(Show::Chars))
printf("\n\n");
}
bool
CDataList::
showSet()
{
int ns = (isRepeat() ? showSet_.size() : showSet_.size() - 1);
for (int i = 0; i < ns; ++i) {
uint show = showSet_[i];
int doffset = showSize(show);
if (! showOne(show))
return false;
offset_ += doffset;
if (length_ > 0) {
--length_;
if (length_ == 0)
break;
}
}
if (isJoin())
printf("\n");
return true;
}
bool
CDataList::
showOne(int show)
{
if (offset_ > 0 && fp_ != stdin)
fseek(fp_, offset_, SEEK_SET);
if (! readData(show))
return false;
printData(show, 1, ! isJoin());
++n_;
return true;
}
void
CDataList::
showAll(int show)
{
if (offset_ > 0 && fp_ != stdin)
fseek(fp_, offset_, SEEK_SET);
while (readData(show)) {
int l = (length_ > 0 ? length_ - n_ : INT_MAX);
printData(show, l, true);
++n_;
if (length_ > 0 && n_ > length_)
break;
}
}
bool
CDataList::
readData(int show)
{
size_t size = showSize(show);
uchar data[8];
int num = fread(data, size, 1, fp_);
if (num != 1)
return false;
encodeData(show, &data[0]);
return true;
}
void
CDataList::
encodeData(uint show, const uchar *data)
{
size_t size = showSize(show);
if (size >= 8) {
memcpy(&dword_[0], data, sizeof(double));
memcpy(&fword_[0], data, 2*sizeof(float ));
memcpy(&iword_[0], data, 2*sizeof(int ));
memcpy(&hword_[0], data, 4*sizeof(short ));
memcpy(&cword_[0], data, 8*sizeof(char ));
}
else if (size >= 4) {
memcpy(&fword_[0], data, sizeof(float ));
memcpy(&iword_[0], data, sizeof(int ));
memcpy(&hword_[0], data, 2*sizeof(short ));
memcpy(&cword_[0], data, 4*sizeof(char ));
}
else if (size >= 2) {
memcpy(&hword_[0], data, sizeof(short ));
memcpy(&cword_[0], data, 2*sizeof(char ));
}
else {
memcpy(&cword_[0], data, sizeof(char ));
}
}
void
CDataList::
printData(uint show, int /*length*/, bool newline)
{
size_t size = showSize(show);
if (size >= 8) {
if (isNumber()) printf("%6d: ", n_);
if (show & uint(Show::Double )) printDouble(show);
if (show & uint(Show::Float )) printFloat(show, 0);
if (show & uint(Show::Integer)) printInteger(show, 0);
if (show & uint(Show::Short )) printShort(show, 0, 2);
if (show & uint(Show::Byte )) printBytes(show, 0, 4);
if (show & uint(Show::Char )) printChar (show, 0, 4);
if (show & uint(Show::Chars )) printChars(show, 0, 4);
if (newline)
printf("\n");
//---
if (show != uint(Show::Double)) {
if (isNumber()) printf(" ");
if (show & uint(Show::Double )) printf("................ ");
if (show & uint(Show::Float )) printFloat(show, 1);
if (show & uint(Show::Integer)) printInteger(show, 1);
if (show & uint(Show::Short )) printShort(show, 1, 2);
if (show & uint(Show::Byte )) printBytes(show, 1, 4);
if (show & uint(Show::Char )) printChar (show, 1, 4);
if (show & uint(Show::Chars )) printChars(show, 1, 4);
if (newline)
printf("\n");
}
}
else if (size >= 4) {
if (isNumber()) printf("%6d: ", n_);
if (show & uint(Show::Float )) printFloat(show, 0);
if (show & uint(Show::Integer)) printInteger(show, 0);
if (show & uint(Show::Short )) printShort(show, 0, 2);
if (show & uint(Show::Byte )) printBytes(show, 0, 4);
if (show & uint(Show::Char )) printChar (show, 0, 4);
if (show & uint(Show::Chars )) printChars(show, 0, 4);
if (newline)
printf("\n");
}
else if (size >= 2) {
if (isNumber()) printf("%6d: ", n_);
if (show & uint(Show::Short)) printShort(show, 0, 1);
if (show & uint(Show::Byte )) printBytes(show, 0, 2);
if (show & uint(Show::Char )) printChar (show, 0, 2);
if (show & uint(Show::Chars)) printChars(show, 0, 2);
if (newline)
printf("\n");
}
else if (size >= 1) {
if (show != uint(Show::Char)) {
if (isNumber()) printf("%6d: ", n_);
if (show & uint(Show::Byte )) printBytes(show, 0, 1);
if (show & uint(Show::Char )) printChar (show, 0, 1);
if (show & uint(Show::Chars)) printChars(show, 0, 1);
if (newline)
printf("\n");
}
else {
printf("%c", encodeChar(cword_[0]));
if (n_ > 0 && ((n_ % width()) == 0))
printf("\n");
}
}
}
void
CDataList::
printDouble(uint show)
{
if (std::isnan(dword_[0])) {
if (show != uint(Show::Double))
printf("NaN ");
else
printf("NaN ");
}
else if (dword_[0] > -DBL_MAX && dword_[0] < DBL_MAX) {
if (dword_[0] > -FLT_MAX && dword_[0] < FLT_MAX) {
char dstring[128];
if (show != uint(Show::Double)) {
sprintf(dstring, "%16.5lf", dword_[0]);
if (strlen(dstring) > 16)
sprintf(dstring, "%16.5lg", dword_[0]);
}
else {
sprintf(dstring, "%.5lf", dword_[0]);
if (strlen(dstring) > 16)
sprintf(dstring, "%.5lg", dword_[0]);
}
printf("%s ", dstring);
}
else {
if (show != uint(Show::Double))
printf("%16.5lg ", dword_[0]);
else
printf("%.5lg ", dword_[0]);
}
}
else {
if (show != uint(Show::Double))
printf("................ ");
else
printf(".... ");
}
}
void
CDataList::
printFloat(uint show, int i)
{
if (isnanf(fword_[i])) {
if (show != uint(Show::Float))
printf("NaN ");
else
printf("NaN ");
}
else if (fword_[i] > -FLT_MAX && fword_[i] < FLT_MAX) {
char fstring[64];
if (show != uint(Show::Float)) {
sprintf(fstring, "%16.5f", fword_[i]);
if (strlen(fstring) > 16)
sprintf(fstring, "%16.5g", fword_[i]);
}
else {
sprintf(fstring, "%.5f", fword_[i]);
if (strlen(fstring) > 16)
sprintf(fstring, "%.5g", fword_[i]);
}
printf("%s ", fstring);
}
else {
if (show != uint(Show::Float))
printf("................ ");
else
printf(".... ");
}
}
void
CDataList::
printInteger(uint show, int i)
{
if (show != uint(Show::Integer))
printf("%16d ", iword_[i]);
else
printf("%d ", iword_[i]);
}
void
CDataList::
printShort(uint show, int i, int n)
{
if (n == 2) {
if (show != uint(Show::Short))
printf("%8d %8d ", hword_[2*i + 0], hword_[2*i + 1]);
else {
printf("%d ", hword_[2*i + 0]);
printf("%d ", hword_[2*i + 1]);
}
}
else {
if (show != uint(Show::Short))
printf("%8d ", hword_[2*i + 0]);
else
printf("%d ", hword_[2*i + 0]);
}
}
void
CDataList::
printBytes(uint show, int i, int n)
{
if (n == 4) {
if (show != uint(Show::Byte))
printf("%3d %3d %3d %3d ", cword_[2*i + 0], cword_[2*i + 1],
cword_[2*i + 2], cword_[2*i + 3]);
else {
printf("%d", cword_[2*i + 0]);
printf("%d", cword_[2*i + 1]);
printf("%d", cword_[2*i + 2]);
printf("%d", cword_[2*i + 3]);
}
}
else if (n == 2) {
if (show != uint(Show::Byte))
printf("%3d %3d ", cword_[2*i + 0], cword_[2*i + 1]);
else {
printf("%d ", cword_[2*i + 0]);
printf("%d ", cword_[2*i + 1]);
}
}
else if (n == 1) {
if (show != uint(Show::Byte))
printf("%3d ", cword_[2*i + 0]);
else
printf("%d ", cword_[2*i + 0]);
}
}
void
CDataList::
printChars(uint /*show*/, int i, int n)
{
char cstring[32];
int j = 0;
for ( ; j < n; j++) {
int k = i*n + j;
if (isprint(cword_[k]) && ! iscntrl(cword_[k]))
cstring[j] = cword_[k];
else
cstring[j] = '.';
}
cstring[j] = '\0';
printf("%s ", cstring);
}
void
CDataList::
printChar(uint show, int i, int n)
{
if (n == 4) {
if (show != uint(Show::Char))
printf("%3c %3c %3c %3c ", encodeChar(cword_[2*i + 0]), encodeChar(cword_[2*i + 1]),
encodeChar(cword_[2*i + 2]), encodeChar(cword_[2*i + 3]));
else
printf("%c%c%c%c ", encodeChar(cword_[2*i + 0]), encodeChar(cword_[2*i + 1]),
encodeChar(cword_[2*i + 2]), encodeChar(cword_[2*i + 3]));
}
else if (n == 2) {
if (show != uint(Show::Char))
printf("%3c %3c ", encodeChar(cword_[2*i + 0]), encodeChar(cword_[2*i + 1]));
else
printf("%c%c ", encodeChar(cword_[2*i + 0]), encodeChar(cword_[2*i + 1]));
}
else if (n == 1) {
if (show != uint(Show::Char))
printf("%3c ", encodeChar(cword_[2*i + 0]));
else
printf("%c ", encodeChar(cword_[2*i + 0]));
}
}
char
CDataList::
encodeChar(char c)
{
if (isprint(c) && ! iscntrl(c))
return c;
return '.';
}
size_t
CDataList::
showSize(uint show) const
{
if (show & uint(Show::Double))
return 8;
if ((show & uint(Show::Chars)) || (show & uint(Show::Integer)) || (show & uint(Show::Float)))
return 4;
if (show & uint(Show::Short))
return 2;
return 1;
}
| 22.20292 | 98 | 0.498455 | colinw7 |
d5b39ffa193a8f72073a18803bfc48b7c3f511fe | 592 | cpp | C++ | android-31/java/io/NotActiveException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/io/NotActiveException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/io/NotActiveException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JString.hpp"
#include "./NotActiveException.hpp"
namespace java::io
{
// Fields
// QJniObject forward
NotActiveException::NotActiveException(QJniObject obj) : java::io::ObjectStreamException(obj) {}
// Constructors
NotActiveException::NotActiveException()
: java::io::ObjectStreamException(
"java.io.NotActiveException",
"()V"
) {}
NotActiveException::NotActiveException(JString arg0)
: java::io::ObjectStreamException(
"java.io.NotActiveException",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
) {}
// Methods
} // namespace java::io
| 21.925926 | 97 | 0.701014 | YJBeetle |
d5b49141afeee1125b245acc75c3de2651c2f55e | 5,158 | tcc | C++ | flens/lapack/la/lanst.tcc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 98 | 2015-01-26T20:31:37.000Z | 2021-09-09T15:51:37.000Z | flens/lapack/la/lanst.tcc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 16 | 2015-01-21T07:43:45.000Z | 2021-12-06T12:08:36.000Z | flens/lapack/la/lanst.tcc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 31 | 2015-01-05T08:06:45.000Z | 2022-01-26T20:12:00.000Z | /*
* Copyright (c) 2014, Michael Lehn
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3) Neither the name of the FLENS development group nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Based on
*
DOUBLE PRECISION FUNCTION DLANST( NORM, N, D, E )
*
* -- LAPACK auxiliary routine (version 3.2) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2006
*/
#ifndef FLENS_LAPACK_LA_LANST_TCC
#define FLENS_LAPACK_LA_LANST_TCC 1
#include <flens/blas/blas.h>
#include <flens/lapack/lapack.h>
namespace flens { namespace lapack {
//== generic lapack implementation =============================================
namespace generic {
template <typename VD, typename VE>
typename VD::ElementType
lanst_impl(Norm norm,
const DenseVector<VD> &d,
const DenseVector<VE> &e)
{
using std::abs;
using std::max;
using std::sqrt;
typedef typename VD::ElementType T;
typedef typename VD::IndexType IndexType;
const T Zero(0), One(1);
const Underscore<IndexType> _;
const IndexType n = d.length();
T normA = 0;
if (n==0) {
normA = Zero;
} else if (norm==MaximumNorm) {
//
// Find max(abs(A(i,j))).
//
normA = abs(d(n));
for (IndexType i=1; i<=n-1; ++i) {
normA = max(normA, abs(d(i)));
normA = max(normA, abs(e(i)));
}
} else if (norm==OneNorm || norm==InfinityNorm) {
//
// Find norm1(A).
//
if (n==1) {
normA = abs(d(1));
} else {
normA = max(abs(d(1)) +abs(e(1)),
abs(e(n-1))+abs(d(n)));
for (IndexType i=2; i<=n-1; ++i) {
normA = max(normA, abs(d(i))+abs(e(i))+abs(e(i-1)));
}
}
} else if (norm==FrobeniusNorm) {
//
// Find normF(A).
//
T scale = Zero;
T sum = One;
if (n>1) {
lassq(e(_(1,n-1)), scale, sum);
sum *= 2;
}
lassq(d, scale, sum);
normA = scale*sqrt(sum);
}
return normA;
}
} // namespace generic
//== interface for native lapack ===============================================
#ifdef USE_CXXLAPACK
namespace external {
template <typename VD, typename VE>
typename VD::ElementType
lanst_impl(Norm norm,
const DenseVector<VD> &d,
const DenseVector<VE> &e)
{
typedef typename VD::IndexType IndexType;
return cxxlapack::lanst<IndexType>(getF77Char(norm),
d.length(),
d.data(),
e.data());
}
} // namespace external
#endif
//== public interface ==========================================================
template <typename VD, typename VE>
typename RestrictTo<IsRealDenseVector<VD>::value
&& IsRealDenseVector<VE>::value,
typename VD::ElementType>::Type
lanst(Norm norm,
const VD &d,
const VE &e)
{
typedef typename VD::ElementType T;
//
// Test the input parameters
//
ASSERT(d.firstIndex()==1);
ASSERT(e.firstIndex()==1);
ASSERT(d.length()==e.length()+1 || d.length()==0);
//
// Call implementation
//
T result = LAPACK_SELECT::lanst_impl(norm, d, e);
# ifdef CHECK_CXXLAPACK
//
// Compare results
//
T result_ = external::lanst_impl(norm, d, e);
if (! isIdentical(result, result_, " result", "result_")) {
ASSERT(0);
}
# endif
return result;
}
} } // namespace lapack, flens
#endif // FLENS_LAPACK_LA_LANST_TCC
| 28.185792 | 80 | 0.588019 | stip |
d5b6f7e628ff6bbd7230a7ed03e838c1f5eafcde | 1,029 | hpp | C++ | Libraries/Engine/Level.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | 3 | 2022-02-11T10:34:33.000Z | 2022-02-24T17:44:17.000Z | Libraries/Engine/Level.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | Libraries/Engine/Level.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | // MIT Licensed (see LICENSE.md).
#pragma once
namespace Zero
{
/// A level is resource that stores a set of objects that can be loaded into
/// a space. Level is different from most resource types in that it does
/// not really store the level data on the object but always loads the
/// data from the file system.
class Level : public Resource
{
public:
ZilchDeclareType(Level, TypeCopyMode::ReferenceType);
Level();
~Level();
// Resource interface
void UpdateContentItem(ContentItem* contentItem) override;
// Save the current contents of the space into the level.
void SaveSpace(Space* space);
// Load the level contents into the space.
void LoadSpace(Space* space);
String GetLoadPath();
/// Path to level file.
String LoadPath;
DataNode* mCacheTree;
};
/// Resource Manager for Levels.
class LevelManager : public ResourceManager
{
public:
DeclareResourceManager(LevelManager, Level);
LevelManager(BoundType* resourceType);
static void ClearCachedLevels();
};
} // namespace Zero
| 22.369565 | 76 | 0.73275 | RyanTylerRae |
d5b757001173aafd1e44201781d322688d59f155 | 963 | cpp | C++ | platforms/android/Dezel/dezel/src/main/jni/wrappers/LayoutWrapper.cpp | logaritmdev/dezel | 507022b806e0ffb91bfe87336c6642634c5123a0 | [
"MIT"
] | 2 | 2018-08-02T13:26:55.000Z | 2019-04-14T18:18:40.000Z | platforms/android/Dezel/dezel/src/main/jni/wrappers/LayoutWrapper.cpp | logaritmdev/dezel | 507022b806e0ffb91bfe87336c6642634c5123a0 | [
"MIT"
] | 2 | 2020-07-07T19:45:35.000Z | 2021-05-08T06:33:03.000Z | platforms/android/Dezel/dezel/src/main/jni/wrappers/LayoutWrapper.cpp | logaritmdev/dezel | 507022b806e0ffb91bfe87336c6642634c5123a0 | [
"MIT"
] | 1 | 2019-06-24T21:53:34.000Z | 2019-06-24T21:53:34.000Z | #include <jni_module_layout.h>
#include "LayoutWrapper.h"
static void
LayoutBeganCallback(DLLayoutRef layout)
{
LayoutWrapperRef wrapper = reinterpret_cast<LayoutWrapperRef>(DLLayoutGetData(layout));
if (wrapper == NULL) {
return;
}
JNI_CALL_VOID_METHOD(
wrapper->env,
wrapper->object,
LayoutDispatchLayoutBeganEvent
);
}
static void
LayoutEndedCallback(DLLayoutRef layout)
{
LayoutWrapperRef wrapper = reinterpret_cast<LayoutWrapperRef>(DLLayoutGetData(layout));
if (wrapper == NULL) {
return;
}
JNI_CALL_VOID_METHOD(
wrapper->env,
wrapper->object,
LayoutDispatchLayoutEndedEvent
);
}
LayoutWrapperRef
LayoutWrapperCreate(JNIEnv *env, jobject object, DLLayoutRef node)
{
LayoutWrapperRef wrapper = new LayoutWrapper();
wrapper->env = env;
wrapper->object = env->NewGlobalRef(object);
DLLayoutSetLayoutBeganCallback(node, &LayoutBeganCallback);
DLLayoutSetLayoutEndedCallback(node, &LayoutEndedCallback);
return wrapper;
} | 21.4 | 89 | 0.779855 | logaritmdev |
d5bac26d7bd25b563ec2ef3d1131aa52666770c8 | 1,871 | cpp | C++ | modules/spatialos/player_controls_sync.cpp | CharlesMicou/spatialgodot | f2d3819af3c8ef12026efc17e5e45f0cc5a4b9b8 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 23 | 2019-03-15T11:25:16.000Z | 2022-02-07T06:26:19.000Z | modules/spatialos/player_controls_sync.cpp | CharlesMicou/spatialgodot | f2d3819af3c8ef12026efc17e5e45f0cc5a4b9b8 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/spatialos/player_controls_sync.cpp | CharlesMicou/spatialgodot | f2d3819af3c8ef12026efc17e5e45f0cc5a4b9b8 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2019-03-23T11:45:38.000Z | 2019-03-23T11:45:38.000Z | #include "player_controls_sync.h"
#include "editor_node.h"
#include "spatial_util.h"
#include <improbable/worker.h>
#include "component_view.h"
#include <spellcrest/player_controls.h>
WorkerLogger PlayerControlsSync::logger = WorkerLogger("player_controls_sync");
void PlayerControlsSync::sync(const Vector2 destination) {
if (controls_component == NULL) {
logger.warn("PlayerControlsSync node has no controls component, unable to sync.");
return;
}
if (controls_component->hasAuthority()) {
float x = destination.x;
float y = destination.y;
godotcore::GodotCoordinates2D asGodotData = godotcore::GodotCoordinates2D(godotcore::GodotCoordinates2D(godotcore::GodotChunk2D(), godotcore::GodotVector2D(x, y)));
controls_component->tryUpdate(spellcrest::PlayerControls::Update{}.set_move_destination(asGodotData));
}
}
Vector2 PlayerControlsSync::get_controls_value() {
if (controls_component == NULL) {
return Vector2();
}
std::pair<float, float> localpos = toLocalGodotPosition(controls_component->getData().move_destination(), 0, 0);
return Vector2(localpos.first, localpos.second);
}
void PlayerControlsSync::set_player_controls_component(Node* component) {
controls_component = dynamic_cast<ComponentView<spellcrest::PlayerControls>*>(component);
if (controls_component == NULL) {
logger.warn("A PlayerControlsSync node received incorrectly configured component refs.");
}
}
PlayerControlsSync::PlayerControlsSync() {
}
void PlayerControlsSync::_bind_methods() {
ClassDB::bind_method(D_METHOD("sync"), &PlayerControlsSync::sync);
ClassDB::bind_method(D_METHOD("set_player_controls_components"), &PlayerControlsSync::set_player_controls_component);
ClassDB::bind_method(D_METHOD("get_controls_value"), &PlayerControlsSync::get_controls_value);
}
| 40.673913 | 172 | 0.750935 | CharlesMicou |
d5c3c11b4e8a0abc93ed89fde09bd8536ae0681a | 8,038 | cc | C++ | Fleece/Core/SharedKeys.cc | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 134 | 2016-05-09T19:42:55.000Z | 2022-01-16T13:05:18.000Z | Fleece/Core/SharedKeys.cc | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 70 | 2016-05-09T05:16:46.000Z | 2022-03-08T19:43:30.000Z | Fleece/Core/SharedKeys.cc | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 32 | 2016-05-19T10:38:06.000Z | 2022-01-30T22:45:25.000Z | //
// SharedKeys.cc
//
// Copyright 2016-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
//
#include "SharedKeys.hh"
#include "FleeceImpl.hh"
#include "FleeceException.hh"
#define LOCK(MUTEX) lock_guard<mutex> _lock(MUTEX)
namespace fleece { namespace impl {
using namespace std;
SharedKeys::SharedKeys()
:_table(2047)
{ }
SharedKeys::~SharedKeys() {
#ifdef __APPLE__
for (auto &str : _platformStringsByKey) {
if (str)
CFRelease(str);
}
#endif
}
key_t::key_t(const Value *v) noexcept {
if (v->isInteger())
_int = (int16_t)v->asInt();
else
_string = v->asString();
}
bool key_t::operator== (const key_t &k) const noexcept {
return shared() ? (_int == k._int) : (_string == k._string);
}
bool key_t::operator< (const key_t &k) const noexcept {
if (shared())
return k.shared() ? (_int < k._int) : true;
else
return k.shared() ? false : (_string < k._string);
}
size_t SharedKeys::count() const {
LOCK(_mutex);
return _count;
}
bool SharedKeys::loadFrom(slice stateData) {
return loadFrom(Value::fromData(stateData));
}
bool SharedKeys::loadFrom(const Value *state) {
if (!state)
return false;
Array::iterator i(state->asArray());
LOCK(_mutex);
if (i.count() <= _count)
return false;
i += _count; // Start at the first _new_ string
for (; i; ++i) {
slice str = i.value()->asString();
if (!str)
return false;
int key;
if (!SharedKeys::_add(str, key))
return false;
}
return true;
}
void SharedKeys::writeState(Encoder &enc) const {
auto count = _count;
enc.beginArray(count);
for (size_t key = 0; key < count; ++key)
enc.writeString(_byKey[key]);
enc.endArray();
}
alloc_slice SharedKeys::stateData() const {
Encoder enc;
writeState(enc);
return enc.finish();
}
bool SharedKeys::encode(slice str, int &key) const {
// Is this string already encoded?
auto entry = _table.find(str);
if (_usuallyTrue(entry.key != nullslice)) {
key = entry.value;
return true;
}
return false;
}
bool SharedKeys::encodeAndAdd(slice str, int &key) {
if (encode(str, key))
return true;
// Should this string be encoded?
if (str.size > _maxKeyLength || !isEligibleToEncode(str))
return false;
LOCK(_mutex);
if (_count >= kMaxCount)
return false;
throwIf(!_inTransaction, SharedKeysStateError, "not in transaction");
// OK, add to table:
return _add(str, key);
}
bool SharedKeys::_add(slice str, int &key) {
auto value = uint16_t(_count);
auto entry = _table.insert(str, value);
if (!entry.key)
return false; // failed
if (entry.value == value) {
// new key:
_byKey[value] = entry.key;
++_count;
}
key = entry.value;
return true;
}
__hot bool SharedKeys::isEligibleToEncode(slice str) const {
for (size_t i = 0; i < str.size; ++i)
if (_usuallyFalse(!isalnum(str[i]) && str[i] != '_' && str[i] != '-'))
return false;
return true;
}
bool SharedKeys::isUnknownKey(int key) const {
LOCK(_mutex);
return _isUnknownKey(key);
}
/** Decodes an integer back to a string. */
slice SharedKeys::decode(int key) const {
throwIf(key < 0, InvalidData, "key must be non-negative");
if (_usuallyFalse(key >= kMaxCount))
return nullslice;
slice str = _byKey[key];
if (_usuallyFalse(!str))
return decodeUnknown(key);
return str;
}
slice SharedKeys::decodeUnknown(int key) const {
// Unrecognized key -- if not in a transaction, try reloading
const_cast<SharedKeys*>(this)->refresh();
// Retry after refreshing:
LOCK(_mutex);
return _byKey[key];
}
vector<slice> SharedKeys::byKey() const {
LOCK(_mutex);
return vector<slice>(&_byKey[0], &_byKey[_count]);
}
SharedKeys::PlatformString SharedKeys::platformStringForKey(int key) const {
throwIf(key < 0, InvalidData, "key must be non-negative");
LOCK(_mutex);
if ((unsigned)key >= _platformStringsByKey.size())
return nullptr;
return _platformStringsByKey[key];
}
void SharedKeys::setPlatformStringForKey(int key, SharedKeys::PlatformString platformKey) const {
LOCK(_mutex);
throwIf(key < 0, InvalidData, "key must be non-negative");
throwIf((unsigned)key >= _count, InvalidData, "key is not yet known");
if ((unsigned)key >= _platformStringsByKey.size())
_platformStringsByKey.resize(key + 1);
#ifdef __APPLE__
_platformStringsByKey[key] = CFStringCreateCopy(kCFAllocatorDefault, platformKey);
#else
_platformStringsByKey[key] = platformKey;
#endif
}
void SharedKeys::revertToCount(size_t toCount) {
LOCK(_mutex);
if (toCount >= _count) {
throwIf(toCount > _count, SharedKeysStateError, "can't revert to a bigger count");
return;
}
// (Iterating backwards helps the ConcurrentArena free up key space.)
for (int key = _count - 1; key >= int(toCount); --key) {
_table.remove(_byKey[key]);
_byKey[key] = nullslice;
}
_count = unsigned(toCount);
}
#pragma mark - PERSISTENCE:
PersistentSharedKeys::PersistentSharedKeys() {
_inTransaction = false;
}
bool PersistentSharedKeys::refresh() {
// CBL-87: Race with transactionBegan, possible to enter a transaction and
// get to here before the transaction reads the new shared keys. They won't
// be read here due to _inTransaction being true
LOCK(_refreshMutex);
return !_inTransaction && read();
}
void PersistentSharedKeys::transactionBegan() {
// CBL-87: Race with refresh, several lines between here and when new
// shared keys are actually read leaving a void in between where the shared
// keys are trying to read but cannot properly be refreshed (via Pusher's
// sendRevision for example)
LOCK(_refreshMutex);
throwIf(_inTransaction, SharedKeysStateError, "already in transaction");
_inTransaction = true;
read(); // Catch up with any external changes
}
void PersistentSharedKeys::transactionEnded() {
if (_inTransaction) {
_committedPersistedCount = _persistedCount;
_inTransaction = false;
}
}
// Subclass's read() method calls this
bool PersistentSharedKeys::loadFrom(const Value *state) {
throwIf(changed(), SharedKeysStateError, "can't load when already changed");
if (!SharedKeys::loadFrom(state))
return false;
_committedPersistedCount = _persistedCount = count();
return true;
}
void PersistentSharedKeys::save() {
if (changed()) {
write(stateData()); // subclass hook
_persistedCount = count();
}
}
void PersistentSharedKeys::revert() {
revertToCount(_committedPersistedCount);
_persistedCount = _committedPersistedCount;
}
} }
| 27.621993 | 101 | 0.585096 | tophatch |
d5c45f8ddea2d7781390aa3acf99aff0824e2cdc | 2,433 | cpp | C++ | examples/dcps/WaitSet/cpp/src/CheckStatus.cpp | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 133 | 2017-11-09T02:10:00.000Z | 2022-03-29T09:45:10.000Z | examples/dcps/WaitSet/cpp/src/CheckStatus.cpp | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 131 | 2017-11-07T14:48:43.000Z | 2022-03-13T15:30:47.000Z | examples/dcps/WaitSet/cpp/src/CheckStatus.cpp | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 94 | 2017-11-09T02:26:19.000Z | 2022-02-24T06:38:25.000Z |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/************************************************************************
* LOGICAL_NAME: CheckStatus.cpp
* FUNCTION: OpenSplice Tutorial example code.
* MODULE: Tutorial for the C++ programming language.
* DATE june 2007.
************************************************************************
*
* This file contains the implementation for the error handling operations.
*
***/
#include "CheckStatus.h"
/* Array to hold the names for all ReturnCodes. */
string RetCodeName[13] =
{
"DDS_RETCODE_OK", "DDS_RETCODE_ERROR", "DDS_RETCODE_UNSUPPORTED",
"DDS_RETCODE_BAD_PARAMETER", "DDS_RETCODE_PRECONDITION_NOT_MET",
"DDS_RETCODE_OUT_OF_RESOURCES", "DDS_RETCODE_NOT_ENABLED",
"DDS_RETCODE_IMMUTABLE_POLICY", "DDS_RETCODE_INCONSISTENT_POLICY",
"DDS_RETCODE_ALREADY_DELETED", "DDS_RETCODE_TIMEOUT", "DDS_RETCODE_NO_DATA",
"DDS_RETCODE_ILLEGAL_OPERATION"
};
/**
* Returns the name of an error code.
**/
string getErrorName(DDS::ReturnCode_t status)
{
return RetCodeName[status];
}
/**
* Check the return status for errors. If there is an error, then terminate.
**/
void checkStatus(DDS::ReturnCode_t status, const char *info)
{
if (status != DDS::RETCODE_OK && status != DDS::RETCODE_NO_DATA)
{
cerr << "Error in " << info << ": " << getErrorName(status).c_str() << endl;
exit(1);
}
}
/**
* Check whether a valid handle has been returned. If not, then terminate.
**/
void checkHandle(void *handle, string info)
{
if (!handle)
{
cerr << "Error in " << info.c_str() << ": Creation failed: invalid handle" << endl;
exit(1);
}
}
| 30.037037 | 87 | 0.644883 | brezillon |
d5c4b7aae8c2ec9456aa4876e4706a520f2e6bff | 1,044 | cpp | C++ | code/leetcode/src/0257.Binary-Tree-Paths.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | 1 | 2021-09-01T14:39:12.000Z | 2021-09-01T14:39:12.000Z | code/leetcode/src/0257.Binary-Tree-Paths.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | code/leetcode/src/0257.Binary-Tree-Paths.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | /**
* @authors Lewis Tian (taseikyo@gmail.com)
* @date 2020-06-24 21:38:48
* @link github.com/taseikyo
*/
/**
* 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 {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string ans;
printNodes(root, ans, result);
return result;
}
void printNodes(TreeNode* root, string& ans,
vector<string>& result) {
if (root == NULL) {
return;
}
ans += to_string(root->val) + "->";
if (root->left == NULL && root->right == NULL) {
ans.erase(ans.length() - 2, 2);
result.push_back(ans);
}
string temp = ans;
printNodes(root->left, temp, result);
temp = ans;
printNodes(root->right, temp, result);
}
}; | 25.463415 | 93 | 0.599617 | taseikyo |
d5c4d7d2f9f2c68470d96df1235da3ddf80adb76 | 719 | cpp | C++ | orbsvcs/SSLIOP/SSLIOP_CredentialsAcquirerFactory.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | orbsvcs/SSLIOP/SSLIOP_CredentialsAcquirerFactory.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | orbsvcs/SSLIOP/SSLIOP_CredentialsAcquirerFactory.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | // $Id: SSLIOP_CredentialsAcquirerFactory.cpp 1861 2011-08-31 16:18:08Z mesnierp $
#include "orbsvcs/SSLIOP/SSLIOP_CredentialsAcquirerFactory.h"
#include "orbsvcs/SSLIOP/SSLIOP_CredentialsAcquirer.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
SecurityLevel3::CredentialsAcquirer_ptr
TAO::SSLIOP::CredentialsAcquirerFactory::make (
TAO::SL3::CredentialsCurator_ptr curator,
const CORBA::Any & acquisition_arguments)
{
SecurityLevel3::CredentialsAcquirer_ptr ca;
ACE_NEW_THROW_EX (ca,
TAO::SSLIOP::CredentialsAcquirer (curator,
acquisition_arguments),
CORBA::NO_MEMORY ());
return ca;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 31.26087 | 82 | 0.7121 | binary42 |
d5c721c6677e867acfcdfbc8768548473dbae0b0 | 35,062 | cc | C++ | mediapipe/util/tracking/box_tracker.cc | virdio/mediapipe | 4a20e9909d55838d5630366ce719844cf06ae85c | [
"Apache-2.0"
] | 17,242 | 2019-06-16T23:19:19.000Z | 2022-03-31T20:19:41.000Z | mediapipe/util/tracking/box_tracker.cc | virdio/mediapipe | 4a20e9909d55838d5630366ce719844cf06ae85c | [
"Apache-2.0"
] | 3,148 | 2019-06-23T19:45:17.000Z | 2022-03-31T16:53:40.000Z | mediapipe/util/tracking/box_tracker.cc | virdio/mediapipe | 4a20e9909d55838d5630366ce719844cf06ae85c | [
"Apache-2.0"
] | 3,712 | 2019-06-18T20:18:54.000Z | 2022-03-31T15:46:46.000Z | // Copyright 2019 The MediaPipe 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.
#include "mediapipe/util/tracking/box_tracker.h"
#include <sys/stat.h>
#include <fstream>
#include <limits>
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "mediapipe/framework/port/integral_types.h"
#include "mediapipe/framework/port/logging.h"
#include "mediapipe/util/tracking/measure_time.h"
#include "mediapipe/util/tracking/tracking.pb.h"
namespace mediapipe {
// Time within which close checkpoints are removed.
static constexpr int kSnapMs = 1000;
static constexpr int kInitCheckpoint = -1;
void MotionBoxStateQuadToVertices(const MotionBoxState::Quad& quad,
std::vector<Vector2_f>* vertices) {
CHECK_EQ(TimedBox::kNumQuadVertices * 2, quad.vertices_size());
CHECK(vertices != nullptr);
vertices->clear();
for (int i = 0; i < TimedBox::kNumQuadVertices; ++i) {
vertices->push_back(
Vector2_f(quad.vertices(i * 2), quad.vertices(i * 2 + 1)));
}
}
void VerticesToMotionBoxStateQuad(const std::vector<Vector2_f>& vertices,
MotionBoxState::Quad* quad) {
CHECK_EQ(TimedBox::kNumQuadVertices, vertices.size());
CHECK(quad != nullptr);
for (const Vector2_f& vertex : vertices) {
quad->add_vertices(vertex.x());
quad->add_vertices(vertex.y());
}
}
void MotionBoxStateFromTimedBox(const TimedBox& box, MotionBoxState* state) {
CHECK(state);
state->set_pos_x(box.left);
state->set_pos_y(box.top);
state->set_width(box.right - box.left);
state->set_height(box.bottom - box.top);
state->set_rotation(box.rotation);
state->set_request_grouping(box.request_grouping);
if (box.quad_vertices.size() == TimedBox::kNumQuadVertices) {
VerticesToMotionBoxStateQuad(box.quad_vertices, state->mutable_quad());
if (box.aspect_ratio > 0.0f) {
state->set_aspect_ratio(box.aspect_ratio);
}
// set pos_x and pos_y to be the top-left vertex x and y coordinates
// set width and height to be max - min of x and y.
float min_x = std::numeric_limits<float>::max();
float max_x = std::numeric_limits<float>::lowest();
float min_y = std::numeric_limits<float>::max();
float max_y = std::numeric_limits<float>::lowest();
for (const auto& vertex : box.quad_vertices) {
min_x = std::min(min_x, vertex.x());
max_x = std::max(max_x, vertex.x());
min_y = std::min(min_y, vertex.y());
max_y = std::max(max_y, vertex.y());
}
state->set_pos_x(min_x);
state->set_pos_y(min_y);
state->set_width(max_x - min_x);
state->set_height(max_y - min_y);
}
}
void TimedBoxFromMotionBoxState(const MotionBoxState& state, TimedBox* box) {
CHECK(box);
const float scale_dx = state.width() * (state.scale() - 1.0f) * 0.5f;
const float scale_dy = state.height() * (state.scale() - 1.0f) * 0.5f;
box->left = state.pos_x() - scale_dx;
box->top = state.pos_y() - scale_dy;
box->right = state.pos_x() + state.width() + scale_dx;
box->bottom = state.pos_y() + state.height() + scale_dy;
box->rotation = state.rotation();
box->confidence = state.tracking_confidence();
box->request_grouping = state.request_grouping();
if (state.has_quad()) {
MotionBoxStateQuadToVertices(state.quad(), &(box->quad_vertices));
if (state.has_aspect_ratio()) {
box->aspect_ratio = state.aspect_ratio();
}
}
}
namespace {
TimedBox BlendTimedBoxes(const TimedBox& lhs, const TimedBox& rhs,
int64 time_msec) {
CHECK_LT(lhs.time_msec, rhs.time_msec);
const double alpha =
(time_msec - lhs.time_msec) * 1.0 / (rhs.time_msec - lhs.time_msec);
return TimedBox::Blend(lhs, rhs, alpha);
}
} // namespace.
TimedBox TimedBox::Blend(const TimedBox& lhs, const TimedBox& rhs, double alpha,
double beta) {
// Due to large timestamps alpha beta should be in double.
TimedBox result;
result.top = alpha * lhs.top + beta * rhs.top;
result.left = alpha * lhs.left + beta * rhs.left;
result.bottom = alpha * lhs.bottom + beta * rhs.bottom;
result.right = alpha * lhs.right + beta * rhs.right;
result.rotation = alpha * lhs.rotation + beta * rhs.rotation;
result.time_msec = std::round(alpha * lhs.time_msec + beta * rhs.time_msec);
result.confidence = alpha * lhs.confidence + beta * rhs.confidence;
if (lhs.quad_vertices.size() == kNumQuadVertices &&
rhs.quad_vertices.size() == kNumQuadVertices) {
result.quad_vertices.clear();
for (int i = 0; i < lhs.quad_vertices.size(); ++i) {
result.quad_vertices.push_back(alpha * lhs.quad_vertices[i] +
beta * rhs.quad_vertices[i]);
}
// Since alpha and beta are not necessarily sum to 1, aspect ratio can not
// be derived with alpha and beta. Here we are simply averaging the
// aspect_ratio as the blended box aspect ratio.
if (lhs.aspect_ratio > 0 && rhs.aspect_ratio > 0) {
result.aspect_ratio = 0.5f * lhs.aspect_ratio + 0.5f * rhs.aspect_ratio;
}
}
return result;
}
TimedBox TimedBox::Blend(const TimedBox& lhs, const TimedBox& rhs,
double alpha) {
return Blend(lhs, rhs, 1.0 - alpha, alpha);
}
std::array<Vector2_f, 4> TimedBox::Corners(float width, float height) const {
if (quad_vertices.size() == kNumQuadVertices) {
std::array<Vector2_f, 4> corners{{
Vector2_f(quad_vertices[0].x() * width, quad_vertices[0].y() * height),
Vector2_f(quad_vertices[1].x() * width, quad_vertices[1].y() * height),
Vector2_f(quad_vertices[2].x() * width, quad_vertices[2].y() * height),
Vector2_f(quad_vertices[3].x() * width, quad_vertices[3].y() * height),
}};
return corners;
} else {
// Rotate 4 corner w.r.t. center.
const Vector2_f center(0.5f * (left + right) * width,
0.5f * (top + bottom) * height);
const std::array<Vector2_f, 4> corners{{
Vector2_f(left * width, top * height),
Vector2_f(left * width, bottom * height),
Vector2_f(right * width, bottom * height),
Vector2_f(right * width, top * height),
}};
const float cos_a = std::cos(rotation);
const float sin_a = std::sin(rotation);
std::array<Vector2_f, 4> transformed_corners;
for (int k = 0; k < 4; ++k) {
// Scale and rotate w.r.t. center.
const Vector2_f rad = corners[k] - center;
const Vector2_f rot_rad(cos_a * rad.x() - sin_a * rad.y(),
sin_a * rad.x() + cos_a * rad.y());
transformed_corners[k] = center + rot_rad;
}
return transformed_corners;
}
}
TimedBox TimedBox::FromProto(const TimedBoxProto& proto) {
TimedBox box;
box.top = proto.top();
box.left = proto.left();
box.bottom = proto.bottom();
box.right = proto.right();
box.rotation = proto.rotation();
box.time_msec = proto.time_msec();
box.request_grouping = proto.request_grouping();
if (proto.has_quad() &&
proto.quad().vertices_size() == kNumQuadVertices * 2) {
MotionBoxStateQuadToVertices(proto.quad(), &(box.quad_vertices));
if (proto.has_aspect_ratio()) {
box.aspect_ratio = proto.aspect_ratio();
}
}
return box;
}
TimedBoxProto TimedBox::ToProto() const {
TimedBoxProto proto;
proto.set_top(top);
proto.set_left(left);
proto.set_bottom(bottom);
proto.set_right(right);
proto.set_rotation(rotation);
proto.set_time_msec(time_msec);
proto.set_confidence(confidence);
proto.set_request_grouping(request_grouping);
if (quad_vertices.size() == kNumQuadVertices) {
VerticesToMotionBoxStateQuad(quad_vertices, proto.mutable_quad());
if (aspect_ratio > 0.0f) {
proto.set_aspect_ratio(aspect_ratio);
}
}
return proto;
}
BoxTracker::BoxTracker(const std::string& cache_dir,
const BoxTrackerOptions& options)
: options_(options), cache_dir_(cache_dir) {
tracking_workers_.reset(new ThreadPool(options_.num_tracking_workers()));
tracking_workers_->StartWorkers();
}
BoxTracker::BoxTracker(
const std::vector<const TrackingDataChunk*>& tracking_data, bool copy_data,
const BoxTrackerOptions& options)
: BoxTracker("", options) {
AddTrackingDataChunks(tracking_data, copy_data);
}
void BoxTracker::AddTrackingDataChunk(const TrackingDataChunk* chunk,
bool copy_data) {
CHECK_GT(chunk->item_size(), 0) << "Empty chunk.";
int64 chunk_time_msec = chunk->item(0).timestamp_usec() / 1000;
int chunk_idx = ChunkIdxFromTime(chunk_time_msec);
CHECK_GE(chunk_idx, tracking_data_.size()) << "Chunk is out of order.";
if (chunk_idx > tracking_data_.size()) {
LOG(INFO) << "Resize tracking_data_ to " << chunk_idx;
tracking_data_.resize(chunk_idx);
}
if (copy_data) {
tracking_data_buffer_.emplace_back(new TrackingDataChunk(*chunk));
tracking_data_.push_back(tracking_data_buffer_.back().get());
} else {
tracking_data_.emplace_back(chunk);
}
}
void BoxTracker::AddTrackingDataChunks(
const std::vector<const TrackingDataChunk*>& tracking_data,
bool copy_data) {
for (const auto item : tracking_data) {
AddTrackingDataChunk(item, copy_data);
}
}
void BoxTracker::NewBoxTrack(const TimedBox& initial_pos, int id,
int64 min_msec, int64 max_msec) {
VLOG(1) << "New box track: " << id << " : " << initial_pos.ToString()
<< " from " << min_msec << " to " << max_msec;
// Mark initialization with checkpoint -1.
absl::MutexLock lock(&status_mutex_);
if (canceling_) {
LOG(WARNING) << "Box Tracker is in cancel state. Refusing request.";
return;
}
++track_status_[id][kInitCheckpoint].tracks_ongoing;
auto operation = [this, initial_pos, id, min_msec, max_msec]() {
this->NewBoxTrackAsync(initial_pos, id, min_msec, max_msec);
};
tracking_workers_->Schedule(operation);
}
std::pair<int64, int64> BoxTracker::TrackInterval(int id) {
absl::MutexLock lock(&path_mutex_);
const Path& path = paths_[id];
if (path.empty()) {
return std::make_pair(-1, -1);
}
auto first_interval = path.begin()->second;
auto last_interval = path.rbegin()->second;
return std::make_pair(first_interval.front().time_msec,
last_interval.back().time_msec);
}
void BoxTracker::NewBoxTrackAsync(const TimedBox& initial_pos, int id,
int64 min_msec, int64 max_msec) {
VLOG(1) << "Async track for id: " << id << " from " << min_msec << " to "
<< max_msec;
// Determine start position and track forward and backward.
int chunk_idx = ChunkIdxFromTime(initial_pos.time_msec);
VLOG(1) << "Starting at chunk " << chunk_idx;
AugmentedChunkPtr tracking_chunk(ReadChunk(id, kInitCheckpoint, chunk_idx));
if (!tracking_chunk.first) {
absl::MutexLock lock(&status_mutex_);
--track_status_[id][kInitCheckpoint].tracks_ongoing;
LOG(ERROR) << "Could not read tracking chunk from file: " << chunk_idx
<< " for start position: " << initial_pos.ToString();
return;
}
// Grab ownership here, to avoid any memory leaks due to early return.
std::unique_ptr<const TrackingDataChunk> chunk_owned;
if (tracking_chunk.second) {
chunk_owned.reset(tracking_chunk.first);
}
const int start_frame =
ClosestFrameIndex(initial_pos.time_msec, *tracking_chunk.first);
VLOG(1) << "Local start frame: " << start_frame;
// Update starting position to coincide with a frame.
TimedBox start_pos = initial_pos;
start_pos.time_msec =
tracking_chunk.first->item(start_frame).timestamp_usec() / 1000;
VLOG(1) << "Request at " << initial_pos.time_msec << " revised to "
<< start_pos.time_msec;
const int checkpoint = start_pos.time_msec;
// TODO:
// Compute min and max for tracking based on existing check points.
if (!WaitToScheduleId(id)) {
// Could not schedule, id already being canceled.
return;
}
// If another checkpoint is close by, cancel that one.
VLOG(1) << "Removing close checkpoints";
absl::MutexLock lock(&status_mutex_);
RemoveCloseCheckpoints(id, checkpoint);
VLOG(1) << "Cancel existing tracks";
CancelTracking(id, checkpoint);
// Remove checkpoint results (to be replaced with current one).
ClearCheckpoint(id, checkpoint);
MotionBoxState start_state;
MotionBoxStateFromTimedBox(start_pos, &start_state);
VLOG(1) << "Adding initial result";
AddBoxResult(start_pos, id, checkpoint, start_state);
// Perform forward and backward tracking and add to current PathSegment.
// Track forward.
track_status_[id][checkpoint].tracks_ongoing += 2;
VLOG(1) << "Starting tracking workers ... ";
AugmentedChunkPtr forward_chunk = tracking_chunk;
AugmentedChunkPtr backward_chunk = tracking_chunk;
if (tracking_chunk.second) { // We have ownership, need a copy here.
forward_chunk = std::make_pair(new TrackingDataChunk(*chunk_owned), true);
backward_chunk = std::make_pair(chunk_owned.release(), true);
}
auto forward_operation = [this, forward_chunk, start_state, start_frame,
chunk_idx, id, checkpoint, min_msec, max_msec]() {
this->TrackingImpl(TrackingImplArgs(forward_chunk, start_state, start_frame,
chunk_idx, id, checkpoint, true, true,
min_msec, max_msec));
};
tracking_workers_->Schedule(forward_operation);
// Track backward.
auto backward_operation = [this, backward_chunk, start_state, start_frame,
chunk_idx, id, checkpoint, min_msec, max_msec]() {
this->TrackingImpl(TrackingImplArgs(backward_chunk, start_state,
start_frame, chunk_idx, id, checkpoint,
false, true, min_msec, max_msec));
};
tracking_workers_->Schedule(backward_operation);
DoneSchedulingId(id);
// Tell a waiting request that we are done scheduling.
status_condvar_.SignalAll();
VLOG(1) << "Scheduling done for " << id;
}
void BoxTracker::RemoveCloseCheckpoints(int id, int checkpoint) {
if (track_status_[id].empty()) {
return;
}
auto pos = track_status_[id].lower_bound(checkpoint);
// Test current and previous location (if possible).
int num_turns = 1;
if (pos != track_status_[id].begin()) {
--pos;
++num_turns;
}
for (int k = 0; k < num_turns; ++k, ++pos) {
if (pos != track_status_[id].end()) {
const int check_pos = pos->first;
// Ignore marker init checkpoint from track_status_.
if (check_pos > kInitCheckpoint &&
std::abs(check_pos - checkpoint) < kSnapMs) {
CancelTracking(id, check_pos);
ClearCheckpoint(id, check_pos);
}
} else {
break;
}
}
}
bool BoxTracker::WaitToScheduleId(int id) {
VLOG(1) << "Wait to schedule id: " << id;
absl::MutexLock lock(&status_mutex_);
while (new_box_track_[id]) {
// Box tracking is currently ongoing for this id.
if (track_status_[id][kInitCheckpoint].canceled) {
// Canceled, remove myself from ongoing tracks.
--track_status_[id][kInitCheckpoint].tracks_ongoing;
status_condvar_.SignalAll();
return false;
}
// Only one request can be processing in the section till end of the
// function NewBoxTrackAsync at a time.
status_condvar_.Wait(&status_mutex_);
}
// We got canceled already, don't proceed.
if (track_status_[id][kInitCheckpoint].canceled) {
--track_status_[id][kInitCheckpoint].tracks_ongoing;
status_condvar_.SignalAll();
return false;
}
// Signal we are about to schedule new tracking.
new_box_track_[id] = true;
VLOG(1) << "Ready to schedule id: " << id;
return true;
}
void BoxTracker::DoneSchedulingId(int id) {
new_box_track_[id] = false;
--track_status_[id][kInitCheckpoint].tracks_ongoing;
}
void BoxTracker::CancelTracking(int id, int checkpoint) {
// Wait for ongoing requests to terminate.
while (track_status_[id][checkpoint].tracks_ongoing != 0) {
// Cancel all ongoing requests.
track_status_[id][checkpoint].canceled = true;
status_condvar_.Wait(&status_mutex_);
}
track_status_[id][checkpoint].canceled = false;
}
bool BoxTracker::GetTimedPosition(int id, int64 time_msec, TimedBox* result,
std::vector<MotionBoxState>* states) {
CHECK(result);
MotionBoxState* lhs_box_state = nullptr;
MotionBoxState* rhs_box_state = nullptr;
if (states) {
CHECK(options_.record_path_states())
<< "Requesting corresponding tracking states requires option "
<< "record_path_states to be set";
states->resize(1);
lhs_box_state = rhs_box_state = &states->at(0);
}
VLOG(1) << "Obtaining result at " << time_msec;
absl::MutexLock lock(&path_mutex_);
const Path& path = paths_[id];
if (path.empty()) {
LOG(ERROR) << "Empty path!";
return false;
}
// Find corresponding checkpoint.
auto check_pos = path.lower_bound(time_msec);
if (check_pos == path.begin()) {
VLOG(1) << "To left";
// We are to the left of the earliest checkpoint.
return TimedBoxAtTime(check_pos->second, time_msec, result, lhs_box_state);
}
if (check_pos == path.end()) {
VLOG(1) << "To right";
--check_pos;
// We are to the right of the lastest checkpoint.
return TimedBoxAtTime(check_pos->second, time_msec, result, rhs_box_state);
}
VLOG(1) << "Blending ...";
// We are inbetween checkpoints, get result for each, then blend.
const PathSegment& rhs = check_pos->second;
const int check_rhs = check_pos->first;
--check_pos;
const PathSegment& lhs = check_pos->second;
const int check_lhs = check_pos->first;
TimedBox lhs_box;
TimedBox rhs_box;
if (states) {
states->resize(2);
lhs_box_state = &states->at(0);
rhs_box_state = &states->at(1);
}
if (!TimedBoxAtTime(lhs, time_msec, &lhs_box, lhs_box_state)) {
return false;
}
if (!TimedBoxAtTime(rhs, time_msec, &rhs_box, rhs_box_state)) {
return false;
}
VLOG(1) << "Blending: " << lhs_box.ToString() << " and "
<< rhs_box.ToString();
const double alpha = (time_msec - check_lhs) * 1.0 / (check_rhs - check_lhs);
*result = TimedBox::Blend(lhs_box, rhs_box, alpha);
return true;
}
bool BoxTracker::IsTrackingOngoingForId(int id) {
absl::MutexLock lock(&status_mutex_);
for (const auto& item : track_status_[id]) {
if (item.second.tracks_ongoing > 0) {
return true;
}
}
return false;
}
bool BoxTracker::IsTrackingOngoing() {
absl::MutexLock lock(&status_mutex_);
return IsTrackingOngoingMutexHeld();
}
bool BoxTracker::IsTrackingOngoingMutexHeld() {
for (const auto& id : track_status_) {
for (const auto& item : id.second) {
if (item.second.tracks_ongoing > 0) {
return true;
}
}
}
return false;
}
BoxTracker::AugmentedChunkPtr BoxTracker::ReadChunk(int id, int checkpoint,
int chunk_idx) {
VLOG(1) << __FUNCTION__ << " id=" << id << " chunk_idx=" << chunk_idx;
if (cache_dir_.empty() && !tracking_data_.empty()) {
if (chunk_idx < tracking_data_.size()) {
return std::make_pair(tracking_data_[chunk_idx], false);
} else {
LOG(ERROR) << "chunk_idx >= tracking_data_.size()";
return std::make_pair(nullptr, false);
}
} else {
std::unique_ptr<TrackingDataChunk> chunk_data(
ReadChunkFromCache(id, checkpoint, chunk_idx));
return std::make_pair(chunk_data.release(), true);
}
}
std::unique_ptr<TrackingDataChunk> BoxTracker::ReadChunkFromCache(
int id, int checkpoint, int chunk_idx) {
VLOG(1) << __FUNCTION__ << " id=" << id << " chunk_idx=" << chunk_idx;
auto format_runtime =
absl::ParsedFormat<'d'>::New(options_.cache_file_format());
std::string chunk_file;
if (format_runtime) {
chunk_file = cache_dir_ + "/" + absl::StrFormat(*format_runtime, chunk_idx);
} else {
LOG(ERROR) << "chache_file_format wrong. fall back to chunk_%04d.";
chunk_file = cache_dir_ + "/" + absl::StrFormat("chunk_%04d", chunk_idx);
}
VLOG(1) << "Reading chunk from cache: " << chunk_file;
std::unique_ptr<TrackingDataChunk> chunk_data(new TrackingDataChunk());
struct stat tmp;
if (stat(chunk_file.c_str(), &tmp)) {
if (!WaitForChunkFile(id, checkpoint, chunk_file)) {
return nullptr;
}
}
VLOG(1) << "File exists, reading ...";
std::ifstream in(chunk_file, std::ios::in | std::ios::binary);
if (!in) {
LOG(ERROR) << "Could not read chunk file: " << chunk_file;
return nullptr;
}
std::string data;
in.seekg(0, std::ios::end);
data.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&data[0], data.size());
in.close();
chunk_data->ParseFromString(data);
VLOG(1) << "Read success";
return chunk_data;
}
bool BoxTracker::WaitForChunkFile(int id, int checkpoint,
const std::string& chunk_file) {
VLOG(1) << "Chunk no exists, waiting for file: " << chunk_file;
const int timeout_msec = options_.read_chunk_timeout_msec();
// Exponential backoff sleep till file exists.
int wait_time_msec = 20;
VLOG(1) << "In wait for chunk ...: " << chunk_file;
// Maximum wait time.
const int kMaxWaitPeriod = 5000;
int total_wait_msec = 0;
bool file_exists = false;
while (!file_exists && total_wait_msec < timeout_msec) {
// Check if we got canceled.
{
absl::MutexLock lock(&status_mutex_);
if (track_status_[id][checkpoint].canceled) {
return false;
}
}
absl::SleepFor(absl::Milliseconds(wait_time_msec));
total_wait_msec += wait_time_msec;
struct stat tmp;
file_exists = stat(chunk_file.c_str(), &tmp) == 0;
if (file_exists) {
VLOG(1) << "Sucessfully waited on " << chunk_file << " for "
<< total_wait_msec;
break;
}
if (wait_time_msec < kMaxWaitPeriod) {
wait_time_msec *= 1.5;
}
}
return file_exists;
}
int BoxTracker::ClosestFrameIndex(int64 msec,
const TrackingDataChunk& chunk) const {
CHECK_GT(chunk.item_size(), 0);
typedef TrackingDataChunk::Item Item;
Item item_to_find;
item_to_find.set_timestamp_usec(msec * 1000);
int pos =
std::lower_bound(chunk.item().begin(), chunk.item().end(), item_to_find,
[](const Item& lhs, const Item& rhs) -> bool {
return lhs.timestamp_usec() < rhs.timestamp_usec();
}) -
chunk.item().begin();
// Skip end.
if (pos == chunk.item_size()) {
return pos - 1;
} else if (pos == 0) {
// Nothing smaller exists.
return 0;
}
// Determine closest timestamp.
const int64 lhs_diff = msec - chunk.item(pos - 1).timestamp_usec() / 1000;
const int64 rhs_diff = chunk.item(pos).timestamp_usec() / 1000 - msec;
if (std::min(lhs_diff, rhs_diff) >= 67) {
LOG(ERROR) << "No frame found within 67ms, probably using wrong chunk.";
}
if (lhs_diff < rhs_diff) {
return pos - 1;
} else {
return pos;
}
}
void BoxTracker::AddBoxResult(const TimedBox& box, int id, int checkpoint,
const MotionBoxState& state) {
absl::MutexLock lock(&path_mutex_);
PathSegment& segment = paths_[id][checkpoint];
auto insert_pos = std::lower_bound(segment.begin(), segment.end(), box);
const bool store_state = options_.record_path_states();
// Don't overwrite an existing box.
if (insert_pos == segment.end() || insert_pos->time_msec != box.time_msec) {
segment.insert(insert_pos,
InternalTimedBox(
box, store_state ? new MotionBoxState(state) : nullptr));
}
}
void BoxTracker::ClearCheckpoint(int id, int checkpoint) {
absl::MutexLock lock(&path_mutex_);
PathSegment& segment = paths_[id][checkpoint];
segment.clear();
}
void BoxTracker::TrackingImpl(const TrackingImplArgs& a) {
TrackStepOptions track_step_options = options_.track_step_options();
ChangeTrackingDegreesBasedOnStartPos(a.start_state, &track_step_options);
MotionBox motion_box(track_step_options);
const int chunk_data_size = a.chunk_data->item_size();
CHECK_GE(a.start_frame, 0);
CHECK_LT(a.start_frame, chunk_data_size);
VLOG(1) << " a.start_frame = " << a.start_frame << " @"
<< a.chunk_data->item(a.start_frame).timestamp_usec() << " with "
<< chunk_data_size << " items";
motion_box.ResetAtFrame(a.start_frame, a.start_state);
auto cleanup_func = [&a, this]() -> void {
if (a.first_call) {
// Signal we are done processing in this direction.
absl::MutexLock lock(&status_mutex_);
--track_status_[a.id][a.checkpoint].tracks_ongoing;
status_condvar_.SignalAll();
}
};
if (a.forward) {
// TrackingData at frame f, contains tracking information from
// frame f to f - 1. Get information at frame f + 1 and invert:
// Tracking from f to f + 1.
for (int f = a.start_frame; f + 1 < chunk_data_size; ++f) {
// Note: we use / 1000 instead of * 1000 to avoid overflow.
if (a.chunk_data->item(f + 1).timestamp_usec() / 1000 > a.max_msec) {
VLOG(2) << "Reached maximum tracking timestamp @" << a.max_msec;
break;
}
VLOG(1) << "Track forward from " << f;
MotionVectorFrame mvf;
MotionVectorFrameFromTrackingData(
a.chunk_data->item(f + 1).tracking_data(), &mvf);
const int track_duration_ms =
TrackingDataDurationMs(a.chunk_data->item(f + 1));
if (track_duration_ms > 0) {
mvf.duration_ms = track_duration_ms;
}
// If this is the first frame in a chunk, there might be an unobserved
// chunk boundary at the first frame.
if (f == 0 && a.chunk_data->item(0).tracking_data().frame_flags() &
TrackingData::FLAG_CHUNK_BOUNDARY) {
mvf.is_chunk_boundary = true;
}
MotionVectorFrame mvf_inverted;
InvertMotionVectorFrame(mvf, &mvf_inverted);
const bool forward_tracking = true;
if (!motion_box.TrackStep(f, mvf_inverted, forward_tracking)) {
VLOG(1) << "Failed forward at frame: " << f;
break;
} else {
// Test if current request is canceled.
{
absl::MutexLock lock(&status_mutex_);
if (track_status_[a.id][a.checkpoint].canceled) {
--track_status_[a.id][a.checkpoint].tracks_ongoing;
status_condvar_.SignalAll();
return;
}
}
TimedBox result;
const MotionBoxState& result_state = motion_box.StateAtFrame(f + 1);
TimedBoxFromMotionBoxState(result_state, &result);
result.time_msec = a.chunk_data->item(f + 1).timestamp_usec() / 1000;
AddBoxResult(result, a.id, a.checkpoint, result_state);
}
if (f + 2 == chunk_data_size && !a.chunk_data->last_chunk()) {
// Last frame, successful track, continue;
AugmentedChunkPtr next_chunk(
ReadChunk(a.id, a.checkpoint, a.chunk_idx + 1));
if (next_chunk.first != nullptr) {
TrackingImplArgs next_args(next_chunk, motion_box.StateAtFrame(f + 1),
0, a.chunk_idx + 1, a.id, a.checkpoint,
a.forward, false, a.min_msec, a.max_msec);
TrackingImpl(next_args);
} else {
cleanup_func();
LOG(ERROR) << "Can't read expected chunk file!";
}
}
}
} else {
// Backward tracking.
// Don't attempt to track from the very first frame backwards.
const int first_frame = a.chunk_data->first_chunk() ? 1 : 0;
for (int f = a.start_frame; f >= first_frame; --f) {
if (a.chunk_data->item(f).timestamp_usec() / 1000 < a.min_msec) {
VLOG(2) << "Reached minimum tracking timestamp @" << a.min_msec;
break;
}
VLOG(1) << "Track backward from " << f;
MotionVectorFrame mvf;
MotionVectorFrameFromTrackingData(a.chunk_data->item(f).tracking_data(),
&mvf);
const int64 track_duration_ms =
TrackingDataDurationMs(a.chunk_data->item(f));
if (track_duration_ms > 0) {
mvf.duration_ms = track_duration_ms;
}
const bool forward_tracking = false;
if (!motion_box.TrackStep(f, mvf, forward_tracking)) {
VLOG(1) << "Failed backward at frame: " << f;
break;
} else {
// Test if current request is canceled.
{
absl::MutexLock lock(&status_mutex_);
if (track_status_[a.id][a.checkpoint].canceled) {
--track_status_[a.id][a.checkpoint].tracks_ongoing;
status_condvar_.SignalAll();
return;
}
}
TimedBox result;
const MotionBoxState& result_state = motion_box.StateAtFrame(f - 1);
TimedBoxFromMotionBoxState(result_state, &result);
result.time_msec = a.chunk_data->item(f).prev_timestamp_usec() / 1000;
AddBoxResult(result, a.id, a.checkpoint, result_state);
}
if (f == first_frame && !a.chunk_data->first_chunk()) {
VLOG(1) << "Read next chunk: " << f << "==" << first_frame << " in "
<< a.chunk_idx;
// First frame, successful track, continue.
AugmentedChunkPtr prev_chunk(
ReadChunk(a.id, a.checkpoint, a.chunk_idx - 1));
if (prev_chunk.first != nullptr) {
const int last_frame = prev_chunk.first->item_size() - 1;
TrackingImplArgs prev_args(prev_chunk, motion_box.StateAtFrame(f - 1),
last_frame, a.chunk_idx - 1, a.id,
a.checkpoint, a.forward, false, a.min_msec,
a.max_msec);
TrackingImpl(prev_args);
} else {
cleanup_func();
LOG(ERROR) << "Can't read expected chunk file! " << a.chunk_idx - 1
<< " while tracking @"
<< a.chunk_data->item(f).timestamp_usec() / 1000
<< " with cutoff " << a.min_msec;
return;
}
}
}
}
cleanup_func();
}
bool TimedBoxAtTime(const PathSegment& segment, int64 time_msec, TimedBox* box,
MotionBoxState* state) {
CHECK(box);
if (segment.empty()) {
return false;
}
TimedBox to_find;
to_find.time_msec = time_msec;
auto pos = std::lower_bound(segment.begin(), segment.end(), to_find);
if (pos != segment.end() && pos->time_msec == time_msec) {
*box = *pos;
if (state) {
*state = *pos->state;
}
return true;
}
constexpr int kMaxDiff = 67;
if (pos == segment.begin()) {
if (pos->time_msec - time_msec < kMaxDiff) {
*box = *pos;
if (state && pos->state) {
*state = *pos->state;
}
return true;
} else {
return false;
}
}
if (pos == segment.end()) {
if (time_msec - pos[-1].time_msec < kMaxDiff) {
*box = pos[-1];
if (state && pos[-1].state) {
*state = *pos[-1].state;
}
return true;
} else {
return false;
}
}
// Interpolation necessary.
*box = BlendTimedBoxes(pos[-1], pos[0], time_msec);
if (state) {
// Grab closest state.
if (std::abs(pos[-1].time_msec - time_msec) <
std::abs(pos[0].time_msec - time_msec)) {
if (pos[-1].state) {
*state = *pos[-1].state;
}
} else {
if (pos[0].state) {
*state = *pos[0].state;
}
}
}
return true;
}
void BoxTracker::ResumeTracking() {
absl::MutexLock lock(&status_mutex_);
canceling_ = false;
}
void BoxTracker::CancelAllOngoingTracks() {
// Get a list of items to be canceled (id, checkpoint)
absl::MutexLock lock(&status_mutex_);
canceling_ = true;
std::vector<std::pair<int, int>> to_be_canceled;
for (auto& id : track_status_) {
for (auto& checkpoint : id.second) {
if (checkpoint.second.tracks_ongoing > 0) {
checkpoint.second.canceled = true;
to_be_canceled.push_back(std::make_pair(id.first, checkpoint.first));
}
}
}
// Wait for ongoing requests to terminate.
auto on_going_test = [&to_be_canceled, this]() -> bool {
status_mutex_.AssertHeld();
for (const auto& item : to_be_canceled) {
if (track_status_[item.first][item.second].tracks_ongoing > 0) {
return true;
}
}
return false;
};
while (on_going_test()) {
status_condvar_.Wait(&status_mutex_);
}
// Indicate we are done canceling.
for (const auto& item : to_be_canceled) {
track_status_[item.first][item.second].canceled = false;
}
}
bool BoxTracker::WaitForAllOngoingTracks(int timeout_us) {
MEASURE_TIME << "Tracking time ...";
absl::MutexLock lock(&status_mutex_);
// Infinite wait for timeout <= 0.
absl::Duration timeout = timeout_us > 0 ? absl::Microseconds(timeout_us)
: absl::InfiniteDuration();
while (timeout > absl::ZeroDuration() && IsTrackingOngoingMutexHeld()) {
absl::Time start_wait = absl::Now();
status_condvar_.WaitWithTimeout(&status_mutex_, timeout);
absl::Duration elapsed = absl::Now() - start_wait;
timeout -= elapsed;
}
return !IsTrackingOngoingMutexHeld();
}
bool BoxTracker::GetTrackingData(int id, int64 request_time_msec,
TrackingData* tracking_data,
int* tracking_data_msec) {
CHECK(tracking_data);
int chunk_idx = ChunkIdxFromTime(request_time_msec);
AugmentedChunkPtr tracking_chunk(ReadChunk(id, kInitCheckpoint, chunk_idx));
if (!tracking_chunk.first) {
absl::MutexLock lock(&status_mutex_);
--track_status_[id][kInitCheckpoint].tracks_ongoing;
LOG(ERROR) << "Could not read tracking chunk from file.";
return false;
}
std::unique_ptr<const TrackingDataChunk> owned_chunk;
if (tracking_chunk.second) {
owned_chunk.reset(tracking_chunk.first);
}
const int closest_frame =
ClosestFrameIndex(request_time_msec, *tracking_chunk.first);
*tracking_data = tracking_chunk.first->item(closest_frame).tracking_data();
if (tracking_data_msec) {
*tracking_data_msec =
tracking_chunk.first->item(closest_frame).timestamp_usec() / 1000;
}
return true;
}
} // namespace mediapipe
| 32.984008 | 80 | 0.64115 | virdio |
d5cded2183622621195f1952f5dd256dcfc2e2c9 | 2,059 | cpp | C++ | llvm-3.5/lib/Target/NVPTX/NVPTXSubtarget.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 3 | 2015-03-08T22:21:34.000Z | 2018-06-25T00:18:51.000Z | llvm-3.5/lib/Target/NVPTX/NVPTXSubtarget.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1 | 2016-09-22T06:35:24.000Z | 2016-09-23T08:33:57.000Z | llvm-3.5/lib/Target/NVPTX/NVPTXSubtarget.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1 | 2021-03-24T06:40:32.000Z | 2021-03-24T06:40:32.000Z | //===- NVPTXSubtarget.cpp - NVPTX Subtarget Information -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the NVPTX specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "NVPTXSubtarget.h"
using namespace llvm;
#define DEBUG_TYPE "nvptx-subtarget"
#define GET_SUBTARGETINFO_ENUM
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "NVPTXGenSubtargetInfo.inc"
// Pin the vtable to this file.
void NVPTXSubtarget::anchor() {}
static std::string computeDataLayout(bool is64Bit) {
std::string Ret = "e";
if (!is64Bit)
Ret += "-p:32:32";
Ret += "-i64:64-v16:16-v32:32-n16:32:64";
return Ret;
}
NVPTXSubtarget &NVPTXSubtarget::initializeSubtargetDependencies(StringRef CPU,
StringRef FS) {
// Provide the default CPU if we don't have one.
if (CPU.empty() && FS.size())
llvm_unreachable("we are not using FeatureStr");
TargetName = CPU.empty() ? "sm_20" : CPU;
ParseSubtargetFeatures(TargetName, FS);
// Set default to PTX 3.2 (CUDA 5.5)
if (PTXVersion == 0) {
PTXVersion = 32;
}
return *this;
}
NVPTXSubtarget::NVPTXSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, const TargetMachine &TM,
bool is64Bit)
: NVPTXGenSubtargetInfo(TT, CPU, FS), Is64Bit(is64Bit), PTXVersion(0),
SmVersion(20), DL(computeDataLayout(is64Bit)),
InstrInfo(initializeSubtargetDependencies(CPU, FS)),
TLInfo((NVPTXTargetMachine &)TM), TSInfo(&DL), FrameLowering(*this) {
Triple T(TT);
if (T.getOS() == Triple::NVCL)
drvInterface = NVPTX::NVCL;
else
drvInterface = NVPTX::CUDA;
}
| 29 | 80 | 0.593006 | randolphwong |
d5d292335c54348c250a7153199e33b654cd9459 | 77,031 | inl | C++ | src/fonts/stb_font_arial_bold_49_usascii.inl | stetre/moonfonts | 5c8010c02ea62edcf42902e09478b0cd14af56ea | [
"MIT"
] | 3 | 2018-03-13T12:51:57.000Z | 2021-10-11T11:32:17.000Z | src/fonts/stb_font_arial_bold_49_usascii.inl | stetre/moonfonts | 5c8010c02ea62edcf42902e09478b0cd14af56ea | [
"MIT"
] | null | null | null | src/fonts/stb_font_arial_bold_49_usascii.inl | stetre/moonfonts | 5c8010c02ea62edcf42902e09478b0cd14af56ea | [
"MIT"
] | null | null | null | // Font generated by stb_font_inl_generator.c (4/1 bpp)
//
// Following instructions show how to use the only included font, whatever it is, in
// a generic way so you can replace it with any other font by changing the include.
// To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_arial_bold_49_usascii_*,
// and separately install each font. Note that the CREATE function call has a
// totally different name; it's just 'stb_font_arial_bold_49_usascii'.
//
/* // Example usage:
static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS];
static void init(void)
{
// optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2
static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH];
STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT);
... create texture ...
// for best results rendering 1:1 pixels texels, use nearest-neighbor sampling
// if allowed to scale up, use bilerp
}
// This function positions characters on integer coordinates, and assumes 1:1 texels to pixels
// Appropriate if nearest-neighbor sampling is used
static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0);
glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0);
glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1);
glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance_int;
}
glEnd();
}
// This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels
// Appropriate if bilinear filtering is used
static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f);
glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance;
}
glEnd();
}
*/
#ifndef STB_FONTCHAR__TYPEDEF
#define STB_FONTCHAR__TYPEDEF
typedef struct
{
// coordinates if using integer positioning
float s0,t0,s1,t1;
signed short x0,y0,x1,y1;
int advance_int;
// coordinates if using floating positioning
float s0f,t0f,s1f,t1f;
float x0f,y0f,x1f,y1f;
float advance;
} stb_fontchar;
#endif
#define STB_FONT_arial_bold_49_usascii_BITMAP_WIDTH 256
#define STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT 280
#define STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT_POW2 512
#define STB_FONT_arial_bold_49_usascii_FIRST_CHAR 32
#define STB_FONT_arial_bold_49_usascii_NUM_CHARS 95
#define STB_FONT_arial_bold_49_usascii_LINE_SPACING 32
static unsigned int stb__arial_bold_49_usascii_pixels[]={
0x200bfff5,0x003ceeff,0x00ffffe6,0x07feedb8,0xd9955000,0x0579bdfd,
0x3fe20000,0xaaaa807f,0x2aaaaa2a,0x512aaaaa,0x55555555,0x7fdc0035,
0x51000004,0x357bdd97,0x0c400000,0xeeeeb800,0x3bae004e,0x3ffe3eee,
0xffff802f,0xf9802eff,0xea803fff,0x007fffff,0x3ffff260,0xffffffff,
0x00002dff,0x2013fff2,0x3a7fffff,0xffffffff,0xfffff15f,0x007fffff,
0x00027fdc,0x3fffff20,0xdfffffff,0xeda80000,0x2e0bdfff,0xff35eeee,
0x2001ffff,0x21ffffff,0x400ffffc,0xffffffff,0x7fffcc02,0x7fffdc03,
0x44007fff,0xffffffeb,0xffffffff,0x002fffff,0x0ffffcc0,0x3fffffc0,
0xfffffffd,0x3ffe2bff,0x3fffffff,0xeffeb980,0x74c0001c,0xffffffff,
0x3fffffff,0x3fff6000,0x91ffffff,0x7f4fffff,0x9803ffff,0x446fffff,
0x7c04ffff,0x6fffffff,0x1ffffcc0,0xffffff10,0x7cc00fff,0xffffffff,
0xffffffff,0x0dffffff,0xbfffb000,0x3ffffe00,0x3fffffa7,0xff15ffff,
0xffffffff,0x7fffdc07,0x03ffffff,0xfffffc80,0xffffffff,0x00efffff,
0x3ffffa60,0xafffffff,0x2e7ffffc,0x805fffff,0x83fffffc,0x201ffffd,
0xffffffff,0x3ffe602f,0x3ffee03f,0x007fffff,0xfffffff7,0x54c3357b,
0xfffffdcb,0x7cc001ff,0xff002fff,0x7ff4ffff,0x5fffffff,0xfffffff1,
0xfb107fff,0xffffffff,0x1001bfff,0xfffffffd,0xffffffff,0x03ffffff,
0x3fffffa0,0xffffffff,0x227ffffe,0x00ffffff,0x07fffffc,0x02ffffd4,
0xffffd533,0x7ffcc09f,0x3fff603f,0x4019adff,0xefffffd8,0xfc88000b,
0x001fffff,0x801ffff6,0x3a7fffff,0xaaaeffff,0x2a66662a,0xd83fffff,
0xffffffff,0x05ffffff,0xffffffc8,0xfdccefff,0xffffffff,0xffffa806,
0xfdbbcfff,0x7fffffff,0x1fffffec,0xbfffff30,0x07ffffc0,0x5fffff80,
0x0ffffe60,0x06ffffe8,0x77ffff40,0xfb300002,0x3001dfff,0x4009ffff,
0x3a199999,0x4006ffff,0x43fffff9,0xfffffffa,0xffffffff,0x3ffe603f,
0x201effff,0xffffffd8,0x7fff403f,0xfe980eff,0x547fffff,0x205fffff,
0x02fffffc,0x00fffff2,0x037ffff4,0x407ffff3,0x005fffff,0x03bffff2,
0x3fea0000,0xffe805ff,0x200001ff,0x006ffffe,0x1fffffcc,0x33fffffe,
0xfffccffb,0x3ffa06ff,0x000dffff,0xfffffff7,0x3fffee01,0x3fe200ff,
0xff87ffff,0xfd00ffff,0xfa80ffff,0xf9007fff,0x7cc0dfff,0x3fe03fff,
0xf5004fff,0x22009fff,0xfffb8000,0x3ffea02f,0x7400007f,0x4006ffff,
0x23fffff9,0x73fffff9,0x3fff29ff,0xfffb81ff,0xb8005fff,0x05ffffff,
0x09fffff9,0xffffff90,0x7fffff90,0x9fffff30,0x5fffff00,0xdffff900,
0x1ffffcc0,0x07fffff0,0x09ffff10,0x77ff6544,0x3333321c,0x81bfff62,
0x004ffffd,0xd377776c,0x800dffff,0x23fffff9,0x70fffffa,0x3ffe69ff,
0xffff81ef,0xd0000fff,0x03ffffff,0x03fffffb,0xffffff30,0xbfffff30,
0x3fffff90,0xbffffb00,0xfffff900,0x1ffffcc0,0x07fffff0,0x40dfffd0,
0xfffffffa,0xffff8aff,0x3fffe23f,0x5fffff01,0xfffff800,0x1bffffa7,
0xfffff300,0x2ffffe47,0x00cc9ff7,0x3fffffe6,0x3fea0004,0xfe83ffff,
0x8800ffff,0xd07fffff,0xe81fffff,0x7006ffff,0x900fffff,0x4c0fffff,
0x3e03ffff,0x4c03ffff,0xf501ffff,0xffffffff,0xfffffbff,0x84fffa85,
0x00fffff9,0x3fffffc0,0x00dffffd,0x3fffff98,0xb9ffffee,0x7d4004ff,
0x000fffff,0x7fffff40,0x7fffff84,0x3ffffe00,0xfffff707,0x7ffffcc7,
0xffff5004,0xfffb803f,0x3ffe607f,0x3fffe03f,0x7ffe402f,0xfffff504,
0xffffdbdf,0x881fffff,0xffc87fff,0xff8007ff,0x3ffa7fff,0x7cc006ff,
0x3ea3ffff,0xff72ffff,0xfffb8009,0xd80007ff,0x445fffff,0x007fffff,
0x41fffffe,0x25fffff8,0x01fffffb,0x7fffff30,0xfffffb80,0x7ffff300,
0x3ffffe20,0x3fffe202,0xfffffb80,0x7fffd40d,0xfff06fff,0xffffe81f,
0xffff8006,0x3ffffa7f,0x7ffcc006,0x3ffe63ff,0x4ffbbfff,0x7fffe400,
0xfb80006f,0x7c46ffff,0x800fffff,0x07fffff8,0x43fffff6,0x006ffffe,
0x17ffffe2,0x3fffff50,0x0ffffe60,0x07ffffd4,0x10bfff70,0x40bfffff,
0x5ffffffa,0x443fffb0,0x005fffff,0x27fffff8,0x006ffffe,0x1fffffcc,
0x3ffffffa,0x74004fff,0x005fffff,0xfffffa80,0xffffff87,0xffff9801,
0x3ffea07f,0xffff9aff,0x7ffc003f,0x7fc407ff,0xff304fff,0x3ff607ff,
0x7ff407ff,0xffffc82f,0xffffe806,0x5fff703f,0x27ffffcc,0x7ffffc00,
0x1bffffa7,0xfffff300,0xfffffa87,0x002effff,0x0ffffffe,0x3ffe6000,
0x7ff41fff,0xfb802fff,0x7c07ffff,0xffbdffff,0x7c000fff,0xd807ffff,
0x981fffff,0xf983ffff,0x7c06ffff,0xfff887ff,0xffd802ff,0xff501fff,
0x7fffd47f,0xfff8003f,0x3fffa7ff,0x7fcc006f,0xffe83fff,0xffffffff,
0x7ffc01cf,0x80003fff,0x1ffffff9,0x37ffffec,0x7fffff40,0x7fffe407,
0x05ffffef,0xfffffe80,0x7fffd400,0x3fe61bef,0x3fea23ff,0x2202ffff,
0xffc85fff,0xff9007ff,0x3f201fff,0x3ffee2ff,0xff8002ff,0x3ffa7fff,
0x7cc006ff,0xd883ffff,0xffffffff,0x3a04ffff,0x004fffff,0xfffffa80,
0x7fffcc1f,0x3ff203ff,0x4c07ffff,0xffffffff,0xfd8002ff,0xe800ffff,
0x4fffffff,0x367ffff3,0x6fffffff,0x427ffcc0,0x004fffff,0x40dffffb,
0x3ee0fffe,0x8002ffff,0x3a7fffff,0x4006ffff,0x03fffff9,0x3ffffff2,
0x0effffff,0x5fffffd8,0xfffb8000,0xffe80fff,0x260cffff,0xfffffffd,
0xffffe807,0x0007ffff,0x03fffff9,0xfffffd10,0x3fffe69f,0xffffffb3,
0xfffa801d,0x7ffffc43,0xffffd003,0x1fffe209,0x03fffff9,0xffffff00,
0x037ffff4,0x3ffffe60,0x7ffe4403,0xffffffff,0xfffffc86,0xffc80006,
0xfa80ffff,0xffffffff,0xffffffff,0xffb807ff,0x04ffffff,0xfffff700,
0x3ffa2003,0xfff34fff,0x3ffff67f,0xfff7006f,0xfffff985,0xffff8801,
0xdfff503f,0x0fffffd8,0xfffff800,0x1bffffa7,0xfffff300,0x7ffe4007,
0x3fffffff,0x3fffffdc,0x7ffec000,0x3ff207ff,0xffffffff,0xfffffdff,
0xffff8807,0x0001ffff,0x03fffff7,0x3fffff20,0x7ffff34f,0x3ffffff6,
0x1fffc803,0x07ffffd4,0x7ffffcc0,0x89fff901,0x00fffffc,0x7fffff80,
0x01bffffa,0x7fffff30,0x76ffdc00,0x47ffffff,0x1ffffffa,0xff8805c0,
0x6405ffff,0xffffffff,0xfffff4ff,0x3fff600f,0x20006fff,0x00fffffb,
0xffffffd8,0x7ffff34f,0x3ffffff6,0x7ffe404f,0x3ffffe41,0x7ffffb80,
0x83ffff10,0x01fffffb,0x7fffff80,0x01bffffa,0x7fffff30,0xaa7fdc00,
0x20ffffff,0x5ffffff8,0x9033fe60,0x07ffffff,0xffffff70,0x7fffc7ff,
0xfff5007f,0x40007fff,0x00fffffc,0x7fffffcc,0xffff30bc,0x3fffb267,
0x3ee01fff,0x7ffe42ff,0xfff8807f,0xfffd06ff,0xfffff70b,0xffff0003,
0x7ffff4ff,0x7ffcc006,0x3ee003ff,0x3fffee4f,0x7ffff41f,0xfffb01ff,
0xffff119f,0x22001fff,0x40bdeeca,0x006fffff,0x1ffffff3,0x7ffe4000,
0xfffe807f,0xfff982ff,0xffffc83f,0x3ffea05f,0x7ffffd43,0x7fffdc00,
0xffffd84f,0xfffffa80,0xffff8002,0x3ffffa7f,0x7ffcc006,0x0a9883ff,
0xff893fee,0x7fcc2fff,0x440effff,0xefffffff,0x04ffffff,0xfff88000,
0xffb006ff,0x8000dfff,0x806ffffd,0x305fffff,0x3a07ffff,0x2607ffff,
0x7fcc4fff,0x3e202fff,0x5c2fffff,0xf304ffff,0x0007ffff,0x74ffffff,
0x4006ffff,0x53fffff9,0x5c7fffff,0x7fff44ff,0xffffc81f,0x7f4c1eff,
0xffffffff,0x26a206ff,0x7ffcc000,0xff9805ff,0x0003ffff,0x027ffff4,
0x0bffffe6,0x81ffffcc,0x00fffffa,0xf88dfff1,0x3606ffff,0x11ffffff,
0x01dffff7,0x13ffffe2,0x3ffffe00,0x1bffffa7,0xfffff300,0x3ffffe27,
0xf993fee6,0xf880ffff,0xbfffffff,0x7ffffcc1,0x202fffff,0x2eeffffa,
0x7ffffd40,0x7fff4404,0x20000fff,0x03fffff8,0x07ffffd4,0x03ffff98,
0x03fffff3,0x320ffff4,0x8bffffff,0xfffffea8,0xffffcdff,0x7ff401ff,
0xff8004ff,0x3ffa7fff,0x7cc006ff,0x3fa3ffff,0xff72ffff,0x3ffffe49,
0xffffff70,0xffddffff,0xffffffff,0xffff880b,0xff300fff,0x7445ffff,
0xfffffdcc,0x4c0003ff,0x401fffff,0x207ffffb,0x103ffff9,0x405fffff,
0xfe85fffb,0xffffffff,0xffffffff,0x1fffffff,0x6ffffc80,0xfffff800,
0x1bffffa7,0xfffff300,0x7ffffe47,0xf54ffbbf,0xc809ffff,0xffffffff,
0xffffffff,0x03ffffff,0x7ffffffc,0xffedbbdf,0x7c46ffff,0xffffffff,
0x5c0000ff,0xb807ffff,0x2607ffff,0xf103ffff,0x4405ffff,0x7cc0ffff,
0xffffffff,0xfffffeff,0x00dfffff,0x1fffff50,0xfffff800,0x1bffffa7,
0xfffff300,0x7ffffc47,0xfedfffff,0x800fffff,0xffffffe9,0xffffffff,
0xefffffff,0xfffff502,0xffffffff,0xf03fffff,0xffffffff,0xf900005f,
0xf900bfff,0x7cc0ffff,0x3fe03fff,0x7ec03fff,0xffd885ff,0xd1efffff,
0xdfffffff,0xfff88007,0x7fc002ff,0x3ffa7fff,0x7cc006ff,0x7d43ffff,
0xffffffff,0x3fffffff,0x7fffe400,0xffffffff,0xffffffff,0xffc81eff,
0xffffffff,0x04ffffff,0xfffffffd,0x3a00005f,0xc802ffff,0x2606ffff,
0x3e03ffff,0x4c03ffff,0x9504ffff,0xc9859dfd,0x201ceefe,0x7ec1aaaa,
0x7c004fff,0x3fa7ffff,0x4c006fff,0xc83fffff,0xffffffff,0x04ffffff,
0xffdb9300,0x5bffffff,0xfffffff5,0x3ffee01f,0xffffffff,0x3f602eff,
0x00beffff,0xffff1000,0x3fff200f,0x3ffe606f,0x3fffe03f,0xfffc803f,
0x0000003f,0x03bfffa2,0x00dffff5,0x27fffff8,0x006ffffe,0x1fffffcc,
0xffffffb8,0x02ffffff,0x55d4c000,0xfffd881a,0xeda804ff,0xdeffffff,
0x00262003,0x7ffdc000,0xfffb004f,0x7ffcc0df,0x3fffe03f,0xfffd004f,
0x0000007f,0x03ffffd1,0x003ffffe,0x3fffffc4,0x00dffffd,0x3fffff98,
0x3ffff620,0x000befff,0xfa800000,0x30000fff,0x00000003,0xffffd800,
0xffffd001,0x7fffcc0d,0x3ffffe03,0xffff1006,0x000003df,0x13ffffaa,
0x02ffffc8,0xffffff50,0x037ffff4,0x3ffffe60,0xbffb3003,0x00000001,
0x000fae00,0x00000000,0xffff8800,0xfffc8806,0x3fe605ff,0x3ffa03ff,
0xa800bfff,0x1cffffff,0xffd50000,0xf880bfff,0x2ae05fff,0x6ffffffc,
0x01bffffa,0x7fffff30,0x027fdc00,0x00000000,0x00000000,0x2e000000,
0x3e01ffff,0xffffffff,0x3fffe603,0x3ffff203,0x4c07ffff,0xfffffffe,
0xb71000ac,0x7fffffff,0x3ffff600,0xfffff880,0x3fa4ffff,0xeeeeffff,
0xfddddd14,0x4007ffff,0x00004ffb,0x00000000,0x00000000,0x7fff4000,
0x7ffffc05,0x2600ffff,0x2203ffff,0xffffffff,0xffff9007,0xdfffffff,
0xffffdddd,0x3fffffff,0x7fffc400,0xfffffa83,0x3fa2ffff,0xffffffff,
0xffffff15,0x4007ffff,0x00004ffb,0x00000000,0x00000000,0x3ffe6000,
0x7fffc00f,0x4c04ffff,0x6403ffff,0x7fffffff,0x3fffa600,0xffffffff,
0xffffffff,0x000cffff,0xc86fffc8,0xffffffff,0x7fffff44,0xff15ffff,
0xffffffff,0x0d54c007,0x00000000,0x00000000,0xb0000000,0xff009fff,
0x019fffff,0x03ffff98,0x7ffffec4,0xeb88007f,0xffffffff,0xffffffff,
0x440002df,0x7ec2ffff,0x86ffffff,0xfffffffe,0xffff15ff,0x07ffffff,
0x00000000,0x00000000,0x00000000,0x0ffff880,0xcfffff80,0xffff3000,
0x3ff66007,0x440007ff,0xffffeecb,0x0bcdefff,0x3fea0000,0x7fffe45f,
0xeed80ace,0x4eeeeeee,0xddddddd1,0x00005ddd,0x00000000,0x00000000,
0x88000000,0x33000999,0x26600013,0x98800099,0x20000019,0x00000098,
0x44066660,0x00000009,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0xb7100000,0x200059dd,0x0005fffc,0x00000060,0x00000130,
0x37bbb72a,0x000000ab,0x3bfb72e2,0x0000abcd,0x03577530,0x26ea2000,
0x3fa00000,0xfffa86ff,0xa980003f,0x5552aaaa,0x7d401555,0x1effffff,
0x3fffe200,0x3b260001,0x2a1bdfff,0x7746eeee,0x36e23eee,0x002cefff,
0x7fffec40,0xffffffff,0xd700000d,0xffffffff,0x0019ffff,0xfffff910,
0x80019fff,0xffffffd8,0x220000ce,0xfc85ffff,0x80002fff,0xd6fffffb,
0x201fffff,0xfffffffb,0xf9000fff,0x5c000bff,0xffffffff,0xfffff72f,
0x34fffff8,0xffffffff,0x3ea0009f,0xffffffff,0x2fffffff,0x3ffa6000,
0xffffffff,0x04ffffff,0x3ffffee0,0x3fffffff,0xfffff700,0x03ffffff,
0x3fffe600,0x0ffffe83,0xfffb8000,0xffffd6ff,0x3fffe01f,0x4ffffecf,
0x1ffff880,0xfffd8800,0xffffffff,0x47ffffba,0xf9cfffff,0xffffffff,
0xb1000eff,0xffffffff,0xffffffff,0xb8001bff,0xffffffff,0xffffffff,
0xfb805fff,0xffffffff,0x403fffff,0xfffffffd,0x03ffffff,0x1ffffb80,
0x007ffff8,0xfffff700,0x3fffffad,0x1ffffb80,0x003ffff2,0x000bfff9,
0x3ffffff2,0xefffffff,0x7fc7ffff,0xffffefff,0xffffffff,0xffe8805f,
0xffffffff,0xffffffff,0xf9001fff,0xffffffff,0xffffffff,0x4c09ffff,
0xffffffff,0xffffffff,0xfffff701,0xffffffff,0xfd8007ff,0x7fcc0fff,
0x700005ff,0x3adfffff,0xd80fffff,0x7fcc6fff,0x3fe202ff,0xf98001ff,
0xceffffff,0xffffffdb,0x7fffc7ff,0xccefffff,0xfffffffe,0x7fffe402,
0xccefffff,0xfffffffd,0xffa806ff,0xefffffff,0xffffdccd,0xd03fffff,
0x7dffffff,0xffffffd5,0xfffff10b,0xfffd79df,0x4001ffff,0xfa86fffe,
0x00003fff,0x2dfffff7,0x80fffffe,0x7c45fffe,0x3f203fff,0xfb0005ff,
0x107fffff,0xfffffffd,0xfffffff8,0xffffa82f,0x3fea06ff,0x01efffff,
0x3fffff62,0x3fe203ff,0x03ffffff,0x7fffffdc,0xfffff06f,0xffff303f,
0xffffb0ff,0xffff50bf,0x3e200bff,0xffc85fff,0x700002ff,0x22dfffff,
0xff019999,0xfff889ff,0xffff104f,0xfff30003,0x7c405fff,0x7c7fffff,
0x01ffffff,0x3fffffe6,0xfffff882,0xf7000dff,0x01ffffff,0x3ffffffa,
0xfff1000e,0xf985ffff,0x3a06ffff,0x7c1fffff,0x700fffff,0x01ffffff,
0x07ffff30,0x001ffffb,0x3fffee00,0xfff8006f,0x5ffff84f,0x00bfff90,
0x3ffffee0,0xffffc806,0x7ffffc7f,0xfffd805f,0xfffc84ff,0xa8005fff,
0x85ffffff,0x6ffffff9,0xffff9800,0x7ffd45ff,0x3fea03ff,0x3fe22fff,
0x7fc04fff,0x32a2ffff,0xfffdcccc,0xffccccdf,0x003ccfff,0x7ffffdc0,
0xffff8006,0x27fffc44,0x00ffffc4,0xfffffc80,0xffff8803,0x7ffffc7f,
0xfffa801f,0xffff85ff,0xd0000fff,0x83ffffff,0x1ffffffc,0xbfffb000,
0xffff8859,0x3ffea03f,0x3ffea0ff,0x7fe403ff,0x3ff24fff,0xffffffff,
0xffffffff,0x0006ffff,0xb7ffffdc,0x80eeeeed,0x7c45fffe,0xffc83fff,
0x3f60005f,0xf002ffff,0xff8fffff,0x9800ffff,0x4c6fffff,0x04ffffff,
0x3fffea00,0x7fffc3ff,0x220005ff,0xfffe800a,0x3fff606f,0x7fffdc6f,
0x7ffdc02f,0x3fff26ff,0xffffffff,0xffffffff,0x40006fff,0xd6fffffb,
0xb01fffff,0xffa8ffff,0x7ffc42ff,0x3fe0001f,0xd001ffff,0xff8fffff,
0xf1007fff,0xfc8fffff,0x000fffff,0x7fffff40,0x3ffffea4,0x0000001f,
0x03fffff9,0x89fffff3,0x02fffffb,0x3fffffd4,0xfffffff9,0xffffffff,
0xdfffffff,0xfffb8000,0xffffd6ff,0xffff501f,0x3ffffa27,0x02fffe40,
0x3ffffe00,0xfffd000f,0xfffff8ff,0x3fffe007,0x3fff60ff,0xc80006ff,
0x2e5fffff,0x00ffffff,0xff300000,0xb55bffff,0x83ffffff,0x03fffffa,
0x7fffffdc,0xffffff90,0xffffffff,0xffffffff,0xffb8000d,0xfffd6fff,
0x3ffa01ff,0xffffffff,0x0ffffc43,0x3fffa000,0xfff000ff,0xffff8fff,
0x3ffe007f,0x7fff47ff,0xb80005ff,0x326fffff,0x007fffff,0x7fd40000,
0xffffffff,0xf980efff,0x6404ffff,0x11ffffff,0xfff93333,0xff33335f,
0x01333dff,0xffffb800,0xfffffd6f,0x3fffe601,0xc86fffff,0x80005fff,
0x01fffffd,0x8ffffff0,0x00ffffff,0x6fffff88,0x27fffffc,0x7ffd4000,
0x3fff67ff,0x000006ff,0xffffd880,0x05ffffff,0x1fffffe2,0xfffffff0,
0x7fffec03,0x2ffffc40,0x3fee0000,0xfffd6fff,0x7f4401ff,0x884fffff,
0x0001ffff,0x2fffffc8,0xfffff980,0x7fffffc7,0xffff9802,0x7ffffc5f,
0xf980003f,0xfd1fffff,0x100bffff,0xdddddddd,0x205ddddd,0xffffffc8,
0x200dffff,0x03fffffd,0xfffffff9,0x37fffc03,0x01ffffd4,0x3ffee000,
0xffffd6ff,0x7953001f,0x3fff2015,0x00266205,0x0bfffff7,0xffffff90,
0x5ffffff8,0xfffffc80,0x7fffffc4,0xff980003,0xffd2ffff,0xf300bfff,
0xffffffff,0xf507ffff,0xffffffff,0x207fffff,0xcffffff9,0xfffffb31,
0x3e205fff,0xffc85fff,0x400001ff,0xd6fffffb,0x001fffff,0x7fffc400,
0xffffea81,0xffff302e,0x7fc403ff,0x7fc7ffff,0x201fffff,0x3ffffff8,
0x27fffffc,0x7ffd4000,0xfffb0fff,0xff300dff,0xffffffff,0xff987fff,
0xeddfffff,0x03ffffff,0xfffffff9,0xffffffff,0x3ea03fff,0xffd83fff,
0x400000ff,0xd6fffffb,0x001fffff,0x2fffe400,0x7fffffec,0xfffd05ff,
0xfd301dff,0xf8ffffff,0x1fffffff,0xfffffd88,0xfffffd86,0xffb80005,
0x3ff27fff,0xf9807fff,0xffffffff,0x7fc3ffff,0xfb83ffff,0xd01fffff,
0xffffffff,0xffffffff,0x3ffee03f,0x6ffff81f,0xffb80000,0xfffd6fff,
0x200001ff,0x5c1ffff8,0xffffffff,0xfff983ff,0xcaacffff,0xffffffff,
0x7fffffc7,0xecaacfff,0x82ffffff,0x06fffffc,0xffffc800,0x3ffff26f,
0xfff9807f,0xffffffff,0x3ffe63ff,0x3fee04ff,0x3f205fff,0xffffffff,
0x1ffffff9,0xfffd9995,0xff99999f,0x79999dff,0xfffb8000,0xffffd6ff,
0x3200001f,0x7fc45fff,0xffea9eff,0xfffd80ff,0xffffffff,0x7fffffff,
0x7ffffffc,0xffffffff,0xf706ffff,0x000fffff,0xbfffffb0,0x7fffffd4,
0x55554401,0xfffffaaa,0x3fffee3f,0x7fff402f,0x3f6a00ff,0xf88dffff,
0xf90fffff,0xffffffff,0xffffffff,0x00dfffff,0xfffffb80,0x1fffffd6,
0xfff10000,0xffffb83f,0x0ffffea1,0x3fffffe2,0xfcffffff,0x7fc7ffff,
0xfffcffff,0xffffffff,0xffff501f,0x440005ff,0x24ffffff,0x4ffffff8,
0x7fffc000,0x3fffa3ff,0xfffd807f,0x153001ff,0x7fffff98,0x3ffffff2,
0xffffffff,0xffffffff,0xb8033106,0xfd5fffff,0x0001ffff,0x90bfff90,
0xfff0ffff,0x3ffa209f,0x3fffffff,0xf8ffffff,0xff57ffff,0xbfffffff,
0x7fffc401,0x320006ff,0x42ffffff,0x0ffffffd,0x3fffe000,0xffff13ff,
0xfff900bf,0xa80005ff,0x325fffff,0xffffffff,0xffffffff,0x16ffffff,
0x80dfffdd,0xd5fffffc,0x001fffff,0x1ffff880,0xf86fffd8,0x7e405fff,
0x21dfffff,0x7c7fffff,0x3a67ffff,0x04efffff,0xffffffd0,0xfff10005,
0xfa81ffff,0x004fffff,0x3fffffe0,0xdfffff13,0xfffff900,0xffc80003,
0x3ff24fff,0xffffffff,0xffffffff,0xff16ffff,0xfc80ffff,0xffd5ffff,
0x80001fff,0xfd05fffc,0xfffd0dff,0x06aa200d,0x23fffffc,0x307fffff,
0xf9800155,0x01ffffff,0x3ffff620,0xfff883ff,0x8002ffff,0x3ffffff9,
0x01fffffe,0x83fffffa,0x405eccaa,0x21ffffff,0xffffe998,0xfffa9999,
0x099999df,0x03fffffe,0x4fffffe8,0x01fffffd,0x7fffc400,0x0dfffd01,
0x000dfffd,0x3fffffc0,0x01fffffe,0x7ffe4000,0x9803ffff,0x6ffffffe,
0x3ffffea0,0xfb1004ff,0x47ffffff,0x03fffffd,0x1fffffe6,0x05fffffb,
0x1fffffea,0xa86ffff8,0xd803ffff,0x304fffff,0x25ffffff,0x00fffffe,
0x17fff200,0xf86fffd8,0x00005fff,0xf1fffffe,0x000fffff,0x3fffe200,
0x21adffff,0xfffffca8,0x7ec01fff,0xbeffffff,0x3ff2e609,0x3fffffff,
0x3fffffee,0xffffe881,0x7fffdc5f,0x7ffcc0ef,0xff103fff,0xfff909ff,
0xfff9003f,0x74c19fff,0xd0ffffff,0x001fffff,0x07fffe20,0xf87fffc8,
0x00004fff,0xf1fffffe,0x000fffff,0x7fffdc00,0xffffffff,0xffffffff,
0xff8805ff,0xffffffff,0xffffffff,0x2fffffff,0x3fffffe2,0xfffbaadf,
0x7c41ffff,0xbdffffff,0x6ffffffd,0x0ffffea0,0x401ffff6,0xfffffff8,
0xffffffff,0x3fffa4ff,0xf90000ff,0xffb80bff,0x3ffea1ff,0x3e00003f,
0x7fc7ffff,0x00007fff,0x7ffffe40,0xffffffff,0xdfffffff,0xfffd3000,
0xffffffff,0xffffffff,0xff305fff,0xffffffff,0x07ffffff,0x3ffffff6,
0xffffffff,0x3fff202f,0x6ffff81f,0x3ffff200,0xffffffff,0x3fa0ffff,
0x8000ffff,0x801ffff8,0xfbafffff,0x0000ffff,0x1fffffe0,0x00ffffff,
0xffd30000,0xffffffff,0x5fffffff,0xfffb1000,0xffffffff,0xffffffff,
0x7ffdc01b,0xffffffff,0x3a206fff,0xffffffff,0x401fffff,0x440ffffd,
0x2004ffff,0xfffffff8,0xffffffff,0x7fffff41,0xfffc8000,0xffff7006,
0x07ffffff,0xffff8000,0x7ffffc7f,0x20000007,0xfffffffc,0xdfffffff,
0x7f5c0000,0xffffffff,0x1dffffff,0xfffff700,0x9fffffff,0xffffd300,
0x1bffffff,0x0dffff00,0x007ffff5,0xfffffd88,0x1fffffff,0x0fffffe8,
0x7fffc400,0x3fff2001,0x004fffff,0xfffff800,0x3fffffc7,0x26000000,
0xffffffdc,0x0002ceff,0x7fffe4c0,0xadffffff,0xffc88000,0x1dffffff,
0x7fffdc00,0x1003efff,0xf709ffff,0x20003fff,0xffffffea,0xffd00bef,
0xc8001fff,0xa8006fff,0x02effffd,0x99990000,0xccccc899,0x00000004,
0x0055d4c4,0x53100000,0x00033577,0x1aba9880,0xaba98000,0xccc98001,
0x4ccca82c,0xba988000,0x0000019a,0x00266660,0x00003100,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x5cc00000,0xabceeeed,0x2e600000,0x01bceeec,0x2aaaaa00,
0x20000002,0x000ffffa,0x2aaaaa00,0x0dd4c002,0x0ffffe00,0x1ab98000,
0xba880000,0x00abceed,0x55d44000,0x654c0001,0x400abdee,0xfffffffb,
0x00dfffff,0x3fff2200,0x0dffffff,0x7fffc400,0x0000006f,0x001bfff2,
0xffffff00,0xffffd500,0xfb005dff,0x44000bff,0xffffffec,0x7e40002e,
0xffffffff,0x20000dff,0xffffffda,0xffd8003f,0x05ffffff,0xffffffd3,
0xffffffff,0xf980019f,0xffffffff,0x2001ffff,0x06fffff8,0x3fa00000,
0x400004ff,0x407fffff,0xfffffffb,0x7dc04fff,0xf30007ff,0xffffffff,
0xd30009ff,0xffffffff,0x07ffffff,0xfffff900,0x03dfffff,0x3fffff60,
0xf984ffff,0xffffffff,0xffffffff,0x3fa2005f,0xffffffff,0x000fffff,
0x0dfffff1,0x3e200000,0x00002fff,0x03fffffc,0xfffffffb,0x01bfffff,
0x003fffe6,0xffffff50,0xdfffffff,0x3ffee001,0xffffffff,0x0effffff,
0xffffe880,0xffffffff,0x7ffe400f,0x2fffffff,0xffffffe8,0xffffffff,
0x003fffff,0xbffffff9,0xfffffd77,0x3ffe2009,0x000006ff,0x01ffff50,
0xffff8000,0xffff907f,0xffffffff,0x7ffc09ff,0x3fe6002f,0xffffffff,
0x805fffff,0xfffffffe,0xffffffff,0x4406ffff,0xffffffff,0x6fffffff,
0x7fffff40,0x4c0fedff,0xdfffffff,0xfffcbaab,0x801fffff,0x82fffffe,
0x007ffffd,0x0dfffff1,0x3f200000,0x800007ff,0x887fffff,0xcfffffff,
0xfffffffc,0x09fffb01,0x7ffffec0,0xffffdbef,0x3ee02fff,0xefffffff,
0xffffeccd,0x3604ffff,0xbeffffff,0xfffffffc,0x3ffffe02,0xfffc803f,
0x36200dff,0x03ffffff,0x06fffff8,0x01fffff3,0xdfffff10,0x3a000000,
0x00005fff,0x87fffff8,0x86fffffc,0x05fffffd,0x200dfff7,0x1ffffff8,
0x7fffff44,0xfffff105,0x36601bff,0x1fffffff,0xffffff98,0xfffffc83,
0xfffff104,0xfffd001f,0xfd1003ff,0xf00bffff,0x220fffff,0x801fffff,
0x06fffff8,0xff880000,0x800003ff,0xf87fffff,0x882fffff,0x307fffff,
0x7001ffff,0x207fffff,0x06fffffb,0x7ffffff9,0x3ffff600,0xfffd84ff,
0xfff104ff,0x3fe20fff,0xf8807fff,0x2006ffff,0x07fffffb,0x3fffffd8,
0x06ffffb8,0xdfffff10,0x980000c0,0x8001ffff,0x3fffe018,0x7fffcc7f,
0x3fff606f,0xffff02ff,0xffff9005,0x3ffe201f,0xfff987ff,0x74003fff,
0x447fffff,0x01ffffff,0x02af37b6,0x1bffffe2,0x3ffffe20,0xddd3002f,
0xfb80199b,0x2e1fffff,0x004fffff,0x4dfffff1,0xcefffec8,0xfff70002,
0x7f6d400f,0x3fe0cdff,0x7fdc7fff,0x3ee04fff,0xfd04ffff,0x4c4009ff,
0x7fffc03a,0xffffe85f,0x7dc000ff,0x2a0bdfff,0x005fffff,0x7ff77540,
0xeeeeffff,0xffffff81,0x4000001e,0xfffffff8,0xffffffc8,0xffff1001,
0x3fffeadf,0x004fffff,0x805fffd8,0xffffffd8,0xffff1fff,0xffffc8ff,
0x3ffea03f,0xfff905ff,0xf300000d,0xff07ffff,0x0007ffff,0x7dc01591,
0x0004ffff,0x7fffffdc,0x2fffffff,0xffffffd8,0x00000bef,0xffffff50,
0x7fffffff,0x7fffc400,0xfffffbff,0x0effffff,0x0ffffe00,0xfffffd30,
0xf7ffffff,0xfe8fffff,0x2602ffff,0x506fffff,0x0001ffff,0x7ffff440,
0x7fffc40f,0x000000ff,0x0ffffff6,0x3ee00351,0xffffffff,0xfa82ffff,
0xffffffff,0x0000acef,0x3fffff60,0x04ffffff,0x7ffffc40,0xffffffff,
0x05ffffff,0x03ffff30,0xffffffe8,0xffffffff,0x7fc7ffff,0x2201ffff,
0x107fffff,0x0005ffff,0xffffb988,0xfffa84ff,0x000007ff,0x97fffff4,
0x2efffffc,0x3ffffee0,0xffffffff,0xfffff902,0xffffffff,0x8800017b,
0xffffffff,0xf88002ff,0xffffffff,0xffffdbbc,0xfb802fff,0x7fdc07ff,
0xbbcfffff,0xfffffffd,0x7ffffc7f,0x3ffe201f,0xffd00fff,0xff80009f,
0x03ffffff,0x0dfffff7,0xfff80000,0xfffeafff,0x80dfffff,0xfffffffb,
0x02ffffff,0x3ffffffa,0xffffffff,0xe98001df,0xffffffff,0xff10000e,
0x01dfffff,0xdffffff3,0x0bfffb00,0xeffffff8,0xffffe981,0x7fffc7ff,
0x3fe201ff,0xf900ffff,0x44000dff,0x2fffffff,0x3fffff20,0x7c000006,
0xffffffff,0xffffffff,0x3ffe200e,0x6c4006ff,0xffffffff,0xffffffff,
0x3fff2001,0xffffffff,0xfff10001,0x4c01ffff,0x02ffffff,0x701ffffc,
0x01ffffff,0x7fffffcc,0x3ffffe27,0x3ffe200f,0xff500fff,0x7cc000ff,
0x0bffffff,0xbfffffb0,0x7c400000,0xffffffff,0xffffffff,0x3ffe205f,
0xd30006ff,0xffffffff,0x5fffffff,0xfffffb00,0xdfffffff,0x3ffe2000,
0xfe804fff,0x2604ffff,0x3201ffff,0x804fffff,0x27fffffd,0x0ffffff8,
0x3ffffe20,0xffff101f,0x3fea0003,0x3fffffff,0x4fffffe8,0x3e200000,
0xefffffff,0xffffb98a,0xfff102ff,0x98000dff,0xffffffeb,0x3fffffff,
0x3fffff60,0xfffffeff,0x05677c5f,0x7fffffc4,0xffffa800,0x3ffee05f,
0x7fffec07,0xfffa801f,0x3ffe27ff,0x3e200fff,0x200fffff,0x0003fffe,
0xfffb7797,0xffd89fff,0x00005fff,0x3ffffe20,0xfff505ff,0x3fe20fff,
0x00006fff,0x3ffff6e2,0x0fffffff,0xffffffb8,0xfffff89f,0xffff53ff,
0xffff889f,0xfff3007f,0x7fec0dff,0x7fffc06f,0xff9800ff,0x3fe27fff,
0x2201ffff,0x00ffffff,0x0017fff2,0xfffff980,0x3ffff21f,0x4000006f,
0x1fffffff,0x3fffff60,0xfffff881,0x26000006,0xfffffffb,0x7fffc43f,
0x3fe60eff,0xfd9fffff,0x7c41ffff,0x3007ffff,0x40ffffff,0x7c04ffff,
0x1007ffff,0xf8ffffff,0x201fffff,0x0ffffff8,0x01fffea0,0xffff5000,
0x7fffdcdf,0x4000007f,0x06ffffff,0x17ffffd4,0x37ffffc4,0x64400000,
0x46ffffff,0x07fffffc,0xdffffff7,0x10ffffff,0x00dfffff,0x1fffffe2,
0x017fffc4,0x0ffffff1,0x3fffffc0,0x07fffffe,0x7fffff88,0x0ffffc40,
0x3ffe0000,0xfff50fff,0x54000fff,0x7ffffc00,0x7ffcc05f,0xfff884ff,
0x554406ff,0xd8005dcb,0x6c7fffff,0x204fffff,0xfffffffc,0xf884ffff,
0x1007ffff,0x20ffffff,0x400ffffa,0x007fffff,0x8ffffff1,0x02fffffe,
0x1bffffe6,0x00ffffe0,0xffffb000,0x3fffe25f,0xf88001ff,0xffe81bef,
0x7c404fff,0xf885ffff,0x4c06ffff,0x00ffffff,0x7ffffd40,0x7fffffc7,
0x7ffff402,0x81ffffff,0x07fffff8,0xdfffff30,0x01bfff20,0x03fffffe,
0x3ffffe60,0x7ffffec7,0x3fffea03,0xfffd805f,0x7ec00005,0x3fe3ffff,
0x8005ffff,0x1efffffa,0x17fffff2,0xbfffff10,0xdfffff10,0xffffff00,
0xfffa8007,0x7fffc7ff,0x7fc400ff,0x4fffffff,0xffffff10,0xffff5003,
0x3fffa0bf,0xffffd804,0xfffa801f,0x7ffe47ff,0x3fee04ff,0xfb804fff,
0xcca887ff,0xffe804fe,0x3ff62fff,0x4001ffff,0x47fffffe,0x06fffffb,
0x27ffffcc,0x37ffffc4,0x7ffffec0,0x3ff6000f,0x7ff46fff,0xf9802fff,
0x1fffffff,0xffffff10,0xffffb009,0xffff109f,0xffff9005,0xfffb009f,
0xfffa8fff,0x3ff606ff,0xf9802fff,0x7fc41fff,0x7c406fff,0x220fffff,
0x05ffffff,0x3fffff20,0x7fffc43f,0x3fea01ff,0xff882fff,0xfa806fff,
0x005fffff,0xbffffff7,0x5fffffd8,0xffffe980,0xf881efff,0x01ffffff,
0x3fffffe6,0x0ffffa82,0xfffffb80,0x3ffe600f,0xfff87fff,0xff982fff,
0x3e007fff,0xffe83fff,0x3f202fff,0xfb87ffff,0x00efffff,0x7fffffd4,
0xffffe80f,0x3fffa05f,0xfff881ff,0xff8806ff,0x0affffff,0xfffffd98,
0x7ffdc1ff,0x3f204fff,0xffffffff,0x7ffc42ff,0x881fffff,0x06fffffe,
0x200dfff9,0xeffffff8,0xffffe880,0xfffd87ff,0xfffe86ff,0x3f6005ff,
0xfffb85ff,0xffb82fff,0xfd04ffff,0x37ffffff,0x7fffecc4,0xff705fff,
0xf709ffff,0x220dffff,0x006fffff,0xfffffff5,0xfffddfff,0x0dffffff,
0x3ffffffa,0xfffdcbce,0xffffffff,0xff10dfff,0x9fffffff,0xfffff755,
0x3ffa05ff,0x3fee004f,0xaacfffff,0xfffffffc,0xffff987f,0xfffccfff,
0x2001ffff,0xf887fffb,0xcfffffff,0xffffffec,0xffff500e,0xffffffff,
0xffffffff,0x7fff401d,0xfeccefff,0x102fffff,0x00dfffff,0x7fffffe4,
0xffffffff,0x00ffffff,0xfffffff3,0xffffffff,0xffffffff,0x3fe29fff,
0xffffffff,0xffffffff,0xffff105f,0xfffe8005,0xffffffff,0x7fffffff,
0xffffff90,0xffffffff,0xfff98009,0xffffa80f,0xffffffff,0x5c01ffff,
0xffffffff,0xffffffff,0x7cc00fff,0xffffffff,0x05ffffff,0x1bffffe2,
0xfffffb00,0xffffffff,0x803fffff,0xfffffffa,0xffffffff,0xfffffbcf,
0xffff10ef,0xfffff97f,0x3dffffff,0x03fffea0,0xfffff300,0x7fffffff,
0x40fffff9,0xfffffffd,0x00efffff,0x02ffff80,0xfffffff9,0x7fffffff,
0x3fffa600,0xffffffff,0x001fffff,0xfffffff3,0x1dffffff,0x7ffffc40,
0xffea8006,0xffffffff,0x000dffff,0xffffffb1,0x3dffffff,0x07ffff44,
0x27fffff1,0xfffffffb,0x3f200dff,0xd10007ff,0xffffffff,0x3ffff25f,
0x7fffdc07,0x04ffffff,0x13fff600,0xffffffb8,0x01efffff,0xfffffc80,
0xffffffff,0x7f44000c,0xffffffff,0xfff8804f,0x2e0006ff,0xfffffffe,
0x0002dfff,0xffffffd7,0x7dc07dff,0x7fffc42f,0x3fff6a3f,0xfe803eff,
0x640005ff,0x1dfffffe,0x01fffff2,0x3fffff6a,0x5c0002ef,0x64406fff,
0xffffffff,0x76540003,0xffffffff,0x7640000c,0x2effffff,0xfffff100,
0x2660000d,0x001aabca,0x55dd4400,0x000e6000,0x8002aa60,0x0001cccc,
0x00035510,0x00dd4c00,0x99993000,0x4ddd4400,0x53000000,0x00001357,
0x0006ae60,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x2aaaa000,0xaa8001aa,0x5550aaaa,
0x00000555,0x55300330,0x55555555,0x55555555,0x55415555,0x001aaaaa,
0x2aaaaaa0,0x2aaaaa0a,0x544001aa,0x542aaaaa,0x001aaaaa,0x2aaaaaaa,
0x2aaaa001,0x2aaaa0aa,0x4c0002aa,0x542aaaaa,0x0002aaaa,0x7fffffd0,
0xffff8800,0xffffd0ff,0x2000001f,0xfc803fc8,0xffffffff,0xffffffff,
0x2e1fffff,0x06ffffff,0xfffff700,0xffffa8bf,0x7e4006ff,0x644fffff,
0x006fffff,0xfffffff1,0x3ffe600d,0x3ff60fff,0x0000ffff,0x1bfffffa,
0x00ffffff,0x3ffffa00,0x7fc4003f,0xffd0ffff,0x00001fff,0x007fff70,
0xfffffff9,0xffffffff,0x3fffffff,0xffffffe8,0x7ffc4003,0xfd80ffff,
0x004fffff,0xfffffff3,0xfffffa81,0xffff5007,0x7001ffff,0xa8dfffff,
0x03ffffff,0xfffff100,0xfffff87f,0xffd00007,0x88007fff,0xd0ffffff,
0x001fffff,0x7fff4c00,0xfffc803f,0xffffffff,0xffffffff,0x7fcc1fff,
0x000fffff,0x3ffffff6,0xfffff103,0xffd003ff,0xf105ffff,0x003fffff,
0xfffffff9,0xfff9005f,0xffff09ff,0x2e000dff,0x40ffffff,0x007fffff,
0xfffffd00,0xfff88007,0xfffd0fff,0x400001ff,0x03fffffc,0xffffffc8,
0xffffffff,0xffffffff,0xfffffc81,0xfff3004f,0xfb80dfff,0x406fffff,
0x5ffffffb,0x3fffffe0,0xffffe803,0xe804ffff,0xc82fffff,0x00ffffff,
0xfffffd80,0x7fffff86,0xfffd0000,0xf88007ff,0xfd0fffff,0x0001ffff,
0x7ffffe40,0xffffc803,0xffffffff,0xffffffff,0xffe881ff,0xe801ffff,
0x01ffffff,0xffffffe8,0xfffff103,0x7fec01ff,0x7c405fff,0xffffffff,
0x7fffc406,0xfff980ff,0x44003fff,0x83ffffff,0x007fffff,0xfffffd00,
0xfff88007,0xfffd0fff,0x400001ff,0x03fffffc,0x3fee0000,0x203fffff,
0x6ffffffa,0x7ffffd40,0xfff3004f,0xfb01ffff,0x807fffff,0x06fffffb,
0x7fffffdc,0x2600ffff,0x207fffff,0x06fffffe,0x7ffffdc0,0xfffff80f,
0xffd00007,0x88007fff,0xd0ffffff,0x001fffff,0x7fffe400,0x5000003f,
0xbfffffff,0xfffffb00,0x3ffe207f,0x5c006fff,0x45ffffff,0x6ffffffa,
0xfffff980,0x3fff600f,0x2fffffff,0x3ffffee0,0x3ffff205,0x3f6001ff,
0xff05ffff,0x0000ffff,0x0ffffffa,0xfffff100,0x3ffffa1f,0x3001100f,
0xffffffdd,0x0007dddd,0xffffff10,0x3fe200df,0xc80fffff,0x02ffffff,
0xfffffe80,0x3ffffa1f,0xfff000ff,0x7fc05fff,0xffffffff,0x3fff604f,
0x3fe603ff,0x1003ffff,0x05ffffff,0x01fffffe,0x7ffff400,0x7fc4003f,
0xffd0ffff,0x76d41fff,0xa80cdfff,0xffffffff,0x0004ffff,0x7fffff44,
0x3ee000ff,0x444fffff,0x05ffffff,0xfffff300,0x3fffeedf,0x3f6003ff,
0xf303ffff,0xfff7ffff,0x7ffc0dff,0x7f401fff,0x5006ffff,0x01ffffff,
0x81fffffe,0xdeeeeee9,0x3fffffa0,0x7ffc4003,0xfffd0fff,0xfffb11ff,
0x83dfffff,0xfffffffa,0x004fffff,0x7ffffec0,0xfe8001ff,0x361fffff,
0x00ffffff,0x3ffff200,0xfffffdff,0x7fdc006f,0xff705fff,0xfffb3fff,
0xfff101ff,0xff700fff,0xb003ffff,0x40bfffff,0x107fffff,0x3fffffff,
0x3fffffe8,0x7fffc400,0xffffd0ff,0xfffffd5f,0x43ffffff,0xfffffffa,
0x004fffff,0x3ffffee0,0xf30003ff,0x2adfffff,0x02ffffff,0x7fff4400,
0xffffffff,0x7fcc001f,0xffb07fff,0x3ffeefff,0xfffa82ff,0xff8805ff,
0x4404ffff,0x02ffffff,0x21fffffe,0xffffffe8,0xfffffe82,0x7ffc4003,
0xfffd0fff,0xffffffff,0xbfffffff,0x7fffffd4,0x04ffffff,0xfffff500,
0xc80009ff,0xeaffffff,0x005fffff,0xfffff500,0x09ffffff,0x3ffffe00,
0xfffff81f,0x9fffff35,0x7fffff90,0x3ffff600,0x7ffd406f,0x7ffc07ff,
0xfffe87ff,0xffd02fff,0x88007fff,0xd0ffffff,0xffffffff,0xffffb77b,
0xff903fff,0x00007fff,0xfffffff1,0x3fa0000d,0xffffffff,0x00000fff,
0x3ffffff6,0x0000efff,0x85fffffd,0x23fffff9,0xd86fffff,0x001fffff,
0x3ffffff5,0x7ffffec0,0x7ffffc04,0x7ffffec7,0x3fffa03f,0x7c4003ff,
0xfd0fffff,0x01ffffff,0x9ffffff3,0x7fffff90,0xffe88000,0x000fffff,
0xfffff300,0x07ffffff,0xfff88000,0x02ffffff,0x3ffff200,0x7fffdc4f,
0x3ffff20f,0x7ffffc0f,0x3ffe2007,0xff104fff,0xf803ffff,0x3f27ffff,
0x403fffff,0x03fffffe,0x7ffffc40,0xfffffd0f,0x7ffe403f,0xfffc85ff,
0x6c0003ff,0x1fffffff,0x7fec0000,0x6fffffff,0xff700000,0x00bfffff,
0xfffffa80,0x37ffff46,0x8bffffea,0x05fffff9,0x7ffffec0,0xfffff507,
0xfffff00d,0x3ffffeef,0xfffe804f,0x7c4003ff,0xfd0fffff,0xa809ffff,
0xc85fffff,0x003fffff,0x3fffff20,0x800002ff,0xfffffff8,0x000001ff,
0xfffffffd,0xff88000d,0x3fe27fff,0x7fc44fff,0x3fee4fff,0x54003fff,
0x81ffffff,0x03fffffd,0xaffffff8,0x04ffffff,0x7fffffd0,0xffff8800,
0xffffd0ff,0xfff9805f,0xfffc86ff,0xf50003ff,0x09ffffff,0x7fd40000,
0x004fffff,0xffff7000,0x007fffff,0xfffffe80,0x5fffff51,0x4dffffd0,
0x01fffffc,0xffffff80,0xffffff84,0xfffff800,0x6fffffff,0x3ffffa00,
0x7fc4003f,0xffd0ffff,0xf9803fff,0xfc86ffff,0x8003ffff,0xfffffff9,
0xd8000005,0x00ffffff,0xfff88000,0xffffffff,0x3ff20001,0xfff93fff,
0xfff901ff,0x3fffa1ff,0xfc8000ff,0x7d47ffff,0xf006ffff,0xffffffff,
0x2001ffff,0x03fffffd,0x7ffffc40,0xfffffd0f,0xffff9803,0xffffc86f,
0x7f44003f,0x00efffff,0xffc80000,0x00005fff,0xffffffd0,0x00dfffff,
0x7ffffd40,0x0dffffd5,0x2bffffea,0x06fffff8,0xfffff300,0x7fffec3f,
0xffff003f,0xffffffff,0x3ff600bf,0x4c003fff,0xd0ffffff,0x801fffff,
0x86fffff8,0x03fffffc,0x7ffffec0,0x000001ff,0xbfffff90,0xff700000,
0xffffffff,0x20007fff,0x8efffff8,0x104fffff,0xf39fffff,0x0009ffff,
0x27fffff4,0x01ffffff,0x3fffffe0,0xffffffff,0xffffd802,0x7fcc004f,
0xffd0ffff,0xf8801fff,0xfc86ffff,0x2003ffff,0xfffffffc,0x20000002,
0x05fffffc,0x7ffc4000,0xfffbffff,0x0001ffff,0xf7ffffff,0x7405ffff,
0xffbeffff,0x20002fff,0x57fffffc,0x00bfffff,0x7ffffffc,0x6fffffff,
0xfffffc80,0x7ffd4005,0x3fffa7ff,0x7fc400ff,0xffc86fff,0xf5003fff,
0x07ffffff,0xfc800000,0x0005ffff,0x7ffffec0,0xfffff75f,0x3f6000df,
0xffffffff,0x3ff200ff,0xffffefff,0x3e60000f,0xfcafffff,0x2002ffff,
0xffffffff,0x3fffffe8,0x7ffffdc0,0x3ff2000f,0x3ffa6fff,0x7c400fff,
0xfc86ffff,0x9803ffff,0x5fffffff,0xc8000000,0x005fffff,0x3fffea00,
0x3ffa0fff,0x8003ffff,0xfffffffb,0x7cc06fff,0xffffffff,0xfe80006f,
0xfffdffff,0x3e000fff,0x30ffffff,0x01ffffff,0x7fffffd4,0xffff1005,
0x7fff4bff,0x7fc400ff,0xffb86fff,0x74403fff,0x0effffff,0xc8000000,
0x005fffff,0xfffff100,0xfff987ff,0x4001ffff,0xfffffff9,0xff803fff,
0xffffffff,0xffb80004,0xffffffff,0x7ffc005f,0x7fec1fff,0x3e204fff,
0x02ffffff,0xffffffd8,0x3fffffa3,0x7fffc400,0xffffb86f,0x7ffec04f,
0x0000ffff,0xfff90000,0x20000bff,0x5ffffffd,0xffffff90,0xffff000d,
0x03ffffff,0xffffffb0,0x00005fff,0xfffffff1,0x8005ffff,0x887fffff,
0x01ffffff,0x3ffffff2,0xffda81cf,0x7f47ffff,0x4400ffff,0xb86fffff,
0xcdffffff,0x3fffee4e,0x9999bfff,0x99999999,0x00019999,0x0bfffff9,
0xffff5000,0x3a201fff,0x03ffffff,0x7ffffec0,0xf7007fff,0xffffffff,
0x3f600001,0xffffffff,0xffff8007,0xffff907f,0x7ffc40bf,0xffffffff,
0xffffffff,0x7fff43ff,0x7fc400ff,0xff986fff,0x5fffffff,0x3fffffee,
0xffffffff,0xffffffff,0xf90007ff,0x000bffff,0xffffff88,0x7ffd403f,
0x2001ffff,0xfffffffb,0xfff3005f,0x00dfffff,0x7fffd400,0x004fffff,
0x07fffff8,0x5ffffff1,0x7ffffe40,0xffffffff,0x87ffffff,0x00fffffe,
0x37ffffc4,0xffffffe8,0x3ffee6ff,0xffffffff,0xffffffff,0x007fffff,
0xbfffff90,0xfffd8000,0xfb006fff,0x00dfffff,0x7fffffcc,0x3fe003ff,
0x05ffffff,0x3ffe2000,0x01ffffff,0x7fffff80,0x3ffffee0,0x7fffdc06,
0xffffffff,0x81efffff,0x00fffffe,0x37ffffc4,0xffffffb8,0x3ffee7ff,
0xffffffff,0xffffffff,0x007fffff,0xbfffff90,0x7ffd4000,0x1001ffff,
0x7fffffff,0x3fffe200,0x2001ffff,0xfffffffd,0x7ec00003,0x06ffffff,
0xffffff00,0xfffffe80,0x7fff4c03,0xffffffff,0x3fa04fff,0x4400ffff,
0x206fffff,0xeffffffa,0x3ffffee5,0xffffffff,0xffffffff,0x90007fff,
0x00bfffff,0x3ffffe20,0x7d4004ff,0x01ffffff,0xffffffd0,0xfffb800f,
0x0001ffff,0x7ffffd40,0xff0003ff,0xfa80ffff,0x400fffff,0xfffffec8,
0x01dfffff,0x07fffff4,0x3ffffe20,0x09ba9806,0xffffffb8,0xffffffff,
0xffffffff,0xf90007ff,0x000bffff,0x3ffffff2,0xfffb0006,0x3200dfff,
0x05ffffff,0x7ffffcc0,0xf000007f,0x03ffffff,0x3ffffe00,0xffffe807,
0x2aa2004f,0x001aabba,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x80000000,0xaaaaaaaa,0x9aaaaaaa,
0xaaa80019,0x55550aaa,0x55555555,0x20013355,0xaaaaaaaa,0xaaaaaaaa,
0x531aaaaa,0x00035555,0x21555553,0xaaaaaaaa,0x5554001a,0x10aaaaaa,
0x00133333,0x2aaaa600,0xaa98001a,0x541aaaaa,0x2a0aaaaa,0x360aaaaa,
0x2a0eeeee,0xaaaaaaaa,0xaaaaaaaa,0x2aaaaaaa,0xfffffffb,0xffffffff,
0x0019dfff,0x21fffffd,0xfffffffe,0xffffffff,0x3f601cff,0xffffffff,
0xffffffff,0xfffb5fff,0xfb000dff,0x3fa1ffff,0x6fffffff,0x3fffe600,
0xf92fffff,0x000bffff,0x3fffff60,0x7ffd4004,0x7c0fffff,0x3e3fffff,
0x3a2fffff,0x3e0fffff,0xffffffff,0xffffffff,0x6fffffff,0xfffffffb,
0xffffffff,0x09ffffff,0x0fffffe8,0xfffffffd,0xffffffff,0x3609ffff,
0xffffffff,0xffffffff,0xffb5ffff,0x8009ffff,0xd0fffffd,0xffffffff,
0x3ff2001f,0x2fffffff,0x0bfffff9,0x3fff6000,0x3ea004ff,0x0fffffff,
0x3ffffff8,0x8bfffffe,0x20fffffe,0xffffffff,0xffffffff,0xffffffff,
0xffffffb6,0xffffffff,0xffffffff,0x7ffff409,0xfffffd0f,0xffffffff,
0xbfffffff,0xffffffb0,0xffffffff,0x2bffffff,0xfffffffd,0x3fff6001,
0xffffd0ff,0x005fffff,0x3ffffffa,0xfff92fff,0x20000bff,0x04fffffd,
0xffffff30,0x3ffe03ff,0x3ffe3fff,0x3ffa2fff,0x3ffe0fff,0xffffffff,
0xffffffff,0xfb6fffff,0xffffffff,0xffffffff,0x07ffffff,0x43fffffa,
0xfffffffe,0xffffffff,0x44ffffff,0xfffffffd,0xffffffff,0xfb5fffff,
0x0bffffff,0x7ffffec0,0xffffffd0,0xf1009fff,0xffffffff,0x3ffff25f,
0xfb00005f,0x3009ffff,0xffffffff,0x7ffffc03,0x3ffffe3f,0x3ffffa2f,
0x3ffffe0f,0xffffffff,0xffffffff,0xfffb6fff,0xffffffff,0xffffffff,
0x3a0fffff,0xfd0fffff,0xffffffff,0xffffffff,0x6c1fffff,0xffffffff,
0xffffffff,0xffb5ffff,0x05ffffff,0x3fffff60,0xffffffd0,0xf500dfff,
0xffffffff,0x3ffff25f,0xfb00005f,0x8809ffff,0xffffffff,0x7ffffc01,
0x3ffffe3f,0x3ffffa2f,0x3ffffe0f,0xffffffff,0xffffffff,0xfffb6fff,
0x366009ff,0x2fffffff,0x0fffffe8,0x07fffffd,0xfffffea8,0x3fff64ff,
0xd80004ff,0xffffffff,0xfffd800f,0xffffd0ff,0x01ffffff,0xffffffc8,
0xff92ffff,0x0000bfff,0x13fffff6,0xfffffe88,0xfff801ff,0x3ffe3fff,
0x26622fff,0xfd800199,0x2004ffff,0x04fffffd,0x7ffffdc0,0xffffe84f,
0xfffffd0f,0x3ffee007,0x3ff66fff,0x80004fff,0xfffffffd,0xffd804ff,
0xfffd0fff,0x5fffffff,0xfffffe80,0xf92fffff,0x000bffff,0x3fffff60,
0xffffd104,0x3e005fff,0x3e3fffff,0x002fffff,0xffffd800,0x3ff6004f,
0x44004fff,0x85ffffff,0xd0fffffe,0x007fffff,0x3ffffffc,0x09fffffb,
0xffffb000,0x03ffffff,0x0fffffd8,0xfbfffffd,0x7c409fff,0xfffdffff,
0xffff92ff,0x360000bf,0xb04fffff,0x5fffffff,0x7ffffc00,0x3ffffe2f,
0xd800002f,0x004fffff,0x13fffff6,0x3ffff600,0xffffe86f,0xfffffd0f,
0x7ffe4007,0xfffb0fff,0xb00009ff,0xffffffff,0xffd80dff,0xfffd0fff,
0xfffff7ff,0x7ffffd40,0x92fffffb,0x00bfffff,0x3ffff600,0xffffd84f,
0x74002fff,0x3e1fffff,0x002fffff,0xffffd800,0x3ff6004f,0xe8004fff,
0xe85fffff,0xfd0fffff,0x4007ffff,0x0ffffffa,0x09fffffb,0xffffb000,
0x7fffffff,0x7ffffec0,0x3fffffd0,0x203fffff,0xfbdffffc,0xff92ffff,
0x0000bfff,0x13fffff6,0xfffffff9,0xfffd0005,0x7fffc3ff,0x800002ff,
0x04fffffd,0x3fffff60,0x7ffc4004,0xffe84fff,0xfffd0fff,0x7e4007ff,
0x3f67ffff,0x0004ffff,0xffffffd8,0x00ffffff,0x21fffffb,0xff7ffffe,
0x3fa07fff,0xfffbbfff,0xffff92ff,0x360000bf,0x324fffff,0x3fffffff,
0xffffb000,0x7ffffc1f,0xd800002f,0x004fffff,0x13fffff6,0xfffffb00,
0xffffd05f,0x3ffffa1f,0x3ffe003f,0x3ff65fff,0x80004fff,0xfafffffd,
0xb05fffff,0x3a1fffff,0xffb7ffff,0xfff10bff,0xffff73ff,0x3ffff25f,
0xfb00005f,0x3ee9ffff,0x03ffffff,0x3ffff200,0x7fffffc7,0xfd800002,
0x2004ffff,0x9cfffffd,0x99999999,0xffffffea,0xfffffd06,0x3fffffa1,
0xfffe8803,0x3ff63fff,0xccccefff,0xcccccccc,0x7ffffec2,0xffffffc8,
0xfffffd81,0x2fffffd0,0xa87ffffb,0xff77ffff,0x3ff25fff,0x00005fff,
0x59fffffb,0xffffffff,0x7fdc0009,0x7fffc7ff,0x800002ff,0x04fffffd,
0x3fffff60,0xffffffff,0xffffffff,0xfffd01ff,0x3fffa1ff,0x99999cff,
0xfffffca9,0x3ff62fff,0xffffffff,0xffffffff,0x7ffffec4,0xffffff88,
0xfffffd86,0x2fffffd0,0x41fffff9,0xf75ffffc,0x3f25ffff,0x0005ffff,
0xdfffffb0,0xffffffff,0x2a0003ff,0x7fc6ffff,0x0002ffff,0xfffffd80,
0x3fff6004,0xffffffff,0xffffffff,0x3fa03fff,0xffd0ffff,0xffffffff,
0xffffffff,0xffd8dfff,0xffffffff,0xffffffff,0x7ffffec4,0xffffff50,
0xfffffd87,0x4fffffd0,0x7c3fffff,0xff73ffff,0x3ff25fff,0x00005fff,
0xfffffffb,0xffffffff,0x3ea000df,0x7ffc5fff,0x00002fff,0x4fffffd8,
0x3ffff600,0xffffffff,0xffffffff,0x7fff401e,0xffffd0ff,0xffffffff,
0xffffffff,0xffffd81d,0xffffffff,0x44ffffff,0x20fffffd,0x0ffffffd,
0x43fffff6,0x367ffffe,0x3e65ffff,0xff71ffff,0x3ff25fff,0x00005fff,
0xfffffffb,0xffffffff,0xf30007ff,0xfff89fff,0x00002fff,0x4fffffd8,
0x3ffff600,0xffffffff,0x2cefffff,0xfffffd00,0x3fffffa1,0xffffffff,
0x1fffffff,0xffffffd8,0xffffffff,0x7ec4ffff,0x3e60ffff,0x365fffff,
0xfd0fffff,0x7fdcffff,0x3ffee7ff,0x3fffee7f,0xfffff92f,0x3f60000b,
0xffffffff,0xffffffcf,0x7fc4000f,0x7fffc4ff,0x3fffa2ff,0x7ec000ff,
0x2004ffff,0xeefffffd,0xffffffff,0x7f4001ef,0xffd0ffff,0xffffffff,
0xffffffff,0x3fff603b,0xccccceff,0x2ccccccc,0x07ffffec,0x3ffffff2,
0x1fffffb2,0x99fffffa,0xfb1fffff,0x7fdcbfff,0xfff92fff,0x20000bff,
0xfffffffd,0xffff73ff,0xff000bff,0xffff87ff,0x3fffa2ff,0x7ec000ff,
0x2004ffff,0x24fffffd,0xfffffc98,0x3fa002ff,0xffd0ffff,0xffffffff,
0x19dfffff,0xfffffd80,0xffd80004,0xffe80fff,0xfffb6fff,0x3fffa1ff,
0x7ffffc7f,0x47fffff4,0x92fffffb,0x00bfffff,0x3ffff600,0x7f44ffff,
0x003fffff,0x3e17fffc,0x3a2fffff,0x000fffff,0x27ffffec,0xfffffb00,
0x3fffe609,0xfd004fff,0x3fa1ffff,0x999cffff,0xfb000099,0x0009ffff,
0x1fffffb0,0xffffff50,0x1fffffb9,0xb1fffffa,0xff3dffff,0x7fdc3fff,
0xfff92fff,0x20000bff,0xfffffffd,0xfffffa84,0x3fa000ff,0x7fffc1ff,
0x3fffa2ff,0x7ec000ff,0x2004ffff,0x04fffffd,0x3fffffea,0xfffe804f,
0xffffd0ff,0xd800007f,0x004fffff,0xfffffd80,0xfffffb00,0x1fffffdf,
0x71fffffa,0xff9fffff,0xfffb8fff,0xffff92ff,0x360000bf,0x04ffffff,
0x3ffffff6,0x3fff6005,0x7fffffc1,0x3fffffa2,0x7ffec000,0x3f6004ff,
0x6404ffff,0x2fffffff,0x7fffff40,0x7fffffd0,0xffd80000,0x80004fff,
0x00fffffd,0xfffffff1,0x3a1fffff,0x7cc7ffff,0xffffffff,0x7fffdc5f,
0xfffff92f,0x3f60000b,0x4c05ffff,0x2fffffff,0x81fff900,0x22ffffff,
0x007ffffe,0x4fffffd8,0x3ffff600,0xfffe804f,0x3a00ffff,0xfd0fffff,
0x0007ffff,0xfffffd80,0xffd80004,0x3ee00fff,0xffffffff,0xffffd0ff,
0xffffff0f,0xfb87ffff,0xff92ffff,0x0000bfff,0x13fffff6,0x3fffff20,
0xffb800ff,0xffffff87,0x006ff882,0x4fffffd8,0x3ffff600,0xfff9804f,
0x3a05ffff,0xfd0fffff,0x0007ffff,0xfffffd80,0xffd80004,0x7f400fff,
0xffffffff,0xfffffd0f,0xffffffb0,0xffb83fff,0xfff92fff,0x20000bff,
0x04fffffd,0xffffff88,0xff80005f,0xfa82ffff,0xffd8006f,0x36004fff,
0x004fffff,0xfffffff7,0x3ffffa05,0xfffffd0f,0xfd800007,0x0004ffff,
0x0fffffd8,0x7ffffcc0,0xfd0fffff,0xff70ffff,0x0fffffff,0x25fffff7,
0x05fffffc,0xffffb000,0x3fee009f,0x002fffff,0x7fffffc0,0x004ffc82,
0x4fffffd8,0x3ffff600,0x3ffa004f,0xe80fffff,0xfd0fffff,0x0007ffff,
0xfffffd80,0xffd80004,0xfc800fff,0xffffffff,0x0fffffd0,0xfffffff3,
0xffff70bf,0x3ffff25f,0x999999df,0x99999999,0xfffffb09,0x7fff4009,
0xfb00ffff,0x7fc3ffff,0x3622ffff,0xd8000fff,0x004fffff,0x13fffff6,
0xfffff880,0xfffe84ff,0xffffd0ff,0xd800007f,0x004fffff,0xfffffd80,
0xffff8800,0xfd0fffff,0x3fe0ffff,0x83ffffff,0x92fffffb,0xffffffff,
0xffffffff,0x367fffff,0x004fffff,0x3fffffe6,0xffffb04f,0x7ffffc3f,
0x5ffff12f,0x3fff6000,0x3f6004ff,0x4004ffff,0xfffffffb,0x7fffff41,
0x7fffffd0,0xffd80000,0x80004fff,0x00fffffd,0xffffff50,0x3fffa1ff,
0xffffb07f,0xff703fff,0x3ff25fff,0xffffffff,0xffffffff,0xfffb3fff,
0xfd8009ff,0x81ffffff,0x21fffffd,0x22ffffff,0x20002ffe,0x04fffffd,
0x3fffff60,0xfffe8004,0x7ff46fff,0xfffd0fff,0x800007ff,0x04fffffd,
0xffffd800,0x3ff6000f,0xfd0fffff,0x3ee0ffff,0x707fffff,0x325fffff,
0xffffffff,0xffffffff,0xfb3fffff,0x8009ffff,0xfffffff8,0xfffffd86,
0x3fffffe1,0x000032a2,0x09fffffb,0x7ffffec0,0xfff88004,0x3fa3ffff,
0xffd0ffff,0x00007fff,0x4fffffd8,0xfffd8000,0x3e6000ff,0xd0ffffff,
0x260fffff,0x05ffffff,0x25fffff7,0xfffffffc,0xffffffff,0xb3ffffff,
0x009fffff,0xffffff90,0xffffd89f,0x3ffffe1f,0xd800002f,0x004fffff,
0x13fffff6,0x7fffdc00,0xfffd0fff,0x3fffa1ff,0x400003ff,0x04fffffd,
0xffffd800,0x7fe4000f,0xffd0ffff,0x7ffc0fff,0xff703fff,0x3ff25fff,
0xffffffff,0xffffffff,0xfffb3fff,0x3a0009ff,0x1fffffff,0x87fffff6,
0x02ffffff,0xfffd8000,0x000004ff,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x44000000,0x09accca9,
0xba988000,0x5555001a,0x55555555,0x55555555,0x55541555,0xaaaaaaaa,
0x00019aaa,0x3332a000,0x5555501c,0x55555555,0x00033555,0x55555400,
0x2a00002a,0xffffffff,0x4fffffff,0xccccb800,0x35555550,0x55555000,
0x7fec4015,0xefffffff,0x7fe44001,0x1effffff,0x3fffffa0,0xffffffff,
0xffffffff,0x3ffffa3f,0xffffffff,0x003effff,0x3ffe6000,0xfffb03ff,
0xffffffff,0x9fffffff,0x7c400003,0x01ffffff,0xffff7000,0xffffffff,
0x88009fff,0xfb1fffff,0x0009ffff,0x03ffffff,0xffffff91,0xbfffffff,
0xffff7001,0xffffffff,0xffffd019,0xffffffff,0xffffffff,0x7fff47ff,
0xffffffff,0xffffffff,0xfe800003,0xfb03ffff,0xffffffff,0xffffffff,
0x0000bfff,0x3fffffee,0xfb00005f,0xffffffff,0x09ffffff,0xfffffd80,
0x9fffffb1,0xfffff000,0xffffd03f,0xffffffff,0x5c01ffff,0xffffffff,
0x86ffffff,0xfffffffe,0xffffffff,0x3fffffff,0x3ffffffa,0xffffffff,
0x05ffffff,0x3fff2000,0xffb03fff,0xffffffff,0xffffffff,0x0000bfff,
0xfffffffd,0xfd00001f,0xffffffff,0x09ffffff,0x7ffffd40,0xfffffb1f,
0xffff0009,0xfffc83ff,0xffefffff,0x06ffffff,0xfffffff3,0xffffffff,
0xffffe89f,0xffffffff,0xffffffff,0x3fffa3ff,0xffffffff,0xffffffff,
0x980005ff,0x3fffffff,0xffffffb0,0xffffffff,0xffffffff,0x7fcc000b,
0x3fffffff,0x7ffc4000,0xffffffff,0x004fffff,0xfffffff5,0x3fffff63,
0xffff8004,0x3ffee1ff,0x5c42efff,0x45ffffff,0xfffffff8,0xfffffcdf,
0x3ffa1fff,0xffffffff,0xffffffff,0x3fa3ffff,0xffffffff,0xffffffff,
0x001fffff,0x3ffffa20,0xffb03fff,0xdddddfff,0xffffdddd,0x001fffff,
0x3fffff20,0x0006ffff,0x6fffffcc,0xcccccccc,0xffb802cc,0xb1ffffff,
0x009fffff,0x3ffffff0,0x27fffffc,0x3ffffe60,0x3fffea0f,0x7fd40bff,
0x3fa4ffff,0x0003ffff,0x7fffff40,0x3ff66203,0x006fffff,0x3fffff20,
0xffb03fff,0x2a009fff,0x2ffffffe,0xffff8800,0x1fffffff,0x3ffee000,
0x100000ff,0xfffffffb,0x3fff63ff,0xff8004ff,0xff31ffff,0x2e00dfff,
0x322fffff,0x204fffff,0x26fffffa,0x03fffffe,0x7fff4000,0xfb3003ff,
0x007fffff,0xffffff50,0x3f607fff,0x4004ffff,0x05fffffe,0xfffffa80,
0x05ffffff,0x3ffff200,0xfb880007,0xffffffff,0xffffb1ff,0xfff0009f,
0x3fee3fff,0xf3002fff,0x7f49ffff,0x7c00ffff,0x3fa7ffff,0x0003ffff,
0x7fffff40,0x3ffe2003,0x2000ffff,0xfffffff8,0xffb03fff,0xb8009fff,
0x006fffff,0xcfffffe8,0x00ffffff,0xdffffd00,0xfffa8000,0xffffffff,
0xffffb1ff,0xfff0009f,0x372a3fff,0x3e6007fe,0xfd15ffff,0xfd00ffff,
0x3fa1ffff,0x0003ffff,0x7fffff40,0x7ffdc003,0x36003fff,0xffffffff,
0xfffb03ff,0xf98009ff,0x4004ffff,0xd7fffff9,0x007fffff,0x13ffffe0,
0xffff7000,0xffffddff,0x3ffff63f,0xfff8004f,0x00201fff,0x3fffffb8,
0xf8805310,0x3fa7ffff,0x0003ffff,0x7fffff40,0xfffe8003,0xff5005ff,
0xffff7fff,0x3fff607f,0x7e4004ff,0x4002ffff,0x74fffffc,0x00dfffff,
0x7fffff10,0x159dfb73,0xfffffb80,0x3fffffb4,0x13fffff6,0x3ffffe00,
0xe880001f,0x000fffff,0x7ffffdc0,0x3fffffa5,0x7f400003,0x8003ffff,
0x07fffffc,0xafffff88,0x03fffffa,0x09fffffb,0xffffff80,0x7fffc000,
0xffff11ff,0xfa8003ff,0xffffffff,0x202fffff,0x362ffffb,0xfb1fffff,
0x0009ffff,0x03ffffff,0xfffe8800,0xe80006ff,0x3a4fffff,0x99cfffff,
0x99999999,0xfe819999,0x8003ffff,0x1ffffffa,0xaffffec0,0x03fffffa,
0x09fffffb,0xfffff710,0xffa800bf,0x7fec6fff,0x5c005fff,0xffffffff,
0x4fffffff,0xd817ff70,0xfb1fffff,0x0009ffff,0x03ffffff,0x7fff4c00,
0x40001fff,0x1ffffff9,0x3ffffffa,0xffffffff,0x1fffffff,0x1ffffff4,
0x7fffcc00,0x3fea01ff,0xfff50fff,0x3ff607ff,0xffffffff,0xffffffff,
0xd8004fff,0x543fffff,0x00ffffff,0x3fffff60,0xffffffff,0x02a84fff,
0x47fffff6,0xfffffffd,0xffffffff,0xffffffff,0xff50001f,0x007fffff,
0xfffff880,0x7ffff44f,0xffffffff,0xffffffff,0x7ffff41f,0xff88003f,
0xf102ffff,0x7d45ffff,0xfb03ffff,0xffffffff,0xffffffff,0x10007fff,
0x81ffffff,0x3ffffff8,0x3ffffe00,0xfffeffff,0x001fffff,0x8fffffec,
0xfffffffd,0xffffffff,0xffffffff,0xffa8001f,0x003fffff,0x7ffff440,
0x7fff40ff,0xffffffff,0xffffffff,0x7fff41ff,0xf88003ff,0xb02fffff,
0xfa8bffff,0xfb03ffff,0xffffffff,0xffffffff,0x70003dff,0x20bfffff,
0x06fffffd,0xffffff10,0xffffb819,0x7ec006ff,0xffb1ffff,0xffffffff,
0xffffffff,0x03ffffff,0xfffffa80,0x440002ff,0x3ffffffe,0xffffffe8,
0xffffffff,0x1fffffff,0x1ffffff4,0x7fffc400,0xfffb83ff,0x7ffd40ff,
0xfffb03ff,0xffffffff,0xffffffff,0x74003dff,0x502fffff,0x03ffffff,
0x5ffd9710,0x7ffffcc0,0x3ff6002f,0xfffb1fff,0xffffffff,0xffffffff,
0x003fffff,0x7fffffc4,0x7440002f,0x05ffffff,0xfffffffd,0xffffffff,
0x83ffffff,0x03fffffe,0xfffff880,0x7fffc42f,0xffffa82f,0xffffb03f,
0xffffffff,0xffffffff,0xf3003fff,0x401fffff,0x05ffffff,0x3ff60000,
0x36004fff,0xfb1fffff,0xffffffff,0xffffffff,0x3fffffff,0x7fffe400,
0x4c0001ff,0xefffffff,0xfffffd00,0x33333339,0x33333333,0x7fffffd0,
0xffff1000,0xfffd85ff,0xffff505f,0x3fff607f,0xaaaaadff,0xffecbaaa,
0x400fffff,0x05fffffc,0x7fffffe4,0xf5000000,0x400bffff,0xb1fffffd,
0x339fffff,0x33333333,0xffffff33,0x7ffec003,0x4c0001ff,0xefffffff,
0x3ffffa00,0x7400003f,0x003fffff,0xffffff98,0x3ffffee1,0xfffff500,
0x3ffff607,0x7fe4004f,0x2204ffff,0xacffffff,0xfcaaaaaa,0x003fffff,
0xffff3000,0x7fec00df,0xfffb1fff,0xff0009ff,0x4003ffff,0x003fffff,
0x7ffffc40,0x7f400eff,0x0003ffff,0x7fffff40,0xfffa8003,0xfff10fff,
0x99999dff,0xbfffffb9,0x3ff63999,0xc8004fff,0x00ffffff,0xfffffff7,
0xffffffff,0x0dffffff,0x3fe20000,0x36007fff,0xfb1fffff,0x0009ffff,
0x03ffffff,0x3ffffe60,0x3fe20001,0x005fffff,0x07fffffd,0xfffe8000,
0xfc8003ff,0x3e27ffff,0xffffffff,0xffffffff,0xfb2fffff,0x0009ffff,
0x3ffffff5,0x3fffffa0,0xffffffff,0xffffffff,0x9800001f,0x006fffff,
0x47fffff6,0x04fffffd,0xffffff80,0xffff5001,0x3e20001f,0x05ffffff,
0x3fffffa0,0x7f400003,0x8003ffff,0x25fffffe,0xfffffff8,0xffffffff,
0x2fffffff,0x09fffffb,0xfffff100,0xffff307f,0xffffffff,0xffffffff,
0x4c40bfff,0x5400ccaa,0x005fffff,0x47fffff6,0x04fffffd,0xffffff80,
0xffff5001,0x3fa0001f,0x005fffff,0x1ffffff4,0x3ffa0000,0x5c003fff,
0x22ffffff,0xfffffff8,0xffffffff,0x2fffffff,0x09fffffb,0xfffff500,
0xffff905f,0xffffffff,0xffffffff,0x3a01ffff,0x403fffff,0x04fffffc,
0x3fffff60,0x9fffffb1,0xfffff000,0x0000003f,0xffffffb0,0xfffd000b,
0x800007ff,0x03fffffe,0x3ffffe20,0x7fffc47f,0xffffffff,0xffffffff,
0xffffb2ff,0xff90009f,0xff01ffff,0xddddffff,0xdddddddd,0x7ffffffd,
0x3fffff20,0x3fffe207,0x3f6001ff,0xffb1ffff,0xf0009fff,0x003fffff,
0xffb80000,0x0006ffff,0x07fffffd,0xfffe8000,0xfd5003ff,0x887fffff,
0xcccccccc,0xfffdcccc,0xb1cccdff,0x009fffff,0xffffffa8,0xfffffa86,
0xffe8000f,0xff306fff,0x8819ffff,0x05fffffd,0x7ffffec0,0x9fffffb1,
0xfffff000,0x3fea003f,0x22004fff,0xdfffffff,0xcccccccc,0xfffd0ccc,
0x333339ff,0x33333333,0x7ff43333,0x9999cfff,0xfffebaa9,0x000effff,
0xfffffa80,0xfffffb03,0x53333339,0xffffd755,0xffb09fff,0x2000bfff,
0x1ffffffb,0xffffffd0,0xfffd759f,0xd8003fff,0xfb1fffff,0x0009ffff,
0x03ffffff,0x3ffffea0,0x3ffee004,0xffffffff,0xffffffff,0xffffffd0,
0xffffffff,0xffffffff,0x7fffff4f,0xffffffff,0xffffffff,0xf500001f,
0x3607ffff,0xffffffff,0xffffffff,0xffffffff,0x7ffffc41,0xff10002f,
0x220bffff,0xffffffff,0xffffffff,0xfffd8004,0xffffb1ff,0xfff0009f,
0x2a003fff,0x004fffff,0xfffffff1,0xffffffff,0x3a1fffff,0xffffffff,
0xffffffff,0x27ffffff,0xfffffffe,0xffffffff,0x02ffffff,0x3ffea000,
0xfffb03ff,0xffffffff,0xffffffff,0xf705ffff,0x000fffff,0xffffffd8,
0xfffff500,0xffffffff,0x3f60007f,0xffb1ffff,0xf0009fff,0x003fffff,
0x13ffffea,0x7ffffd40,0xffffffff,0x0fffffff,0xfffffffd,0xffffffff,
0xffffffff,0x7ffffff4,0xffffffff,0x01dfffff,0x7ffd4000,0xfffb03ff,
0xffffffff,0xffffffff,0x3fa07fff,0x0004ffff,0x7fffffd4,0x3fffaa03,
0xffffffff,0x3ff60002,0xfffb1fff,0xff0009ff,0x2003ffff,0x04fffffa,
0xffffff90,0xffffffff,0x21ffffff,0xfffffffe,0xffffffff,0x7fffffff,
0x3ffffffa,0xffffffff,0x0002efff,0xfffff500,0x3ffff607,0xffffffff,
0xffffffff,0xffff302d,0xf00003ff,0x00dfffff,0xfffffff7,0xd800039d,
0xfb1fffff,0x0009ffff,0x03ffffff,0x3ffffea0,0xffffb004,0xffffffff,
0xffffffff,0x3fffffa1,0xffffffff,0xffffffff,0x3ffffa7f,0xffffffff,
0x0002cdef,0x7fffd400,0xffffb03f,0xffffffff,0x17bddfff,0xfffffd80,
0xff900006,0x2003ffff,0x0009ba98,0x3ffff600,0xfffffb1f,0xffff0009,
0x000003ff,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x7ffc4000,0xffffffff,0xffffffff,
0x2000003f,0x0004c000,0x00000002,0x00004c40,0x00999880,0x00662000,
0x00198000,0x000c4000,0x4000c400,0xeeec8009,0xffff11ee,0xffffffff,
0xffffffff,0xb8800007,0x7f64c04f,0x401cdfff,0x000002df,0x7fffe4c0,
0x0001bdef,0xfffffd91,0xa8007bff,0xfffffffd,0xb70000be,0x5bfffffd,
0x4eeeed80,0x77fff654,0xeeee980c,0x3ffb261e,0xdb880bdf,0xb02cefff,
0x225fffff,0xffffffff,0xffffffff,0x0003ffff,0x09fff930,0x7fffffe4,
0x3e04ffff,0x0000beff,0x3fff6200,0xffffffff,0x7ffec003,0xffffffff,
0x7f5400ef,0xffffffff,0x26004fff,0xfffffffe,0xfd02efff,0x3f62bfff,
0xffffffff,0x7ffffcc1,0xffffff71,0x7f441dff,0x4fffffff,0x2fffffd8,
0xfffffff1,0xffffffff,0x007fffff,0xffffea80,0xfffe884f,0xffffffff,
0xffff80ef,0x00000cff,0x7fffffd4,0xffffffff,0xfffd801e,0xffffffff,
0xf500efff,0xffffffff,0x09ffffff,0xffffff90,0xffffffff,0xbffffd05,
0xffffffd1,0x4c5fffff,0xfd9fffff,0xffffffff,0xffff98ef,0x3fffffff,
0x97ffffec,0xfffffff8,0xffffffff,0x001fffff,0xfffffb88,0xffe84fff,
0xffffffff,0x7c0fffff,0xdfffffff,0xffa80001,0xffffffff,0x1fffffff,
0x3fffff20,0xffffffff,0xff886fff,0xffffffff,0x3fffffff,0x3fffff20,
0xffffffff,0x7ff41fff,0xfffffeff,0xffffffff,0x3ffffe66,0xffffffff,
0xffefffff,0xffffffff,0x3ff61fff,0x99912fff,0x99999999,0xfffffd99,
0xffc98007,0xffffffff,0x7ffffdc4,0xfffcabdf,0x7ffc3fff,0xefffffff,
0xfff10002,0xdbdfffff,0xdfffffff,0x3ffffe20,0xffcaacef,0x641fffff,
0x99cfffff,0xffffeb98,0xffff106f,0xffb9bfff,0xe8dfffff,0xffffffff,
0xffffdbbe,0xfff32fff,0x59dfffff,0xfffffff9,0xfb77dfff,0x6cbfffff,
0x002fffff,0x3ffffe20,0x3ff6a005,0xffffffff,0x3ffe22ff,0xfe882fff,
0x3f60ffff,0xffffffff,0x2000cfff,0xdffffffd,0x7fffec40,0xfffb83ff,
0x3ffe05ff,0x7ff42fff,0x3fe205ff,0xfd81ffff,0xa81effff,0x22ffffff,
0xfffffffe,0xfffffa80,0xfffff33f,0xfff507ff,0x903fffff,0x44ffffff,
0x00099999,0x1bffff60,0x3fffae20,0xffffffff,0x7ffec0be,0x3fe603ff,
0x7e4c3fff,0xffffffff,0x4401dfff,0x04ffffff,0x7fffffe4,0x7ff65cc0,
0x3ffff200,0x7ffffc3f,0x055ed405,0xffffffa8,0x3ffff600,0x3ffffa5f,
0x3ff601ff,0xfff34fff,0x7f40bfff,0x304fffff,0x00ffffff,0x7ffd4000,
0x3f2201ff,0xffffffff,0x3e01cfff,0xd807ffff,0x2a07ffff,0xfffffffd,
0x702effff,0x00dfffff,0x0ffffffe,0xfff50020,0xffff87ff,0x0000adff,
0x13fffff2,0x1359df30,0x27fffff4,0x3ffffea0,0xffffff35,0x7fffec01,
0x7fffc07f,0x800000ff,0x04fffff8,0xffffffb5,0x05bfffff,0xdfffff10,
0xfffff700,0xffeb8801,0xffffffff,0x3fffa0bf,0xff7002ff,0x4000bfff,
0xfffffeb8,0x7ffffec4,0x001befff,0x0fffffec,0x7fff4000,0x7fcc02ff,
0xfff35fff,0xffc80fff,0x7fc05fff,0x0000ffff,0x6ffffd80,0x3fffffe0,
0x00beffff,0x3ffffe60,0xaaaaaaae,0x1fffffca,0x3fff6a00,0x4fffffff,
0x07fffffe,0x7ffffcc0,0x3f6e6006,0xffffffff,0x7ffffdc4,0xdfffffff,
0x7fff400a,0xe80001ff,0x401fffff,0x36fffff9,0x80dfffff,0x04fffffc,
0x07fffff4,0x3fea0000,0x3fe02fff,0x1cffffff,0xffff5000,0xffffffff,
0xffffffff,0xfd710005,0x29ffffff,0x0ffffff8,0xfffff100,0x7ff5c40f,
0xffffffff,0xffc84fff,0xffffffff,0xf00cffff,0x001fffff,0xfffffd00,
0xffff9803,0xfffff36f,0xffffc80b,0x7fff403f,0x400000ff,0x406ffffe,
0x1fffffff,0x7ffe4000,0xffffffff,0xffffffff,0x7e40002f,0xf34fffff,
0x800fffff,0x80ffffff,0xfffffffb,0xffffffff,0xffffb04f,0xffffffff,
0xff885fff,0x00007fff,0x01fffffd,0x6fffff88,0x0bfffff3,0x3fffffc8,
0x7fffff40,0x3e600000,0x7c03ffff,0xefffffff,0xfff70002,0xffffffff,
0xffffffff,0xd710007f,0x9fffffff,0x1fffffe2,0xfffff880,0xfffffb87,
0xfaacefff,0x2604ffff,0xfffffffc,0x1fffffff,0x07fffffc,0x7fff4000,
0x7fc400ff,0xfff36fff,0xffc80bff,0x7f403fff,0x0000ffff,0x3fffff60,
0x7ffffc00,0x1cffffff,0x3fffea00,0xaaaaaadf,0xaaaaaaaa,0x3ff6a001,
0xffffffff,0x3fffffe4,0xffff3000,0xffffb8df,0x7cc0adff,0x8804ffff,
0xffffffda,0x746fffff,0x001fffff,0xfffffe80,0x7fffc400,0xfffff36f,
0xffffc80b,0x7fff403f,0x300000ff,0x00bfffff,0xffffffb3,0x17dfffff,
0xfffff980,0x22000005,0xfffffffb,0x20bfffff,0x02ffffff,0xbfffff50,
0x3fffffe8,0x3ffffea0,0xfdb88004,0x47ffffff,0x02fffffd,0xfe81abb8,
0x4400ffff,0xf36fffff,0xc80bffff,0x403fffff,0x00fffffe,0xffff9000,
0x7e44003f,0xffffffff,0xf101cfff,0x100dffff,0xfffda800,0xffffffff,
0xffff902e,0x3ffa00df,0x3fe23fff,0x7d406fff,0x2604ffff,0x3fee200a,
0x3f20ffff,0xf805ffff,0xfd0effff,0x8801ffff,0xf36fffff,0xc80bffff,
0x403fffff,0x00fffffe,0xffff8800,0x3ae0006f,0xffffffff,0x740befff,
0x202fffff,0x42bdeff8,0xffffffc8,0x1dffffff,0x7ffffcc0,0x7ffd402f,
0x3fea1fff,0x7ec05fff,0x36e4ffff,0xe804fffe,0x2a0fffff,0x00ffffff,
0x9bffffea,0x00fffffe,0xb7ffffc4,0x05fffff9,0x1fffffe4,0x3fffffa0,
0x5fffffb0,0xfffff700,0xfb500007,0xffffffff,0x7fd45fff,0xfb00ffff,
0x7ecdffff,0xffffffff,0x2000cfff,0x3fffffff,0xffffff70,0xfffff989,
0xffff700f,0x7ffdc9ff,0x3e200fff,0xfe86ffff,0x981effff,0x23ffffff,
0x00fffffe,0xb7ffffc4,0x05fffff9,0x1fffffe4,0x3fffffa0,0x5fffffb0,
0xfffffb00,0x64c00001,0xffffffff,0x7fff44ff,0xf950bfff,0x7c5fffff,
0xffffffff,0xa8000bef,0xefffffff,0xffffecac,0xfff886ff,0x3261dfff,
0x4fffffff,0x3fffffe2,0x7ff4c1be,0xffa84fff,0xbbdfffff,0xfffffffe,
0x3fffffa0,0x7fffc400,0xfffff36f,0xffffc80b,0x7fff403f,0xffffb0ff,
0xffff005f,0x200000bf,0xffffffb8,0x7ffd44ff,0xffffffff,0x7c6fffff,
0xdfffffff,0xffc80002,0xffffffff,0x1fffffff,0xffffffd0,0xffffffdf,
0xfb8bffff,0xffffffff,0xfffffffe,0xffffb00f,0xffffffff,0xfe85ffff,
0x4400ffff,0xf36fffff,0xc80bffff,0x403fffff,0xb0fffffe,0x805fffff,
0x01fffffa,0xfea80000,0xfa84ffff,0xffffffff,0x40efffff,0x1cffffff,
0x7fec0000,0xffffffff,0x202fffff,0xfffffff9,0xfeefffff,0xffc87fff,
0xffffffff,0x01ffffff,0x3fffffa2,0xffffffff,0xffffe83f,0x7ffc400f,
0xffff36ff,0xfffc80bf,0x7ff403ff,0xfffb0fff,0xffc805ff,0x000007ff,
0x27ffe4c0,0xfffffe88,0x0effffff,0x00bffff8,0x3fea0000,0xffffffff,
0xfb800dff,0xffffffff,0xfffff74f,0xfffff705,0xffffffff,0x3fee005d,
0xffffffff,0xfffd03ff,0xff8801ff,0xfff36fff,0xffc80bff,0x7f403fff,
0xffb0ffff,0xfe805fff,0x00006fff,0x09f71000,0x7fffee44,0x3e02dfff,
0x0000002e,0x3ffffae2,0x4002dfff,0xffffffd8,0x3fffe62e,0xffd7105f,
0x5dffffff,0xfffb3000,0x019fffff,0x07fffff4,0x3ffffe20,0xbfffff36,
0xfffffc80,0x7ffff403,0x3e20000f,0x0004ffff,0x00080000,0x0026aea2,
0x00000006,0x01575310,0x37531000,0x53100000,0x00003557,0x004d5cc4,
0x00000000,0x00000000,0x7fffcc00,0x0000003f,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x40000000,0x01fffffa,
0x4ccccc40,0x99999999,0x99999999,0x00000999,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x03ffffee,0xfffff500,
0xffffffff,0xffffffff,0x00009fff,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x07ffffe4,0x3fffea00,0xffffffff,
0xffffffff,0x0004ffff,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x1fffff60,0x3fffea00,0xffffffff,0xffffffff,
0x0004ffff,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x1fffffa0,0x33332600,0xcccccccc,0xcccccccc,0x0002cccc,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x776c0200,0xee9806ee,0xddd74eee,0x754007dd,
0xdd94eeee,0xed801ddd,0x6c00eeee,0x7545eeee,0xeeeeeeee,0xeeeeeeee,
0x5554001e,0xdb1001aa,0x801ddddd,0x0deeeeed,0x7ffffb00,0x00000000,
0x00fffc80,0x55555000,0xddddd135,0x37fff225,0xffffff0b,0xfffff300,
0x3ffffe6b,0x3fff6007,0xffff52ff,0x7ffc405f,0x3e602fff,0x7dc5ffff,
0xffffffff,0xffffffff,0x7ffc002f,0x3ee003ff,0x205fffff,0x2ffffffc,
0xfffff100,0x3ffe200d,0xffffffff,0xffffffff,0x7fdc05ff,0xffff800f,
0x7ffffc7f,0xfffff8bf,0xfffffe8b,0xffffff2f,0xfffff300,0x7fffff4b,
0xffff8802,0x3fffe27f,0x3ffea04f,0x3ee04fff,0x7dc2ffff,0xffffffff,
0xffffffff,0x7ffc002f,0x7ec003ff,0x982fffff,0x05ffffff,0x3fffff20,
0xfff8802f,0xffffffff,0xffffffff,0x7fd405ff,0xfffff007,0xffffff8f,
0xbfffff8b,0xfffffffd,0x0ffffff0,0xbfffff30,0x2fffffdc,0x7ffffdc0,
0x3ffffec4,0xffffff90,0x7fffec0d,0x7fffdc0f,0xffffffff,0x02ffffff,
0x1fffffc0,0x3fffe200,0x3fa20fff,0x000effff,0xfffffff1,0xffff100d,
0xffffffff,0xffffffff,0x3ea144bf,0xfff8286f,0x7fffc7ff,0xffff8bff,
0xffffffef,0x3ffffe5f,0xffff9807,0x3fffe25f,0x7ff400ff,0x7fdc0fff,
0xffd01fff,0x101fffff,0x70bfffff,0xffffffff,0xffffffff,0xff8003ff,
0xa8003fff,0x24ffffff,0x1ffffffc,0x3ffff200,0x4401ffff,0xffffffff,
0xffffffff,0x2e5fffff,0x2bff32ef,0x7fc1feb8,0x7ffc7fff,0xfff8bfff,
0xffffffff,0x3fffe2ff,0xfff9807f,0x7ffe45ff,0x3fe603ff,0xff885fff,
0xff883fff,0x82ffffff,0x82fffffa,0x99999998,0xfffffa99,0xff8003ff,
0xb0003fff,0x53ffffff,0x07ffffff,0x7ffffc40,0x4405ffff,0xffffffff,
0xffffffff,0x3a5fffff,0xdffbefff,0x7c4ffffc,0x7fc7ffff,0xff8bffff,
0x9cffffff,0x7fffc7da,0xfff9807f,0x7ffcc5ff,0x3ff206ff,0xffd02fff,
0xfff50dff,0x909fffff,0x001fffff,0x3ffffa20,0xff0004ff,0x20007fff,
0xefffffe8,0x06fffffe,0x7ffffdc0,0x201fffff,0xccccccc8,0xcccccccc,
0x33cccccc,0xffffffff,0x8dffffff,0x746fffff,0xf8afffff,0x02ffffff,
0x07fffff8,0x5fffff98,0x1fffffe8,0x0ffffff0,0x07ffffdc,0x3ffffff2,
0xffff86ff,0x3f60005f,0x005fffff,0x0fffffe0,0xffff9800,0xffffffff,
0x7fffc000,0x4ffffebf,0x40000000,0xfffffeb9,0x03ceffff,0xffd8bff3,
0xfff89fff,0xff006fff,0xf300ffff,0xf70bffff,0xf509ffff,0x4c09ffff,
0x742fffff,0xfffeffff,0x3fffe60f,0xffb0003f,0x201dffff,0xaaaaaaa8,
0xadfffffa,0x02aaaaaa,0x7fffffe4,0x4002ffff,0xb8fffffb,0x000fffff,
0x2a000000,0x001fffff,0xffb89ff7,0xfff88fff,0xff002fff,0xf300ffff,
0xf10bffff,0xfb0fffff,0xe803ffff,0x3e24ffff,0xfffcdfff,0x3fffee2f,
0xffc8000f,0x200fffff,0xfffffff8,0xffffffff,0x05ffffff,0xffffffe8,
0xfe8005ff,0xfff15fff,0x000009ff,0x3ffa2000,0xfd004fff,0xffffa87f,
0xffffff17,0x3fffe003,0xfffa807f,0xfff905ff,0x7ffc43ff,0xffc806ff,
0x3ffea7ff,0x4ffffabf,0x01bffff6,0x3ffffee0,0x7fc401ff,0xffffffff,
0xffffffff,0xf8805fff,0x0effffff,0x7fffd400,0x3ffff21f,0xcccc880f,
0xcccccccc,0xcccccccc,0xfffe883c,0x2203fffc,0xff886ffd,0xffff15ff,
0x3fe001ff,0xfa807fff,0xf305ffff,0x7dc9ffff,0x9802ffff,0xfb1fffff,
0xfff13fff,0x3fffe2df,0x7fd4003f,0x802fffff,0xfffffff8,0xffffffff,
0x05ffffff,0xffffffb0,0xfffd000d,0xffff98df,0xffff883f,0xffffffff,
0xffffffff,0x7fff445f,0x305fffd2,0x3603ffff,0xfff13eee,0x7fc00fff,
0x5400ffff,0x205fffff,0x3a7ffffe,0x2007ffff,0xff3fffff,0x7fff4fff,
0xfffffa8f,0x3ffe6001,0x1003ffff,0xffffffff,0xffffffff,0x00bfffff,
0xfffffff5,0x7fcc009f,0xffe83fff,0xfff886ff,0xffffffff,0xffffffff,
0x7ffec5ff,0x03fffea5,0x0005dff1,0x0ffffff1,0x7fffffc0,0x7fffd400,
0x3ffee05f,0xffff9aff,0x3ff2004f,0xffff9dff,0x2bffff25,0x006ffffc,
0x3fffffe2,0x3fe2004f,0xffffffff,0xffffffff,0x7c405fff,0xffffffff,
0xfffb001f,0xfff701ff,0xfff885ff,0xffffffff,0xffffffff,0x1ffd85ff,
0x3b8177ec,0x3ffe2000,0x3fe007ff,0x5c00ffff,0x205fffff,0xbcfffff8,
0x001fffff,0x2fffffea,0x3e63ffff,0xffffcfff,0xffd1004f,0x800bffff,
0xaaaaaaa8,0xadfffffa,0x02aaaaaa,0x7fffffec,0x400effff,0x05fffff9,
0x8dfffff1,0xfffffff8,0xffffffff,0x05ffffff,0x00191097,0x7ffc4000,
0x3fe007ff,0x6401ffff,0x405fffff,0xfefffffc,0xf8006fff,0xffffffff,
0x7ffffc1f,0x001fffff,0xbffffffb,0x3fe00000,0x20003fff,0xfffffffb,
0x405fffff,0x01fffffd,0x87fffff2,0xfffffff8,0xffffffff,0x05ffffff,
0x80000000,0x07fffff8,0x3fffffa0,0x3fffe602,0x7fcc05ff,0xffffffff,
0xfffd8003,0xd87fffff,0xffffffff,0xffff9007,0x00000dff,0x01fffffc,
0xfffff980,0xfffffccf,0xffff102f,0xfff980df,0x000005ff,0x00000000,
0xfffff100,0x7ffec00d,0xfe880eff,0x805fffff,0xfffffffe,0xff50007f,
0x0bffffff,0xfffffff7,0xfff7009f,0x3333ffff,0x33333333,0xfffff800,
0xfffd0003,0x3ffe2dff,0x9880ffff,0x98009999,0x00019999,0x00000000,
0xfff10000,0x7dc00dff,0x8befffff,0xfffffec9,0xffb805ff,0x04ffffff,
0xfffff100,0xff307fff,0x03ffffff,0xffffff98,0xffffffff,0x007fffff,
0x01fffffc,0x7ffffe40,0x3fffea1f,0x000005ff,0x00000000,0x00000000,
0x1bffffe2,0xfffff980,0xffffffff,0x05ffffff,0xffffff88,0x360001ff,
0x1fffffff,0xfffffff0,0xffff300f,0xffffffff,0xffffffff,0xfffff800,
0x7ffcc003,0xffd84fff,0x54c3ffff,0x5542aaaa,0x5101aaaa,0x30003599,
0x7ffffe41,0xaaa98005,0xaaaaaaaa,0x3fffe200,0x7fd4006f,0xffffffff,
0xffffe9ef,0xffff9005,0xb8000dff,0x07ffffff,0x3ffffff6,0xffff9804,
0xffffffff,0x7fffffff,0x7ffffc00,0x3ffa2003,0xf880efff,0x21ffffff,
0x47fffffc,0x44ffffff,0xffffffe9,0x0fb801cf,0x0fffffec,0x43fffffa,
0xfffffffc,0x2200ffff,0x006fffff,0xffffffb8,0xffd0efff,0x3e600bff,
0x003fffff,0x7ffffc40,0x3ffee05f,0xf9802fff,0xffffffff,0xffffffff,
0x7fc007ff,0x32003fff,0x02ffffff,0x3fffffea,0x3fffff26,0x7fffffc7,
0x3ffffee4,0xbeffffff,0x407fecc0,0x745ffffd,0xf90fffff,0xffffffff,
0x7fc401ff,0x70006fff,0x7bfffffb,0x05ffffe8,0x3fffffa0,0xffe80000,
0x3e202fff,0x3007ffff,0xffffffff,0xffffffff,0xa800ffff,0x5001aaaa,
0x09ffffff,0xffffffb0,0x3fffff29,0x7fffffc7,0xffffff74,0xffffffff,
0xfffffddf,0xffffd101,0x7fffff41,0xffffff90,0x401fffff,0x06fffff8,
0x001a9800,0x00000000,0x00000000,0x00000000,0x00000000,0x3ffff200,
0x7ffffc7f,0xfffff94f,0xffffffff,0xffffffff,0x3ffa201f,0x3ffffa4f,
0xfffff90f,0x01ffffff,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x7ffe4000,0x7fffc7ff,0xffff94ff,0xffffffff,0xffffffff,
0x7fc401ff,0xffffd0ff,0x3ffff21f,0x0fffffff,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x3fee0000,0x7ff46fff,0x9ff93fff,
0x3ff26215,0xffffffff,0xbb8803ff,0xfffffd1b,0x333332a1,0x00cccccc,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x3ffe6000,
0x7ffe45ff,0x003f92ff,0xffffffb5,0x000001df,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x1fffffc4,0x43ffffee,
0x65c4000a,0x00000ace,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x5ffffd00,0x07ffff98,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x7fffec00,
0x37fffc40,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x3bbae000,0x09dddb06,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
};
static signed short stb__arial_bold_49_usascii_x[95]={ 0,3,2,0,1,1,1,1,2,1,0,1,2,1,
3,-1,1,3,1,1,0,1,1,1,1,1,4,3,2,1,2,2,1,0,3,2,3,3,3,2,3,2,0,3,
3,3,3,1,3,1,3,1,0,3,-1,0,0,-1,0,3,-1,0,2,-1,0,1,2,1,1,1,0,1,3,3,
-3,2,3,2,3,1,2,1,2,1,0,3,0,0,0,0,0,1,3,0,1, };
static signed short stb__arial_bold_49_usascii_y[95]={ 39,7,7,7,5,7,7,7,7,7,7,12,32,24,
32,7,7,7,7,7,7,8,7,8,7,7,16,16,11,15,11,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,43,7,15,7,15,7,15,7,15,7,7,
7,7,7,15,15,15,15,15,15,15,8,16,16,16,16,16,16,7,7,7,19, };
static unsigned short stb__arial_bold_49_usascii_w[95]={ 0,8,17,24,22,36,30,8,12,12,17,23,8,13,
7,14,22,15,22,22,24,23,22,22,22,22,7,8,22,23,22,23,42,32,27,28,27,25,22,30,26,8,21,29,
23,31,26,32,25,33,29,27,26,26,31,42,30,31,26,11,14,12,22,26,11,22,24,23,24,22,16,23,21,7,
13,22,7,35,21,25,24,24,16,22,15,21,24,35,24,24,22,15,6,16,24, };
static unsigned short stb__arial_bold_49_usascii_h[95]={ 0,32,12,33,39,34,33,12,42,42,16,23,15,7,
7,33,33,32,32,33,32,32,33,31,33,33,23,31,25,17,25,32,42,32,32,33,32,32,32,33,32,32,33,32,
32,32,32,33,32,36,32,33,32,33,32,32,32,32,32,41,33,41,18,5,7,25,33,25,33,25,32,34,32,32,
42,32,32,24,24,25,33,33,24,25,32,24,23,23,23,33,23,42,42,42,9, };
static unsigned short stb__arial_bold_49_usascii_s[95]={ 255,228,173,198,149,1,29,247,97,1,220,
124,238,236,228,85,125,239,52,163,129,215,215,1,152,175,247,246,24,196,70,
28,54,182,154,186,101,75,92,121,1,237,223,198,174,142,115,88,66,172,28,
1,1,1,199,156,125,93,66,124,148,136,173,24,216,119,60,165,100,47,238,
206,28,245,110,231,58,211,189,93,63,38,1,142,50,18,40,65,148,230,101,
38,31,14,191, };
static unsigned short stb__arial_bold_49_usascii_t[95]={ 1,146,264,44,1,44,79,245,1,1,245,
245,245,264,264,79,79,179,179,79,179,179,79,213,44,44,213,146,213,245,213,
179,1,179,179,79,179,179,146,44,180,146,44,146,146,146,146,44,146,1,146,
79,147,113,113,113,113,113,113,1,79,1,245,239,264,213,79,213,79,213,79,
1,113,44,1,113,146,213,213,213,44,44,245,213,113,245,245,245,245,1,245,
1,1,1,264, };
static unsigned short stb__arial_bold_49_usascii_a[95]={ 195,234,333,390,390,624,507,167,
234,234,273,410,195,234,195,195,390,390,390,390,390,390,390,390,
390,390,234,234,410,410,410,429,684,507,507,507,507,468,429,546,
507,195,390,507,429,585,507,546,468,546,507,468,429,507,468,662,
468,468,429,234,195,234,410,390,234,390,429,390,429,390,234,429,
429,195,195,390,195,624,429,429,429,429,273,390,234,429,390,546,
390,390,351,273,196,273,410, };
// Call this function with
// font: NULL or array length
// data: NULL or specified size
// height: STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT or STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT_POW2
// return value: spacing between lines
static void stb_font_arial_bold_49_usascii(stb_fontchar font[STB_FONT_arial_bold_49_usascii_NUM_CHARS],
unsigned char data[STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT][STB_FONT_arial_bold_49_usascii_BITMAP_WIDTH],
int height)
{
int i,j;
if (data != 0) {
unsigned int *bits = stb__arial_bold_49_usascii_pixels;
unsigned int bitpack = *bits++, numbits = 32;
for (i=0; i < STB_FONT_arial_bold_49_usascii_BITMAP_WIDTH*height; ++i)
data[0][i] = 0; // zero entire bitmap
for (j=1; j < STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT-1; ++j) {
for (i=1; i < STB_FONT_arial_bold_49_usascii_BITMAP_WIDTH-1; ++i) {
unsigned int value;
if (numbits==0) bitpack = *bits++, numbits=32;
value = bitpack & 1;
bitpack >>= 1, --numbits;
if (value) {
if (numbits < 3) bitpack = *bits++, numbits = 32;
data[j][i] = (bitpack & 7) * 0x20 + 0x1f;
bitpack >>= 3, numbits -= 3;
} else {
data[j][i] = 0;
}
}
}
}
// build font description
if (font != 0) {
float recip_width = 1.0f / STB_FONT_arial_bold_49_usascii_BITMAP_WIDTH;
float recip_height = 1.0f / height;
for (i=0; i < STB_FONT_arial_bold_49_usascii_NUM_CHARS; ++i) {
// pad characters so they bilerp from empty space around each character
font[i].s0 = (stb__arial_bold_49_usascii_s[i]) * recip_width;
font[i].t0 = (stb__arial_bold_49_usascii_t[i]) * recip_height;
font[i].s1 = (stb__arial_bold_49_usascii_s[i] + stb__arial_bold_49_usascii_w[i]) * recip_width;
font[i].t1 = (stb__arial_bold_49_usascii_t[i] + stb__arial_bold_49_usascii_h[i]) * recip_height;
font[i].x0 = stb__arial_bold_49_usascii_x[i];
font[i].y0 = stb__arial_bold_49_usascii_y[i];
font[i].x1 = stb__arial_bold_49_usascii_x[i] + stb__arial_bold_49_usascii_w[i];
font[i].y1 = stb__arial_bold_49_usascii_y[i] + stb__arial_bold_49_usascii_h[i];
font[i].advance_int = (stb__arial_bold_49_usascii_a[i]+8)>>4;
font[i].s0f = (stb__arial_bold_49_usascii_s[i] - 0.5f) * recip_width;
font[i].t0f = (stb__arial_bold_49_usascii_t[i] - 0.5f) * recip_height;
font[i].s1f = (stb__arial_bold_49_usascii_s[i] + stb__arial_bold_49_usascii_w[i] + 0.5f) * recip_width;
font[i].t1f = (stb__arial_bold_49_usascii_t[i] + stb__arial_bold_49_usascii_h[i] + 0.5f) * recip_height;
font[i].x0f = stb__arial_bold_49_usascii_x[i] - 0.5f;
font[i].y0f = stb__arial_bold_49_usascii_y[i] - 0.5f;
font[i].x1f = stb__arial_bold_49_usascii_x[i] + stb__arial_bold_49_usascii_w[i] + 0.5f;
font[i].y1f = stb__arial_bold_49_usascii_y[i] + stb__arial_bold_49_usascii_h[i] + 0.5f;
font[i].advance = stb__arial_bold_49_usascii_a[i]/16.0f;
}
}
}
#ifndef STB_SOMEFONT_CREATE
#define STB_SOMEFONT_CREATE stb_font_arial_bold_49_usascii
#define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_arial_bold_49_usascii_BITMAP_WIDTH
#define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT
#define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_arial_bold_49_usascii_BITMAP_HEIGHT_POW2
#define STB_SOMEFONT_FIRST_CHAR STB_FONT_arial_bold_49_usascii_FIRST_CHAR
#define STB_SOMEFONT_NUM_CHARS STB_FONT_arial_bold_49_usascii_NUM_CHARS
#define STB_SOMEFONT_LINE_SPACING STB_FONT_arial_bold_49_usascii_LINE_SPACING
#endif
| 68.532918 | 127 | 0.811206 | stetre |
d5d39d65bcd29a5f3ef342fdb428128bf7363589 | 7,790 | cpp | C++ | dlc/src/v20210125/model/ViewResponseInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | dlc/src/v20210125/model/ViewResponseInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | dlc/src/v20210125/model/ViewResponseInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/dlc/v20210125/model/ViewResponseInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Dlc::V20210125::Model;
using namespace std;
ViewResponseInfo::ViewResponseInfo() :
m_viewBaseInfoHasBeenSet(false),
m_columnsHasBeenSet(false),
m_propertiesHasBeenSet(false),
m_createTimeHasBeenSet(false),
m_modifiedTimeHasBeenSet(false)
{
}
CoreInternalOutcome ViewResponseInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ViewBaseInfo") && !value["ViewBaseInfo"].IsNull())
{
if (!value["ViewBaseInfo"].IsObject())
{
return CoreInternalOutcome(Error("response `ViewResponseInfo.ViewBaseInfo` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_viewBaseInfo.Deserialize(value["ViewBaseInfo"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_viewBaseInfoHasBeenSet = true;
}
if (value.HasMember("Columns") && !value["Columns"].IsNull())
{
if (!value["Columns"].IsArray())
return CoreInternalOutcome(Error("response `ViewResponseInfo.Columns` is not array type"));
const rapidjson::Value &tmpValue = value["Columns"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Column item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_columns.push_back(item);
}
m_columnsHasBeenSet = true;
}
if (value.HasMember("Properties") && !value["Properties"].IsNull())
{
if (!value["Properties"].IsArray())
return CoreInternalOutcome(Error("response `ViewResponseInfo.Properties` is not array type"));
const rapidjson::Value &tmpValue = value["Properties"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Property item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_properties.push_back(item);
}
m_propertiesHasBeenSet = true;
}
if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull())
{
if (!value["CreateTime"].IsString())
{
return CoreInternalOutcome(Error("response `ViewResponseInfo.CreateTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_createTime = string(value["CreateTime"].GetString());
m_createTimeHasBeenSet = true;
}
if (value.HasMember("ModifiedTime") && !value["ModifiedTime"].IsNull())
{
if (!value["ModifiedTime"].IsString())
{
return CoreInternalOutcome(Error("response `ViewResponseInfo.ModifiedTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_modifiedTime = string(value["ModifiedTime"].GetString());
m_modifiedTimeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void ViewResponseInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_viewBaseInfoHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ViewBaseInfo";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_viewBaseInfo.ToJsonObject(value[key.c_str()], allocator);
}
if (m_columnsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Columns";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_columns.begin(); itr != m_columns.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_propertiesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Properties";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_properties.begin(); itr != m_properties.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_createTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreateTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator);
}
if (m_modifiedTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ModifiedTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_modifiedTime.c_str(), allocator).Move(), allocator);
}
}
ViewBaseInfo ViewResponseInfo::GetViewBaseInfo() const
{
return m_viewBaseInfo;
}
void ViewResponseInfo::SetViewBaseInfo(const ViewBaseInfo& _viewBaseInfo)
{
m_viewBaseInfo = _viewBaseInfo;
m_viewBaseInfoHasBeenSet = true;
}
bool ViewResponseInfo::ViewBaseInfoHasBeenSet() const
{
return m_viewBaseInfoHasBeenSet;
}
vector<Column> ViewResponseInfo::GetColumns() const
{
return m_columns;
}
void ViewResponseInfo::SetColumns(const vector<Column>& _columns)
{
m_columns = _columns;
m_columnsHasBeenSet = true;
}
bool ViewResponseInfo::ColumnsHasBeenSet() const
{
return m_columnsHasBeenSet;
}
vector<Property> ViewResponseInfo::GetProperties() const
{
return m_properties;
}
void ViewResponseInfo::SetProperties(const vector<Property>& _properties)
{
m_properties = _properties;
m_propertiesHasBeenSet = true;
}
bool ViewResponseInfo::PropertiesHasBeenSet() const
{
return m_propertiesHasBeenSet;
}
string ViewResponseInfo::GetCreateTime() const
{
return m_createTime;
}
void ViewResponseInfo::SetCreateTime(const string& _createTime)
{
m_createTime = _createTime;
m_createTimeHasBeenSet = true;
}
bool ViewResponseInfo::CreateTimeHasBeenSet() const
{
return m_createTimeHasBeenSet;
}
string ViewResponseInfo::GetModifiedTime() const
{
return m_modifiedTime;
}
void ViewResponseInfo::SetModifiedTime(const string& _modifiedTime)
{
m_modifiedTime = _modifiedTime;
m_modifiedTimeHasBeenSet = true;
}
bool ViewResponseInfo::ModifiedTimeHasBeenSet() const
{
return m_modifiedTimeHasBeenSet;
}
| 30.07722 | 141 | 0.66534 | sinjoywong |
d5d64b11b121e19842b238644d3569e369ec75bc | 1,170 | hpp | C++ | src/server.hpp | mrc-g/FogMon | dc040e5566d4fa6b0fca80fb46767f40f19b7c2e | [
"MIT"
] | 7 | 2019-05-08T08:25:40.000Z | 2021-06-19T10:42:56.000Z | src/server.hpp | mrc-g/FogMon | dc040e5566d4fa6b0fca80fb46767f40f19b7c2e | [
"MIT"
] | 5 | 2020-03-07T15:24:27.000Z | 2022-03-12T00:49:53.000Z | src/server.hpp | mrc-g/FogMon | dc040e5566d4fa6b0fca80fb46767f40f19b7c2e | [
"MIT"
] | 4 | 2020-03-05T17:05:42.000Z | 2021-11-21T16:00:56.000Z | #ifndef SERVER_HPP_
#define SERVER_HPP_
#include <string>
#include <thread>
class IAgent;
class IConnections;
#include <thread>
/**
* Define a server that accept connections an IConnections handle it
*/
class Server {
private:
/**
* the state of the server true=running else is closing
*/
bool running;
/**
* Holds the port to listen to
*/
uint16_t portC;
/**
* thread of the listener to terminate it
*/
std::thread listenerThread;
/**
* Holds the handler of the new connections
*/
IConnections* connection;
/**
* fd to wake up the listener thread during poll
*/
int efd;
/**
* The listener function used to create the socket and wait for new connections
*/
void listener();
public:
/**
* @param conn the handler of the connections
* @param port the port to listen to
*/
Server(IConnections *conn, int port);
~Server();
/**
* Start the listener thread
*/
void start();
/**
* Stop the thread
*/
void stop();
/**
* @return the port of the listener
*/
int getPort();
};
#endif | 16.714286 | 83 | 0.588889 | mrc-g |
d5d897c866c575ac0e60e357dcbab72cbd6e7263 | 1,050 | cpp | C++ | ws6/ProdUtil.cpp | mylorik/OOP345 | 0034a803a7ee98e13ea36d805993d4727c3a09e4 | [
"MIT"
] | null | null | null | ws6/ProdUtil.cpp | mylorik/OOP345 | 0034a803a7ee98e13ea36d805993d4727c3a09e4 | [
"MIT"
] | null | null | null | ws6/ProdUtil.cpp | mylorik/OOP345 | 0034a803a7ee98e13ea36d805993d4727c3a09e4 | [
"MIT"
] | null | null | null | // Name: Artem Kulihina
// Seneca Student ID: 128516168
// Seneca email: akulihin@myseneca.ca
// Date of completion: 02.11.2018
//
// I confirm that the content of this file is created by me,
// with the exception of the parts provided to me by my professor.
#include <string>
#include <cctype>
#include "ProdUtil.h"
#include "Product.h"
#include "TaxableProduct.h"
namespace w6
{
std::ostream& operator<<(std::ostream& os, const iProduct& src)
{
src.display(os);
return os << std::endl;
}
iProduct* readProduct(std::ifstream& ifs)
{
char c = ifs.peek();
if (c != EOF && c != '\n')
{
std::string product_number;
double product_price;
ifs >> product_number >> product_price;
ifs.ignore();
c = ifs.peek();
if (std::isalpha(c))
{
ifs.ignore(256, '\n');
if (c == 'H' || c == 'P')
return new TaxableProduct(product_number, product_price, c);
std::string error = "Unrecognizable Tax Code!";
throw error;
}
return new Product(product_number, product_price);
}
return nullptr;
}
}
| 20.588235 | 66 | 0.646667 | mylorik |
d5d8d2ba88bfbe7ad100f17e91e8d167006b3f63 | 1,986 | cpp | C++ | lib/error.cpp | gabrielcuvillier/stdext | 3a5346deab9f3fd86aa66384222792313daa7524 | [
"MIT"
] | 1 | 2019-10-02T12:51:19.000Z | 2019-10-02T12:51:19.000Z | lib/error.cpp | gabrielcuvillier/stdext | 3a5346deab9f3fd86aa66384222792313daa7524 | [
"MIT"
] | null | null | null | lib/error.cpp | gabrielcuvillier/stdext | 3a5346deab9f3fd86aa66384222792313daa7524 | [
"MIT"
] | null | null | null | // Copyright (c) 2019 - Gabriel Cuvillier, Continuation Labs (www.continuation-labs.com)
// Licensed under the MIT License.
// Main header
#include <stdext/error>
// std
#include <cstdio> // std::fprintf, stderr
#include <cstdlib> // std::abort
#include <exception> // std::set_terminate
#include <string> // std::string
// stdext
#include <stdext/fs>
void stdext::install_unhandled_exception_handler() noexcept
{
std::set_terminate( []() {
std::fprintf( stderr, "Terminate handler called: aborting the program.\n" );
std::abort();
} );
}
template<>
const char* stdext::enum_to_string( stdext::InternalError err ) noexcept
{
switch ( err ) {
case stdext::InternalError::AssertionFailed: return "InternalError::AssertionFailed";
}
return "InternalError::<unknown>";
}
void stdext::PRINTERROR( const char* file, int line, int col, const char* func, const char* message ) noexcept
{
std::fprintf( stderr, "Failure in %s, line %d:%d: function '%s': '%s'\n",
stdext::get_file_name( std::string( file ) ).c_str(), line, col, func, message );
}
namespace
{
const char* const abort_msg = " Aborting function\n";
const char* const abort_prog = " Aborting program\n";
const char* const skipping_iteration_msg = " Skipping iteration\n";
const char* const abort_loop_msg = " Aborting loop\n";
const char* const continue_msg = " Continuing\n";
} // namespace
void stdext::EPICFAIL_RET() noexcept { std::fprintf( stderr, abort_msg ); }
void stdext::EPICFAIL_CRASH() noexcept { std::fprintf( stderr, abort_prog ); }
void stdext::EPICFAIL_RET_VOID() noexcept { std::fprintf( stderr, abort_msg ); }
void stdext::EPICFAIL_RET_INT() noexcept { std::fprintf( stderr, abort_msg ); }
void stdext::EPICFAIL_LOOP() noexcept { std::fprintf( stderr, skipping_iteration_msg ); }
void stdext::EPICFAIL_LOOP_BREAK() noexcept { std::fprintf( stderr, abort_loop_msg ); }
void stdext::EPICFAIL_NOP() noexcept { std::fprintf( stderr, continue_msg ); }
| 32.557377 | 110 | 0.70292 | gabrielcuvillier |
d5df0056a57d0ab2789b04d18b7eb3b1c837dc62 | 17,119 | cpp | C++ | ASCIILib/DialogFrame.cpp | Natman64/ASCIILib | 04f661416261467df0d6f816fa31e870c0fcd8a9 | [
"MIT"
] | 1 | 2019-09-27T11:20:10.000Z | 2019-09-27T11:20:10.000Z | ASCIILib/DialogFrame.cpp | NQNStudios/ASCIILib | 04f661416261467df0d6f816fa31e870c0fcd8a9 | [
"MIT"
] | 13 | 2015-09-27T23:58:19.000Z | 2015-09-28T16:24:11.000Z | ASCIILib/DialogFrame.cpp | Natman64/ASCIILib | 04f661416261467df0d6f816fa31e870c0fcd8a9 | [
"MIT"
] | null | null | null | #include "DialogFrame.h"
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <sstream>
#include "Log.h"
#include "StringTokenizer.h"
#include "Game.h"
using namespace ascii;
namespace
{
const unsigned int LINE_BREAK_AMOUNT = 2;
}
ascii::DialogFrame::DialogFrame(Rectangle frame, DialogStyle* style, ascii::Game* game)
: mFrame(frame), mTextColor(style->TextColor), mpGame(game),
mLastCharX(mFrame.x), mLastCharY(mFrame.y),
mMarkedCharX(0), mMarkedCharY(0),
// FIXME this code does not account for right-to-left dialog!
frameStartX(frame.left()), frameStartY(frame.top()),
frameFinishX(frame.right() - 1), frameFinishY(frame.bottom() - 1),
mpStyle(style), mDummyCellsPassed(0)
{
}
int ascii::DialogFrame::Width()
{
return frameFinishX - frameStartX + 1;
}
int ascii::DialogFrame::Height()
{
return frameFinishY - frameStartY + 1;
}
void ascii::DialogFrame::AddWord(UnicodeString word)
{
// Count the length of the word, including trailing whitespace
int lengthWithSpace = word.length();
// Copy and trim the word of whitespace
UnicodeString trimmed = word;
trimmed.trim();
// Count the length without trailing whitespace
int length = trimmed.length();
if (lengthWithSpace == 0 || length == 0)
{
// TODO something goes wrong here and I don't know why, but this return
// statement avoids the bug
Log::Error("Tried to add an empty word");
return;
}
// Calculate where the word needs to be placed
unsigned int drawX = mLastCharX;
unsigned int drawY = mLastCharY;
// Calculate where the word will terminate if inserted on the current line
const unsigned int finishX = drawX + length - 1;
if (finishX > frameFinishX)
{
//Log("Wrapping to the next line because of word");
//ULog(word);
// Wrap to the next line if necessary
drawX = frameStartX;
++drawY;
}
// Add the word (including trailing white-space) as a token mapped with
// its screen position.
mWords.push_back(ScrollingWord(word, Point(drawX, drawY), mpStyle));
// Store the coordinates where the word terminated, so we can place the
// next word
mLastCharX = drawX + lengthWithSpace;
mLastCharY = drawY;
}
void ascii::DialogFrame::AddHeading(UnicodeString heading)
{
// Make sure the heading will fit on a line
if (heading.length() > Width())
{
Log::Error("Tried to add a heading which was too long to fit on a line: " + heading);
return;
}
// Calculate where the heading needs to be placed
unsigned int drawX = (frameStartX + frameFinishX) / 2 - heading.length() / 2;
unsigned int drawY = mLastCharY;
// Add the word as a token mapped with its screen position.
mWords.push_back(ScrollingWord(heading, Point(drawX, drawY), mpStyle));
mLastCharX = drawX + heading.length() - 1;
}
UnicodeString ascii::DialogFrame::AddParagraphFlush(UnicodeString paragraph)
{
if (mLastCharY > frameFinishY) return paragraph;
vector<int> wordCounts;
vector<vector<UnicodeString> > lines;
vector<int> lineLengths;
int words = 0;
int lineLength = 0;
StringTokenizer tokenizer(paragraph);
UnicodeString remainder;
vector<UnicodeString> line;
while (tokenizer.HasNextToken())
{
// Retrieve the next token untrimmed
UnicodeString word = tokenizer.NextToken(false);
// Count the token's length trimmed
UnicodeString trimmed(word);
trimmed.trim();
lineLength += trimmed.length();
if (lineLength <= Width())
{
//Log("Adding justified word");
//ULog(word);
// Add the token untrimmed
line.push_back(word);
// Increase line length to account for untrimmed version before
// counting the next token
lineLength += word.length() - trimmed.length();
//Log("Line length after adding word: ");
//Log(lineLength);
}
else
{
lineLength -= trimmed.length();
if (mLastCharY + lines.size() >= frameFinishY)
{
remainder = word + tokenizer.BufferRemainder();
break;
}
else
{
wordCounts.push_back(line.size());
lines.push_back(line);
if (IsWhiteSpace(line.back()[line.back().length() - 1]))
{
lineLength -= 1;
}
lineLengths.push_back(lineLength);
//Log("-------------------------------");
//Log("Adding justified word");
//ULog(word);
line.clear();
line.push_back(word);
lineLength = word.length();
//Log("Line length after adding word: ");
//Log(lineLength);
}
}
}
if (!line.empty())
{
lines.push_back(line);
wordCounts.push_back(line.size());
lineLengths.push_back(lineLength);
lineLength = 0;
}
for (int i = 0; i < lines.size(); ++i)
{
vector<UnicodeString> line = lines[i];
int wordCount = wordCounts[i];
int lineLength = lineLengths[i];
int extraSpaces = Width() - lineLength;
//Log("Extra spaces: ");
//Log(extraSpaces);
vector<int> spaces;
if (wordCount > 1)
{
for (int j = 0; j < wordCount - 1; ++j)
{
spaces.push_back(0);
}
for (int j = extraSpaces - 1; j >= 0; --j)
{
int whichGap = j % spaces.size();
spaces[whichGap] += 1;
}
}
else
{
spaces.push_back(0);
}
// The last word has no trailing spaces
spaces.push_back(0);
int k = 0;
for (int i = 0; i < line.size(); ++i)
{
UnicodeString uword = line[i];
if (CanFitWord(uword))
{
AddWord(uword);
RevealLetters(uword.length());
if (lineLength > 3 * Width() / 4)
{
mLastCharX += spaces[k++];
}
}
}
}
//Log::Print("Returning a remainder");
//Log::Print(remainder);
return remainder;
}
void ascii::DialogFrame::AddSurface(Surface* surface)
{
// Make sure the surface will fit on a line
if (surface->width() > Width())
{
Log::Error("Tried to add a surface which was too wide to fit in this DialogFrame.");
return;
}
// Make sure the surface will fit vertically in the remaining space
if (surface->height() > (frameFinishY + 1 - mLastCharY))
{
Log::Error("Tried to add a surface which was too tall to fit in this DialogFrame.");
return;
}
// Place the surface in the frame
Point position(mLastCharX, mLastCharY);
mSurfaces[position] = surface;
// Continue filling the DialogFrame one line below the bottom of the surface
mLastCharY += surface->height();
HalfLineBreak();
}
UnicodeString ascii::DialogFrame::MockWord(UnicodeString word, UChar mockLetter)
{
UnicodeString mockWord;
for (int i = 0; i < word.length(); ++i)
{
mockWord += mockLetter;
}
return mockWord;
}
bool ascii::DialogFrame::AddMockParagraph(UnicodeString paragraph, UChar mockLetter)
{
StringTokenizer tokenizer(paragraph);
while (tokenizer.HasNextToken())
{
UnicodeString word = tokenizer.NextToken();
UnicodeString mockWord = MockWord(word, mockLetter) + " ";
if (CanFitWord(mockWord))
{
AddWord(mockWord);
RevealLetters(mockWord.length());
}
else
{
return false;
}
}
if (CanLineBreak())
{
LineBreak();
return true;
}
return false;
}
void ascii::DialogFrame::FillMockParagraphs(UChar mockLetter)
{
bool fitLastParagraph = true;
while (fitLastParagraph)
{
// Add a random currently loaded paragraph, converted into the mock
// character
UnicodeString paragraph = mpGame->textManager()->GetRandomText(Width()*2);
fitLastParagraph = AddMockParagraph(paragraph, mockLetter);
}
}
void ascii::DialogFrame::FillMockParagraphsFlush(UChar mockLetter)
{
int maxLettersLeft = (frameFinishY - mLastCharY + 1) * Width();
int letters = 0;
while (letters < maxLettersLeft)
{
UnicodeString paragraph = mpGame->textManager()->GetRandomText(Width()*2);
StringTokenizer tokenizer(paragraph);
UnicodeString mockParagraph;
while (tokenizer.HasNextToken())
{
UnicodeString word = tokenizer.NextToken();
UnicodeString mockWord = MockWord(word, mockLetter);
mockParagraph += mockWord + " ";
letters += mockWord.length() + 1;
}
AddParagraphFlush(mockParagraph);
if (CanLineBreak())
{
LineBreak();
}
else
{
++mLastCharY;
}
}
}
void ascii::DialogFrame::LineBreak()
{
// Don't line break ever if the style doesn't allow it
if (!mpStyle->LineBreaks)
return;
// Only break for a single line if this frame is empty. We'll just assume a
// parent object wrapped into this frame after filling an old one
if (mLastCharX == frameStartX && mLastCharY == frameStartY)
{
HalfLineBreak();
return;
}
mLastCharX = frameStartX;
mLastCharY += LINE_BREAK_AMOUNT;
}
void ascii::DialogFrame::HalfLineBreak()
{
if (mpStyle->LineBreaks)
{
mLastCharX = frameStartX;
mLastCharY += LINE_BREAK_AMOUNT / 2;
}
}
bool ascii::DialogFrame::CanFitWord(UnicodeString word)
{
// If we're already past the end of the frame because of a line break,
// no go.
if (mLastCharY > frameFinishY) return false;
// If the word is wider than the frame, no go
if (word.length() > mFrame.width)
{
Log::Error("Tried to add word '" + word + "' to a dialog frame for which it was too wide");
return false;
}
// Calculate the end of the word if placed immediately after the previous
// one
word.trim();
if (word.length() == 0)
{
Log::Print("Warning! Trying to add a word composed only of white-space");
}
int finishX = mLastCharX + word.length() - 1;
// If it can't fit on this line, can it fit on the next?
if (finishX > frameFinishX)
{
//Log("Token doesn't fit in this frame:");
//ULog(word);
//Log(frameFinishX - finishX);
//Log(word.length());
// Fits as long as we can wrap to another line
return mLastCharY < frameFinishY;
}
return true; // It fits on the current line
}
bool ascii::DialogFrame::CanFitHeading()
{
// 3 lines must remain in order for any text to be fit after the line
// breaking following the heading
int linesRequired = LINE_BREAK_AMOUNT + 1;
return (frameFinishY - mLastCharY + 1 >= linesRequired);
}
bool ascii::DialogFrame::CanLineBreak()
{
// This doesn't make sense but trust me on it
if (!mpStyle->LineBreaks) return true;
// This frame can fit a line break as long as it's above its last line.
return mLastCharY < frameFinishY;
}
int ascii::DialogFrame::RevealedLetters()
{
int sum = 0;
for (int i = 0; i < mWords.size(); ++i)
{
sum += mWords[i].RevealedLetters();
}
return sum;
}
int ascii::DialogFrame::LettersToReveal()
{
// Return the greatest number of letters that any child ScrollingWord is
// missing. The sum is not returned because every ScrollingWord currently
// in the frame reveals itself simultaneously
int max = 0;
for (int i = 0; i < mWords.size(); ++i)
{
ScrollingWord word = mWords[i];
if (word.LettersToReveal() > max)
{
max = word.LettersToReveal();
}
}
return max;
}
void ascii::DialogFrame::RevealLetters(int amount)
{
// Reveal letters on every word that's currently scrolling
// (This can be used to reveal multiple words at the same time in
// different places!)
for (auto it = mWords.begin(); it != mWords.end(); ++it)
{
if (!it->Revealed())
{
it->RevealLetters(amount);
}
}
}
void ascii::DialogFrame::RevealAllLetters()
{
// Reveal all letters on every word in the message
for (auto it = mWords.begin(); it != mWords.end(); ++it)
{
if (!it->Revealed())
{
it->RevealAllLetters();
}
}
}
void ascii::DialogFrame::HideLetters(int amount, int dummyCells)
{
if (mDummyCellsPassed < dummyCells)
{
++mDummyCellsPassed;
return;
}
// Hide letters on every word that is currently being hidden
// (This can be used to hide multiple words at the same time in different
// places!)
for (auto it = mWords.begin(); it != mWords.end(); ++it)
{
if (!it->Hidden())
{
it->HideLetters(amount);
// TODO handle hiding all words at once for special dialog
break;
}
}
}
bool ascii::DialogFrame::AllWordsRevealed()
{
// If no words have been added, then all words are revealed
if (mWords.empty())
{
return true;
}
// Otherwise check all of them, until finding one that isn't fully revealed
for (auto it = mWords.begin(); it != mWords.end(); ++it)
{
if (!it->Revealed())
{
return false;
}
}
// If none is unfinished, then all words are revealed
return true;
}
bool ascii::DialogFrame::AllWordsHidden()
{
// If no words have been added, then all words are hidden
if (mWords.empty())
{
return true;
}
// Otherwise check all of them, until finding one that isn't fully hidden
for (auto it = mWords.begin(); it != mWords.end(); ++it)
{
if (!it->Hidden())
{
return false;
}
}
// If none aren't fully hidden, all are fully hidden
return true;
}
void ascii::DialogFrame::Clear()
{
// clear all scrolling words
mWords.clear();
// clear all surface
mSurfaces.clear();
// move the "cursor" back to the beginning
mLastCharX = frameStartX;
mLastCharY = frameStartY;
}
void ascii::DialogFrame::Draw(Graphics& graphics, Preferences* config)
{
// Draw every scrolling word
for (auto it = mWords.begin(); it != mWords.end(); ++it)
{
it->Draw(graphics);
}
// Draw every surface
for (auto it = mSurfaces.begin(); it != mSurfaces.end(); ++it)
{
graphics.blitSurface(it->second, it->first.x, it->first.y);
}
// If debug view is enabled, display the text frame's bounding
// rectangle visually:
if (config->GetBool("debug-view"))
{
for (int x = frameStartX; x <= frameFinishX; ++x)
{
for (int y = frameStartY; y <= frameFinishY; ++y)
{
graphics.setBackgroundColor(x, y, Color::Red);
}
}
}
}
void ascii::DialogFrame::DrawCursor(Graphics& graphics)
{
// If this frame's DialogStyle requires a cursor, draw it following all
// text that has been revealed
if (mpStyle->HasCursor)
{
Point cursorPosition(mLastCharX, mLastCharY);
if (!mWords.empty())
{
cursorPosition = mWords.back().NextCell();
// Draw on the next line if it would appear past the end of this
// one
if (cursorPosition.x > frameFinishX)
{
cursorPosition.x = frameStartX;
cursorPosition.y += 1;
}
}
graphics.setBackgroundColor(cursorPosition.x, cursorPosition.y,
mpStyle->CursorColor);
}
}
bool ascii::DialogFrame::HasWords()
{
// This might be some hackish trickery
return !mWords.empty() || !mSurfaces.empty();
}
void ascii::DialogFrame::MarkPosition()
{
mMarkedCharX = mLastCharX;
mMarkedCharY = mLastCharY;
}
void ascii::DialogFrame::RewindPosition()
{
mLastCharX = mMarkedCharX;
mLastCharY = mMarkedCharY;
}
| 27.30303 | 100 | 0.563234 | Natman64 |
d5df2eb55b98f6ef4656593b467e673b41d377b4 | 688 | cpp | C++ | calculator/WeatherParameter.cpp | fmidev/smartmet-library-calculator | 19366ff5af4d3a456d1841c3c3cb598eb900d86a | [
"MIT"
] | null | null | null | calculator/WeatherParameter.cpp | fmidev/smartmet-library-calculator | 19366ff5af4d3a456d1841c3c3cb598eb900d86a | [
"MIT"
] | null | null | null | calculator/WeatherParameter.cpp | fmidev/smartmet-library-calculator | 19366ff5af4d3a456d1841c3c3cb598eb900d86a | [
"MIT"
] | null | null | null | // ======================================================================
/*!
* \file
* \brief Documentation of TextGen::WeatherParameter
*/
// ======================================================================
/*!
* \enum TextGen::WeatherParameter
*
* \brief Enumeration of parameters that can be analyzed
*
* This enumeration is separate from that in newbase library because
* we may enumerate phenomena which are not represented separately
* in newbase. For example, we list Snow and Sleet as separate parameters
* for which one can calculate a Probability.
*
*/
// ======================================================================
#include "WeatherParameter.h"
| 32.761905 | 73 | 0.502907 | fmidev |
d5dfad945734e76ce646fc9a9984657129d8fffc | 7,848 | cpp | C++ | Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/LowLevelParticles/src/PtBatcher.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/LowLevelParticles/src/PtBatcher.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/LowLevelParticles/src/PtBatcher.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PtBatcher.h"
#if PX_USE_PARTICLE_SYSTEM_API
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
#endif
#include "task/PxTask.h"
#include "PtContext.h"
#include "PtParticleSystemSim.h"
#include "PtParticleSystemSimCpu.h"
using namespace physx;
using namespace Pt;
namespace
{
template <class T>
static void sortBatchedInputs(ParticleSystemSim** particleSystems, T* inputs, PxU32 batchSize, PxU32& cpuOffset,
PxU32& cpuCount, PxU32& gpuOffset, PxU32& gpuCount)
{
PX_UNUSED(particleSystems);
PX_UNUSED(inputs);
cpuOffset = 0;
gpuOffset = 0;
// in place sort of both arrays
PxU32 i = 0;
PxU32 j = 0;
while((i < batchSize) && (j < batchSize))
{
#if PX_SUPPORT_GPU_PHYSX
if(particleSystems[i]->isGpuV())
{
j = i + 1;
while(j < batchSize && particleSystems[j]->isGpuV())
{
j++;
}
if(j < batchSize)
{
Ps::swap(particleSystems[i], particleSystems[j]);
if(inputs)
{
Ps::swap(inputs[i], inputs[j]);
}
i++;
}
}
else
#endif
{
i++;
}
}
gpuOffset = i;
cpuCount = gpuOffset;
gpuCount = batchSize - cpuCount;
}
}
Batcher::Batcher(class Context& _context)
: shapeGenTask(0, "Pt::Batcher::shapeGen")
, dynamicsCpuTask(0, "Pt::Batcher::dynamicsCpu")
, collPrepTask(0, "Pt::Batcher::collPrep")
, collisionCpuTask(0, "Pt::Batcher::collisionCpu")
, context(_context)
{
}
PxBaseTask& Batcher::scheduleShapeGeneration(ParticleSystemSim** particleSystems, ParticleShapesUpdateInput* inputs,
PxU32 batchSize, PxBaseTask& continuation)
{
PxU32 cpuOffset = 0;
PxU32 cpuCount = batchSize;
#if PX_SUPPORT_GPU_PHYSX
PxU32 gpuOffset, gpuCount;
sortBatchedInputs(particleSystems, inputs, batchSize, cpuOffset, cpuCount, gpuOffset, gpuCount);
if(context.getSceneGpuFast() && gpuCount > 0)
{
PxBaseTask& task = context.getSceneGpuFast()->scheduleParticleShapeUpdate(
particleSystems + gpuOffset, inputs + gpuOffset, gpuCount, continuation);
shapeGenTask.addDependent(task);
task.removeReference();
}
#endif
for(PxU32 i = cpuOffset; i < (cpuOffset + cpuCount); ++i)
{
PxBaseTask& task =
static_cast<ParticleSystemSimCpu*>(particleSystems[i])->schedulePacketShapesUpdate(inputs[i], continuation);
shapeGenTask.addDependent(task);
task.removeReference();
}
if(shapeGenTask.getReference() == 0)
{
continuation.addReference();
return continuation;
}
while(shapeGenTask.getReference() > 1)
shapeGenTask.removeReference();
return shapeGenTask;
}
PxBaseTask& Batcher::scheduleDynamicsCpu(ParticleSystemSim** particleSystems, PxU32 batchSize, PxBaseTask& continuation)
{
PxU32 cpuOffset = 0;
PxU32 cpuCount = batchSize;
#if PX_SUPPORT_GPU_PHYSX
PxU32 gpuOffset, gpuCount;
sortBatchedInputs(particleSystems, (PxU8*)NULL, batchSize, cpuOffset, cpuCount, gpuOffset, gpuCount);
#endif
for(PxU32 i = cpuOffset; i < (cpuOffset + cpuCount); ++i)
{
PxBaseTask& task = static_cast<ParticleSystemSimCpu*>(particleSystems[i])->scheduleDynamicsUpdate(continuation);
dynamicsCpuTask.addDependent(task);
task.removeReference();
}
if(dynamicsCpuTask.getReference() == 0)
{
continuation.addReference();
return continuation;
}
while(dynamicsCpuTask.getReference() > 1)
dynamicsCpuTask.removeReference();
return dynamicsCpuTask;
}
PxBaseTask& Batcher::scheduleCollisionPrep(ParticleSystemSim** particleSystems, PxLightCpuTask** inputPrepTasks,
PxU32 batchSize, PxBaseTask& continuation)
{
PxU32 cpuOffset = 0;
PxU32 cpuCount = batchSize;
#if PX_SUPPORT_GPU_PHYSX
PxU32 gpuOffset, gpuCount;
sortBatchedInputs(particleSystems, inputPrepTasks, batchSize, cpuOffset, cpuCount, gpuOffset, gpuCount);
if(context.getSceneGpuFast() && gpuCount > 0)
{
PxBaseTask& gpuCollisionInputTask = context.getSceneGpuFast()->scheduleParticleCollisionInputUpdate(
particleSystems + gpuOffset, gpuCount, continuation);
for(PxU32 i = gpuOffset; i < (gpuOffset + gpuCount); ++i)
{
inputPrepTasks[i]->setContinuation(&gpuCollisionInputTask);
collPrepTask.addDependent(*inputPrepTasks[i]);
inputPrepTasks[i]->removeReference();
}
gpuCollisionInputTask.removeReference();
}
#else
PX_UNUSED(particleSystems);
PX_UNUSED(batchSize);
#endif
for(PxU32 i = cpuOffset; i < (cpuOffset + cpuCount); ++i)
{
inputPrepTasks[i]->setContinuation(&continuation);
collPrepTask.addDependent(*inputPrepTasks[i]);
inputPrepTasks[i]->removeReference();
}
if(collPrepTask.getReference() == 0)
{
continuation.addReference();
return continuation;
}
while(collPrepTask.getReference() > 1)
collPrepTask.removeReference();
return collPrepTask;
}
PxBaseTask& Batcher::scheduleCollisionCpu(ParticleSystemSim** particleSystems, PxU32 batchSize, PxBaseTask& continuation)
{
PxU32 cpuOffset = 0;
PxU32 cpuCount = batchSize;
#if PX_SUPPORT_GPU_PHYSX
PxU32 gpuOffset, gpuCount;
sortBatchedInputs(particleSystems, (PxU8*)NULL, batchSize, cpuOffset, cpuCount, gpuOffset, gpuCount);
#endif
for(PxU32 i = cpuOffset; i < (cpuOffset + cpuCount); ++i)
{
PxBaseTask& task = static_cast<ParticleSystemSimCpu*>(particleSystems[i])->scheduleCollisionUpdate(continuation);
collisionCpuTask.addDependent(task);
task.removeReference();
}
if(collisionCpuTask.getReference() == 0)
{
continuation.addReference();
return continuation;
}
while(collisionCpuTask.getReference() > 1)
collisionCpuTask.removeReference();
return collisionCpuTask;
}
PxBaseTask& Batcher::schedulePipelineGpu(ParticleSystemSim** particleSystems, PxU32 batchSize, PxBaseTask& continuation)
{
#if PX_SUPPORT_GPU_PHYSX
PxU32 cpuOffset, cpuCount, gpuOffset, gpuCount;
sortBatchedInputs(particleSystems, (PxU8*)NULL, batchSize, cpuOffset, cpuCount, gpuOffset, gpuCount);
if(context.getSceneGpuFast() && gpuCount > 0)
{
return context.getSceneGpuFast()->scheduleParticlePipeline(particleSystems + gpuOffset, gpuCount, continuation);
}
#else
PX_UNUSED(batchSize);
PX_UNUSED(particleSystems);
#endif
continuation.addReference();
return continuation;
}
#endif // PX_USE_PARTICLE_SYSTEM_API
| 30.65625 | 121 | 0.747324 | windystrife |
d5e10077a710ca79d5a9c42054fb12ad6e5f7d1c | 898 | cpp | C++ | test/vpunsignedshorttest.cpp | prodigeinfo/libvapor | eb23abd8c211f4a5b04dcee757ea323451011924 | [
"BSD-3-Clause"
] | null | null | null | test/vpunsignedshorttest.cpp | prodigeinfo/libvapor | eb23abd8c211f4a5b04dcee757ea323451011924 | [
"BSD-3-Clause"
] | null | null | null | test/vpunsignedshorttest.cpp | prodigeinfo/libvapor | eb23abd8c211f4a5b04dcee757ea323451011924 | [
"BSD-3-Clause"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <vapor/vpunsignedshort.hpp>
using namespace std;
using namespace vapor;
BOOST_AUTO_TEST_SUITE(test_suite1)
BOOST_AUTO_TEST_CASE(vpunsignedshort_serialize)
{
vparchive_t expect, result;
vpunsignedshort vpn;
expect = "unsignedShort;5;12345";
vpn = 12345;
result = vpn.serialize();
BOOST_REQUIRE_EQUAL(expect, result);
}
BOOST_AUTO_TEST_CASE(vpunsignedshort_deserialize)
{
unsigned short expect;
vpunsignedshort result;
vparchive_t s;
try {
result.deserialize("void;5;12345");
BOOST_FAIL("bad type shoud fail [" + boost::lexical_cast<std::string>(result) + "]");
}
catch (invalid_argument ex) {}
s = "unsignedShort;5;12345";
expect = 12345;
result.deserialize(s.c_str());
BOOST_REQUIRE_EQUAL(expect, result);
}
BOOST_AUTO_TEST_SUITE_END()
| 21.902439 | 93 | 0.711581 | prodigeinfo |
d5e3ac356fe0624b33af57a8a8fa9213b9038089 | 11,125 | cpp | C++ | oneflow/core/intrusive/list_test.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2022-03-14T11:17:56.000Z | 2022-03-14T11:17:56.000Z | oneflow/core/intrusive/list_test.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | null | null | null | oneflow/core/intrusive/list_test.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2021-12-15T02:14:49.000Z | 2021-12-15T02:14:49.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// include sstream first to avoid some compiling error
// caused by the following trick
// reference: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65899
#include <sstream>
#include "gtest/gtest.h"
#define private public
#include "oneflow/core/common/util.h"
#include "oneflow/core/intrusive/intrusive.h"
namespace oneflow {
namespace test {
namespace {
class TestListItem : public intrusive::Base {
public:
void __Init__() { clear_cnt(); }
void __Delete__() {
if (has_cnt()) { --*mut_cnt(); }
}
// Getters
bool has_cnt() const { return cnt_ != nullptr; }
int cnt() const { return *cnt_; }
bool is_foo_list_empty() const { return foo_list_.empty(); }
// Setters
void set_cnt(int* val) { cnt_ = val; }
void clear_cnt() { cnt_ = nullptr; }
int* mut_cnt() { return cnt_; }
size_t ref_cnt() const { return intrusive_ref_.ref_cnt(); }
intrusive::ListHook foo_list_;
private:
friend class intrusive::Ref;
intrusive::Ref* mut_intrusive_ref() { return &intrusive_ref_; }
TestListItem() : foo_list_(), intrusive_ref_(), cnt_() {}
intrusive::Ref intrusive_ref_;
int* cnt_;
};
using TestList = intrusive::List<INTRUSIVE_FIELD(TestListItem, foo_list_)>;
TEST(List, empty) {
TestList foo_list;
ASSERT_TRUE(foo_list.empty());
ASSERT_EQ(foo_list.size(), 0);
}
TEST(List, empty_Begin) {
TestList foo_list;
intrusive::shared_ptr<TestListItem> obj_ptr;
obj_ptr = foo_list.Begin();
ASSERT_TRUE(!obj_ptr);
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(!obj_ptr);
}
TEST(List, empty_Next) {
TestList foo_list;
intrusive::shared_ptr<TestListItem> obj_ptr;
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(!obj_ptr);
ASSERT_TRUE(!next);
obj_ptr = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(!obj_ptr);
obj_ptr = next;
next = foo_list.Next(next.Mutable());
ASSERT_TRUE(!obj_ptr);
ASSERT_TRUE(!next);
}
TEST(List, PushFront) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushFront(item0.Mutable());
foo_list.PushFront(item1.Mutable());
intrusive::shared_ptr<TestListItem> obj_ptr;
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(obj_ptr == item1);
ASSERT_TRUE(next == item0);
}
TEST(List, destructor) {
int elem_cnt = 2;
{
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
item0->set_cnt(&elem_cnt);
auto item1 = intrusive::make_shared<TestListItem>();
item1->set_cnt(&elem_cnt);
foo_list.PushFront(item0.Mutable());
foo_list.PushFront(item1.Mutable());
}
ASSERT_EQ(elem_cnt, 0);
elem_cnt = 2;
auto item0 = intrusive::make_shared<TestListItem>();
{
TestList foo_list;
item0->set_cnt(&elem_cnt);
auto item1 = intrusive::make_shared<TestListItem>();
item1->set_cnt(&elem_cnt);
foo_list.PushFront(item0.Mutable());
foo_list.PushFront(item1.Mutable());
}
ASSERT_EQ(elem_cnt, 1);
}
TEST(List, PushBack) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
intrusive::shared_ptr<TestListItem> obj_ptr;
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(obj_ptr == item0);
ASSERT_TRUE(next == item1);
}
TEST(List, Erase) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item1->ref_cnt(), 2);
foo_list.Erase(item1.Mutable());
ASSERT_EQ(item1->ref_cnt(), 1);
intrusive::shared_ptr<TestListItem> obj_ptr;
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(obj_ptr == item0);
ASSERT_TRUE(!next);
}
TEST(List, PopBack) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item1->ref_cnt(), 2);
foo_list.PopBack();
ASSERT_EQ(item1->ref_cnt(), 1);
intrusive::shared_ptr<TestListItem> obj_ptr;
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(obj_ptr == item0);
ASSERT_TRUE(!next);
}
TEST(List, PopFront) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item0->ref_cnt(), 2);
foo_list.PopFront();
ASSERT_EQ(item0->ref_cnt(), 1);
intrusive::shared_ptr<TestListItem> obj_ptr;
intrusive::shared_ptr<TestListItem> next;
obj_ptr = foo_list.Begin();
next = foo_list.Next(obj_ptr.Mutable());
ASSERT_TRUE(!next);
}
TEST(List, Clear) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item0->ref_cnt(), 2);
ASSERT_EQ(item1->ref_cnt(), 2);
foo_list.Clear();
ASSERT_TRUE(foo_list.empty());
ASSERT_EQ(item0->ref_cnt(), 1);
ASSERT_EQ(item1->ref_cnt(), 1);
}
TEST(List, UNSAFE_FOR_EACH_PTR) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
int i = 0;
INTRUSIVE_UNSAFE_FOR_EACH_PTR(item, &foo_list) {
if (i == 0) {
ASSERT_TRUE(item == item0.Mutable());
} else if (i == 1) {
ASSERT_TRUE(item == item1.Mutable());
}
++i;
}
ASSERT_EQ(i, 2);
}
TEST(List, FOR_EACH) {
TestList foo_list;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
int i = 0;
INTRUSIVE_FOR_EACH(item, &foo_list) {
if (i == 0) {
ASSERT_TRUE(item == item0);
foo_list.Erase(item.Mutable());
} else if (i == 1) {
ASSERT_TRUE(item == item1);
foo_list.Erase(item.Mutable());
}
++i;
}
ASSERT_EQ(i, 2);
ASSERT_TRUE(foo_list.empty());
ASSERT_EQ(item0->ref_cnt(), 1);
ASSERT_EQ(item1->ref_cnt(), 1);
}
class TestIntrusiveListHead final : public intrusive::Base {
public:
// types
using FooList = intrusive::List<INTRUSIVE_FIELD(TestListItem, foo_list_)>;
// Getters
const FooList& foo_list() const { return foo_list_; }
// Setters
FooList* mut_foo_list() { return &foo_list_; }
private:
friend class intrusive::Ref;
intrusive::Ref* mut_intrusive_ref() { return &intrusive_ref_; }
TestIntrusiveListHead() : intrusive_ref_(), foo_list_() {}
intrusive::Ref intrusive_ref_;
FooList foo_list_;
};
TEST(List, intrusive_list_for_each) {
auto foo_list_head = intrusive::make_shared<TestIntrusiveListHead>();
auto& foo_list = *foo_list_head->mut_foo_list();
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item0->ref_cnt(), 2);
ASSERT_EQ(item1->ref_cnt(), 2);
int i = 0;
INTRUSIVE_FOR_EACH(item, &foo_list) {
if (i == 0) {
ASSERT_TRUE(item == item0);
foo_list.Erase(item.Mutable());
} else if (i == 1) {
ASSERT_TRUE(item == item1);
foo_list.Erase(item.Mutable());
}
++i;
}
ASSERT_EQ(i, 2);
ASSERT_TRUE(foo_list.empty());
ASSERT_EQ(item0->ref_cnt(), 1);
ASSERT_EQ(item1->ref_cnt(), 1);
}
class TestIntrusiveListHeadWrapper final : public intrusive::Base {
public:
// Getters
const TestIntrusiveListHead& head() const {
if (head_) { return head_.Get(); }
static const auto default_val = intrusive::make_shared<TestIntrusiveListHead>();
return default_val.Get();
}
// Setters
TestIntrusiveListHead* mut_head() {
if (!head_) { head_ = intrusive::make_shared<TestIntrusiveListHead>(); }
return head_.Mutable();
}
void clear_head() {
if (head_) { head_.Reset(); }
}
private:
friend class intrusive::Ref;
intrusive::Ref* mut_intrusive_ref() { return &intrusive_ref_; }
TestIntrusiveListHeadWrapper() : intrusive_ref_(), head_() {}
intrusive::Ref intrusive_ref_;
intrusive::shared_ptr<TestIntrusiveListHead> head_;
};
TEST(List, nested_list_delete) {
auto foo_list_head = intrusive::make_shared<TestIntrusiveListHeadWrapper>();
auto& foo_list = *foo_list_head->mut_head()->mut_foo_list();
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item0->ref_cnt(), 2);
ASSERT_EQ(item1->ref_cnt(), 2);
int i = 0;
INTRUSIVE_UNSAFE_FOR_EACH_PTR(item, &foo_list) {
if (i == 0) {
ASSERT_TRUE(item == item0.Mutable());
} else if (i == 1) {
ASSERT_TRUE(item == item1.Mutable());
}
++i;
}
ASSERT_EQ(i, 2);
foo_list_head->clear_head();
ASSERT_EQ(item0->ref_cnt(), 1);
ASSERT_EQ(item1->ref_cnt(), 1);
}
TEST(List, MoveTo) {
TestList foo_list;
TestList foo_list0;
auto item0 = intrusive::make_shared<TestListItem>();
auto item1 = intrusive::make_shared<TestListItem>();
ASSERT_EQ(item0->is_foo_list_empty(), true);
ASSERT_EQ(item1->is_foo_list_empty(), true);
foo_list.PushBack(item0.Mutable());
foo_list.PushBack(item1.Mutable());
ASSERT_EQ(item0->is_foo_list_empty(), false);
ASSERT_EQ(item1->is_foo_list_empty(), false);
ASSERT_EQ(foo_list.size(), 2);
ASSERT_EQ(foo_list0.empty(), true);
ASSERT_EQ(item0->ref_cnt(), 2);
ASSERT_EQ(item1->ref_cnt(), 2);
foo_list.MoveTo(&foo_list0);
ASSERT_EQ(foo_list0.size(), 2);
ASSERT_EQ(foo_list.empty(), true);
ASSERT_TRUE(foo_list0.Begin() == item0.Mutable());
ASSERT_TRUE(foo_list0.Last() == item1.Mutable());
ASSERT_EQ(item0->ref_cnt(), 2);
ASSERT_EQ(item1->ref_cnt(), 2);
}
} // namespace
} // namespace test
} // namespace oneflow
| 29.509284 | 84 | 0.698966 | L-Net-1992 |
d5e4dd898852222cc34bd3fc24f21155f128d33b | 6,855 | cpp | C++ | src/jnc_api/jnc_DerivableType.cpp | vovkos/jancy | df693ef8072aeb4280d771a7d146041978ffce1f | [
"MIT"
] | 48 | 2017-04-21T15:55:22.000Z | 2021-11-19T16:40:25.000Z | src/jnc_api/jnc_DerivableType.cpp | vovkos/jancy | df693ef8072aeb4280d771a7d146041978ffce1f | [
"MIT"
] | 5 | 2018-09-18T07:43:46.000Z | 2021-07-31T15:41:09.000Z | src/jnc_api/jnc_DerivableType.cpp | vovkos/jancy | df693ef8072aeb4280d771a7d146041978ffce1f | [
"MIT"
] | 11 | 2018-10-06T11:33:43.000Z | 2022-03-04T10:16:23.000Z | //..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_DerivableType.h"
#ifdef _JNC_DYNAMIC_EXTENSION_LIB
# include "jnc_ExtensionLib.h"
#elif defined(_JNC_CORE)
# include "jnc_ct_DerivableType.h"
#endif
//..............................................................................
#ifdef _JNC_DYNAMIC_EXTENSION_LIB
JNC_EXTERN_C
size_t
jnc_BaseTypeSlot_getOffset(jnc_BaseTypeSlot* baseType) {
return jnc_g_dynamicExtensionLibHost->m_baseTypeSlotFuncTable->m_getOffsetFunc(baseType);
}
JNC_EXTERN_C
size_t
jnc_BaseTypeSlot_getVtableIndex(jnc_BaseTypeSlot* baseType) {
return jnc_g_dynamicExtensionLibHost->m_baseTypeSlotFuncTable->m_getVtableIndexFunc(baseType);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
JNC_EXTERN_C
uint_t
jnc_Field_getPtrTypeFlags(jnc_Field* field) {
return jnc_g_dynamicExtensionLibHost->m_fieldFuncTable->m_getPtrTypeFlagsFunc(field);
}
JNC_EXTERN_C
size_t
jnc_Field_getOffset(jnc_Field* field) {
return jnc_g_dynamicExtensionLibHost->m_fieldFuncTable->m_getOffsetFunc(field);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
JNC_EXTERN_C
jnc_Function*
jnc_DerivableType_getStaticConstructor(jnc_DerivableType* type) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getStaticConstructorFunc(type);
}
JNC_EXTERN_C
jnc_OverloadableFunction
jnc_DerivableType_getConstructor(jnc_DerivableType* type) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getConstructorFunc(type);
}
JNC_EXTERN_C
jnc_Function*
jnc_DerivableType_getDestructor(jnc_DerivableType* type) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getDestructorFunc(type);
}
JNC_EXTERN_C
jnc_OverloadableFunction
jnc_DerivableType_getUnaryOperator(
jnc_DerivableType* type,
jnc_UnOpKind opKind
) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getUnaryOperatorFunc(type, opKind);
}
JNC_EXTERN_C
jnc_OverloadableFunction
jnc_DerivableType_getBinaryOperator(
jnc_DerivableType* type,
jnc_BinOpKind opKind
) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getBinaryOperatorFunc(type, opKind);
}
JNC_EXTERN_C
jnc_OverloadableFunction
jnc_DerivableType_getCallOperator(jnc_DerivableType* type) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getCallOperatorFunc(type);
}
JNC_EXTERN_C
size_t
jnc_DerivableType_getCastOperatorCount(jnc_DerivableType* type) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getCastOperatorCountFunc(type);
}
JNC_EXTERN_C
jnc_Function*
jnc_DerivableType_getCastOperator(
jnc_DerivableType* type,
size_t index
) {
return jnc_g_dynamicExtensionLibHost->m_derivableTypeFuncTable->m_getCastOperatorFunc(type, index);
}
#else // _JNC_DYNAMIC_EXTENSION_LIB
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_BaseTypeSlot_getOffset(jnc_BaseTypeSlot* baseType) {
return baseType->getOffset();
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_BaseTypeSlot_getVtableIndex(jnc_BaseTypeSlot* baseType) {
return baseType->getVtableIndex();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
JNC_EXTERN_C
JNC_EXPORT_O
uint_t
jnc_Field_getPtrTypeFlags(jnc_Field* field) {
return field->getPtrTypeFlags();
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_Field_getOffset(jnc_Field* field) {
return field->getOffset();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Function*
jnc_DerivableType_getStaticConstructor(jnc_DerivableType* type) {
return type->getStaticConstructor();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_OverloadableFunction
jnc_DerivableType_getConstructor(jnc_DerivableType* type) {
return type->getConstructor();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Function*
jnc_DerivableType_getDestructor(jnc_DerivableType* type) {
return type->getDestructor();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_OverloadableFunction
jnc_DerivableType_getUnaryOperator(
jnc_DerivableType* type,
jnc_UnOpKind opKind
) {
return type->getUnaryOperator((jnc::UnOpKind)opKind);
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_OverloadableFunction
jnc_DerivableType_getBinaryOperator(
jnc_DerivableType* type,
jnc_BinOpKind opKind
) {
return type->getBinaryOperator((jnc::BinOpKind)opKind);
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_OverloadableFunction
jnc_DerivableType_getCallOperator(jnc_DerivableType* type) {
return type->getCallOperator();
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_getCastOperatorCount(jnc_DerivableType* type) {
return type->getCastOperatorArray().getCount();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Function*
jnc_DerivableType_getCastOperator(
jnc_DerivableType* type,
size_t index
) {
return type->getCastOperatorArray()[index];
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_getBaseTypeCount(jnc_DerivableType* type) {
return type->getBaseTypeArray().getCount();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_BaseTypeSlot*
jnc_DerivableType_getBaseType(
jnc_DerivableType* type,
size_t index
) {
return type->getBaseTypeArray() [index];
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_findBaseTypeOffset(
jnc_DerivableType* type,
jnc_Type* baseType
) {
return type->findBaseTypeOffset(baseType);
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_getStaticVariableCount(jnc_DerivableType* type) {
return type->getStaticVariableArray().getCount();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Variable*
jnc_DerivableType_getStaticVariable(
jnc_DerivableType* type,
size_t index
) {
return type->getStaticVariableArray()[index];
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_getFieldCount(jnc_DerivableType* type) {
return type->getFieldArray().getCount();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Field*
jnc_DerivableType_getField(
jnc_DerivableType* type,
size_t index
) {
return type->getFieldArray()[index];
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_getMethodCount(jnc_DerivableType* type) {
return type->getMethodArray().getCount();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Function*
jnc_DerivableType_getMethod(
jnc_DerivableType* type,
size_t index
) {
return type->getMethodArray()[index];
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_DerivableType_getPropertyCount(jnc_DerivableType* type) {
return type->getPropertyArray().getCount();
}
JNC_EXTERN_C
JNC_EXPORT_O
jnc_Property*
jnc_DerivableType_getProperty(
jnc_DerivableType* type,
size_t index
) {
return type->getPropertyArray()[index];
}
#endif // _JNC_DYNAMIC_EXTENSION_LIB
| 22.47541 | 103 | 0.768053 | vovkos |
d5e572fcf3fe72934cef6d27a971b7646c24ca35 | 1,874 | cpp | C++ | Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 1 | 2021-11-26T08:29:28.000Z | 2021-11-26T08:29:28.000Z | Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 1 | 2022-02-09T08:28:12.000Z | 2022-02-09T08:28:12.000Z | /*
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
#include <LibWeb/DOM/Element.h>
namespace Web::Bindings {
bool CSSStyleDeclarationWrapper::internal_has_property(JS::PropertyName const& name) const
{
if (!name.is_string())
return Base::internal_has_property(name);
// FIXME: These should actually use camelCase versions of the property names!
auto property_id = CSS::property_id_from_string(name.to_string());
return property_id != CSS::PropertyID::Invalid;
}
JS::Value CSSStyleDeclarationWrapper::internal_get(JS::PropertyName const& name, JS::Value receiver) const
{
if (!name.is_string())
return Base::internal_get(name, receiver);
// FIXME: These should actually use camelCase versions of the property names!
auto property_id = CSS::property_id_from_string(name.to_string());
if (property_id == CSS::PropertyID::Invalid)
return Base::internal_get(name, receiver);
if (auto maybe_property = impl().property(property_id); maybe_property.has_value())
return js_string(vm(), maybe_property->value->to_string());
return js_string(vm(), String::empty());
}
bool CSSStyleDeclarationWrapper::internal_set(JS::PropertyName const& name, JS::Value value, JS::Value receiver)
{
if (!name.is_string())
return Base::internal_set(name, value, receiver);
// FIXME: These should actually use camelCase versions of the property names!
auto property_id = CSS::property_id_from_string(name.to_string());
if (property_id == CSS::PropertyID::Invalid)
return Base::internal_set(name, value, receiver);
auto css_text = value.to_string(global_object());
if (vm().exception())
return false;
return impl().set_property(property_id, css_text);
}
}
| 36.745098 | 112 | 0.71825 | TheCrott |
d5e91b4055d47089a1923a34fe12cb477a0ea8c4 | 2,698 | cpp | C++ | bytezero/storages/bytezerosdk.cpp | alackfeng/bytezeroqt | 27978eb28a0637234be07a6a9daa6dcc9c684d40 | [
"MIT"
] | null | null | null | bytezero/storages/bytezerosdk.cpp | alackfeng/bytezeroqt | 27978eb28a0637234be07a6a9daa6dcc9c684d40 | [
"MIT"
] | null | null | null | bytezero/storages/bytezerosdk.cpp | alackfeng/bytezeroqt | 27978eb28a0637234be07a6a9daa6dcc9c684d40 | [
"MIT"
] | null | null | null | #include "bytezerosdk.h"
static const char* BYTEZERO_SDK_VERSION = "v1.0.0";
static QString BYTEZERO_APP_NAME = QObject::tr("bytezero");
static QString BYTEZERO_APP_TEST_NAME = QObject::tr("bytezero_test");
BytezeroSdk::BytezeroSdk(QObject *parent) : QObject(parent), m_config(new Config())
{
QThreadPool::globalInstance()->setMaxThreadCount(3);
m_appMode = m_config->appMode();
qDebug() << "BytezeroSdk::BytezeroSdk - sdk." << this << ", app " << m_appMode << ", " << Utils::getAppDataPath();
}
BytezeroSdk::~BytezeroSdk()
{
}
BytezeroSdk *BytezeroSdk::reset()
{
return this;
}
BytezeroSdk *BytezeroSdk::init(QQmlApplicationEngine *qmlEngine)
{
engine = qmlEngine;
rootContext = engine->rootContext();
registerContexts();
registerModels();
return this;
}
BytezeroSdk *BytezeroSdk::loadLanguage(QTranslator *translator)
{
m_translator = translator;
QLocale locale;
QString languageName = m_config->appLanguage();
if(languageName == "") {
languageName = locale.name();
}
setLanguage(languageName);
return this;
}
bool BytezeroSdk::is_online()
{
return false;
}
bool BytezeroSdk::device_online(const device_access_func &)
{
return false;
}
bool BytezeroSdk::db_online(const db_access_func &)
{
return false;
}
QString BytezeroSdk::version() const
{
return BYTEZERO_SDK_VERSION;
}
QString BytezeroSdk::title() const
{
return (m_appMode == 2) ? QObject::tr("bytezero") : QObject::tr("bytezero_test");
}
QString BytezeroSdk::language() const
{
return m_language;
}
void BytezeroSdk::setLanguage(QString lang)
{
if(m_language == lang) return;
if(m_translator) {
QString langBaseName = ":/i18n/bytezero_";
if(lang == "zh_CN") {
langBaseName += lang;
} else {
langBaseName += "en";
}
if (m_translator->load(langBaseName)) {
QGuiApplication::instance()->installTranslator(m_translator);
engine->retranslate();
m_language = lang;
} else {
qWarning() << "BytezeroSdk::setLanguage - language file load failed." << langBaseName << ", " << QGuiApplication::applicationDirPath();
}
}
m_config->setAppLanguage(m_language);
emit languageChanged();
}
void BytezeroSdk::registerContexts()
{
// qDebug() << "BytezeroSdk::registerContexts - call.";
if(0 == engine) {
return;
}
rootContext->setContextProperty("bzSdk", this);
}
void BytezeroSdk::registerModels()
{
// qDebug() << "BytezeroSdk::registerModels - call.";
}
| 24.089286 | 148 | 0.627131 | alackfeng |
d5ea7ea15b1074c29b6be67d04c93929ebc54ee8 | 296 | cpp | C++ | B2S2 - Lab of Algorithm Design/1043_f.cpp | abc1236762/UniversityHomework | 688f6fc45d610f84c0c24a6d5ab75ea70ea6a59f | [
"MIT"
] | null | null | null | B2S2 - Lab of Algorithm Design/1043_f.cpp | abc1236762/UniversityHomework | 688f6fc45d610f84c0c24a6d5ab75ea70ea6a59f | [
"MIT"
] | 4 | 2021-03-28T14:06:09.000Z | 2021-03-28T14:06:10.000Z | B2S2 - Lab of Algorithm Design/1043_f.cpp | abc1236762/UniversityHomework | 688f6fc45d610f84c0c24a6d5ab75ea70ea6a59f | [
"MIT"
] | 1 | 2020-04-29T16:00:32.000Z | 2020-04-29T16:00:32.000Z | #include <iostream>
using namespace std;
int main(int argc, char **argv) {
int n = 0, m = 0;
while (cin >> n) {
while (n--) {
cin >> m;
int result = 1;
while (m % 3 == 0) m /= 3, result *= 3;
while (m % 5 == 0) m /= 5, result *= 5;
cout << result << endl;
}
}
return 0;
} | 17.411765 | 42 | 0.489865 | abc1236762 |
d5eab3c79a6b10531133865f90611aa338c38f1c | 3,519 | hpp | C++ | trajopt_sco/include/trajopt_sco/optimizers.hpp | Levi-Armstrong/trajopt_ros | a90cd90478d4048af501ad503360d8dfd7460f20 | [
"BSD-2-Clause"
] | 2 | 2017-12-08T14:43:43.000Z | 2017-12-09T16:41:36.000Z | trajopt_sco/include/trajopt_sco/optimizers.hpp | Levi-Armstrong/trajopt_ros | a90cd90478d4048af501ad503360d8dfd7460f20 | [
"BSD-2-Clause"
] | 2 | 2017-12-08T04:57:34.000Z | 2020-02-07T21:46:45.000Z | trajopt_sco/include/trajopt_sco/optimizers.hpp | Levi-Armstrong/trajopt_ros | a90cd90478d4048af501ad503360d8dfd7460f20 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <string>
#include <trajopt_sco/modeling.hpp>
#include <boost/function.hpp>
/*
* Algorithms for non-convex, constrained optimization
*/
namespace sco {
using std::string;
using std::vector;
enum OptStatus {
OPT_CONVERGED,
OPT_SCO_ITERATION_LIMIT, // hit iteration limit before convergence
OPT_PENALTY_ITERATION_LIMIT,
OPT_FAILED,
INVALID
};
static const char* OptStatus_strings[] = {
"CONVERGED",
"SCO_ITERATION_LIMIT",
"PENALTY_ITERATION_LIMIT",
"FAILED",
"INVALID"
};
inline string statusToString(OptStatus status) {
return OptStatus_strings[status];
}
struct OptResults {
DblVec x; // solution estimate
OptStatus status;
double total_cost;
vector<double> cost_vals;
DblVec cnt_viols;
int n_func_evals, n_qp_solves;
void clear() {
x.clear();
status = INVALID;
cost_vals.clear();
cnt_viols.clear();
n_func_evals = 0;
n_qp_solves = 0;
}
OptResults() {clear();}
};
std::ostream& operator<<(std::ostream& o, const OptResults& r);
class Optimizer {
/*
* Solves an optimization problem
*/
public:
virtual OptStatus optimize() = 0;
virtual ~Optimizer() {}
virtual void setProblem(OptProbPtr prob) {prob_ = prob;}
void initialize(const vector<double>& x);
vector<double>& x() {return results_.x;}
OptResults& results() {return results_;}
typedef boost::function<void(OptProb*, DblVec&)> Callback;
void addCallback(const Callback& f); // called before each iteration
protected:
vector<Callback> callbacks_;
void callCallbacks(DblVec& x);
OptProbPtr prob_;
OptResults results_;
};
class BasicTrustRegionSQP : public Optimizer {
/*
* Alternates between convexifying objectives and constraints and then solving convex subproblem
* Uses a merit function to decide whether or not to accept the step
* merit function = objective + merit_err_coeff * | constraint_error |
* Note: sometimes the convexified objectives and constraints lead to an infeasible subproblem
* In that case, you should turn them into penalties and solve that problem
* (todo: implement penalty-based sqp that gracefully handles infeasible constraints)
*/
public:
double improve_ratio_threshold_, // minimum ratio true_improve/approx_improve to accept step
min_trust_box_size_, // if trust region gets any smaller, exit and report convergence
min_approx_improve_, // if model improves less than this, exit and report convergence
min_approx_improve_frac_, // if model improves less than this, exit and report convergence
max_iter_,
trust_shrink_ratio_, // if improvement is less than improve_ratio_threshold, shrink trust region by this ratio
trust_expand_ratio_, // see above
cnt_tolerance_, // after convergence of penalty subproblem, if constraint violation is less than this, we're done
max_merit_coeff_increases_, // number of times that we jack up penalty coefficient
merit_coeff_increase_ratio_, // ratio that we increate coeff each time
max_time_ // not yet implemented
;
double merit_error_coeff_, // initial penalty coefficient
trust_box_size_ // current size of trust region (component-wise)
;
BasicTrustRegionSQP();
BasicTrustRegionSQP(OptProbPtr prob);
void setProblem(OptProbPtr prob);
OptStatus optimize();
protected:
void adjustTrustRegion(double ratio);
void setTrustBoxConstraints(const vector<double>& x);
void initParameters();
ModelPtr model_;
};
}
| 31.141593 | 122 | 0.7289 | Levi-Armstrong |
d5eb0563dc8f258ba50d1435f0ea354f2d4a679c | 1,441 | cpp | C++ | test/treehash.test.cpp | habara-k/ac-library | c48e576430c335d7037fa88e9fa5f6a61858e68a | [
"Unlicense"
] | null | null | null | test/treehash.test.cpp | habara-k/ac-library | c48e576430c335d7037fa88e9fa5f6a61858e68a | [
"Unlicense"
] | null | null | null | test/treehash.test.cpp | habara-k/ac-library | c48e576430c335d7037fa88e9fa5f6a61858e68a | [
"Unlicense"
] | null | null | null | #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2821"
#include <atcoder/treehash>
#include <atcoder/dsu>
#include <iostream>
#include <map>
using namespace atcoder;
using namespace std;
int main() {
int n1, m1; cin >> n1 >> m1;
vector<vector<int>> g1(n1);
dsu uf(n1);
for (int i = 0; i < m1; i++) {
int u, v; cin >> u >> v; --u, --v;
g1[u].emplace_back(v);
g1[v].emplace_back(u);
uf.merge(u, v);
}
int n2; cin >> n2;
vector<vector<int>> g2(n2);
for (int i = 0; i < n2-1; i++) {
int u, v; cin >> u >> v; --u, --v;
g2[u].emplace_back(v);
g2[v].emplace_back(u);
}
vector<int> roots;
for (int i = 0; i < n1; ++i) if (uf.leader(i) == i) roots.emplace_back(i);
map<int,map<int,int>> ord;
for (int i = 0; i < n1; ++i) {
ord[uf.leader(i)][i] = -1;
}
map<int,vector<vector<int>>> g;
for (auto& tp : ord) {
int cnt = 0;
for (auto& p : tp.second) {
p.second = cnt++;
}
g[tp.first].resize(cnt);
}
for (int u = 0; u < n1; ++u) {
int r = uf.leader(u);
for (int v : g1[u]) {
g[r][ord[r][u]].emplace_back(ord[r][v]);
}
}
int ans = 0;
auto hash = TreeHash{g2}.get();
for (auto &tp : g) {
auto h = TreeHash{tp.second}.get();
ans += h == hash;
}
cout << ans << endl;
}
| 23.241935 | 79 | 0.476058 | habara-k |
d5eb9293100420ea64dae68846204509de9f2d39 | 2,513 | cpp | C++ | MeshViewer/MainViewerWidget.cpp | 565353780/peeling-art | 7427321c8cbf076361c8de2281a0f0cde7fd38bb | [
"MIT"
] | null | null | null | MeshViewer/MainViewerWidget.cpp | 565353780/peeling-art | 7427321c8cbf076361c8de2281a0f0cde7fd38bb | [
"MIT"
] | null | null | null | MeshViewer/MainViewerWidget.cpp | 565353780/peeling-art | 7427321c8cbf076361c8de2281a0f0cde7fd38bb | [
"MIT"
] | null | null | null | #include "MainViewerWidget.h"
#include <QHBoxLayout>
MainViewerWidget::MainViewerWidget(QWidget* _parent/* =0 */)
{
initViewerWindow();
LoadMeshSuccess = false;
child_viewer = new MainChildWidget();
}
MainViewerWidget::~MainViewerWidget()
{
};
void MainViewerWidget::initViewerWindow()
{
createViewerDialog();
QHBoxLayout* main_layout = new QHBoxLayout();
main_layout->addWidget(MeshViewer, 1);
this->setLayout(main_layout);
connect(MeshViewer,SIGNAL(setMouseMode_signal(int)),SIGNAL(setMouseMode_signal_main(int)));
connect(MeshViewer,SIGNAL(setDrawMode_signal(int)),SIGNAL(setDrawMode_signal_main(int)));
}
void MainViewerWidget::createViewerDialog()
{
QGLFormat glFormat;
glFormat.setSampleBuffers(true);
glFormat.setSamples(16);
MeshViewer = new InteractiveViewerWidget(glFormat, NULL);
MeshViewer->setAcceptDrops(true);
connect(MeshViewer,SIGNAL(loadMeshOK(bool,QString)), this, SLOT(LoadMeshFromInner(bool,QString)) );
}
void MainViewerWidget::open_mesh_gui(QString fname)
{
if (fname.isEmpty() || !MeshViewer->openMesh(fname.toLocal8Bit()))
{
QString msg = "Cannot read mesh from file:\n '";
msg += fname;
msg += "'";
QMessageBox::critical(NULL, windowTitle(), msg);
}
else
{
LoadMeshSuccess = true;
MeshViewer->setDrawMode(InteractiveViewerWidget::FLAT_POINTS);
MeshViewer->setMouseMode(InteractiveViewerWidget::TRANS);
if(LoadMeshSuccess)
{
SetMeshForALL();
}
emit(haveLoadMesh(fname));
}
}
void MainViewerWidget::save_mesh_gui(QString fname)
{
if (fname.isEmpty() || !MeshViewer->saveMesh(fname.toLocal8Bit()))
{
QString msg = "Cannot read mesh from file:\n '";
msg += fname;
msg += "'";
QMessageBox::critical(NULL, windowTitle(), msg);
}
}
void MainViewerWidget::save_screen_gui(QString fname)
{
if (fname.isEmpty() || !MeshViewer->saveScreen(fname.toLocal8Bit()))
{
QString msg = "Cannot save image to file:\n '";
msg += fname;
msg += "'";
QMessageBox::critical(NULL, windowTitle(), msg);
}
}
| 31.024691 | 559 | 0.576602 | 565353780 |
d5eccc5795916c0fa10943584aa1ab5dacc91fc7 | 1,568 | inl | C++ | SoftRP/TextureRenderTargetImpl.inl | loreStefani/SoftRP | 2676145f74c734b272268820b1e1c503aa8ff765 | [
"MIT"
] | null | null | null | SoftRP/TextureRenderTargetImpl.inl | loreStefani/SoftRP | 2676145f74c734b272268820b1e1c503aa8ff765 | [
"MIT"
] | null | null | null | SoftRP/TextureRenderTargetImpl.inl | loreStefani/SoftRP | 2676145f74c734b272268820b1e1c503aa8ff765 | [
"MIT"
] | null | null | null | #ifndef SOFTRP_TEXTURE_RENDER_TARGET_IMPL_INL_
#define SOFTRP_TEXTURE_RENDER_TARGET_IMPL_INL_
#include "TextureRenderTarget.h"
namespace SoftRP {
inline TextureRenderTarget::TextureRenderTarget(unsigned int width, unsigned int height)
: m_texture{ width, height } {}
inline TextureRenderTarget::TextureRenderTarget(const TextureRenderTarget& rt) : m_texture{ rt.m_texture } {}
inline TextureRenderTarget& TextureRenderTarget::operator=(const TextureRenderTarget& rt) {
m_texture = rt.m_texture;
}
inline TextureRenderTarget::TextureRenderTarget(TextureRenderTarget&& rt) : m_texture{ std::move(rt.m_texture) } {}
inline TextureRenderTarget& TextureRenderTarget::operator=(TextureRenderTarget&& rt) {
m_texture = std::move(rt.m_texture);
}
inline unsigned int TextureRenderTarget::width() const{
return m_texture.width();
}
inline unsigned int TextureRenderTarget::height() const{
return m_texture.height();
}
inline void TextureRenderTarget::resize(unsigned int width, unsigned int height) {
m_texture.resize(width, height);
}
inline void TextureRenderTarget::set(unsigned int i, unsigned int j, Math::Vector4 value) {
m_texture.set(i, j, value);
}
inline Math::Vector4 TextureRenderTarget::get(unsigned int i, unsigned int j) {
return m_texture.get(i, j);
}
inline void TextureRenderTarget::clear(Math::Vector4 value) {
m_texture.clear(value);
}
#ifdef SOFTRP_MULTI_THREAD
inline void TextureRenderTarget::clear(Math::Vector4 value, ThreadPool& threadPool) {
m_texture.clear(value, threadPool);
}
#endif
}
#endif
| 29.584906 | 116 | 0.772321 | loreStefani |
d5ee9ff667a99b99a5f9e28cc3b35438cfcb90f3 | 4,943 | cc | C++ | lmctfy/cli/commands/notify.cc | claytonbrown/lmctfy | 94729318edb06f7d149f67581a07a4c70ed29250 | [
"Apache-2.0"
] | 1,145 | 2015-01-01T22:07:47.000Z | 2022-03-30T19:19:23.000Z | lmctfy/cli/commands/notify.cc | claytonbrown/lmctfy | 94729318edb06f7d149f67581a07a4c70ed29250 | [
"Apache-2.0"
] | 9 | 2015-01-09T08:50:27.000Z | 2020-02-11T09:16:20.000Z | lmctfy/cli/commands/notify.cc | claytonbrown/lmctfy | 94729318edb06f7d149f67581a07a4c70ed29250 | [
"Apache-2.0"
] | 123 | 2015-01-02T12:10:08.000Z | 2021-10-12T02:49:48.000Z | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lmctfy/cli/commands/notify.h"
#include <memory>
#include <string>
using ::std::string;
#include <vector>
#include "gflags/gflags.h"
#include "base/logging.h"
#include "base/notification.h"
#include "lmctfy/cli/command.h"
#include "include/lmctfy.h"
#include "include/lmctfy.pb.h"
#include "util/errors.h"
#include "strings/numbers.h"
#include "strings/substitute.h"
#include "util/task/codes.pb.h"
#include "util/task/statusor.h"
DECLARE_string(lmctfy_config);
using ::std::unique_ptr;
using ::std::vector;
using ::strings::Substitute;
using ::util::Status;
using ::util::StatusOr;
namespace containers {
namespace lmctfy {
namespace cli {
// TODO(vmarmol): Add the ability to stream notifications.
// Handle a notification by storing the status and notifying the waiting thread.
static void NotificationHandler(Notification *notification, Status *out_status,
Container *container, Status status) {
*out_status = status;
notification->Notify();
}
// Register and wait for the specified event in the specified container.
static Status RegisterNotification(const EventSpec &spec,
const string &container_name,
const ContainerApi *lmctfy,
OutputMap *output) {
// Ensure the container exists.
unique_ptr<Container> container(
RETURN_IF_ERROR(lmctfy->Get(container_name)));
// Ask for the notification and wait for it to occur.
Status status;
Notification notification;
RETURN_IF_ERROR(
container->RegisterNotification(spec,
NewPermanentCallback(&NotificationHandler,
¬ification, &status)));
notification.WaitForNotification();
output->Add("notification_status", Substitute("$0", status.error_code()));
return status;
}
// Register and wait for an out of memory notification.
Status MemoryOomHandler(const vector<string> &argv, const ContainerApi *lmctfy,
OutputMap *output) {
// Args: oom <container name>
if (argv.size() != 2) {
return Status(::util::error::INVALID_ARGUMENT,
"See help for supported options.");
}
const string container_name = argv[1];
EventSpec spec;
spec.mutable_oom();
return RegisterNotification(spec, container_name, lmctfy, output);
}
// Register and wait for a memory usage threshold notification.
Status MemoryThresholdHandler(const vector<string> &argv,
const ContainerApi *lmctfy,
OutputMap *output) {
// Args: threshold <container name> <threshold in bytes>
if (argv.size() != 3) {
return Status(::util::error::INVALID_ARGUMENT,
"See help for supported options.");
}
const string container_name = argv[1];
uint64 threshold;
if (!SimpleAtoi(argv[2], &threshold)) {
return Status(
::util::error::INVALID_ARGUMENT,
Substitute("Failed to parse a threshold from \"$0\"", argv[2]));
}
EventSpec spec;
spec.mutable_memory_threshold()->set_usage(threshold);
return RegisterNotification(spec, container_name, lmctfy, output);
}
void RegisterNotifyCommands() {
RegisterRootCommand(SUB(
"notify",
"Register for and deliver a notification for the specified event. "
"Exit after the notification occurs.",
"<resource> <event> <container name> [<event arguments>]",
{SUB("memory", "Register for and deliver a memory related notification.",
"<event> <container name> [<event arguments>]",
{CMD("oom",
"Register for and deliver an out of memory notification. "
"The notification is triggered when the container runs out of "
"memory.",
"<container name>", CMD_TYPE_SETTER, 1, 1, &MemoryOomHandler),
CMD("threshold",
"Register for and deliver a memory usage threshold "
"notification. "
"The notification is triggered when the memory usage goes "
"above the specified threshold.",
"<container name> <threshold in bytes>", CMD_TYPE_SETTER, 2, 2,
&MemoryThresholdHandler)})}));
}
} // namespace cli
} // namespace lmctfy
} // namespace containers
| 35.561151 | 80 | 0.657698 | claytonbrown |
d5efe7ba44ca84209382dd004825c9c3d88d0541 | 604 | cpp | C++ | uva/c/11858.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/c/11858.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/c/11858.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | #include<cstdio>
#include<algorithm>
using namespace std;
const int N = 1000005;
int s[N], t[N];
long long go(int st, int ed) {
int i, j, k, m = (st + ed)/2;
long long sum = 0;
if (st >= ed) return 0;
sum = go(st, m) + go(m+1, ed);
for (i = st, j = m+1, k = st; k <= ed; ++k) {
if (j <= ed && (i > m || s[j] < s[i]))
t[k] = s[j++], sum += m - i + 1;
else t[k] = s[i++];
}
for (k = st; k <= ed; ++k) s[k] = t[k];
return sum;
}
main() {
int i, n;
while (scanf("%d", &n) == 1) {
for (i = 0; i < n; ++i)
scanf("%d", s+i);
printf("%lld\n", go(0, n-1));
}
}
| 22.37037 | 47 | 0.432119 | dk00 |
d5f021b20e661a790f445aaa139f3bf23ecfb3ed | 4,031 | cpp | C++ | src/PoseEstimationP3PKneip.cpp | SolarFramework/SolARModuleOpenGV | c02dee04380b45788e6a83433b4327dfc6763036 | [
"Apache-2.0"
] | 1 | 2019-12-23T07:48:01.000Z | 2019-12-23T07:48:01.000Z | src/PoseEstimationP3PKneip.cpp | SolarFramework/SolARModuleOpenGV | c02dee04380b45788e6a83433b4327dfc6763036 | [
"Apache-2.0"
] | null | null | null | src/PoseEstimationP3PKneip.cpp | SolarFramework/SolARModuleOpenGV | c02dee04380b45788e6a83433b4327dfc6763036 | [
"Apache-2.0"
] | 1 | 2019-07-24T15:03:48.000Z | 2019-07-24T15:03:48.000Z | /**
* @copyright Copyright (c) 2017 B-com http://www.b-com.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 "PoseEstimationP3PKneip.h"
#include "SolARModuleOpengv_traits.h"
#include "core/Log.h"
#include <opengv/absolute_pose/methods.hpp>
#include <opengv/absolute_pose/CentralAbsoluteAdapter.hpp>
#include <opengv/math/cayley.hpp>
XPCF_DEFINE_FACTORY_CREATE_INSTANCE(SolAR::MODULES::OPENGV::PoseEstimationP3PKneip);
namespace xpcf = org::bcom::xpcf;
namespace SolAR {
using namespace datastructure;
namespace MODULES {
namespace OPENGV {
PoseEstimationP3PKneip::PoseEstimationP3PKneip():ConfigurableBase(xpcf::toUUID<PoseEstimationP3PKneip>())
{
addInterface<api::solver::pose::I3DTransformFinderFrom2D3D>(this);
LOG_DEBUG(" SolARPoseEstimationOpengv constructor");
}
PoseEstimationP3PKneip::~PoseEstimationP3PKneip(){
}
FrameworkReturnCode PoseEstimationP3PKneip::estimate( const std::vector<Point2Df> & imagePoints,
const std::vector<Point3Df> & worldPoints,
Transform3Df & pose,
const Transform3Df initialPose) {
if ( imagePoints.size() < 3 || worldPoints.size() < 3){
return FrameworkReturnCode::_ERROR_;
}
Eigen::Matrix<float,3,3> k_invert = m_intrinsicParams.inverse();
std::vector<Eigen::Vector3f> buffer_vector;
buffer_vector.resize( imagePoints.size());
opengv::bearingVectors_t bearing_buffer;
opengv::points_t points;
for(unsigned int k =0; k < imagePoints.size(); k++){
points.push_back( opengv::point_t( worldPoints[k].getX(), worldPoints[k].getY(), worldPoints[k].getZ()));
//without distorsion
Eigen::Vector3f tmp = k_invert*Eigen::Vector3f(imagePoints[k].getX(), imagePoints[k].getY(), 1.0f);
bearing_buffer.push_back(opengv::point_t( tmp[0], tmp[1],tmp[2]));
bearing_buffer[k] /=tmp.norm();
}
opengv::rotation_t rotationgv;
opengv::absolute_pose::CentralAbsoluteAdapter adapter( bearing_buffer, points, rotationgv );
opengv::transformations_t epnp_transformation;
size_t iterations = 50;
for(size_t i = 0; i < iterations; i++){
epnp_transformation = opengv::absolute_pose::p3p_kneip(adapter);
}
//epnp_transformation.data();
//for now, I just get the first result provided
if (epnp_transformation.size() > 1)
{
pose(0, 0) = epnp_transformation[0](0, 0);
pose(0, 1) = epnp_transformation[0](0, 1);
pose(0, 2) = epnp_transformation[0](0, 2);
pose(0, 3) = epnp_transformation[0](0, 3);
pose(1, 0) = epnp_transformation[0](1, 0);
pose(1, 1) = epnp_transformation[0](1, 1);
pose(1, 2) = epnp_transformation[0](1, 2);
pose(1, 3) = epnp_transformation[0](1, 3);
pose(2, 0) = epnp_transformation[0](2, 0);
pose(2, 1) = epnp_transformation[0](2, 1);
pose(2, 2) = epnp_transformation[0](2, 2);
pose(2, 3) = epnp_transformation[0](2, 3);
pose(3, 0) = 0;
pose(3, 1) = 0;
pose(3, 2) = 0;
pose(3, 3) = 1;
}
return FrameworkReturnCode::_SUCCESS;
}
void PoseEstimationP3PKneip::setCameraParameters(const CamCalibration & intrinsicParams, const CamDistortion & distorsionParams) {
m_intrinsicParams = intrinsicParams;
m_distorsionParams =distorsionParams;
}
}
}
}
| 32.248 | 130 | 0.650955 | SolarFramework |
d5f1891b7253bceb366aa30612718a4b1fed56b4 | 5,851 | cpp | C++ | tdmq/src/v20200217/model/Producer.cpp | TencentCloud/tencentcloud-sdk-cpp | 896da198abe6f75c0dc90901131d709143186b77 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | tdmq/src/v20200217/model/Producer.cpp | TencentCloud/tencentcloud-sdk-cpp | 896da198abe6f75c0dc90901131d709143186b77 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | tdmq/src/v20200217/model/Producer.cpp | TencentCloud/tencentcloud-sdk-cpp | 896da198abe6f75c0dc90901131d709143186b77 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tdmq/v20200217/model/Producer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tdmq::V20200217::Model;
using namespace std;
Producer::Producer() :
m_environmentIdHasBeenSet(false),
m_topicNameHasBeenSet(false),
m_countConnectHasBeenSet(false),
m_connectionSetsHasBeenSet(false)
{
}
CoreInternalOutcome Producer::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("EnvironmentId") && !value["EnvironmentId"].IsNull())
{
if (!value["EnvironmentId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Producer.EnvironmentId` IsString=false incorrectly").SetRequestId(requestId));
}
m_environmentId = string(value["EnvironmentId"].GetString());
m_environmentIdHasBeenSet = true;
}
if (value.HasMember("TopicName") && !value["TopicName"].IsNull())
{
if (!value["TopicName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Producer.TopicName` IsString=false incorrectly").SetRequestId(requestId));
}
m_topicName = string(value["TopicName"].GetString());
m_topicNameHasBeenSet = true;
}
if (value.HasMember("CountConnect") && !value["CountConnect"].IsNull())
{
if (!value["CountConnect"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `Producer.CountConnect` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_countConnect = value["CountConnect"].GetInt64();
m_countConnectHasBeenSet = true;
}
if (value.HasMember("ConnectionSets") && !value["ConnectionSets"].IsNull())
{
if (!value["ConnectionSets"].IsArray())
return CoreInternalOutcome(Core::Error("response `Producer.ConnectionSets` is not array type"));
const rapidjson::Value &tmpValue = value["ConnectionSets"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Connection item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_connectionSets.push_back(item);
}
m_connectionSetsHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void Producer::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_environmentIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EnvironmentId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_environmentId.c_str(), allocator).Move(), allocator);
}
if (m_topicNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TopicName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_topicName.c_str(), allocator).Move(), allocator);
}
if (m_countConnectHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CountConnect";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_countConnect, allocator);
}
if (m_connectionSetsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ConnectionSets";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_connectionSets.begin(); itr != m_connectionSets.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
}
string Producer::GetEnvironmentId() const
{
return m_environmentId;
}
void Producer::SetEnvironmentId(const string& _environmentId)
{
m_environmentId = _environmentId;
m_environmentIdHasBeenSet = true;
}
bool Producer::EnvironmentIdHasBeenSet() const
{
return m_environmentIdHasBeenSet;
}
string Producer::GetTopicName() const
{
return m_topicName;
}
void Producer::SetTopicName(const string& _topicName)
{
m_topicName = _topicName;
m_topicNameHasBeenSet = true;
}
bool Producer::TopicNameHasBeenSet() const
{
return m_topicNameHasBeenSet;
}
int64_t Producer::GetCountConnect() const
{
return m_countConnect;
}
void Producer::SetCountConnect(const int64_t& _countConnect)
{
m_countConnect = _countConnect;
m_countConnectHasBeenSet = true;
}
bool Producer::CountConnectHasBeenSet() const
{
return m_countConnectHasBeenSet;
}
vector<Connection> Producer::GetConnectionSets() const
{
return m_connectionSets;
}
void Producer::SetConnectionSets(const vector<Connection>& _connectionSets)
{
m_connectionSets = _connectionSets;
m_connectionSetsHasBeenSet = true;
}
bool Producer::ConnectionSetsHasBeenSet() const
{
return m_connectionSetsHasBeenSet;
}
| 29.40201 | 140 | 0.679371 | TencentCloud |
d5f481cf93f4874a412755e232e2e5838a5162ba | 325 | hpp | C++ | libs/actor/src/impl/protocol.hpp | nousxiong/gce | 722edb8c91efaf16375664d66134ecabb16e1447 | [
"BSL-1.0"
] | 118 | 2015-01-24T01:16:46.000Z | 2022-03-09T07:31:21.000Z | libs/actor/src/impl/protocol.hpp | txwdyzcb/gce | 722edb8c91efaf16375664d66134ecabb16e1447 | [
"BSL-1.0"
] | 1 | 2015-09-24T13:03:11.000Z | 2016-12-24T04:00:59.000Z | libs/actor/src/impl/protocol.hpp | txwdyzcb/gce | 722edb8c91efaf16375664d66134ecabb16e1447 | [
"BSL-1.0"
] | 30 | 2015-03-12T09:21:45.000Z | 2021-12-15T01:55:08.000Z | #ifndef GCE_IMPL_PROTOCOL_HPP
#define GCE_IMPL_PROTOCOL_HPP
#include <config.hpp>
namespace gce
{
namespace msg
{
struct header
{
header()
: size_(0)
, type_(match_nil)
{
}
boost::uint32_t size_;
match_t type_;
};
}
}
GCE_PACK(gce::msg::header, (size_&sfix)(type_));
#endif /// GCE_IMPL_PROTOCOL_HPP
| 12.037037 | 48 | 0.683077 | nousxiong |
d5f6a8d006c95213770eb2cbcb2225f5ead0103e | 9,860 | hpp | C++ | src/hwlm/noodle_engine_simd.hpp | GerHobbelt/hyperscan | 698763b02110dab121f2ddf2724f7c690ee5d895 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 146 | 2021-02-15T14:13:57.000Z | 2022-03-30T19:06:13.000Z | src/hwlm/noodle_engine_simd.hpp | GerHobbelt/hyperscan | 698763b02110dab121f2ddf2724f7c690ee5d895 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 35 | 2021-01-26T10:21:21.000Z | 2022-03-23T09:50:20.000Z | src/hwlm/noodle_engine_simd.hpp | GerHobbelt/hyperscan | 698763b02110dab121f2ddf2724f7c690ee5d895 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 12 | 2021-03-26T15:02:20.000Z | 2022-03-10T13:14:32.000Z | /*
* Copyright (c) 2017, Intel Corporation
* Copyright (c) 2020-2021, VectorCamp PC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* SIMD engine agnostic noodle scan parts */
#include "util/supervector/supervector.hpp"
static u8 CASEMASK[] = { 0xff, 0xdf };
static really_inline
u8 caseClear8(u8 x, bool noCase)
{
return static_cast<u8>(x & CASEMASK[(u8)noCase]);
}
template<uint16_t S>
static really_inline SuperVector<S> getMask(u8 c, bool noCase) {
u8 k = caseClear8(c, noCase);
return SuperVector<S>(k);
}
template<uint16_t S>
static really_inline SuperVector<S> getCaseMask(void) {
return SuperVector<S>(CASEMASK[1]);
}
static really_really_inline
hwlm_error_t single_zscan(const struct noodTable *n,const u8 *d, const u8 *buf,
Z_TYPE z, size_t len, const struct cb_info *cbi) {
while (unlikely(z)) {
Z_TYPE pos = JOIN(findAndClearLSB_, Z_BITS)(&z);
size_t matchPos = d - buf + pos;
DEBUG_PRINTF("match pos %zu\n", matchPos);
hwlmcb_rv_t rv = final(n, buf, len, n->msk_len != 1, cbi, matchPos);
RETURN_IF_TERMINATED(rv);
}
return HWLM_SUCCESS;
}
static really_really_inline
hwlm_error_t double_zscan(const struct noodTable *n,const u8 *d, const u8 *buf,
Z_TYPE z, size_t len, const struct cb_info *cbi) {
while (unlikely(z)) {
Z_TYPE pos = JOIN(findAndClearLSB_, Z_BITS)(&z);
size_t matchPos = d - buf + pos - 1;
DEBUG_PRINTF("match pos %zu\n", matchPos);
hwlmcb_rv_t rv = final(n, buf, len, true, cbi, matchPos);
RETURN_IF_TERMINATED(rv);
}
return HWLM_SUCCESS;
}
// The short scan routine. It is used both to scan data up to an
// alignment boundary if needed and to finish off data that the aligned scan
// function can't handle (due to small/unaligned chunk at end)
template<uint16_t S>
static really_inline
hwlm_error_t scanSingleUnaligned(const struct noodTable *n, const u8 *buf,
SuperVector<S> caseMask, SuperVector<S> mask1,
const struct cb_info *cbi, size_t len, size_t start,
size_t end) {
const u8 *d = buf + start;
DEBUG_PRINTF("start %zu end %zu\n", start, end);
const size_t l = end - start;
DEBUG_PRINTF("l = %ld\n", l);
//assert(l <= 64);
if (!l) {
return HWLM_SUCCESS;
}
typename SuperVector<S>::movemask_type mask = SINGLE_LOAD_MASK(l);
SuperVector<S> v = SuperVector<S>::loadu(d) & caseMask;
typename SuperVector<S>::movemask_type z = mask & mask1.eqmask(v);
return single_zscan(n, d, buf, z, len, cbi);
}
template<uint16_t S>
static really_inline
hwlm_error_t scanDoubleUnaligned(const struct noodTable *n, const u8 *buf,
SuperVector<S> caseMask, SuperVector<S> mask1, SuperVector<S> mask2, typename SuperVector<S>::movemask_type *lastz1,
const struct cb_info *cbi, size_t len, size_t start, size_t end) {
const u8 *d = buf + start;
DEBUG_PRINTF("start %zu end %zu\n", start, end);
const size_t l = end - start;
assert(l <= S);
if (!l) {
return HWLM_SUCCESS;
}
SuperVector<S> v = SuperVector<S>::loadu(d) & caseMask;
typename SuperVector<S>::movemask_type mask = DOUBLE_LOAD_MASK(l);
typename SuperVector<S>::movemask_type z1 = mask1.eqmask(v);
typename SuperVector<S>::movemask_type z2 = mask2.eqmask(v);
typename SuperVector<S>::movemask_type z = mask & (*lastz1 | z1 << 1) & z2;
*lastz1 = z1 >> (l -1);
return double_zscan(n, d, buf, z, len, cbi);
}
template <uint16_t S>
static really_inline
hwlm_error_t scanSingleMain(const struct noodTable *n, const u8 *buf,
size_t len, size_t offset,
SuperVector<S> caseMask, SuperVector<S> mask1,
const struct cb_info *cbi) {
size_t start = offset + n->msk_len - 1;
size_t end = len;
const u8 *d = buf + start;
const u8 *e = buf + end;
DEBUG_PRINTF("start %p end %p \n", d, e);
assert(d < e);
if (d + S <= e) {
// peel off first part to cacheline boundary
const u8 *d1 = ROUNDUP_PTR(d, S);
DEBUG_PRINTF("until aligned %p \n", d1);
if (scanSingleUnaligned(n, buf, caseMask, mask1, cbi, len, start, d1 - buf) == HWLM_TERMINATED) {
return HWLM_TERMINATED;
}
d = d1;
size_t loops = (end - (d - buf)) / S;
DEBUG_PRINTF("loops %ld \n", loops);
for (size_t i = 0; i < loops; i++, d+= S) {
DEBUG_PRINTF("d %p \n", d);
const u8 *base = ROUNDUP_PTR(d, 64);
// On large packet buffers, this prefetch appears to get us about 2%.
__builtin_prefetch(base + 256);
SuperVector<S> v = SuperVector<S>::load(d) & caseMask;
typename SuperVector<S>::movemask_type z = mask1.eqmask(v);
hwlm_error_t rv = single_zscan(n, d, buf, z, len, cbi);
RETURN_IF_TERMINATED(rv);
}
}
DEBUG_PRINTF("d %p e %p \n", d, e);
// finish off tail
return scanSingleUnaligned(n, buf, caseMask, mask1, cbi, len, d - buf, end);
}
template <uint16_t S>
static really_inline
hwlm_error_t scanDoubleMain(const struct noodTable *n, const u8 *buf,
size_t len, size_t offset,
SuperVector<S> caseMask, SuperVector<S> mask1, SuperVector<S> mask2,
const struct cb_info *cbi) {
// we stop scanning for the key-fragment when the rest of the key can't
// possibly fit in the remaining buffer
size_t end = len - n->key_offset + 2;
size_t start = offset + n->msk_len - n->key_offset;
typename SuperVector<S>::movemask_type lastz1{0};
const u8 *d = buf + start;
const u8 *e = buf + end;
DEBUG_PRINTF("start %p end %p \n", d, e);
assert(d < e);
if (d + S <= e) {
// peel off first part to cacheline boundary
const u8 *d1 = ROUNDUP_PTR(d, S);
DEBUG_PRINTF("until aligned %p \n", d1);
if (scanDoubleUnaligned(n, buf, caseMask, mask1, mask2, &lastz1, cbi, len, start, d1 - buf) == HWLM_TERMINATED) {
return HWLM_TERMINATED;
}
d = d1;
size_t loops = (end - (d - buf)) / S;
DEBUG_PRINTF("loops %ld \n", loops);
for (size_t i = 0; i < loops; i++, d+= S) {
DEBUG_PRINTF("d %p \n", d);
const u8 *base = ROUNDUP_PTR(d, 64);
// On large packet buffers, this prefetch appears to get us about 2%.
__builtin_prefetch(base + 256);
SuperVector<S> v = SuperVector<S>::load(d) & caseMask;
typename SuperVector<S>::movemask_type z1 = mask1.eqmask(v);
typename SuperVector<S>::movemask_type z2 = mask2.eqmask(v);
typename SuperVector<S>::movemask_type z = (z1 << 1 | lastz1) & z2;
lastz1 = z1 >> Z_SHIFT;
hwlm_error_t rv = double_zscan(n, d, buf, z, len, cbi);
RETURN_IF_TERMINATED(rv);
}
}
DEBUG_PRINTF("d %p e %p \n", d, e);
// finish off tail
return scanDoubleUnaligned(n, buf, caseMask, mask1, mask2, &lastz1, cbi, len, d - buf, end);
}
// Single-character specialisation, used when keyLen = 1
static really_inline
hwlm_error_t scanSingle(const struct noodTable *n, const u8 *buf, size_t len,
size_t start, bool noCase, const struct cb_info *cbi) {
if (!ourisalpha(n->key0)) {
noCase = 0; // force noCase off if we don't have an alphabetic char
}
const SuperVector<VECTORSIZE> caseMask{noCase ? getCaseMask<VECTORSIZE>() : SuperVector<VECTORSIZE>::Ones()};
const SuperVector<VECTORSIZE> mask1{getMask<VECTORSIZE>(n->key0, noCase)};
return scanSingleMain(n, buf, len, start, caseMask, mask1, cbi);
}
static really_inline
hwlm_error_t scanDouble(const struct noodTable *n, const u8 *buf, size_t len,
size_t start, bool noCase, const struct cb_info *cbi) {
const SuperVector<VECTORSIZE> caseMask{noCase ? getCaseMask<VECTORSIZE>() : SuperVector<VECTORSIZE>::Ones()};
const SuperVector<VECTORSIZE> mask1{getMask<VECTORSIZE>(n->key0, noCase)};
const SuperVector<VECTORSIZE> mask2{getMask<VECTORSIZE>(n->key1, noCase)};
return scanDoubleMain(n, buf, len, start, caseMask, mask1, mask2, cbi);
}
| 39.282869 | 149 | 0.638742 | GerHobbelt |
d5f839e43706d7103b864cb0da6a9a052939c505 | 2,071 | cpp | C++ | 00-Starter/src/Player.cpp | BenjaminGonvers/SAE921-GRP4100-Box2D | 0ea3ff05bdd21ebc96ec1661a8766b370b8fab1c | [
"MIT"
] | null | null | null | 00-Starter/src/Player.cpp | BenjaminGonvers/SAE921-GRP4100-Box2D | 0ea3ff05bdd21ebc96ec1661a8766b370b8fab1c | [
"MIT"
] | null | null | null | 00-Starter/src/Player.cpp | BenjaminGonvers/SAE921-GRP4100-Box2D | 0ea3ff05bdd21ebc96ec1661a8766b370b8fab1c | [
"MIT"
] | null | null | null | #include "Player.h"
#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
#include <BodyFixtureType.h>
Player::Player(b2World& world, sf::Texture* texture, sf::SoundBuffer* sound_buffer, sf::Vector2f& pos, b2Vec2 vertices[], const int& number_vertices, b2BodyType body_type) :
PhysicalObject(world, texture, pos,vertices,number_vertices,body_type )
{
b2FixtureDef new_fixture_def;
b2Vec2 new_fixture_vertices[4];
b2PolygonShape dynamicBox_;
new_fixture_vertices[0].x = vertices[3].x - 0.2f;
new_fixture_vertices[0].y = vertices[3].y - 0.1f;
new_fixture_vertices[1].x = vertices[2].x + 0.2f;
new_fixture_vertices[1].y = vertices[2].y - 0.1f;
new_fixture_vertices[2].x = vertices[2].x + 0.2f;
new_fixture_vertices[2].y = vertices[2].y - 0.2f;
new_fixture_vertices[3].x = vertices[3].x - 0.1f;
new_fixture_vertices[3].y = vertices[3].y - 0.2f;
dynamicBox_.Set(new_fixture_vertices, 4);
new_fixture_def.shape= &dynamicBox_;
new_fixture_def.isSensor = true;
new_fixture_def.userData.pointer = static_cast<std::uintptr_t>(BodyFixtureType::PlayerFootSensor);
footSensorFixture_ = body_->CreateFixture(&new_fixture_def);
body_->SetFixedRotation(true);
jump_sound_.setBuffer(*sound_buffer);
}
void Player::Check_Player_Action()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
if (!w_keyboard_pressed_&&isGrounded())
{
body_->ApplyLinearImpulse(b2Vec2(0, 15), body_->GetWorldCenter(), true);
jump_sound_.play();
w_keyboard_pressed_ = true;
}
}else
{
w_keyboard_pressed_ = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
body_->ApplyForceToCenter(b2Vec2(30, 0), true);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
body_->ApplyForceToCenter(b2Vec2(-30, 0), true);
}
}
bool Player::isGrounded() const
{
return footContactsCounter_ > 0;
}
void Player::startFootContact()
{
footContactsCounter_ += 1;
}
void Player::endFootContact()
{
footContactsCounter_ -= 1;
}
void Player::StartContact()
{
footContactsCounter_ += 1;
}
void Player::EndContact()
{
footContactsCounter_ -= 1;
}
| 22.51087 | 173 | 0.725254 | BenjaminGonvers |
d5fe2d76ea09661d1b4d7fee826b86f5a9f6236c | 4,858 | cc | C++ | public/c/tests/system/buffer_unittest.cc | niftich/mojo | cb29e37b254b43f432d70d1bf7661e1f9ef31577 | [
"BSD-3-Clause"
] | 1 | 2021-03-29T04:24:25.000Z | 2021-03-29T04:24:25.000Z | public/c/tests/system/buffer_unittest.cc | niftich/mojo | cb29e37b254b43f432d70d1bf7661e1f9ef31577 | [
"BSD-3-Clause"
] | null | null | null | public/c/tests/system/buffer_unittest.cc | niftich/mojo | cb29e37b254b43f432d70d1bf7661e1f9ef31577 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file tests the C buffer API (the functions declared in
// mojo/public/c/include/mojo/system/buffer.h).
#include <mojo/system/buffer.h>
#include <mojo/result.h>
#include <mojo/system/handle.h>
#include "third_party/gtest/include/gtest/gtest.h"
namespace {
const MojoHandleRights kDefaultSharedBufferHandleRights =
MOJO_HANDLE_RIGHT_DUPLICATE | MOJO_HANDLE_RIGHT_TRANSFER |
MOJO_HANDLE_RIGHT_GET_OPTIONS | MOJO_HANDLE_RIGHT_SET_OPTIONS |
MOJO_HANDLE_RIGHT_MAP_READABLE | MOJO_HANDLE_RIGHT_MAP_WRITABLE |
MOJO_HANDLE_RIGHT_MAP_EXECUTABLE;
// The only handle that's guaranteed to be invalid is |MOJO_HANDLE_INVALID|.
// Tests that everything that takes a handle properly recognizes it.
TEST(BufferTest, InvalidHandle) {
MojoHandle out_handle = MOJO_HANDLE_INVALID;
EXPECT_EQ(
MOJO_RESULT_INVALID_ARGUMENT,
MojoDuplicateBufferHandle(MOJO_HANDLE_INVALID, nullptr, &out_handle));
MojoBufferInformation buffer_info = {};
EXPECT_EQ(
MOJO_RESULT_INVALID_ARGUMENT,
MojoGetBufferInformation(MOJO_HANDLE_INVALID, &buffer_info,
static_cast<uint32_t>(sizeof(buffer_info))));
void* write_pointer = nullptr;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoMapBuffer(MOJO_HANDLE_INVALID, 0u, 1u, &write_pointer,
MOJO_MAP_BUFFER_FLAG_NONE));
// This isn't an "invalid handle" test, but we'll throw it in here anyway
// (since it involves a look-up).
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoUnmapBuffer(nullptr));
}
TEST(BufferTest, Basic) {
// Create a shared buffer (|h0|).
MojoHandle h0 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateSharedBuffer(nullptr, 100, &h0));
EXPECT_NE(h0, MOJO_HANDLE_INVALID);
// The handle should have the correct rights.
MojoHandleRights rights = MOJO_HANDLE_RIGHT_NONE;
EXPECT_EQ(MOJO_RESULT_OK, MojoGetRights(h0, &rights));
EXPECT_EQ(kDefaultSharedBufferHandleRights, rights);
// Check information about the buffer from |h0|.
MojoBufferInformation info = {};
static const uint32_t kInfoSize = static_cast<uint32_t>(sizeof(info));
EXPECT_EQ(MOJO_RESULT_OK, MojoGetBufferInformation(h0, &info, kInfoSize));
EXPECT_EQ(kInfoSize, info.struct_size);
EXPECT_EQ(MOJO_BUFFER_INFORMATION_FLAG_NONE, info.flags);
EXPECT_EQ(100u, info.num_bytes);
// Map everything.
void* pointer = nullptr;
EXPECT_EQ(MOJO_RESULT_OK,
MojoMapBuffer(h0, 0, 100, &pointer, MOJO_MAP_BUFFER_FLAG_NONE));
ASSERT_TRUE(pointer);
static_cast<char*>(pointer)[50] = 'x';
// Duplicate |h0| to |h1|.
MojoHandle h1 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoDuplicateHandle(h0, &h1));
EXPECT_NE(h1, MOJO_HANDLE_INVALID);
EXPECT_NE(h1, h0);
// The new handle should have the correct rights.
rights = MOJO_HANDLE_RIGHT_NONE;
EXPECT_EQ(MOJO_RESULT_OK, MojoGetRights(h1, &rights));
EXPECT_EQ(kDefaultSharedBufferHandleRights, rights);
// Check information about the buffer from |h1|.
info = MojoBufferInformation();
EXPECT_EQ(MOJO_RESULT_OK, MojoGetBufferInformation(h1, &info, kInfoSize));
EXPECT_EQ(kInfoSize, info.struct_size);
EXPECT_EQ(MOJO_BUFFER_INFORMATION_FLAG_NONE, info.flags);
EXPECT_EQ(100u, info.num_bytes);
// Close |h0|.
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h0));
// The mapping should still be good.
static_cast<char*>(pointer)[51] = 'y';
// Unmap it.
EXPECT_EQ(MOJO_RESULT_OK, MojoUnmapBuffer(pointer));
// Map half of |h1|.
pointer = nullptr;
EXPECT_EQ(MOJO_RESULT_OK,
MojoMapBuffer(h1, 50, 50, &pointer, MOJO_MAP_BUFFER_FLAG_NONE));
ASSERT_TRUE(pointer);
// It should have what we wrote.
EXPECT_EQ('x', static_cast<char*>(pointer)[0]);
EXPECT_EQ('y', static_cast<char*>(pointer)[1]);
// Unmap it.
EXPECT_EQ(MOJO_RESULT_OK, MojoUnmapBuffer(pointer));
// Test duplication with reduced rights.
MojoHandle h2 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoDuplicateHandleWithReducedRights(
h1, MOJO_HANDLE_RIGHT_DUPLICATE, &h2));
EXPECT_NE(h2, MOJO_HANDLE_INVALID);
EXPECT_NE(h2, h1);
// |h2| should have the correct rights.
rights = MOJO_HANDLE_RIGHT_NONE;
EXPECT_EQ(MOJO_RESULT_OK, MojoGetRights(h2, &rights));
EXPECT_EQ(kDefaultSharedBufferHandleRights & ~MOJO_HANDLE_RIGHT_DUPLICATE,
rights);
// Trying to duplicate |h2| should fail.
MojoHandle h3 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_PERMISSION_DENIED, MojoDuplicateHandle(h2, &h3));
EXPECT_EQ(MOJO_HANDLE_INVALID, h3);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h1));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h2));
}
// TODO(vtl): Add multi-threaded tests.
} // namespace
| 36.526316 | 76 | 0.742487 | niftich |
d5ff3c6462aa3185696e70f9629ae1d1810870c7 | 4,468 | hpp | C++ | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/condition_edge.hpp | WJaworskiRobotec/scenario_simulator_v2 | c23497ac8716dcefef20d4b5a4ff1185e01f48e6 | [
"Apache-2.0"
] | 45 | 2021-04-12T22:43:25.000Z | 2022-02-27T23:57:53.000Z | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/condition_edge.hpp | WJaworskiRobotec/scenario_simulator_v2 | c23497ac8716dcefef20d4b5a4ff1185e01f48e6 | [
"Apache-2.0"
] | 140 | 2021-04-13T04:28:19.000Z | 2022-03-30T12:44:32.000Z | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/condition_edge.hpp | WJaworskiRobotec/scenario_simulator_v2 | c23497ac8716dcefef20d4b5a4ff1185e01f48e6 | [
"Apache-2.0"
] | 13 | 2021-05-22T02:24:49.000Z | 2022-03-25T05:16:31.000Z | // Copyright 2015-2020 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSCENARIO_INTERPRETER__SYNTAX__CONDITION_EDGE_HPP_
#define OPENSCENARIO_INTERPRETER__SYNTAX__CONDITION_EDGE_HPP_
#include <iostream>
namespace openscenario_interpreter
{
inline namespace syntax
{
/* ---- ConditionEdge ----------------------------------------------------------
*
* <xsd:simpleType name="ConditionEdge">
* <xsd:union>
* <xsd:simpleType>
* <xsd:restriction base="xsd:string">
* <xsd:enumeration value="rising"/>
* <xsd:enumeration value="falling"/>
* <xsd:enumeration value="risingOrFalling"/>
* <xsd:enumeration value="none"/>
* </xsd:restriction>
* </xsd:simpleType>
* <xsd:simpleType>
* <xsd:restriction base="parameter"/>
* </xsd:simpleType>
* </xsd:union>
* </xsd:simpleType>
*
* Tier IV Extension:
* - Add enumeration <xsd.enumeration value="sticky"/>
*
* -------------------------------------------------------------------------- */
struct ConditionEdge
{
enum value_type {
/* ---- NOTE ---------------------------------------------------------------
*
* A condition defined with a 'none' edge shall return true at discrete
* time t if its logical expression is true at discrete time t.
*
* Default constructor select this.
*
* ---------------------------------------------------------------------- */
none,
/* ---- NOTE ---------------------------------------------------------------
*
* A condition defined with a rising edge shall return true at discrete
* time t if its logical expression is true at discrete time t and its
* logical expression was false at discrete time t-ts, where ts is the
* simulation sampling time.
*
* ---------------------------------------------------------------------- */
rising,
/* ---- NOTE ---------------------------------------------------------------
*
* A condition defined with a falling edge shall return true at discrete
* time t if its logical expression is false at discrete time t and its
* logical expression was true at discrete time t-ts, where ts is the
* simulation sampling time.
*
* ---------------------------------------------------------------------- */
falling,
/* ---- NOTE ---------------------------------------------------------------
*
* A condition defined with a 'risingOrFalling' edge shall return true at
* discrete time t if its logical expression is true at discrete time t
* and its logical expression was false at discrete time t-ts OR if its
* logical expression is false at discrete time t and its logical
* expression was true at discrete time t-ts. ts is the simulation
* sampling time.
*
* ---------------------------------------------------------------------- */
risingOrFalling,
/* ---- NOTE ---------------------------------------------------------------
*
* A condition defined by a 'sticky' edge returns true at discrete time
* t + k (0 < k) if its logical expression evaluates to true at discrete
* time t. This edge is provided for simply defining assertions such as
* "Did the Ego car pass over checkpoint X?
*
* This is NOT an OpenSCENARIO 1.0.0 standard feature (Tier IV extension).
*
* ---------------------------------------------------------------------- */
sticky,
} value;
explicit ConditionEdge() = default;
operator value_type() const noexcept { return value; }
};
auto operator>>(std::istream & is, ConditionEdge &) -> std::istream &;
auto operator<<(std::ostream & os, const ConditionEdge &) -> std::ostream &;
} // namespace syntax
} // namespace openscenario_interpreter
#endif // OPENSCENARIO_INTERPRETER__SYNTAX__CONDITION_EDGE_HPP_
| 38.517241 | 80 | 0.539391 | WJaworskiRobotec |
91019dd777e90e2e851cccf671d9668bcea7f19b | 7,059 | cpp | C++ | src/Geometry/pcube/fpcube.cpp | squarefk/spheretree-fixed | 79ec91538030a271f7aba16e22dc20c9ebb63444 | [
"Unlicense"
] | 17 | 2016-08-12T13:15:41.000Z | 2021-11-11T10:03:48.000Z | src/Geometry/pcube/fpcube.cpp | squarefk/spheretree-fixed | 79ec91538030a271f7aba16e22dc20c9ebb63444 | [
"Unlicense"
] | null | null | null | src/Geometry/pcube/fpcube.cpp | squarefk/spheretree-fixed | 79ec91538030a271f7aba16e22dc20c9ebb63444 | [
"Unlicense"
] | 9 | 2016-04-26T16:15:45.000Z | 2020-10-29T00:12:12.000Z |
/*
* FAST POLYGON-CUBE INTERSECTION TESTS
* by Daniel Green
* January 1994
*
*
* The original inspiration for this routine comes from the triangle-cube
* intersection algorithm in Graphics Gems III by Douglas Voorhies.
* Aside from the fact that the original code was special-cased for triangles
* only, it suffered from some bugs. Don Hatch re-wrote the non-trivial tests
* using the same basic ideas, fixed the bugs and also made it more
* general and efficient. Don's implementation performs just the
* intersection calculations without any trivial accept or reject tests,
* and is embodied in the routine polygon_intersects_cube().
*
* The function implemented here is simply a wrapper that begins with a
* slightly more efficient version of Voorhies' original trivial reject tests
* and only calls polygon_intersects_cube() when those tests fail.
* The result is a fast and robust polygon-cube tester.
*
* Also included here is trivial_vertex_tests() which is used by
* fast_polygon_intersects_cube(). It can be used to quickly test an entire
* set of vertices for trivial reject or accept. This is useful for testing
* polyhedra or polygon meshes.
*
* WARNING: When used to test intersection of a polyhedron with the unit cube,
* remember that these routines only test *surfaces* and not volumes.
* If polygon_intersects_cube() reports no intersection with any of the faces
* of the polyhedron, the caller should be aware that the polyhedron
* could still contain the whole unit cube which would then need to be checked
* with a point-within-polyhedron test. The origin would be a natural point
* to check in such a test.
*/
#include "pcube.h"
#ifndef __cplusplus
#define inline
#endif
#define TEST_AGAINST_PARALLEL_PLANES(posbit, negbit, value, limit) \
if (mask & (posbit|negbit)) { \
register real temp = value; \
if ((mask & posbit) && temp > limit) \
outcode |= posbit; \
else if ((mask & negbit) && temp < -limit) \
outcode |= negbit; \
} \
/*
* Tells which of the six face-planes the given point is outside of.
* Only tests faces not represented in "mask".
*/
static inline unsigned long
face_plane(const real p[3], unsigned long mask)
{
register unsigned long outcode = 0L;
TEST_AGAINST_PARALLEL_PLANES(0x001, 0x002, p[0], 0.5)
TEST_AGAINST_PARALLEL_PLANES(0x004, 0x008, p[1], 0.5)
TEST_AGAINST_PARALLEL_PLANES(0x010, 0x020, p[2], 0.5)
return(outcode);
}
/*
* Tells which of the twelve edge planes the given point is outside of.
* Only tests faces not represented in "mask".
*/
static inline unsigned long
bevel_2d(const real p[3], unsigned long mask)
{
register unsigned long outcode = 0L;
TEST_AGAINST_PARALLEL_PLANES(0x001, 0x002, p[0] + p[1], 1.0)
TEST_AGAINST_PARALLEL_PLANES(0x004, 0x008, p[0] - p[1], 1.0)
TEST_AGAINST_PARALLEL_PLANES(0x010, 0x020, p[0] + p[2], 1.0)
TEST_AGAINST_PARALLEL_PLANES(0x040, 0x080, p[0] - p[2], 1.0)
TEST_AGAINST_PARALLEL_PLANES(0x100, 0x200, p[1] + p[2], 1.0)
TEST_AGAINST_PARALLEL_PLANES(0x400, 0x800, p[1] - p[2], 1.0)
return(outcode);
}
/*
* Tells which of the eight corner planes the given point is outside of.
* Only tests faces not represented in "mask".
*/
static inline unsigned long
bevel_3d(const real p[3], unsigned long mask)
{
register unsigned long outcode = 0L;
TEST_AGAINST_PARALLEL_PLANES(0x001, 0x002, p[0] + p[1] + p[2], 1.5)
TEST_AGAINST_PARALLEL_PLANES(0x004, 0x008, p[0] + p[1] - p[2], 1.5)
TEST_AGAINST_PARALLEL_PLANES(0x010, 0x020, p[0] - p[1] + p[2], 1.5)
TEST_AGAINST_PARALLEL_PLANES(0x040, 0x080, p[0] - p[1] - p[2], 1.5)
return(outcode);
}
/*
* Returns 1 if any of the vertices are inside the cube of edge length 1
* centered at the origin (trivial accept), 0 if all vertices are outside
* of any testing plane (trivial reject), -1 otherwise (couldn't help).
*/
EXTERN int
trivial_vertex_tests(int nverts, const real verts[][3],
int already_know_verts_are_outside_cube)
{
register unsigned long cum_and; /* cumulative logical ANDs */
register int i;
/*
* Compare the vertices with all six face-planes.
* If it's known that no vertices are inside the unit cube
* we can exit the loop early if we run out of bounding
* planes that all vertices might be outside of. That simply means
* that this test failed and we can go on to the next one.
* If we must test for vertices within the cube, the loop is slightly
* different in that we can trivially accept if we ever do find a
* vertex within the cube, but we can't break the loop early if we run
* out of planes to reject against because subsequent vertices might
* still be within the cube.
*/
cum_and = ~0L; /* Set to all "1" bits */
if(already_know_verts_are_outside_cube) {
for(i=0; i<nverts; i++)
if(0L == (cum_and = face_plane(verts[i], cum_and)))
break; /* No planes left to trivially reject */
}
else {
for(i=0; i<nverts; i++) {
/* Note the ~0L mask below to always test all planes */
unsigned long face_bits = face_plane(verts[i], ~0L);
if(0L == face_bits) /* vertex is inside the cube */
return 1; /* trivial accept */
cum_and &= face_bits;
}
}
if(cum_and != 0L) /* All vertices outside some face plane. */
return 0; /* Trivial reject */
/*
* Now do the just the trivial reject test against the 12 edge planes.
*/
cum_and = ~0L; /* Set to all "1" bits */
for(i=0; i<nverts; i++)
if(0L == (cum_and = bevel_2d(verts[i], cum_and)))
break; /* No planes left that might trivially reject */
if(cum_and != 0L) /* All vertices outside some edge plane. */
return 0; /* Trivial reject */
/*
* Now do the trivial reject test against the 8 corner planes.
*/
cum_and = ~0L; /* Set to all "1" bits */
for(i=0; i<nverts; i++)
if(0L == (cum_and = bevel_3d(verts[i], cum_and)))
break; /* No planes left that might trivially reject */
if(cum_and != 0L) /* All vertices outside some corner plane. */
return 0; /* Trivial reject */
/*
* By now we know that the polygon is not to the outside of any of the
* test planes and can't be trivially accepted *or* rejected.
*/
return -1;
}
/*
* This is a version of the same polygon-cube intersection that first calls
* trivial_vertex_tests() to hopefully skip the more expensive definitive test.
* It simply calls polygon_intersects_cube() when that fails.
* Note that after the trivial tests we at least know that all vertices are
* outside the cube and can therefore pass a true flag to
* polygon_intersects_cube().
*/
EXTERN int
fast_polygon_intersects_cube(int nverts, const real verts[][3],
const real polynormal[3],
int already_know_verts_are_outside_cube,
int already_know_edges_are_outside_cube)
{
int quick_test = trivial_vertex_tests(nverts, verts,
already_know_verts_are_outside_cube);
if(-1 == quick_test)
return polygon_intersects_cube(nverts, verts, polynormal, 1,
already_know_edges_are_outside_cube);
else
return quick_test;
}
| 33.77512 | 79 | 0.704632 | squarefk |
9102488853d9d5e6e2efa2095887ee0bfdb10f5a | 9,764 | cpp | C++ | VoxViz/VoxVizCore/DataSetReader.cpp | apecoraro/VoxVizThesis | 43aeb666cc9f5005d9ec5b81acd4cc38aae0e0fd | [
"MIT"
] | 3 | 2017-11-13T09:52:06.000Z | 2019-06-27T16:57:58.000Z | VoxViz/VoxVizCore/DataSetReader.cpp | apecoraro/VoxVizThesis | 43aeb666cc9f5005d9ec5b81acd4cc38aae0e0fd | [
"MIT"
] | null | null | null | VoxViz/VoxVizCore/DataSetReader.cpp | apecoraro/VoxVizThesis | 43aeb666cc9f5005d9ec5b81acd4cc38aae0e0fd | [
"MIT"
] | 4 | 2018-03-27T17:08:02.000Z | 2021-01-28T06:36:44.000Z | #include "VoxVizCore/DataSetReader.h"
#include "VoxVizCore/PVMReader.h"
#include "VoxVizCore/SmartPtr.h"
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace vox;
static const char * const PATH_SEPARATORS = "/\\";
static unsigned int PATH_SEPARATORS_LEN = 2;
std::string DataSetReader::GetFilePath(const std::string& fileName)
{
std::string::size_type slash = fileName.find_last_of(PATH_SEPARATORS);
if (slash==std::string::npos)
return std::string();
else
return std::string(fileName, 0, slash);
}
std::string DataSetReader::GetFileExtension(const std::string& fileName)
{
static const char * const PATH_SEPARATORS = "/\\";
std::string::size_type dot = fileName.find_last_of('.');
std::string::size_type slash = fileName.find_last_of(PATH_SEPARATORS);
if (dot==std::string::npos || (slash!=std::string::npos && dot<slash))
return std::string("");
return std::string(fileName.begin()+dot+1, fileName.end());
}
VolumeDataSet* DataSetReader::readVolumeDataFile(const std::string& inputFile)
{
std::string ext = GetFileExtension(inputFile);
if(ext == "pvm")
{
return PVMReader::instance().readVolumeData(inputFile);
}
else if(ext == "gvx" || ext == "gvp")
{
return new VolumeDataSet(inputFile);
}
else
{
std::ifstream inputStream;
inputStream.open(inputFile.c_str());
if(inputStream.is_open() != true)
return NULL;
std::string text;
inputStream >> text;
if(text != "VOXEL_HEADER")
return NULL;
QVector3D pos;
QQuaternion orient;
double scale = 1.0;
size_t dimX=0, dimY=0, dimZ=0;
bool typeIsScalars = false;
bool formatIsUByte = false;
while(inputStream.eof() != true)
{
inputStream >> text;
if(text == "POSITION")
{
double x, y, z;
inputStream >> x >> y >> z;
if(inputStream.fail())
break;
pos.setX(x);
pos.setY(y);
pos.setZ(z);
}
else if(text == "ORIENTATION")
{
double x, y, z, angle;
inputStream >> x >> y >> z >> angle;
if(inputStream.fail())
break;
orient = QQuaternion::fromAxisAndAngle(x, y, z, angle);
}
else if(text == "SCALE")
{
inputStream >> scale;
if(inputStream.fail())
break;
}
else if(text == "DIMENSIONS")
{
inputStream >> dimX >> dimY >> dimZ;
if(inputStream.fail())
break;
}
else if(text == "TYPE")
{
inputStream >> text;
if(inputStream.fail())
break;
typeIsScalars = (text == "SCALARS");
}
else if(text == "FORMAT")
{
inputStream >> text;
if(inputStream.fail())
break;
formatIsUByte = (text == "GL_RGBA8" || text == "GL_R8");
}
else if(text == "VOXEL_HEADER_END")
{
break;
}
}
if(dimX == 0 || dimY == 0 || dimZ == 0)
return NULL;
SmartPtr<VolumeDataSet> spData = new VolumeDataSet(inputFile,
pos, orient,
scale, scale, scale,
dimX, dimY, dimZ);
inputStream >> text;
if(text == "VOXEL_SCALARS")
{
spData->initVoxels();
for(size_t z = 0; z < dimZ; ++z)
{
std::string voxSlice;
inputStream >> voxSlice;
if(voxSlice != "VOXEL_SLICE")
return NULL;
for(size_t y = 0; y < dimY; ++y)
{
for(size_t x = 0; x < dimX; ++x)
{
float value;
inputStream >> value;
if(inputStream.fail())
return NULL;
spData->value(x, y, z) = static_cast<unsigned char>(value * 255.0f);
}
}
}
}
else
{
size_t voxelCount = dimX * dimY * dimZ;
if(text == "VOXEL_IMAGE_FILE")
{
std::string extBinaryFile = inputFile + ".voxb";
//inputStream >> extBinaryFile;
std::ifstream binaryInputStream;
binaryInputStream.open(extBinaryFile,
std::ios_base::in |
std::ios_base::binary);
if(binaryInputStream.is_open() == false)
return NULL;
Vec4f* pVoxelColors = new Vec4f[voxelCount];
binaryInputStream.read((char*)pVoxelColors,
sizeof(Vec4f) * voxelCount);
spData->setColors(pVoxelColors);
}
else if(text == "VOXEL_SUB_IMAGE_FILES")
{
QFileInfo fileInfo(QString(inputFile.c_str()));
QDir baseDir = fileInfo.dir();
while(inputStream.eof() != true)
{
std::string subImageText;
inputStream >> subImageText;
if(subImageText != "VOXEL_SUB_IMAGE_FILE")
break;
unsigned int rangeStartX, rangeStartY, rangeStartZ;
inputStream >> rangeStartX;
inputStream >> rangeStartY;
inputStream >> rangeStartZ;
if(inputStream.fail())
return NULL;
unsigned int rangeEndX, rangeEndY, rangeEndZ;
inputStream >> rangeEndX;
inputStream >> rangeEndY;
inputStream >> rangeEndZ;
if(inputStream.fail())
return NULL;
//skip the space character
inputStream.seekg(1, std::ios_base::cur);
std::stringbuf extBinaryFile;
inputStream.get(extBinaryFile);
if(inputStream.fail())
return NULL;
std::stringstream extBinaryFilePath;
extBinaryFilePath << baseDir.absolutePath().toAscii().data()
<< "/"
<< extBinaryFile.str();
std::cout << "Loading sub-image: "
<< extBinaryFilePath.str() << std::endl;
std::ifstream binaryInputStream;
binaryInputStream.open(extBinaryFilePath.str(),
std::ios_base::in |
std::ios_base::binary);
if(binaryInputStream.is_open() == false)
return NULL;
VolumeDataSet::SubVolume::Format format = VolumeDataSet::SubVolume::FORMAT_UBYTE_RGBA;
if(formatIsUByte == true)
{
if(typeIsScalars == true)
format = VolumeDataSet::SubVolume::FORMAT_UBYTE_SCALARS;
}
else
format = VolumeDataSet::SubVolume::FORMAT_FLOAT_RGBA;
VolumeDataSet::SubVolume subVolume(rangeStartX, rangeStartY, rangeStartZ,
rangeEndX, rangeEndY, rangeEndZ,
format);
int ubyteFormat;
binaryInputStream.read((char*)&ubyteFormat, sizeof(int));
if((ubyteFormat == 0 && formatIsUByte) || (ubyteFormat != 0 && formatIsUByte == false))
return NULL;
unsigned int dataSize;
binaryInputStream.read((char*)&dataSize, sizeof(unsigned int));
if(dataSize != subVolume.dataSize())
return NULL;
binaryInputStream.read((char*)subVolume.data(),
subVolume.dataSize());
spData->addSubVolume(subVolume);
}
}
else
{
Vec4ub* pVoxelColors = new Vec4ub[voxelCount];
spData->setColors(pVoxelColors);
for(size_t z = 0; z < dimZ; ++z)
{
std::string voxSlice;
inputStream >> voxSlice;
if(voxSlice != "VOXEL_SLICE")
return NULL;
for(size_t y = 0; y < dimY; ++y)
{
for(size_t x = 0; x < dimX; ++x)
{
float r, g, b, a;
inputStream >> r >> g >> b >> a;
if(inputStream.fail())
return NULL;
spData->setColor(x, y, z,
r, g, b, a);
}
}
}
}
}
return spData.release();
}
}
| 35.376812 | 107 | 0.436194 | apecoraro |
9104150482f82dc3178dbffb9ebbccef66fe0881 | 153 | hpp | C++ | scenes/sphere_animation.hpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | null | null | null | scenes/sphere_animation.hpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | null | null | null | scenes/sphere_animation.hpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | 1 | 2021-03-18T08:05:35.000Z | 2021-03-18T08:05:35.000Z | #ifndef SPHERE_ANIMATION_HPP
#define SPHERE_ANIMATION_HPP
#include "renderer/Scene.hpp"
void renderSphereAnimation ();
#endif // SPHERE_ANIMATION_HPP
| 17 | 30 | 0.816993 | AdrienVannson |
9104df44ec7178eef0332e31ad31133da2826c40 | 206 | cpp | C++ | TOI16/Resource/Pattern Matching Algorithm/Knuth - Morris - Pratt/KMP.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Resource/Pattern Matching Algorithm/Knuth - Morris - Pratt/KMP.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Resource/Pattern Matching Algorithm/Knuth - Morris - Pratt/KMP.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
void KMP(string s,string t)
{
int n = s.length();
int m = t.length();
int i = 0, j = 1;
int lps[m+1] = {0};
}
main()
{
string s;
string t;
KMP(s,t);
}
| 11.444444 | 27 | 0.558252 | mrmuffinnxz |
9106d61feff462942f2afc9fdfb8f8e20c1cbd37 | 6,055 | cc | C++ | dali/operators/reader/numpy_reader_gpu_op.cc | awolant/DALI | ace3e0bee44b7b10cdf7255ec02e143646c68ce1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/reader/numpy_reader_gpu_op.cc | awolant/DALI | ace3e0bee44b7b10cdf7255ec02e143646c68ce1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/reader/numpy_reader_gpu_op.cc | awolant/DALI | ace3e0bee44b7b10cdf7255ec02e143646c68ce1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020-2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include "dali/core/mm/memory.h"
#include "dali/core/mm/malloc_resource.h"
#include "dali/operators/reader/numpy_reader_gpu_op.h"
#include "dali/pipeline/data/views.h"
namespace dali {
namespace {
/**
* @brief Allocates memory that's suitable for use with GDS / CUfile
*
* Currently (CUDA 11.4) GPUDirect Storage can work only with memory allocated with cudaMalloc and
* cuMemAlloc. Since DALI is transitioning to CUDA Virtual Memory Management for memory
* allocation, we need a special allocator that's compatible with GDS.
*/
std::shared_ptr<uint8_t> gds_alloc(size_t bytes) {
uint8_t *ptr = nullptr;
CUDA_CALL(cudaMalloc(&ptr, bytes));
return std::shared_ptr<uint8_t>(ptr, [](void *mem) {
CUDA_DTOR_CALL(cudaFree(mem));
});
}
} // namespace
NumpyReaderGPU::NumpyReaderGPU(const OpSpec& spec)
: NumpyReader<GPUBackend, NumpyFileWrapperGPU>(spec),
thread_pool_(num_threads_, spec.GetArgument<int>("device_id"), false),
sg_(1 << 18, spec.GetArgument<int>("max_batch_size")) {
prefetched_batch_tensors_.resize(prefetch_queue_depth_);
for (auto &t : prefetched_batch_tensors_)
t.set_alloc_func(gds_alloc);
// set a device guard
DeviceGuard g(device_id_);
// init loader
bool shuffle_after_epoch = spec.GetArgument<bool>("shuffle_after_epoch");
loader_ = InitLoader<NumpyLoaderGPU>(spec, std::vector<string>(), shuffle_after_epoch);
kmgr_transpose_.Resize<TransposeKernel>(1, 1);
}
void NumpyReaderGPU::Prefetch() {
// We actually prepare the next batch
DomainTimeRange tr("[DALI][NumpyReaderGPU] Prefetch #" + to_string(curr_batch_producer_),
DomainTimeRange::kRed);
DataReader<GPUBackend, NumpyFileWrapperGPU>::Prefetch();
auto &curr_batch = prefetched_batch_queue_[curr_batch_producer_];
auto &curr_tensor_list = prefetched_batch_tensors_[curr_batch_producer_];
// get shapes
for (size_t data_idx = 0; data_idx < curr_batch.size(); ++data_idx) {
thread_pool_.AddWork([&curr_batch, data_idx](int tid) {
curr_batch[data_idx]->read_meta_f();
});
}
thread_pool_.RunAll();
// resize the current batch
auto ref_type = curr_batch[0]->get_type();
auto ref_shape = curr_batch[0]->get_shape();
TensorListShape<> tmp_shapes(curr_batch.size(), ref_shape.sample_dim());
for (size_t data_idx = 0; data_idx < curr_batch.size(); ++data_idx) {
auto &sample = curr_batch[data_idx];
DALI_ENFORCE(ref_type == sample->get_type(), make_string("Inconsistent data! "
"The data produced by the reader has inconsistent type:\n"
"type of [", data_idx, "] is ", sample->get_type(), " whereas\n"
"type of [0] is ", ref_type));
DALI_ENFORCE(
ref_shape.sample_dim() == sample->get_shape().sample_dim(),
make_string(
"Inconsistent data! The data produced by the reader has inconsistent dimensionality:\n"
"[",
data_idx, "] has ", sample->get_shape().sample_dim(),
" dimensions whereas\n"
"[0] has ",
ref_shape.sample_dim(), " dimensions."));
tmp_shapes.set_tensor_shape(data_idx, sample->get_shape());
}
// Check if the curr_tensor_list has the proper allocator.
// Some buffers allocated with a different method can slip in because output buffers
// are swapped with ones in prefetched_batch_tensors_ when all samples can be returned
// without any changes.
// See the line `std::swap(output, prefetched_batch_tensors_[curr_batch_consumer_]);`
// in numpy_reader_gpu_op_impl.cu
if (!dynamic_cast<mm::cuda_malloc_memory_resource*>(mm::GetDefaultDeviceResource())) {
auto *tgt = curr_tensor_list.alloc_func().target<shared_ptr<uint8_t>(*)(size_t)>();
if (!tgt || *tgt != &gds_alloc) {
curr_tensor_list.Reset();
curr_tensor_list.set_alloc_func(gds_alloc);
}
}
curr_tensor_list.Resize(tmp_shapes, ref_type);
size_t chunk_size = static_cast<size_t>( \
div_ceil(static_cast<uint64_t>(curr_tensor_list.nbytes()),
static_cast<uint64_t>(thread_pool_.NumThreads())));
// read the data
for (size_t data_idx = 0; data_idx < curr_tensor_list.ntensor(); ++data_idx) {
curr_tensor_list.SetMeta(data_idx, curr_batch[data_idx]->get_meta());
size_t image_bytes = static_cast<size_t>(volume(curr_tensor_list.tensor_shape(data_idx))
* curr_tensor_list.type_info().size());
uint8_t* dst_ptr = static_cast<uint8_t*>(curr_tensor_list.raw_mutable_tensor(data_idx));
size_t file_offset = 0;
while (image_bytes > 0) {
size_t read_bytes = std::min(image_bytes, chunk_size);
void* buffer = static_cast<void*>(dst_ptr);
thread_pool_.AddWork([&curr_batch, data_idx, buffer, file_offset, read_bytes](int tid) {
curr_batch[data_idx]->read_sample_f(buffer, file_offset, read_bytes);
});
// update addresses
dst_ptr += read_bytes;
file_offset += read_bytes;
image_bytes -= read_bytes;
}
}
thread_pool_.RunAll();
for (size_t data_idx = 0; data_idx < curr_tensor_list.ntensor(); ++data_idx) {
curr_batch[data_idx]->file_stream->Close();
}
}
DALI_REGISTER_OPERATOR(readers__Numpy, NumpyReaderGPU, GPU);
// Deprecated alias
DALI_REGISTER_OPERATOR(NumpyReader, NumpyReaderGPU, GPU);
} // namespace dali
| 39.575163 | 99 | 0.69711 | awolant |