text
string | meta
dict |
|---|---|
/* Copyright (c) 2017, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The Astrobee platform is 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 <lk_optical_flow/lk_optical_flow_nodelet.h>
#include <pluginlib/class_list_macros.h>
#include <ff_msgs/CameraRegistration.h>
namespace lk_optical_flow {
LKOpticalFlowNodelet::LKOpticalFlowNodelet(void) : ff_util::FreeFlyerNodelet(NODE_OPTICAL_FLOW) {}
void LKOpticalFlowNodelet::Initialize(ros::NodeHandle* nh) {
camera_id_ = 0;
inst_.reset(new LKOpticalFlow());
// Initialize lua config reader
config_.AddFile("optical_flow.config");
config_.AddFile("cameras.config");
ReadParams();
config_timer_ = nh->createTimer(ros::Duration(1), [this](ros::TimerEvent e) {
config_.CheckFilesUpdated(std::bind(&LKOpticalFlowNodelet::ReadParams, this));
}, false, true);
// Create all our subscribers and publishers
image_transport::ImageTransport img_transp(*nh);
img_sub_ = img_transp.subscribe(TOPIC_HARDWARE_NAV_CAM, 1, &LKOpticalFlowNodelet::ImageCallback, this);
if (debug_view_) {
image_transport::ImageTransport img_transp_priv(*nh);
img_pub_ = img_transp_priv.advertise(TOPIC_LOCALIZATION_OF_DEBUG, 1);
}
feature_pub_ = nh->advertise<ff_msgs::Feature2dArray>(TOPIC_LOCALIZATION_OF_FEATURES, 1);
reg_pub_ = nh->advertise<ff_msgs::CameraRegistration>(TOPIC_LOCALIZATION_OF_REGISTRATION, 1);
enable_srv_ = nh->advertiseService(SERVICE_LOCALIZATION_OF_ENABLE, &LKOpticalFlowNodelet::EnableService, this);
}
void LKOpticalFlowNodelet::ReadParams() {
// Read config files into lua
if (!config_.ReadFiles()) {
ROS_ERROR("Error loading optical flow parameters.");
return;
}
if (!config_.GetBool("debug_view", &debug_view_))
ROS_FATAL("Unspecified debug_view.");
inst_->ReadParams(&config_);
}
bool LKOpticalFlowNodelet::EnableService(ff_msgs::SetBool::Request & req, ff_msgs::SetBool::Response & res) {
if (req.enable) {
image_transport::ImageTransport img_transp(getNodeHandle());
img_sub_ = img_transp.subscribe(TOPIC_HARDWARE_NAV_CAM, 1, &LKOpticalFlowNodelet::ImageCallback, this);
} else {
img_sub_.shutdown();
}
res.success = true;
return true;
}
void LKOpticalFlowNodelet::ImageCallback(const sensor_msgs::ImageConstPtr& msg) {
// Signal to the EKF that we are processing this image. (The EKF must perform
// state augmentation at this instant.)
ff_msgs::CameraRegistration r;
ros::Time timestamp = ros::Time::now();
r.header = std_msgs::Header();
r.header.stamp = timestamp;
r.camera_id = ++camera_id_;
reg_pub_.publish(r);
ros::spinOnce();
// actually process the optical flow image
ff_msgs::Feature2dArray features;
inst_->OpticalFlow(msg, &features);
features.camera_id = camera_id_;
// Publish corners
feature_pub_.publish(features);
// Publish optical flow image
if (debug_view_)
img_pub_.publish(inst_->ShowDebugWindow(msg));
}
}; // namespace lk_optical_flow
PLUGINLIB_EXPORT_CLASS(lk_optical_flow::LKOpticalFlowNodelet, nodelet::Nodelet)
|
{
"language": "C++"
}
|
#include "vrclient_private.h"
#include "vrclient_defs.h"
#include "openvr_v0.9.20/openvr.h"
using namespace vr;
extern "C" {
#include "struct_converters.h"
}
#include "cppIVRCompositor_IVRCompositor_014.h"
#ifdef __cplusplus
extern "C" {
#endif
void cppIVRCompositor_IVRCompositor_014_SetTrackingSpace(void *linux_side, ETrackingUniverseOrigin eOrigin)
{
((IVRCompositor*)linux_side)->SetTrackingSpace((vr::ETrackingUniverseOrigin)eOrigin);
}
vr::ETrackingUniverseOrigin cppIVRCompositor_IVRCompositor_014_GetTrackingSpace(void *linux_side)
{
return ((IVRCompositor*)linux_side)->GetTrackingSpace();
}
vr::EVRCompositorError cppIVRCompositor_IVRCompositor_014_WaitGetPoses(void *linux_side, TrackedDevicePose_t * pRenderPoseArray, uint32_t unRenderPoseArrayCount, TrackedDevicePose_t * pGamePoseArray, uint32_t unGamePoseArrayCount)
{
return ((IVRCompositor*)linux_side)->WaitGetPoses((vr::TrackedDevicePose_t *)pRenderPoseArray, (uint32_t)unRenderPoseArrayCount, (vr::TrackedDevicePose_t *)pGamePoseArray, (uint32_t)unGamePoseArrayCount);
}
vr::EVRCompositorError cppIVRCompositor_IVRCompositor_014_GetLastPoses(void *linux_side, TrackedDevicePose_t * pRenderPoseArray, uint32_t unRenderPoseArrayCount, TrackedDevicePose_t * pGamePoseArray, uint32_t unGamePoseArrayCount)
{
return ((IVRCompositor*)linux_side)->GetLastPoses((vr::TrackedDevicePose_t *)pRenderPoseArray, (uint32_t)unRenderPoseArrayCount, (vr::TrackedDevicePose_t *)pGamePoseArray, (uint32_t)unGamePoseArrayCount);
}
vr::EVRCompositorError cppIVRCompositor_IVRCompositor_014_GetLastPoseForTrackedDeviceIndex(void *linux_side, TrackedDeviceIndex_t unDeviceIndex, TrackedDevicePose_t * pOutputPose, TrackedDevicePose_t * pOutputGamePose)
{
return ((IVRCompositor*)linux_side)->GetLastPoseForTrackedDeviceIndex((vr::TrackedDeviceIndex_t)unDeviceIndex, (vr::TrackedDevicePose_t *)pOutputPose, (vr::TrackedDevicePose_t *)pOutputGamePose);
}
vr::EVRCompositorError cppIVRCompositor_IVRCompositor_014_Submit(void *linux_side, EVREye eEye, Texture_t * pTexture, VRTextureBounds_t * pBounds, EVRSubmitFlags nSubmitFlags)
{
return ((IVRCompositor*)linux_side)->Submit((vr::EVREye)eEye, (const vr::Texture_t *)pTexture, (const vr::VRTextureBounds_t *)pBounds, (vr::EVRSubmitFlags)nSubmitFlags);
}
void cppIVRCompositor_IVRCompositor_014_ClearLastSubmittedFrame(void *linux_side)
{
((IVRCompositor*)linux_side)->ClearLastSubmittedFrame();
}
void cppIVRCompositor_IVRCompositor_014_PostPresentHandoff(void *linux_side)
{
((IVRCompositor*)linux_side)->PostPresentHandoff();
}
bool cppIVRCompositor_IVRCompositor_014_GetFrameTiming(void *linux_side, Compositor_FrameTiming * pTiming, uint32_t unFramesAgo)
{
return ((IVRCompositor*)linux_side)->GetFrameTiming((vr::Compositor_FrameTiming *)pTiming, (uint32_t)unFramesAgo);
}
float cppIVRCompositor_IVRCompositor_014_GetFrameTimeRemaining(void *linux_side)
{
return ((IVRCompositor*)linux_side)->GetFrameTimeRemaining();
}
void cppIVRCompositor_IVRCompositor_014_FadeToColor(void *linux_side, float fSeconds, float fRed, float fGreen, float fBlue, float fAlpha, bool bBackground)
{
((IVRCompositor*)linux_side)->FadeToColor((float)fSeconds, (float)fRed, (float)fGreen, (float)fBlue, (float)fAlpha, (bool)bBackground);
}
void cppIVRCompositor_IVRCompositor_014_FadeGrid(void *linux_side, float fSeconds, bool bFadeIn)
{
((IVRCompositor*)linux_side)->FadeGrid((float)fSeconds, (bool)bFadeIn);
}
vr::EVRCompositorError cppIVRCompositor_IVRCompositor_014_SetSkyboxOverride(void *linux_side, Texture_t * pTextures, uint32_t unTextureCount)
{
return ((IVRCompositor*)linux_side)->SetSkyboxOverride((const vr::Texture_t *)pTextures, (uint32_t)unTextureCount);
}
void cppIVRCompositor_IVRCompositor_014_ClearSkyboxOverride(void *linux_side)
{
((IVRCompositor*)linux_side)->ClearSkyboxOverride();
}
void cppIVRCompositor_IVRCompositor_014_CompositorBringToFront(void *linux_side)
{
((IVRCompositor*)linux_side)->CompositorBringToFront();
}
void cppIVRCompositor_IVRCompositor_014_CompositorGoToBack(void *linux_side)
{
((IVRCompositor*)linux_side)->CompositorGoToBack();
}
void cppIVRCompositor_IVRCompositor_014_CompositorQuit(void *linux_side)
{
((IVRCompositor*)linux_side)->CompositorQuit();
}
bool cppIVRCompositor_IVRCompositor_014_IsFullscreen(void *linux_side)
{
return ((IVRCompositor*)linux_side)->IsFullscreen();
}
uint32_t cppIVRCompositor_IVRCompositor_014_GetCurrentSceneFocusProcess(void *linux_side)
{
return ((IVRCompositor*)linux_side)->GetCurrentSceneFocusProcess();
}
uint32_t cppIVRCompositor_IVRCompositor_014_GetLastFrameRenderer(void *linux_side)
{
return ((IVRCompositor*)linux_side)->GetLastFrameRenderer();
}
bool cppIVRCompositor_IVRCompositor_014_CanRenderScene(void *linux_side)
{
return ((IVRCompositor*)linux_side)->CanRenderScene();
}
void cppIVRCompositor_IVRCompositor_014_ShowMirrorWindow(void *linux_side)
{
((IVRCompositor*)linux_side)->ShowMirrorWindow();
}
void cppIVRCompositor_IVRCompositor_014_HideMirrorWindow(void *linux_side)
{
((IVRCompositor*)linux_side)->HideMirrorWindow();
}
bool cppIVRCompositor_IVRCompositor_014_IsMirrorWindowVisible(void *linux_side)
{
return ((IVRCompositor*)linux_side)->IsMirrorWindowVisible();
}
void cppIVRCompositor_IVRCompositor_014_CompositorDumpImages(void *linux_side)
{
((IVRCompositor*)linux_side)->CompositorDumpImages();
}
bool cppIVRCompositor_IVRCompositor_014_ShouldAppRenderWithLowResources(void *linux_side)
{
return ((IVRCompositor*)linux_side)->ShouldAppRenderWithLowResources();
}
void cppIVRCompositor_IVRCompositor_014_ForceInterleavedReprojectionOn(void *linux_side, bool bOverride)
{
((IVRCompositor*)linux_side)->ForceInterleavedReprojectionOn((bool)bOverride);
}
void cppIVRCompositor_IVRCompositor_014_ForceReconnectProcess(void *linux_side)
{
((IVRCompositor*)linux_side)->ForceReconnectProcess();
}
void cppIVRCompositor_IVRCompositor_014_SuspendRendering(void *linux_side, bool bSuspend)
{
((IVRCompositor*)linux_side)->SuspendRendering((bool)bSuspend);
}
#ifdef __cplusplus
}
#endif
|
{
"language": "C++"
}
|
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtScript/QScriptValue>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
#include <qmetaobject.h>
#include <qsslcipher.h>
#include <QVariant>
#include <qsslcipher.h>
static const char * const qtscript_QSslCipher_function_names[] = {
"QSslCipher"
// static
// prototype
, "authenticationMethod"
, "encryptionMethod"
, "isNull"
, "keyExchangeMethod"
, "name"
, "operator_assign"
, "equals"
, "protocol"
, "protocolString"
, "supportedBits"
, "usedBits"
, "toString"
};
static const char * const qtscript_QSslCipher_function_signatures[] = {
"\nQSslCipher other\nString name, SslProtocol protocol"
// static
// prototype
, ""
, ""
, ""
, ""
, ""
, "QSslCipher other"
, "QSslCipher other"
, ""
, ""
, ""
, ""
""
};
static const int qtscript_QSslCipher_function_lengths[] = {
2
// static
// prototype
, 0
, 0
, 0
, 0
, 0
, 1
, 1
, 0
, 0
, 0
, 0
, 0
};
static QScriptValue qtscript_QSslCipher_throw_ambiguity_error_helper(
QScriptContext *context, const char *functionName, const char *signatures)
{
QStringList lines = QString::fromLatin1(signatures).split(QLatin1Char('\n'));
QStringList fullSignatures;
for (int i = 0; i < lines.size(); ++i)
fullSignatures.append(QString::fromLatin1("%0(%1)").arg(functionName).arg(lines.at(i)));
return context->throwError(QString::fromLatin1("QSslCipher::%0(): could not find a function match; candidates are:\n%1")
.arg(functionName).arg(fullSignatures.join(QLatin1String("\n"))));
}
Q_DECLARE_METATYPE(QSslCipher)
Q_DECLARE_METATYPE(QSslCipher*)
Q_DECLARE_METATYPE(QSsl::SslProtocol)
//
// QSslCipher
//
static QScriptValue qtscript_QSslCipher_prototype_call(QScriptContext *context, QScriptEngine *)
{
#if QT_VERSION > 0x040400
Q_ASSERT(context->callee().isFunction());
uint _id = context->callee().data().toUInt32();
#else
uint _id;
if (context->callee().isFunction())
_id = context->callee().data().toUInt32();
else
_id = 0xBABE0000 + 11;
#endif
Q_ASSERT((_id & 0xFFFF0000) == 0xBABE0000);
_id &= 0x0000FFFF;
QSslCipher* _q_self = qscriptvalue_cast<QSslCipher*>(context->thisObject());
if (!_q_self) {
return context->throwError(QScriptContext::TypeError,
QString::fromLatin1("QSslCipher.%0(): this object is not a QSslCipher")
.arg(qtscript_QSslCipher_function_names[_id+1]));
}
switch (_id) {
case 0:
if (context->argumentCount() == 0) {
QString _q_result = _q_self->authenticationMethod();
return QScriptValue(context->engine(), _q_result);
}
break;
case 1:
if (context->argumentCount() == 0) {
QString _q_result = _q_self->encryptionMethod();
return QScriptValue(context->engine(), _q_result);
}
break;
case 2:
if (context->argumentCount() == 0) {
bool _q_result = _q_self->isNull();
return QScriptValue(context->engine(), _q_result);
}
break;
case 3:
if (context->argumentCount() == 0) {
QString _q_result = _q_self->keyExchangeMethod();
return QScriptValue(context->engine(), _q_result);
}
break;
case 4:
if (context->argumentCount() == 0) {
QString _q_result = _q_self->name();
return QScriptValue(context->engine(), _q_result);
}
break;
case 5:
if (context->argumentCount() == 1) {
QSslCipher _q_arg0 = qscriptvalue_cast<QSslCipher>(context->argument(0));
QSslCipher _q_result = _q_self->operator=(_q_arg0);
return qScriptValueFromValue(context->engine(), _q_result);
}
break;
case 6:
if (context->argumentCount() == 1) {
QSslCipher _q_arg0 = qscriptvalue_cast<QSslCipher>(context->argument(0));
bool _q_result = _q_self->operator==(_q_arg0);
return QScriptValue(context->engine(), _q_result);
}
break;
case 7:
if (context->argumentCount() == 0) {
QSsl::SslProtocol _q_result = _q_self->protocol();
return qScriptValueFromValue(context->engine(), _q_result);
}
break;
case 8:
if (context->argumentCount() == 0) {
QString _q_result = _q_self->protocolString();
return QScriptValue(context->engine(), _q_result);
}
break;
case 9:
if (context->argumentCount() == 0) {
int _q_result = _q_self->supportedBits();
return QScriptValue(context->engine(), _q_result);
}
break;
case 10:
if (context->argumentCount() == 0) {
int _q_result = _q_self->usedBits();
return QScriptValue(context->engine(), _q_result);
}
break;
case 11: {
QString result;
QDebug d(&result);
d << *_q_self;
return QScriptValue(context->engine(), result);
}
default:
Q_ASSERT(false);
}
return qtscript_QSslCipher_throw_ambiguity_error_helper(context,
qtscript_QSslCipher_function_names[_id+1],
qtscript_QSslCipher_function_signatures[_id+1]);
}
static QScriptValue qtscript_QSslCipher_static_call(QScriptContext *context, QScriptEngine *)
{
uint _id = context->callee().data().toUInt32();
Q_ASSERT((_id & 0xFFFF0000) == 0xBABE0000);
_id &= 0x0000FFFF;
switch (_id) {
case 0:
if (context->thisObject().strictlyEquals(context->engine()->globalObject())) {
return context->throwError(QString::fromLatin1("QSslCipher(): Did you forget to construct with 'new'?"));
}
if (context->argumentCount() == 0) {
QSslCipher _q_cpp_result;
QScriptValue _q_result = context->engine()->newVariant(context->thisObject(), qVariantFromValue(_q_cpp_result));
return _q_result;
} else if (context->argumentCount() == 1) {
QSslCipher _q_arg0 = qscriptvalue_cast<QSslCipher>(context->argument(0));
QSslCipher _q_cpp_result(_q_arg0);
QScriptValue _q_result = context->engine()->newVariant(context->thisObject(), qVariantFromValue(_q_cpp_result));
return _q_result;
} else if (context->argumentCount() == 2) {
QString _q_arg0 = context->argument(0).toString();
QSsl::SslProtocol _q_arg1 = qscriptvalue_cast<QSsl::SslProtocol>(context->argument(1));
QSslCipher _q_cpp_result(_q_arg0, _q_arg1);
QScriptValue _q_result = context->engine()->newVariant(context->thisObject(), qVariantFromValue(_q_cpp_result));
return _q_result;
}
break;
default:
Q_ASSERT(false);
}
return qtscript_QSslCipher_throw_ambiguity_error_helper(context,
qtscript_QSslCipher_function_names[_id],
qtscript_QSslCipher_function_signatures[_id]);
}
QScriptValue qtscript_create_QSslCipher_class(QScriptEngine *engine)
{
engine->setDefaultPrototype(qMetaTypeId<QSslCipher*>(), QScriptValue());
QScriptValue proto = engine->newVariant(qVariantFromValue((QSslCipher*)0));
for (int i = 0; i < 12; ++i) {
QScriptValue fun = engine->newFunction(qtscript_QSslCipher_prototype_call, qtscript_QSslCipher_function_lengths[i+1]);
fun.setData(QScriptValue(engine, uint(0xBABE0000 + i)));
proto.setProperty(QString::fromLatin1(qtscript_QSslCipher_function_names[i+1]),
fun, QScriptValue::SkipInEnumeration);
}
engine->setDefaultPrototype(qMetaTypeId<QSslCipher>(), proto);
engine->setDefaultPrototype(qMetaTypeId<QSslCipher*>(), proto);
QScriptValue ctor = engine->newFunction(qtscript_QSslCipher_static_call, proto, qtscript_QSslCipher_function_lengths[0]);
ctor.setData(QScriptValue(engine, uint(0xBABE0000 + 0)));
return ctor;
}
|
{
"language": "C++"
}
|
/* ------------------------------------------------------------------------------
*
* # Dimple.js - multiple vertical lines
*
* Demo of multiple line chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-line-vertical-multiple", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(50, 25, 20, 30);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add line
myChart
.addSeries("Channel", dimple.plot.line)
.interpolation = "basis";
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
}, 100)
}
});
});
|
{
"language": "C++"
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
////////////////////////////////////////////////////////////////////////
#include "pxr/pxr.h"
#include "pxr/base/tf/registryManager.h"
#include "pxr/base/tf/scriptModuleLoader.h"
#include "pxr/base/tf/token.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfScriptModuleLoader) {
// List of direct dependencies for this library.
const std::vector<TfToken> reqs = {
TfToken("sdf"),
TfToken("tf"),
TfToken("usd"),
TfToken("usdGeom")
};
TfScriptModuleLoader::GetInstance().
RegisterLibrary(TfToken("usdAbc"), TfToken("pxr.UsdAbc"), reqs);
}
PXR_NAMESPACE_CLOSE_SCOPE
|
{
"language": "C++"
}
|
/***************************************************************************
ADM_vidDecTelecide - description
-------------------
email : [email protected]
Port of Donal Graft Decimate which is (c) Donald Graft
http://www.neuron2.net
http://puschpull.org/avisynth/decomb_reference_manual.html
***************************************************************************/
/*
Decimate plugin for Avisynth -- performs 1-in-N
decimation on a stream of progressive frames, which are usually
obtained from the output of my Telecide plugin for Avisynth.
For each group of N successive frames, this filter deletes the
frame that is most similar to its predecessor. Thus, duplicate
frames coming out of Telecide can be removed using Decimate. This
filter adjusts the frame rate of the clip as
appropriate. Selection of the cycle size is selected by specifying
a parameter to Decimate() in the Avisynth scipt.
Copyright (C) 2003 Donald A. Graft
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
The author can be contacted at:
Donald Graft
[email protected].
*/
#include "ADM_default.h"
#include "decimate.h"
#include "DIA_factory.h"
#include "dec_desc.cpp"
// Add the hook to make it valid plugin
DECLARE_VIDEO_FILTER( Decimate, // Class
1,0,0, // Version
ADM_UI_ALL, // UI
VF_INTERLACING, // Category
"decimate", // internal name (must be uniq!)
QT_TRANSLATE_NOOP("decimate","Decomb decimate"), // Display name
QT_TRANSLATE_NOOP("decimate","Donald Graft decimate. Remove duplicate after telecide.") // Description
);
/**
\fn configure
*/
bool Decimate::configure(void)
{
deciMate *_param=&configuration;
#define PX(x) &(configuration.x)
#define SZT(x) sizeof(x)/sizeof(diaMenuEntry *)
ELEM_TYPE_FLOAT t1=(ELEM_TYPE_FLOAT)_param->threshold;
ELEM_TYPE_FLOAT t2=(ELEM_TYPE_FLOAT)_param->threshold2;
diaMenuEntry tMode[]={
{0, QT_TRANSLATE_NOOP("decimate","Discard closer"),NULL},
{1, QT_TRANSLATE_NOOP("decimate","Replace (interpolate)"),NULL},
{2, QT_TRANSLATE_NOOP("decimate","Discard longer dupe (animés)"),NULL},
{3, QT_TRANSLATE_NOOP("decimate","Pulldown dupe removal"),NULL}
};
diaMenuEntry tQuality[]={
{0, QT_TRANSLATE_NOOP("decimate","Fastest (no chroma, partial luma)"),NULL},
// {1, QT_TRANSLATE_NOOP("decimate","Fast (partial luma and chroma)"),NULL},
{2, QT_TRANSLATE_NOOP("decimate","Medium (full luma, no chroma)"),NULL},
// {3, QT_TRANSLATE_NOOP("decimate","Slow (full luma and chroma)"),NULL}
};
diaElemMenu menuMode(PX(mode),QT_TRANSLATE_NOOP("decimate","_Mode:"), 4,tMode);
diaElemMenu menuQuality(PX(quality),QT_TRANSLATE_NOOP("decimate","_Quality:"), sizeof(tQuality)/sizeof(diaMenuEntry),tQuality);
diaElemFloat menuThresh1(&t1,QT_TRANSLATE_NOOP("decimate","_Threshold 1:"),0,100.);
diaElemFloat menuThresh2(&t2,QT_TRANSLATE_NOOP("decimate","T_hreshold 2:"),0,100.);
diaElemUInteger cycle(PX(cycle),QT_TRANSLATE_NOOP("decimate","C_ycle:"),2,40);
diaElemToggle show(PX(show),QT_TRANSLATE_NOOP("decimate","Sho_w"));
diaElem *elems[]={&cycle,&menuMode,&menuQuality,&menuThresh1,&menuThresh2,&show};
if(diaFactoryRun(QT_TRANSLATE_NOOP("decimate","Decomb Decimate"),6,elems))
{
_param->threshold=(double )t1;
_param->threshold2=(double )t2;
updateInfo();
reset();
return 1;
}
return 0;
}
/**
\fn getConfiguration
*/
const char *Decimate::getConfiguration(void)
{
static char strparam[255]={0};
snprintf(strparam,254," Decomb Decimate cycle:%d",configuration.cycle);
return strparam;
}
/**
\fn updateInfo
*/
void Decimate::updateInfo(void)
{
if(configuration.cycle<2)
{
ADM_error("Telecide:bad configuration! cycle<2\n");
return;
}
double inc=info.frameIncrement;
inc*=configuration.cycle;
inc/=configuration.cycle-1;
info.frameIncrement=inc;
}
/**
\fn reset
\brief reset counters. Must be called each time a change is made (params/seek)
*/
void Decimate::reset(void)
{
last_request = -1;
firsttime = true;
all_video_cycle = true;
hints_invalid=false;
}
/**
\fn Ctor
*/
Decimate::Decimate( ADM_coreVideoFilter *in,CONFcouple *couples) :
ADM_coreVideoFilterCached(11,in,couples)
{
char buf[80];
unsigned int *p;
deciMate *_param=&configuration;
//
// Init here
if(!couples || !ADM_paramLoad(couples,deciMate_param,&configuration))
{
_param->cycle=5;
_param->mode=3;
_param->show=false;
_param->debug=false;
_param->quality=2;
_param->threshold=0;
_param->threshold2=3.0;
}
ADM_assert(_param->cycle);
if (_param->mode == 0 || _param->mode == 2 || _param->mode == 3)
{
updateInfo();
}
sum = (unsigned int *) ADM_alloc(MAX_BLOCKS * MAX_BLOCKS * sizeof(unsigned int));
ADM_assert(sum);
if (configuration.debug)
{
OutputDebugString( "Decimate %s by Donald Graft, Copyright 2003\n", 0); // VERSION
}
reset();
}
/**
\fn getCoupledConf
*/
bool Decimate::getCoupledConf(CONFcouple **couples)
{
return ADM_paramSave(couples, deciMate_param,&configuration);
}
void Decimate::setCoupledConf(CONFcouple *couples)
{
ADM_paramLoad(couples, deciMate_param, &configuration);
}
/**
\fn dtor
*/
Decimate::~Decimate(void)
{
if (sum != NULL) ADM_dealloc(sum);
sum=NULL;
}
/**
\fn getNextFrame
*/
bool Decimate::getNextFrame(uint32_t *fn,ADMImage *data)
{
switch(configuration.mode)
{
case 0: return get0(fn,data);break;
case 1: return get1(fn,data);break;
case 2: return get2(fn,data);break;
case 3: return get3(fn,data);break;
default: ADM_assert(0);
}
return false;
}
/**
\fn get0
\brief A B C... if B is close enough to A discard it.
*/
bool Decimate::get0(uint32_t *fn,ADMImage *data)
{
bool forced = false;
ADMImage *src,*next;
double metric;
char buf[256];
int useframe,dropframe;
int start;
deciMate *_param=&configuration;
/* Normal decimation. Remove the frame most similar to its preceding frame. */
/* Determine the correct frame to use and get it. */
int cycle=configuration.cycle;
int sourceFrame = (nextFrame*cycle)/(cycle-1);
int cycleStartFrame = (sourceFrame / cycle) * cycle;
int inframe=nextFrame;
*fn=nextFrame;
GETFRAME(sourceFrame, src);
if(!src)
{
ADM_info("Decimate: End of video stream, cannot get frame %d\n",useframe);
vidCache->unlockAll();
return false;
}
nextFrame++;
FindDuplicate(cycleStartFrame, &dropframe, &metric, &forced);
if (sourceFrame >= dropframe) sourceFrame++;
GETFRAME(sourceFrame, src);
if(!src)
{
vidCache->unlockAll();
return false;
}
data->duplicate(src);
vidCache->unlockAll();
if (configuration.show == true)
{
sprintf(buf, "Decimate %d", 0); DrawString(data, 0, 0, buf);
sprintf(buf, "Copyright 2003 Donald Graft"); DrawString(data, 0, 1, buf);
sprintf(buf,"%d: %3.2f", start, showmetrics[0]); DrawString(data, 0, 3, buf);
sprintf(buf,"%d: %3.2f", start + 1, showmetrics[1]); DrawString(data, 0, 4, buf);
sprintf(buf,"%d: %3.2f", start + 2, showmetrics[2]); DrawString(data, 0, 5, buf);
sprintf(buf,"%d: %3.2f", start + 3, showmetrics[3]); DrawString(data, 0, 6, buf);
sprintf(buf,"%d: %3.2f", start + 4, showmetrics[4]); DrawString(data, 0, 7, buf);
sprintf(buf,"in frm %d, use frm %d", inframe, useframe);DrawString(data, 0, 8, buf);
sprintf(buf,"dropping frm %d%s", dropframe, last_forced == true ? ", forced!" : "");
DrawString(data, 0, 9, buf);
}
if (configuration.debug)
{
if (!(inframe % _param->cycle))
{
OutputDebugString("Decimate: %d: %3.2f\n", start, showmetrics[0]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 1, showmetrics[1]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 2, showmetrics[2]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 3, showmetrics[3]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 4, showmetrics[4]);
}
OutputDebugString("Decimate: in frm %d, use frm %d\n", inframe, useframe);
OutputDebugString("Decimate: dropping frm %d%s\n", dropframe, last_forced == true ? ", forced!" : "");
}
return true;
}
/**
\fn get1
\brief mode=1, A B C D => A BC D, i.e. (B,C) is replaced by BC, blend between B & C
*/
bool Decimate::get1(uint32_t *fn,ADMImage *data)
{
bool forced = false;
ADMImage *src,*next;
int useframe,dropframe;
deciMate *_param=&configuration;
int cycle=configuration.cycle;
int sourceFrame = (nextFrame*cycle)/(cycle-1);
int cycleStartFrame = (sourceFrame / cycle) * cycle;
unsigned int hint, film = 1;
int inframe=nextFrame;
double metric;
char buf[256];
GETFRAME(sourceFrame, src);
if(!src)
{
ADM_info("Decimate: End of video stream, cannot get frame %d\n",useframe);
vidCache->unlockAll();
return false;
}
*fn=nextFrame;
nextFrame++;
if (GetHintingData(YPLANE(src), &hint) == false)
{
film = hint & PROGRESSIVE;
}
/* Find the most similar frame as above but replace it with a blend of
the preceding and following frames. */
FindDuplicate(cycleStartFrame, &dropframe, &metric, &forced);
if (!film || sourceFrame != dropframe || (_param->threshold && metric > _param->threshold))
{
data->duplicate(src);
vidCache->unlockAll();
if (configuration.show == true)
{
sprintf(buf, "Decimate %d", 0); DrawString(data, 0, 0, buf);
sprintf(buf, "Copyright 2003 Donald Graft"); DrawString(data, 0, 1, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame, showmetrics[0]); DrawString(data, 0, 3, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 1, showmetrics[1]); DrawString(data, 0, 4, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 2, showmetrics[2]); DrawString(data, 0, 5, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 3, showmetrics[3]); DrawString(data, 0, 6, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 4, showmetrics[4]); DrawString(data, 0, 7, buf);
sprintf(buf,"infrm %d", inframe);
DrawString(data, 0, 8, buf);
if (last_forced == false)
sprintf(buf,"chose %d, passing through", dropframe);
else
sprintf(buf,"chose %d, passing through, forced!", dropframe);
DrawString(data, 0, 9, buf);
}
if (configuration.debug)
{
if (!(inframe % _param->cycle))
{
OutputDebugString("Decimate: %d: %3.2f\n", start, showmetrics[0]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 1, showmetrics[1]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 2, showmetrics[2]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 3, showmetrics[3]);
OutputDebugString("Decimate: %d: %3.2f\n", start + 4, showmetrics[4]);
}
OutputDebugString("Decimate: in frm %d\n", inframe);
if (last_forced == false)
{
OutputDebugString("Decimate: chose %d, passing through\n", dropframe);
}
else
{
OutputDebugString("Decimate: chose %d, passing through, forced!\n", dropframe);
}
}
return true;
}
if (configuration.debug)
{
if (!(inframe % _param->cycle))
{
OutputDebugString( "Decimate: %d: %3.2f\n", start, showmetrics[0]);
OutputDebugString( "Decimate: %d: %3.2f\n", start + 1, showmetrics[1]);
OutputDebugString( "Decimate: %d: %3.2f\n", start + 2, showmetrics[2]);
OutputDebugString( "Decimate: %d: %3.2f\n", start + 3, showmetrics[3]);
OutputDebugString( "Decimate: %d: %3.2f\n", start + 4, showmetrics[4]);
}
OutputDebugString("Decimate: in frm %d\n", inframe);
if (last_forced == false)
{
OutputDebugString("Decimate: chose %d, blending %d and %d\n", dropframe, inframe, nextfrm);
}
else
{
OutputDebugString("Decimate: chose %d, blending %d and %d, forced!\n", dropframe, inframe, nextfrm);
}
}
// Blend current frame with next frame
GETFRAME(sourceFrame+1, next);
if(!next)
data->duplicate(src);
else
data->blend(src,next);
vidCache->unlockAll();
if (configuration.show == true)
{
sprintf(buf, "Decimate %d", 0); DrawString(data, 0, 0, buf);
sprintf(buf, "Copyright 2003 Donald Graft"); DrawString(data, 0, 1, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame, showmetrics[0]); DrawString(data, 0, 3, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 1, showmetrics[1]); DrawString(data, 0, 4, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 2, showmetrics[2]); DrawString(data, 0, 5, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 3, showmetrics[3]); DrawString(data, 0, 6, buf);
sprintf(buf,"%d: %3.2f", cycleStartFrame + 4, showmetrics[4]); DrawString(data, 0, 7, buf);
sprintf(buf,"infrm %d", inframe);
DrawString(data, 0, 8, buf);
if (last_forced == false)
sprintf(buf,"chose %d, blending %d and %d",dropframe, sourceFrame, sourceFrame+1);
else
sprintf(buf,"chose %d, blending %d and %d, forced!", dropframe, sourceFrame, sourceFrame+1);
DrawString(data, 0, 9, buf);
}
return true;
}
/**
\fn get2
\fn remove one frame from longest duplicate (anime)
*/
bool Decimate::get2(uint32_t *fn,ADMImage *data)
{
bool forced = false;
double metric;
char buf[256];
deciMate *_param=&configuration;
int cycle=configuration.cycle;
int sourceFrame = (nextFrame*cycle)/(cycle-1);
int cycleStartFrame = (sourceFrame / cycle) * cycle;
int useframe,dropframe;
*fn=nextFrame;
int inframe=nextFrame;
ADMImage *src,*next;
GETFRAME(sourceFrame, src);
if(!src)
{
ADM_info("Decimate: End of video stream, cannot get frame %d\n",useframe);
vidCache->unlockAll();
return false;
}
nextFrame++;
/* Delete the duplicate in the longest string of duplicates. */
FindDuplicate2(cycleStartFrame, &dropframe, &forced);
if (sourceFrame >= dropframe)
sourceFrame++;
GETFRAME(sourceFrame, src);
if(!src)
{
vidCache->unlockAll();
return false;
}
data->duplicate(src);
vidCache->unlockAll();
if (configuration.show == true)
{
int start = (useframe / _param->cycle) * _param->cycle;
sprintf(buf, "Decimate %d", 0); DrawString(data, 0, 0, buf);
sprintf(buf, "Copyright 2003 Donald Graft"); DrawString(data, 0, 1, buf);
sprintf(buf,"in frm %d, use frm %d", inframe, useframe); DrawString(data, 0, 3, buf);
sprintf(buf,"%d: %3.2f (%s)", cycleStartFrame, showmetrics[0], Dshow[0] ? "new" : "dup"); DrawString(data, 0, 4, buf);
sprintf(buf,"%d: %3.2f (%s)", cycleStartFrame + 1, showmetrics[1],Dshow[1] ? "new" : "dup");DrawString(data, 0, 5, buf);
sprintf(buf,"%d: %3.2f (%s)", cycleStartFrame + 2, showmetrics[2],Dshow[2] ? "new" : "dup");DrawString(data, 0, 6, buf);
sprintf(buf,"%d: %3.2f (%s)", cycleStartFrame + 3, showmetrics[3],Dshow[3] ? "new" : "dup");DrawString(data, 0, 7, buf);
sprintf(buf,"%d: %3.2f (%s)", cycleStartFrame + 4, showmetrics[4],Dshow[4] ? "new" : "dup");DrawString(data, 0, 8, buf);
sprintf(buf,"Dropping frm %d%s", dropframe, last_forced == true ? " forced!" : "");
DrawString(data, 0, 9, buf);
}
if (configuration.debug)
{
sprintf(buf,"Decimate: inframe %d useframe %d\n", inframe, useframe);
OutputDebugString(buf);
}
return true;
}
/**
\fn get3
\brief ivtc (after telecide)
*/
bool Decimate::get3(uint32_t *fn,ADMImage *data)
{
bool forced = false;
ADMImage *src,*next;
int dropframe;
double metric;
char buf[256];
deciMate *_param=&configuration;
/* Decimate by removing a duplicate from film cycles and doing a
blend rate conversion on the video cycles. */
if (_param->cycle != 5)// env->ThrowError("Decimate: mode=3 requires cycle=5");
{
ADM_error("Decimate: mode=3 requires cycle=5\n");
return false;
}
int sourceFrame = (nextFrame*5)/4;
int cycleStartFrame = (sourceFrame /5) * 5;
*fn=nextFrame;
GETFRAME(sourceFrame, src);
if(!src)
{
ADM_info("Decimate: End of video stream, cannot get frame %d\n",sourceFrame);
vidCache->unlockAll();
return false;
}
int inframe=nextFrame;
nextFrame++;
FindDuplicate(cycleStartFrame, &dropframe, &metric, &forced);
/* Use hints from Telecide about film versus video. Also use the difference
metric of the most similar frame in the cycle; if it exceeds threshold,
assume it's a video cycle. */
if (!(inframe % 4))
{
all_video_cycle = false;
if (_param->threshold && metric > _param->threshold)
{
all_video_cycle = true;
}
if ((hints_invalid == false) &&
(!(hints[0] & PROGRESSIVE) ||
!(hints[1] & PROGRESSIVE) ||
!(hints[2] & PROGRESSIVE) ||
!(hints[3] & PROGRESSIVE) ||
!(hints[4] & PROGRESSIVE)))
{
all_video_cycle = true;
}
}
if (all_video_cycle == false)
{
/* It's film, so decimate in the normal way. */
if (sourceFrame >= dropframe) sourceFrame++;
GETFRAME(sourceFrame, src);
if(!src)
{
vidCache->unlockAll();
return false;
}
data->duplicate(src);
vidCache->unlockAll();
DrawShow(data, sourceFrame, forced, dropframe, metric, inframe);
return true; // return src;
}
else
{
switch(inframe %4)
{
case 0:
/* It's a video cycle. Output the first frame of the cycle. */
GETFRAME(sourceFrame, src);
data->duplicate(src);
vidCache->unlockAll();
break;
case 3:
/* It's a video cycle. Output the last frame of the cycle. */
GETFRAME(sourceFrame+1, src);
if(!src)
{
vidCache->unlockAll();
return false;
}
data->duplicate(src);
vidCache->unlockAll();
break;
case 1: case 2:
/* It's a video cycle. Make blends for the remaining frames. */
if ((inframe % 4) == 1) // MEANX dont understand the difference ?
{
GETFRAME(sourceFrame, src);
GETFRAME(sourceFrame+1, next);
if(!next) next=src;
}
else
{
GETFRAME(sourceFrame + 1, src);
GETFRAME(sourceFrame, next);
if(!src) src=next;
}
data->blend(src,next);
vidCache->unlockAll();
break;
default:
ADM_assert(0);break;
}
DrawShow(data, 0, forced, dropframe, metric, inframe);
return true; // return src;
}
GETFRAME(sourceFrame, src); // MEANX : not sure (jw detected a problem here)
data->duplicate(src);
vidCache->unlockAll();
DrawShow(data, 0, forced, dropframe, metric, inframe);
return true;
}
/**
\fn goToTime
*/
bool Decimate::goToTime(uint64_t usSeek)
{
reset();
return ADM_coreVideoFilterCached::goToTime(usSeek);
}
// EOF
|
{
"language": "C++"
}
|
#ifndef __UICOMBO_H__
#define __UICOMBO_H__
#pragma once
namespace DuiLib {
/////////////////////////////////////////////////////////////////////////////////////
//
class CComboWnd;
class UILIB_API CComboUI : public CContainerUI, public IListOwnerUI
{
friend class CComboWnd;
public:
CComboUI();
LPCTSTR GetClass() const;
LPVOID GetInterface(LPCTSTR pstrName);
void DoInit();
UINT GetControlFlags() const;
CDuiString GetText() const;
void SetEnabled(bool bEnable = true);
CDuiString GetDropBoxAttributeList();
void SetDropBoxAttributeList(LPCTSTR pstrList);
SIZE GetDropBoxSize() const;
void SetDropBoxSize(SIZE szDropBox);
int GetCurSel() const;
bool SelectItem(int iIndex, bool bTakeFocus = false);
bool SetItemIndex(CControlUI* pControl, int iIndex);
bool Add(CControlUI* pControl);
bool AddAt(CControlUI* pControl, int iIndex);
bool Remove(CControlUI* pControl);
bool RemoveAt(int iIndex);
void RemoveAll();
bool Activate();
RECT GetTextPadding() const;
void SetTextPadding(RECT rc);
LPCTSTR GetNormalImage() const;
void SetNormalImage(LPCTSTR pStrImage);
LPCTSTR GetHotImage() const;
void SetHotImage(LPCTSTR pStrImage);
LPCTSTR GetPushedImage() const;
void SetPushedImage(LPCTSTR pStrImage);
LPCTSTR GetFocusedImage() const;
void SetFocusedImage(LPCTSTR pStrImage);
LPCTSTR GetDisabledImage() const;
void SetDisabledImage(LPCTSTR pStrImage);
TListInfoUI* GetListInfo();
void SetItemFont(int index);
void SetItemTextStyle(UINT uStyle);
RECT GetItemTextPadding() const;
void SetItemTextPadding(RECT rc);
DWORD GetItemTextColor() const;
void SetItemTextColor(DWORD dwTextColor);
DWORD GetItemBkColor() const;
void SetItemBkColor(DWORD dwBkColor);
LPCTSTR GetItemBkImage() const;
void SetItemBkImage(LPCTSTR pStrImage);
bool IsAlternateBk() const;
void SetAlternateBk(bool bAlternateBk);
DWORD GetSelectedItemTextColor() const;
void SetSelectedItemTextColor(DWORD dwTextColor);
DWORD GetSelectedItemBkColor() const;
void SetSelectedItemBkColor(DWORD dwBkColor);
LPCTSTR GetSelectedItemImage() const;
void SetSelectedItemImage(LPCTSTR pStrImage);
DWORD GetHotItemTextColor() const;
void SetHotItemTextColor(DWORD dwTextColor);
DWORD GetHotItemBkColor() const;
void SetHotItemBkColor(DWORD dwBkColor);
LPCTSTR GetHotItemImage() const;
void SetHotItemImage(LPCTSTR pStrImage);
DWORD GetDisabledItemTextColor() const;
void SetDisabledItemTextColor(DWORD dwTextColor);
DWORD GetDisabledItemBkColor() const;
void SetDisabledItemBkColor(DWORD dwBkColor);
LPCTSTR GetDisabledItemImage() const;
void SetDisabledItemImage(LPCTSTR pStrImage);
DWORD GetItemLineColor() const;
void SetItemLineColor(DWORD dwLineColor);
bool IsItemShowHtml();
void SetItemShowHtml(bool bShowHtml = true);
SIZE EstimateSize(SIZE szAvailable);
void SetPos(RECT rc);
void DoEvent(TEventUI& event);
void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue);
void DoPaint(HDC hDC, const RECT& rcPaint);
void PaintText(HDC hDC);
void PaintStatusImage(HDC hDC);
protected:
CComboWnd* m_pWindow;
int m_iCurSel;
RECT m_rcTextPadding;
CDuiString m_sDropBoxAttributes;
SIZE m_szDropBox;
UINT m_uButtonState;
CDuiString m_sNormalImage;
CDuiString m_sHotImage;
CDuiString m_sPushedImage;
CDuiString m_sFocusedImage;
CDuiString m_sDisabledImage;
TListInfoUI m_ListInfo;
};
} // namespace DuiLib
#endif // __UICOMBO_H__
|
{
"language": "C++"
}
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
==============================================================================*/
#if !defined(FUSION_REVERSE_VIEW_ITERATOR_07202005_0835)
#define FUSION_REVERSE_VIEW_ITERATOR_07202005_0835
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/iterator_base.hpp>
#include <boost/fusion/support/category_of.hpp>
#include <boost/fusion/iterator/mpl/convert_iterator.hpp>
#include <boost/fusion/adapted/mpl/mpl_iterator.hpp>
#include <boost/fusion/view/reverse_view/detail/deref_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/next_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/prior_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/advance_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/distance_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/value_of_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/deref_data_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/value_of_data_impl.hpp>
#include <boost/fusion/view/reverse_view/detail/key_of_impl.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/static_assert.hpp>
namespace boost { namespace fusion
{
struct reverse_view_iterator_tag;
template <typename First>
struct reverse_view_iterator
: iterator_base<reverse_view_iterator<First> >
{
typedef convert_iterator<First> converter;
typedef typename converter::type first_type;
typedef reverse_view_iterator_tag fusion_tag;
typedef typename traits::category_of<first_type>::type category;
BOOST_STATIC_ASSERT((
is_base_of<
bidirectional_traversal_tag
, category>::value));
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
reverse_view_iterator(First const& in_first)
: first(converter::call(in_first)) {}
first_type first;
private:
// silence MSVC warning C4512: assignment operator could not be generated
reverse_view_iterator& operator= (reverse_view_iterator const&);
};
}}
#ifdef BOOST_FUSION_WORKAROUND_FOR_LWG_2408
namespace std
{
template <typename First>
struct iterator_traits< ::boost::fusion::reverse_view_iterator<First> >
{ };
}
#endif
#endif
|
{
"language": "C++"
}
|
/* crypto/asn1/d2i_pu.c */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifdef __GEOS__
#include <Ansi/stdio.h>
#else
#include <stdio.h>
#endif
#include "cryptlib.h"
#include "bn.h"
#include "evp.h"
#include "objects.h"
#include "x509.h"
EVP_PKEY *d2i_PublicKey(type,a,pp,length)
int type;
EVP_PKEY **a;
unsigned char **pp;
long length;
{
EVP_PKEY *ret;
if ((a == NULL) || (*a == NULL))
{
if ((ret=EVP_PKEY_new()) == NULL)
{
ASN1err(ASN1_F_D2I_PUBLICKEY,ERR_R_EVP_LIB);
return(NULL);
}
}
else ret= *a;
ret->save_type=type;
ret->type=EVP_PKEY_type(type);
switch (ret->type)
{
#ifndef NO_RSA
case EVP_PKEY_RSA:
if ((ret->pkey.rsa=d2i_RSAPublicKey(NULL,pp,length)) == NULL)
{
ASN1err(ASN1_F_D2I_PUBLICKEY,ERR_R_ASN1_LIB);
goto err;
}
break;
#endif
#ifndef NO_DSA
case EVP_PKEY_DSA:
if ((ret->pkey.dsa=d2i_DSAPublicKey(NULL,pp,length)) == NULL)
{
ASN1err(ASN1_F_D2I_PUBLICKEY,ERR_R_ASN1_LIB);
goto err;
}
break;
#endif
default:
ASN1err(ASN1_F_D2I_PUBLICKEY,ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE);
goto err;
break;
}
if (a != NULL) (*a)=ret;
return(ret);
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret))) EVP_PKEY_free(ret);
return(NULL);
}
|
{
"language": "C++"
}
|
#ifndef BOOST_MPL_LIST_AUX_SIZE_HPP_INCLUDED
#define BOOST_MPL_LIST_AUX_SIZE_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/size_fwd.hpp>
#include <boost/mpl/list/aux_/tag.hpp>
namespace boost { namespace mpl {
template<>
struct size_impl< aux::list_tag >
{
template< typename List > struct apply
: List::size
{
};
};
}}
#endif // BOOST_MPL_LIST_AUX_SIZE_HPP_INCLUDED
|
{
"language": "C++"
}
|
#pragma once
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Empty.h>
#include <geometry_msgs/Twist.h>
#include "dronet_perception/CNN_out.h"
namespace deep_navigation
{
class deepNavigation final
{
public:
deepNavigation(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private);
deepNavigation() : deepNavigation(ros::NodeHandle(), ros::NodeHandle("~") ) {}
void run();
private:
// ROS
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
ros::Subscriber deep_network_sub_;
ros::Subscriber state_change_sub_;
ros::Publisher desired_velocity_pub_;
// Callback for networks outputs
void deepNetworkCallback(const dronet_perception::CNN_out::ConstPtr& msg);
void stateChangeCallback(const std_msgs::Bool& msg);
double probability_of_collision_;
double steering_angle_;
bool use_network_out_; // If True, it will use the network out, else will use zero
// Parameters
void loadParameters();
double alpha_velocity_, alpha_yaw_; // Smoothers for CNN outs
double critical_prob_coll_;
double max_forward_index_;
std::string name_;
// Internal variables
double desired_forward_velocity_;
double desired_angular_velocity_;
geometry_msgs::Twist cmd_velocity_;
};
class HeightChange{
public:
HeightChange(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private);
HeightChange() : HeightChange(ros::NodeHandle(), ros::NodeHandle("~") ) {}
virtual ~HeightChange();
void run();
private:
// ROS
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
ros::Subscriber is_up_sub_;
ros::Subscriber move_sub_;
ros::Subscriber alt_c_sub_;
ros::Publisher desired_velocity_pub_;
// Callback for networks outputs
void is_up(const std_msgs::Empty& msg);
void move(const std_msgs::Empty& msg);
void change_altitude(const std_msgs::Empty& msg);
std::string name_;
bool is_up_;
bool change_altitude_, should_move_;
};
}
|
{
"language": "C++"
}
|
/* Copyright 2017 The TensorFlow 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 <memory>
#include <string>
#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/ops_testutil.h"
namespace tensorflow {
namespace {
class SerializeTensorOpTest : public OpsTestBase {
protected:
template <typename T>
void MakeOp(const TensorShape& input_shape, std::function<T(int)> functor) {
TF_ASSERT_OK(NodeDefBuilder("myop", "SerializeTensor")
.Input(FakeInput(DataTypeToEnum<T>::value))
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
AddInput<T>(input_shape, functor);
}
void ParseSerializedWithNodeDef(const NodeDef& parse_node_def,
Tensor* serialized, Tensor* parse_output) {
std::unique_ptr<Device> device(
DeviceFactory::NewDevice("CPU", {}, "/job:a/replica:0/task:0"));
gtl::InlinedVector<TensorValue, 4> inputs;
inputs.push_back({nullptr, serialized});
Status status;
std::unique_ptr<OpKernel> op(CreateOpKernel(DEVICE_CPU, device.get(),
cpu_allocator(), parse_node_def,
TF_GRAPH_DEF_VERSION, &status));
TF_EXPECT_OK(status);
OpKernelContext::Params params;
params.device = device.get();
params.inputs = &inputs;
params.frame_iter = FrameAndIter(0, 0);
params.op_kernel = op.get();
std::vector<AllocatorAttributes> attrs;
test::SetOutputAttrs(¶ms, &attrs);
OpKernelContext ctx(¶ms);
op->Compute(&ctx);
TF_EXPECT_OK(status);
*parse_output = *ctx.mutable_output(0);
}
template <typename T>
void ParseSerializedOutput(Tensor* serialized, Tensor* parse_output) {
NodeDef parse;
TF_ASSERT_OK(NodeDefBuilder("parse", "ParseTensor")
.Input(FakeInput(DT_STRING))
.Attr("out_type", DataTypeToEnum<T>::value)
.Finalize(&parse));
ParseSerializedWithNodeDef(parse, serialized, parse_output);
}
};
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_half) {
MakeOp<Eigen::half>(TensorShape({10}), [](int x) -> Eigen::half {
return static_cast<Eigen::half>(x / 10.);
});
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<Eigen::half>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<Eigen::half>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_float) {
MakeOp<float>(TensorShape({1, 10}),
[](int x) -> float { return static_cast<float>(x / 10.); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<float>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<float>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_double) {
MakeOp<double>(TensorShape({5, 5}),
[](int x) -> double { return static_cast<double>(x / 10.); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<double>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<double>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_int64) {
MakeOp<int64>(TensorShape({2, 3, 4}),
[](int x) -> int64 { return static_cast<int64>(x - 10); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<int64>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<int64>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_int32) {
MakeOp<int32>(TensorShape({4, 2}),
[](int x) -> int32 { return static_cast<int32>(x + 7); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<int32>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<int32>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_int16) {
MakeOp<int16>(TensorShape({8}),
[](int x) -> int16 { return static_cast<int16>(x + 18); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<int16>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<int16>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_int8) {
MakeOp<int8>(TensorShape({2}),
[](int x) -> int8 { return static_cast<int8>(x + 8); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<int8>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<int8>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_uint16) {
MakeOp<uint16>(TensorShape({1, 3}),
[](int x) -> uint16 { return static_cast<uint16>(x + 2); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<uint16>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<uint16>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_uint8) {
MakeOp<uint8>(TensorShape({2, 1, 1}),
[](int x) -> uint8 { return static_cast<uint8>(x + 1); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<uint8>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<uint8>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_complex64) {
MakeOp<complex64>(TensorShape({}), [](int x) -> complex64 {
return complex64{static_cast<float>(x / 8.), static_cast<float>(x / 2.)};
});
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<complex64>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<complex64>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_complex128) {
MakeOp<complex128>(TensorShape({3}), [](int x) -> complex128 {
return complex128{x / 3., x / 2.};
});
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<complex128>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<complex128>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_bool) {
MakeOp<bool>(TensorShape({1}),
[](int x) -> bool { return static_cast<bool>(x % 2); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<bool>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<bool>(parse_output, GetInput(0));
}
TEST_F(SerializeTensorOpTest, SerializeTensorOpTest_string) {
MakeOp<string>(TensorShape({10}),
[](int x) -> string { return std::to_string(x / 10.); });
TF_ASSERT_OK(RunOpKernel());
Tensor parse_output;
ParseSerializedOutput<string>(GetOutput(0), &parse_output);
test::ExpectTensorEqual<string>(parse_output, GetInput(0));
}
} // namespace
} // namespace tensorflow
|
{
"language": "C++"
}
|
/*
Copyright (c) 2010, The Barbarian Group
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "cinder/Cinder.h"
// This path is not used on 64-bit Mac or Windows. On the Mac we only use this path for <=Mac OS 10.7
#if ( defined( CINDER_MAC ) && ( ! defined( __LP64__ ) ) && ( MAC_OS_X_VERSION_MIN_REQUIRED < 1080 ) ) || ( defined( CINDER_MSW ) && ( ! defined( _WIN64 ) ) )
#include "cinder/ImageIo.h"
#include "cinder/Stream.h"
#include "cinder/qtime/QuickTime.h"
#include <string>
// These forward declarations prevent us from having to bring all of QuickTime into the global namespace in MSW
//! \cond
#if defined( CINDER_MSW )
typedef struct ComponentInstanceRecord ComponentInstanceRecord;
typedef ComponentInstanceRecord * ComponentInstance;
typedef ComponentInstance DataHandler;
typedef struct TrackType** Track;
typedef struct MediaType** Media;
typedef struct OpaqueICMCompressionSession* ICMCompressionSessionRef;
typedef struct OpaqueICMCompressionSessionOptions* ICMCompressionSessionOptionsRef;
typedef const struct OpaqueICMEncodedFrame* ICMEncodedFrameRef;
typedef signed long OSStatus;
typedef unsigned long CodecType;
typedef unsigned long ICMCompressionPassModeFlags;
#else
#include <QuickTime/QuickTime.h>
#include <QuickTime/ImageCompression.h>
#endif // defined( CINDER_MSW )
//! \endcond
namespace cinder { namespace qtime {
class MovieWriter;
typedef std::shared_ptr<MovieWriter> MovieWriterRef;
class MovieWriter {
struct Obj;
public:
//! Defines the encoding parameters of a MovieWriter
class Format {
public:
Format();
Format( uint32_t codec, float quality );
Format( const ICMCompressionSessionOptionsRef settings, uint32_t codec, float quality, float frameRate, bool enableMultiPass );
Format( const Format &format );
~Format();
const Format& operator=( const Format &format );
//! Returns the four character code for the QuickTime codec. Types can be found in QuickTime's ImageCompression.h.
uint32_t getCodec() const { return mCodec; }
//! Sets the four character code for the QuickTime codec. Defaults to \c PNG (\c 'png '). Additional types can be found in QuickTime's \c ImageCompression.h.
Format& setCodec( uint32_t codec ) { mCodec = codec; return *this; }
//! Returns the overall quality for encoding in the range of [\c 0,\c 1.0]. Defaults to \c 0.99. \c 1.0 corresponds to lossless.
float getQuality() const { return mQualityFloat; }
//! Sets the overall quality for encoding. Must be in a range of [\c 0,\c 1.0]. Defaults to \c 0.99. \c 1.0 corresponds to lossless.
Format& setQuality( float quality );
//! Returns the standard duration of a frame measured in seconds
float getDefaultDuration() const { return mDefaultTime; }
//! Sets the default duration of a frame, measured in seconds. Defaults to \c 1/30 sec, meaning \c 30 FPS.
Format& setDefaultDuration( float defaultDuration ) { mDefaultTime = defaultDuration; return *this; }
//! Returns the integer base value for the encoding time scale. Defaults to \c 600
long getTimeScale() const { return mTimeBase; }
//! Sets the integer base value for encoding time scale. Defaults to \c 600.
Format& setTimeScale( long timeScale ) { mTimeBase = timeScale; return *this; }
//! Returns the gamma value by which image data is encoded.
float getGamma() const { return mGamma; }
//! Sets the gamma value by which image data is encoded. Defaults to \c 2.5 on MSW and \c 2.2 on Mac OS X.
Format& setGamma( float gamma ) { mGamma = gamma; return *this; }
//! Returns if temporal compression (allowing \b P or \b B frames) is enabled. Defaults to \c true.
bool isTemporal() const;
//! Enables temporal compression (allowing \b P or \b B frames). Defaults to \c true.
Format& enableTemporal( bool enable = true );
//! Returns if frame reordering is enabled. Defaults to \c true. In order to encode \b B frames, a compressor must reorder frames, which means that the order in which they will be emitted and stored (the decode order) is different from the order in which they were presented to the compressor (the display order).
bool isReordering() const;
//! Enables frame reordering. Defaults to \c true. In order to encode \b B frames, a compressor must reorder frames, which means that the order in which they will be emitted and stored (the decode order) is different from the order in which they were presented to the compressor (the display order).
Format& enableReordering( bool enable = true );
//! Gets the maximum number of frames between key frames. Default is \c 0, which indicates that the compressor should choose where to place all key frames. Compressors are allowed to generate key frames more frequently if this would result in more efficient compression.
int32_t getMaxKeyFrameRate() const;
//! Sets the maximum number of frames between key frames. Default is \c 0, which indicates that the compressor should choose where to place all key frames. Compressors are allowed to generate key frames more frequently if this would result in more efficient compression.
Format& setMaxKeyFrameRate( int32_t rate );
//! Returns whether a codec is allowed to change frame times. Defaults to \c true. Some compressors are able to identify and coalesce runs of identical frames and output single frames with longer duration, or output frames at a different frame rate from the original.
bool isFrameTimeChanges() const;
//! Sets whether a codec is allowed to change frame times. Defaults to \c true. Some compressors are able to identify and coalesce runs of identical frames and output single frames with longer duration, or output frames at a different frame rate from the original.
Format& enableFrameTimeChanges( bool enable = true );
//! Returns whether multiPass encoding is enabled. Defaults to \c false.
bool isMultiPass() const { return mEnableMultiPass; }
//! Enables multiPass encoding. Defaults to \c false. While multiPass encoding can result in significantly smaller movies, it often takes much longer to compress and requires the creation of two temporary files for storing intermediate results.
Format& enableMultiPass( bool enable = true ) { mEnableMultiPass = enable; return *this; }
private:
void initDefaults();
uint32_t mCodec;
long mTimeBase;
float mDefaultTime;
float mQualityFloat;
float mGamma;
bool mEnableMultiPass;
ICMCompressionSessionOptionsRef mOptions;
friend class MovieWriter;
friend struct Obj;
};
MovieWriter() {}
MovieWriter( const fs::path &path, int32_t width, int32_t height, const Format &format = Format::Format() );
static MovieWriterRef create( const fs::path &path, int32_t width, int32_t height, const Format &format = Format::Format() )
{ return std::shared_ptr<MovieWriter>( new MovieWriter( path, width, height, format ) ); }
//! Returns the Movie's default frame duration measured in seconds. You can also think of this as the Movie's frameRate.
float getDefaultDuration() const { return mObj->mFormat.mDefaultTime; }
//! Returns the width of the Movie in pixels
int32_t getWidth() const { return mObj->mWidth; }
//! Returns the height of the Movie in pixels
int32_t getHeight() const { return mObj->mHeight; }
//! Returns the size of the Movie in pixels
ivec2 getSize() const { return ivec2( getWidth(), getHeight() ); }
//! Returns the Movie's aspect ratio, which is its width / height
float getAspectRatio() const { return getWidth() / (float)getHeight(); }
//! Returns the bounding Area of the Movie in pixels: [0,0]-(width,height)
Area getBounds() const { return Area( 0, 0, getWidth(), getHeight() ); }
//! Returns the Movie's Format
const Format& getFormat() const { return mObj->mFormat; }
/** \brief Presents the user with the standard compression options dialog. Optional \a previewImage provides a still image as a preview (currently ignored on Mac OS X). Returns \c false if user cancelled.
\image html qtime/MovieWriter/qtime_settings_small.png **/
static bool getUserCompressionSettings( Format *result, ImageSourceRef previewImage = ImageSourceRef() );
/** \brief Appends a frame to the Movie. The optional \a duration parameter allows a frame to be inserted for a time other than the Format's default duration.
\note Calling addFrame() after a call to finish() will throw a MovieWriterExcAlreadyFinished exception. **/
void addFrame( const ImageSourceRef &imageSource, float duration = -1.0f ) { mObj->addFrame( imageSource, duration ); }
//! Returns the number of frames in the movie
uint32_t getNumFrames() const { return mObj->mNumFrames; }
//! Completes the encoding of the movie and closes the file. Calling finish() more than once has no effect.
void finish() { mObj->finish(); }
enum { CODEC_H264 = 'avc1', CODEC_JPEG = 'jpeg', CODEC_MP4 = 'mp4v', CODEC_PNG = 'png ', CODEC_RAW = 'raw ', CODEC_ANIMATION = 'rle ' };
private:
/// \cond
struct Obj {
Obj( const fs::path &path, int32_t width, int32_t height, const Format &format );
~Obj();
void addFrame( const ImageSourceRef &imageSource, float duration );
void createCompressionSession();
void finish();
static OSStatus encodedFrameOutputCallback( void *refCon, ::ICMCompressionSessionRef session, OSStatus err, ICMEncodedFrameRef encodedFrame, void *reserved );
::Movie mMovie;
::DataHandler mDataHandler;
::Track mTrack;
::Media mMedia;
::ICMCompressionSessionRef mCompressionSession;
::ICMCompressionPassModeFlags mMultiPassModeFlags;
fs::path mPath;
uint32_t mNumFrames;
int64_t mCurrentTimeValue;
int32_t mWidth, mHeight;
Format mFormat;
bool mRequestedMultiPass, mDoingMultiPass, mFinished;
IoStreamRef mMultiPassFrameCache;
std::vector<std::pair<int64_t,int64_t> > mFrameTimes;
};
/// \endcond
std::shared_ptr<Obj> mObj;
public:
//@{
//! Emulates shared_ptr-like behavior
typedef std::shared_ptr<Obj> MovieWriter::*unspecified_bool_type;
operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &MovieWriter::mObj; }
void reset() { mObj.reset(); }
//@}
};
class MovieWriterExc : public Exception {
};
class MovieWriterExcInvalidPath : public MovieWriterExc {
};
class MovieWriterExcFrameEncode : public MovieWriterExc {
};
class MovieWriterExcAlreadyFinished : public MovieWriterExc {
};
} } // namespace cinder::qtime
#endif // end of 64-bit / 10.8+ test
|
{
"language": "C++"
}
|
/*
* ProxyCommitData.h
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2020 Apple Inc. and the FoundationDB project 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.
*/
#pragma once
#if defined(NO_INTELLISENSE) && !defined(FDBSERVER_PROXYCOMMITDATA_ACTOR_G_H)
#define FDBSERVER_PROXYCOMMITDATA_ACTOR_G_H
#include "fdbserver/ProxyCommitData.actor.g.h"
#elif !defined(FDBSERVER_PROXYCOMMITDATA_ACTOR_H)
#define FDBSERVER_PROXYCOMMITDATA_ACTOR_H
#include "fdbclient/FDBTypes.h"
#include "fdbrpc/Stats.h"
#include "fdbserver/Knobs.h"
#include "fdbserver/LogSystemDiskQueueAdapter.h"
#include "flow/IRandom.h"
#include "flow/actorcompiler.h" // This must be the last #include.
DESCR struct SingleKeyMutation {
Standalone<StringRef> shardBegin;
Standalone<StringRef> shardEnd;
int64_t tag1;
int64_t tag2;
int64_t tag3;
};
struct ApplyMutationsData {
Future<Void> worker;
Version endVersion;
Reference<KeyRangeMap<Version>> keyVersion;
};
struct ProxyStats {
CounterCollection cc;
Counter txnCommitIn, txnCommitVersionAssigned, txnCommitResolving, txnCommitResolved, txnCommitOut,
txnCommitOutSuccess, txnCommitErrors;
Counter txnConflicts;
Counter commitBatchIn, commitBatchOut;
Counter mutationBytes;
Counter mutations;
Counter conflictRanges;
Counter keyServerLocationIn, keyServerLocationOut, keyServerLocationErrors;
Counter txnExpensiveClearCostEstCount;
Version lastCommitVersionAssigned;
LatencySample commitLatencySample;
LatencyBands commitLatencyBands;
Future<Void> logger;
explicit ProxyStats(UID id, Version* pVersion, NotifiedVersion* pCommittedVersion,
int64_t* commitBatchesMemBytesCountPtr)
: cc("ProxyStats", id.toString()),
txnCommitIn("TxnCommitIn", cc), txnCommitVersionAssigned("TxnCommitVersionAssigned", cc),
txnCommitResolving("TxnCommitResolving", cc), txnCommitResolved("TxnCommitResolved", cc),
txnCommitOut("TxnCommitOut", cc), txnCommitOutSuccess("TxnCommitOutSuccess", cc),
txnCommitErrors("TxnCommitErrors", cc), txnConflicts("TxnConflicts", cc), commitBatchIn("CommitBatchIn", cc),
commitBatchOut("CommitBatchOut", cc), mutationBytes("MutationBytes", cc), mutations("Mutations", cc),
conflictRanges("ConflictRanges", cc), keyServerLocationIn("KeyServerLocationIn", cc),
keyServerLocationOut("KeyServerLocationOut", cc), keyServerLocationErrors("KeyServerLocationErrors", cc),
lastCommitVersionAssigned(0), txnExpensiveClearCostEstCount("ExpensiveClearCostEstCount", cc),
commitLatencySample("CommitLatencyMetrics", id, SERVER_KNOBS->LATENCY_METRICS_LOGGING_INTERVAL,
SERVER_KNOBS->LATENCY_SAMPLE_SIZE),
commitLatencyBands("CommitLatencyMetrics", id, SERVER_KNOBS->STORAGE_LOGGING_DELAY) {
specialCounter(cc, "LastAssignedCommitVersion", [this]() { return this->lastCommitVersionAssigned; });
specialCounter(cc, "Version", [pVersion]() { return *pVersion; });
specialCounter(cc, "CommittedVersion", [pCommittedVersion]() { return pCommittedVersion->get(); });
specialCounter(cc, "CommitBatchesMemBytesCount",
[commitBatchesMemBytesCountPtr]() { return *commitBatchesMemBytesCountPtr; });
logger = traceCounters("ProxyMetrics", id, SERVER_KNOBS->WORKER_LOGGING_INTERVAL, &cc, "ProxyMetrics");
}
};
struct ProxyCommitData {
UID dbgid;
int64_t commitBatchesMemBytesCount;
ProxyStats stats;
MasterInterface master;
vector<ResolverInterface> resolvers;
LogSystemDiskQueueAdapter* logAdapter;
Reference<ILogSystem> logSystem;
IKeyValueStore* txnStateStore;
NotifiedVersion committedVersion; // Provided that this recovery has succeeded or will succeed, this version is
// fully committed (durable)
Version minKnownCommittedVersion; // No version smaller than this one will be used as the known committed version
// during recovery
Version version; // The version at which txnStateStore is up to date
Promise<Void> validState; // Set once txnStateStore and version are valid
double lastVersionTime;
KeyRangeMap<std::set<Key>> vecBackupKeys;
uint64_t commitVersionRequestNumber;
uint64_t mostRecentProcessedRequestNumber;
KeyRangeMap<Deque<std::pair<Version, int>>> keyResolvers;
KeyRangeMap<ServerCacheInfo> keyInfo;
KeyRangeMap<bool> cacheInfo;
std::map<Key, ApplyMutationsData> uid_applyMutationsData;
bool firstProxy;
double lastCoalesceTime;
bool locked;
Optional<Value> metadataVersion;
double commitBatchInterval;
int64_t localCommitBatchesStarted;
NotifiedVersion latestLocalCommitBatchResolving;
NotifiedVersion latestLocalCommitBatchLogging;
RequestStream<GetReadVersionRequest> getConsistentReadVersion;
RequestStream<CommitTransactionRequest> commit;
Database cx;
Reference<AsyncVar<ServerDBInfo>> db;
EventMetricHandle<SingleKeyMutation> singleKeyMutationEvent;
std::map<UID, Reference<StorageInfo>> storageCache;
std::map<Tag, Version> tag_popped;
Deque<std::pair<Version, Version>> txsPopVersions;
Version lastTxsPop;
bool popRemoteTxs;
vector<Standalone<StringRef>> whitelistedBinPathVec;
Optional<LatencyBandConfig> latencyBandConfig;
double lastStartCommit;
double lastCommitLatency;
int updateCommitRequests = 0;
NotifiedDouble lastCommitTime;
vector<double> commitComputePerOperation;
UIDTransactionTagMap<TransactionCommitCostEstimation> ssTrTagCommitCost;
// The tag related to a storage server rarely change, so we keep a vector of tags for each key range to be slightly
// more CPU efficient. When a tag related to a storage server does change, we empty out all of these vectors to
// signify they must be repopulated. We do not repopulate them immediately to avoid a slow task.
const vector<Tag>& tagsForKey(StringRef key) {
auto& tags = keyInfo[key].tags;
if (!tags.size()) {
auto& r = keyInfo.rangeContaining(key).value();
r.populateTags();
return r.tags;
}
return tags;
}
bool needsCacheTag(KeyRangeRef range) {
auto ranges = cacheInfo.intersectingRanges(range);
for (auto r : ranges) {
if (r.value()) {
return true;
}
}
return false;
}
void updateLatencyBandConfig(Optional<LatencyBandConfig> newLatencyBandConfig) {
if (newLatencyBandConfig.present() != latencyBandConfig.present() ||
(newLatencyBandConfig.present() &&
newLatencyBandConfig.get().commitConfig != latencyBandConfig.get().commitConfig)) {
TraceEvent("LatencyBandCommitUpdatingConfig").detail("Present", newLatencyBandConfig.present());
stats.commitLatencyBands.clearBands();
if (newLatencyBandConfig.present()) {
for (auto band : newLatencyBandConfig.get().commitConfig.bands) {
stats.commitLatencyBands.addThreshold(band);
}
}
}
latencyBandConfig = newLatencyBandConfig;
}
void updateSSTagCost(const UID& id, const TagSet& tagSet, MutationRef m, int cost) {
auto [it, _] = ssTrTagCommitCost.try_emplace(id, TransactionTagMap<TransactionCommitCostEstimation>());
for (auto& tag : tagSet) {
auto& costItem = it->second[tag];
if (m.isAtomicOp() || m.type == MutationRef::Type::SetValue || m.type == MutationRef::Type::ClearRange) {
costItem.opsSum++;
costItem.costSum += cost;
}
}
}
ProxyCommitData(UID dbgid, MasterInterface master, RequestStream<GetReadVersionRequest> getConsistentReadVersion,
Version recoveryTransactionVersion, RequestStream<CommitTransactionRequest> commit,
Reference<AsyncVar<ServerDBInfo>> db, bool firstProxy)
: dbgid(dbgid), stats(dbgid, &version, &committedVersion, &commitBatchesMemBytesCount), master(master),
logAdapter(nullptr), txnStateStore(nullptr), popRemoteTxs(false), committedVersion(recoveryTransactionVersion),
version(0), minKnownCommittedVersion(0), lastVersionTime(0), commitVersionRequestNumber(1),
mostRecentProcessedRequestNumber(0), getConsistentReadVersion(getConsistentReadVersion), commit(commit),
lastCoalesceTime(0), localCommitBatchesStarted(0), locked(false),
commitBatchInterval(SERVER_KNOBS->COMMIT_TRANSACTION_BATCH_INTERVAL_MIN), firstProxy(firstProxy),
cx(openDBOnServer(db, TaskPriority::DefaultEndpoint, true, true)), db(db),
singleKeyMutationEvent(LiteralStringRef("SingleKeyMutation")), commitBatchesMemBytesCount(0), lastTxsPop(0),
lastStartCommit(0), lastCommitLatency(SERVER_KNOBS->REQUIRED_MIN_RECOVERY_DURATION), lastCommitTime(0) {
commitComputePerOperation.resize(SERVER_KNOBS->PROXY_COMPUTE_BUCKETS, 0.0);
}
};
#include "flow/unactorcompiler.h"
#endif // FDBSERVER_PROXYCOMMITDATA_H
|
{
"language": "C++"
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/elasticfilesystem/EFS_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace EFS
{
namespace Model
{
/**
* <p>Returned if the mount target is not in the correct state for the
* operation.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/IncorrectMountTargetState">AWS
* API Reference</a></p>
*/
class AWS_EFS_API IncorrectMountTargetState
{
public:
IncorrectMountTargetState();
IncorrectMountTargetState(Aws::Utils::Json::JsonView jsonValue);
IncorrectMountTargetState& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
inline const Aws::String& GetErrorCode() const{ return m_errorCode; }
inline bool ErrorCodeHasBeenSet() const { return m_errorCodeHasBeenSet; }
inline void SetErrorCode(const Aws::String& value) { m_errorCodeHasBeenSet = true; m_errorCode = value; }
inline void SetErrorCode(Aws::String&& value) { m_errorCodeHasBeenSet = true; m_errorCode = std::move(value); }
inline void SetErrorCode(const char* value) { m_errorCodeHasBeenSet = true; m_errorCode.assign(value); }
inline IncorrectMountTargetState& WithErrorCode(const Aws::String& value) { SetErrorCode(value); return *this;}
inline IncorrectMountTargetState& WithErrorCode(Aws::String&& value) { SetErrorCode(std::move(value)); return *this;}
inline IncorrectMountTargetState& WithErrorCode(const char* value) { SetErrorCode(value); return *this;}
inline const Aws::String& GetMessage() const{ return m_message; }
inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }
inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }
inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }
inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }
inline IncorrectMountTargetState& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}
inline IncorrectMountTargetState& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}
inline IncorrectMountTargetState& WithMessage(const char* value) { SetMessage(value); return *this;}
private:
Aws::String m_errorCode;
bool m_errorCodeHasBeenSet;
Aws::String m_message;
bool m_messageHasBeenSet;
};
} // namespace Model
} // namespace EFS
} // namespace Aws
|
{
"language": "C++"
}
|
// RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wno-unused-value %s -verify
// prvalue
void prvalue() {
auto&& x = []()->void { };
auto& y = []()->void { }; // expected-error{{cannot bind to a temporary of type}}
}
namespace std {
class type_info;
}
struct P {
virtual ~P();
};
void unevaluated_operand(P &p, int i) {
int i2 = sizeof([] ()->int { return 0; }()); // expected-error{{lambda expression in an unevaluated operand}}
const std::type_info &ti1 = typeid([&]() -> P& { return p; }());
const std::type_info &ti2 = typeid([&]() -> int { return i; }()); // expected-error{{lambda expression in an unevaluated operand}}
}
template<typename T>
struct Boom {
Boom(const Boom&) {
T* x = 1; // expected-error{{cannot initialize a variable of type 'int *' with an rvalue of type 'int'}} \
// expected-error{{cannot initialize a variable of type 'double *' with an rvalue of type 'int'}}
}
void tickle() const;
};
void odr_used(P &p, Boom<int> boom_int, Boom<float> boom_float,
Boom<double> boom_double) {
const std::type_info &ti1
= typeid([=,&p]() -> P& { boom_int.tickle(); return p; }()); // expected-note{{in instantiation of member function 'Boom<int>::Boom' requested here}}
// This does not cause the instantiation of the Boom copy constructor,
// because the copy-initialization of the capture of boom_float occurs in an
// unevaluated operand.
const std::type_info &ti2
= typeid([=]() -> int { boom_float.tickle(); return 0; }()); // expected-error{{lambda expression in an unevaluated operand}}
auto foo = [=]() -> int { boom_double.tickle(); return 0; }; // expected-note{{in instantiation of member function 'Boom<double>::Boom' requested here}}
}
|
{
"language": "C++"
}
|
.class final Landroid/view/ViewRoot$TrackballAxis;
.super Ljava/lang/Object;
.source "ViewRoot.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/view/ViewRoot;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x18
name = "TrackballAxis"
.end annotation
# static fields
.field static final ACCEL_MOVE_SCALING_FACTOR:F = 0.025f
.field static final FAST_MOVE_TIME:J = 0x96L
.field static final MAX_ACCELERATION:F = 20.0f
# instance fields
.field absPosition:F
.field acceleration:F
.field dir:I
.field lastMoveTime:J
.field nonAccelMovement:I
.field position:F
.field step:I
# direct methods
.method constructor <init>()V
.locals 2
.prologue
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
const/high16 v0, 0x3f80
iput v0, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
const-wide/16 v0, 0x0
iput-wide v0, p0, Landroid/view/ViewRoot$TrackballAxis;->lastMoveTime:J
return-void
.end method
# virtual methods
.method collect(FJLjava/lang/String;)F
.locals 8
.parameter "off"
.parameter "time"
.parameter "axis"
.prologue
const/4 v6, 0x0
cmpl-float v6, p1, v6
if-lez v6, :cond_3
const/high16 v6, 0x4316
mul-float/2addr v6, p1
float-to-long v3, v6
.local v3, normTime:J
iget v6, p0, Landroid/view/ViewRoot$TrackballAxis;->dir:I
if-gez v6, :cond_0
const/4 v6, 0x0
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
const/4 v6, 0x0
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->step:I
const/high16 v6, 0x3f80
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
const-wide/16 v6, 0x0
iput-wide v6, p0, Landroid/view/ViewRoot$TrackballAxis;->lastMoveTime:J
:cond_0
const/4 v6, 0x1
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->dir:I
:goto_0
const-wide/16 v6, 0x0
cmp-long v6, v3, v6
if-lez v6, :cond_2
iget-wide v6, p0, Landroid/view/ViewRoot$TrackballAxis;->lastMoveTime:J
sub-long v1, p2, v6
.local v1, delta:J
iput-wide p2, p0, Landroid/view/ViewRoot$TrackballAxis;->lastMoveTime:J
iget v0, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
.local v0, acc:F
cmp-long v6, v1, v3
if-gez v6, :cond_7
sub-long v6, v3, v1
long-to-float v6, v6
const v7, 0x3ccccccd
mul-float v5, v6, v7
.local v5, scale:F
const/high16 v6, 0x3f80
cmpl-float v6, v5, v6
if-lez v6, :cond_1
mul-float/2addr v0, v5
:cond_1
const/high16 v6, 0x41a0
cmpg-float v6, v0, v6
if-gez v6, :cond_6
move v6, v0
:goto_1
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
.end local v0 #acc:F
.end local v1 #delta:J
.end local v5 #scale:F
:cond_2
:goto_2
iget v6, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
add-float/2addr v6, p1
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
iget v6, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
invoke-static {v6}, Ljava/lang/Math;->abs(F)F
move-result v6
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->absPosition:F
return v6
.end local v3 #normTime:J
:cond_3
const/4 v6, 0x0
cmpg-float v6, p1, v6
if-gez v6, :cond_5
neg-float v6, p1
const/high16 v7, 0x4316
mul-float/2addr v6, v7
float-to-long v3, v6
.restart local v3 #normTime:J
iget v6, p0, Landroid/view/ViewRoot$TrackballAxis;->dir:I
if-lez v6, :cond_4
const/4 v6, 0x0
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
const/4 v6, 0x0
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->step:I
const/high16 v6, 0x3f80
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
const-wide/16 v6, 0x0
iput-wide v6, p0, Landroid/view/ViewRoot$TrackballAxis;->lastMoveTime:J
:cond_4
const/4 v6, -0x1
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->dir:I
goto :goto_0
.end local v3 #normTime:J
:cond_5
const-wide/16 v3, 0x0
.restart local v3 #normTime:J
goto :goto_0
.restart local v0 #acc:F
.restart local v1 #delta:J
.restart local v5 #scale:F
:cond_6
const/high16 v6, 0x41a0
goto :goto_1
.end local v5 #scale:F
:cond_7
sub-long v6, v1, v3
long-to-float v6, v6
const v7, 0x3ccccccd
mul-float v5, v6, v7
.restart local v5 #scale:F
const/high16 v6, 0x3f80
cmpl-float v6, v5, v6
if-lez v6, :cond_8
div-float/2addr v0, v5
:cond_8
const/high16 v6, 0x3f80
cmpl-float v6, v0, v6
if-lez v6, :cond_9
move v6, v0
:goto_3
iput v6, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
goto :goto_2
:cond_9
const/high16 v6, 0x3f80
goto :goto_3
.end method
.method generate(F)I
.locals 8
.parameter "precision"
.prologue
const/4 v7, 0x1
const/high16 v6, 0x4000
const/high16 v5, 0x3f80
const/4 v2, 0x0
.local v2, movement:I
const/4 v3, 0x0
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->nonAccelMovement:I
:goto_0
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
const/4 v4, 0x0
cmpl-float v3, v3, v4
if-ltz v3, :cond_1
move v1, v7
.local v1, dir:I
:goto_1
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->step:I
packed-switch v3, :pswitch_data_0
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->absPosition:F
cmpg-float v3, v3, v5
if-gez v3, :cond_3
:cond_0
return v2
.end local v1 #dir:I
:cond_1
const/4 v3, -0x1
move v1, v3
goto :goto_1
.restart local v1 #dir:I
:pswitch_0
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->absPosition:F
cmpg-float v3, v3, p1
if-ltz v3, :cond_0
add-int/2addr v2, v1
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->nonAccelMovement:I
add-int/2addr v3, v1
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->nonAccelMovement:I
iput v7, p0, Landroid/view/ViewRoot$TrackballAxis;->step:I
goto :goto_0
:pswitch_1
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->absPosition:F
cmpg-float v3, v3, v6
if-ltz v3, :cond_0
add-int/2addr v2, v1
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->nonAccelMovement:I
add-int/2addr v3, v1
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->nonAccelMovement:I
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
if-lez v1, :cond_2
const/high16 v4, -0x4000
:goto_2
add-float/2addr v3, v4
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
invoke-static {v3}, Ljava/lang/Math;->abs(F)F
move-result v3
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->absPosition:F
const/4 v3, 0x2
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->step:I
goto :goto_0
:cond_2
move v4, v6
goto :goto_2
:cond_3
add-int/2addr v2, v1
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
if-ltz v1, :cond_4
const/high16 v4, -0x4080
:goto_3
add-float/2addr v3, v4
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
invoke-static {v3}, Ljava/lang/Math;->abs(F)F
move-result v3
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->absPosition:F
iget v0, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
.local v0, acc:F
const v3, 0x3f8ccccd
mul-float/2addr v0, v3
const/high16 v3, 0x41a0
cmpg-float v3, v0, v3
if-gez v3, :cond_5
move v3, v0
:goto_4
iput v3, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
goto :goto_0
.end local v0 #acc:F
:cond_4
move v4, v5
goto :goto_3
.restart local v0 #acc:F
:cond_5
iget v3, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
goto :goto_4
nop
:pswitch_data_0
.packed-switch 0x0
:pswitch_0
:pswitch_1
.end packed-switch
.end method
.method reset(I)V
.locals 2
.parameter "_step"
.prologue
const/4 v0, 0x0
iput v0, p0, Landroid/view/ViewRoot$TrackballAxis;->position:F
const/high16 v0, 0x3f80
iput v0, p0, Landroid/view/ViewRoot$TrackballAxis;->acceleration:F
const-wide/16 v0, 0x0
iput-wide v0, p0, Landroid/view/ViewRoot$TrackballAxis;->lastMoveTime:J
iput p1, p0, Landroid/view/ViewRoot$TrackballAxis;->step:I
const/4 v0, 0x0
iput v0, p0, Landroid/view/ViewRoot$TrackballAxis;->dir:I
return-void
.end method
|
{
"language": "C++"
}
|
/*
Pencil - Traditional Animation Software
Copyright (C) 2005-2007 Patrick Corrieri & Pascal Naidon
Copyright (C) 2012-2020 Matthew Chiawen Chang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "exportimagedialog.h"
#include "ui_exportimageoptions.h"
#include "util.h"
ExportImageDialog::ExportImageDialog(QWidget* parent, FileType eFileType) :
ImportExportDialog(parent, ImportExportDialog::Export, eFileType),
ui(new Ui::ExportImageOptions)
{
ui->setupUi(getOptionsGroupBox());
if (eFileType == FileType::IMAGE_SEQUENCE)
{
setWindowTitle(tr("Export image sequence"));
}
else
{
setWindowTitle(tr("Export image"));
ui->frameRangeGroupBox->hide();
}
connect(ui->formatComboBox, &QComboBox::currentTextChanged, this, &ExportImageDialog::formatChanged);
formatChanged(getExportFormat()); // Make sure file extension matches format combobox
}
ExportImageDialog::~ExportImageDialog()
{
delete ui;
}
void ExportImageDialog::setCamerasInfo(const std::vector<std::pair<QString, QSize>>& cameraInfo)
{
Q_ASSERT(ui->cameraCombo);
ui->cameraCombo->clear();
for (const std::pair<QString, QSize>& it : cameraInfo)
{
ui->cameraCombo->addItem(it.first, it.second);
}
const auto indexChanged = static_cast<void(QComboBox::*)(int i)>(&QComboBox::currentIndexChanged);
connect(ui->cameraCombo, indexChanged, this, &ExportImageDialog::cameraComboChanged);
cameraComboChanged(0);
}
void ExportImageDialog::setDefaultRange(int startFrame, int endFrame, int endFrameWithSounds)
{
mEndFrame = endFrame;
mEndFrameWithSounds = endFrameWithSounds;
QSignalBlocker b1( ui->startSpinBox );
QSignalBlocker b2( ui->endSpinBox );
ui->startSpinBox->setValue( startFrame );
ui->endSpinBox->setValue( endFrame );
connect(ui->frameCheckBox, &QCheckBox::clicked, this, &ExportImageDialog::frameCheckboxClicked);
}
int ExportImageDialog::getStartFrame() const
{
return ui->startSpinBox->value();
}
int ExportImageDialog::getEndFrame() const
{
return ui->endSpinBox->value();
}
void ExportImageDialog::frameCheckboxClicked(bool checked)
{
int e = (checked) ? mEndFrameWithSounds : mEndFrame;
ui->endSpinBox->setValue(e);
}
void ExportImageDialog::setExportSize(QSize size)
{
ui->imgWidthSpinBox->setValue(size.width());
ui->imgHeightSpinBox->setValue(size.height());
}
QSize ExportImageDialog::getExportSize() const
{
return QSize(ui->imgWidthSpinBox->value(), ui->imgHeightSpinBox->value());
}
bool ExportImageDialog::getTransparency() const
{
return ui->cbTransparency->checkState() == Qt::Checked;
}
bool ExportImageDialog::getExportKeyframesOnly() const
{
return ui->cbExportKeyframesOnly->checkState() == Qt::Checked;
}
QString ExportImageDialog::getExportFormat() const
{
return ui->formatComboBox->currentText();
}
QString ExportImageDialog::getCameraLayerName() const
{
return ui->cameraCombo->currentText();
}
void ExportImageDialog::formatChanged(const QString& format)
{
setFileExtension(format.toLower());
setTransparencyOptionVisibility(format);
}
void ExportImageDialog::cameraComboChanged(int index)
{
const QSize cameraSize = ui->cameraCombo->itemData(index).toSize();
ui->imgWidthSpinBox->setValue(cameraSize.width());
ui->imgHeightSpinBox->setValue(cameraSize.height());
}
void ExportImageDialog::setTransparencyOptionVisibility(const QString &format)
{
if (format == "JPG" || format == "BMP")
ui->cbTransparency->setDisabled(true);
else
ui->cbTransparency->setDisabled(false);
}
|
{
"language": "C++"
}
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/random.h"
#include <math.h>
#include <limits>
#include <vector>
#include "rtc_base/numerics/math_utils.h" // unsigned difference
#include "test/gtest.h"
namespace webrtc {
namespace {
// Computes the positive remainder of x/n.
template <typename T>
T fdiv_remainder(T x, T n) {
RTC_CHECK_GE(n, 0);
T remainder = x % n;
if (remainder < 0)
remainder += n;
return remainder;
}
} // namespace
// Sample a number of random integers of type T. Divide them into buckets
// based on the remainder when dividing by bucket_count and check that each
// bucket gets roughly the expected number of elements.
template <typename T>
void UniformBucketTest(T bucket_count, int samples, Random* prng) {
std::vector<int> buckets(bucket_count, 0);
uint64_t total_values = 1ull << (std::numeric_limits<T>::digits +
std::numeric_limits<T>::is_signed);
T upper_limit =
std::numeric_limits<T>::max() -
static_cast<T>(total_values % static_cast<uint64_t>(bucket_count));
ASSERT_GT(upper_limit, std::numeric_limits<T>::max() / 2);
for (int i = 0; i < samples; i++) {
T sample;
do {
// We exclude a few numbers from the range so that it is divisible by
// the number of buckets. If we are unlucky and hit one of the excluded
// numbers we just resample. Note that if the number of buckets is a
// power of 2, then we don't have to exclude anything.
sample = prng->Rand<T>();
} while (sample > upper_limit);
buckets[fdiv_remainder(sample, bucket_count)]++;
}
for (T i = 0; i < bucket_count; i++) {
// Expect the result to be within 3 standard deviations of the mean.
EXPECT_NEAR(buckets[i], samples / bucket_count,
3 * sqrt(samples / bucket_count));
}
}
TEST(RandomNumberGeneratorTest, BucketTestSignedChar) {
Random prng(7297352569824ull);
UniformBucketTest<signed char>(64, 640000, &prng);
UniformBucketTest<signed char>(11, 440000, &prng);
UniformBucketTest<signed char>(3, 270000, &prng);
}
TEST(RandomNumberGeneratorTest, BucketTestUnsignedChar) {
Random prng(7297352569824ull);
UniformBucketTest<unsigned char>(64, 640000, &prng);
UniformBucketTest<unsigned char>(11, 440000, &prng);
UniformBucketTest<unsigned char>(3, 270000, &prng);
}
TEST(RandomNumberGeneratorTest, BucketTestSignedShort) {
Random prng(7297352569824ull);
UniformBucketTest<int16_t>(64, 640000, &prng);
UniformBucketTest<int16_t>(11, 440000, &prng);
UniformBucketTest<int16_t>(3, 270000, &prng);
}
TEST(RandomNumberGeneratorTest, BucketTestUnsignedShort) {
Random prng(7297352569824ull);
UniformBucketTest<uint16_t>(64, 640000, &prng);
UniformBucketTest<uint16_t>(11, 440000, &prng);
UniformBucketTest<uint16_t>(3, 270000, &prng);
}
TEST(RandomNumberGeneratorTest, BucketTestSignedInt) {
Random prng(7297352569824ull);
UniformBucketTest<signed int>(64, 640000, &prng);
UniformBucketTest<signed int>(11, 440000, &prng);
UniformBucketTest<signed int>(3, 270000, &prng);
}
TEST(RandomNumberGeneratorTest, BucketTestUnsignedInt) {
Random prng(7297352569824ull);
UniformBucketTest<unsigned int>(64, 640000, &prng);
UniformBucketTest<unsigned int>(11, 440000, &prng);
UniformBucketTest<unsigned int>(3, 270000, &prng);
}
// The range of the random numbers is divided into bucket_count intervals
// of consecutive numbers. Check that approximately equally many numbers
// from each inteval are generated.
void BucketTestSignedInterval(unsigned int bucket_count,
unsigned int samples,
int32_t low,
int32_t high,
int sigma_level,
Random* prng) {
std::vector<unsigned int> buckets(bucket_count, 0);
ASSERT_GE(high, low);
ASSERT_GE(bucket_count, 2u);
uint32_t interval = unsigned_difference<int32_t>(high, low) + 1;
uint32_t numbers_per_bucket;
if (interval == 0) {
// The computation high - low + 1 should be 2^32 but overflowed
// Hence, bucket_count must be a power of 2
ASSERT_EQ(bucket_count & (bucket_count - 1), 0u);
numbers_per_bucket = (0x80000000u / bucket_count) * 2;
} else {
ASSERT_EQ(interval % bucket_count, 0u);
numbers_per_bucket = interval / bucket_count;
}
for (unsigned int i = 0; i < samples; i++) {
int32_t sample = prng->Rand(low, high);
EXPECT_LE(low, sample);
EXPECT_GE(high, sample);
buckets[unsigned_difference<int32_t>(sample, low) / numbers_per_bucket]++;
}
for (unsigned int i = 0; i < bucket_count; i++) {
// Expect the result to be within 3 standard deviations of the mean,
// or more generally, within sigma_level standard deviations of the mean.
double mean = static_cast<double>(samples) / bucket_count;
EXPECT_NEAR(buckets[i], mean, sigma_level * sqrt(mean));
}
}
// The range of the random numbers is divided into bucket_count intervals
// of consecutive numbers. Check that approximately equally many numbers
// from each inteval are generated.
void BucketTestUnsignedInterval(unsigned int bucket_count,
unsigned int samples,
uint32_t low,
uint32_t high,
int sigma_level,
Random* prng) {
std::vector<unsigned int> buckets(bucket_count, 0);
ASSERT_GE(high, low);
ASSERT_GE(bucket_count, 2u);
uint32_t interval = high - low + 1;
uint32_t numbers_per_bucket;
if (interval == 0) {
// The computation high - low + 1 should be 2^32 but overflowed
// Hence, bucket_count must be a power of 2
ASSERT_EQ(bucket_count & (bucket_count - 1), 0u);
numbers_per_bucket = (0x80000000u / bucket_count) * 2;
} else {
ASSERT_EQ(interval % bucket_count, 0u);
numbers_per_bucket = interval / bucket_count;
}
for (unsigned int i = 0; i < samples; i++) {
uint32_t sample = prng->Rand(low, high);
EXPECT_LE(low, sample);
EXPECT_GE(high, sample);
buckets[(sample - low) / numbers_per_bucket]++;
}
for (unsigned int i = 0; i < bucket_count; i++) {
// Expect the result to be within 3 standard deviations of the mean,
// or more generally, within sigma_level standard deviations of the mean.
double mean = static_cast<double>(samples) / bucket_count;
EXPECT_NEAR(buckets[i], mean, sigma_level * sqrt(mean));
}
}
TEST(RandomNumberGeneratorTest, UniformUnsignedInterval) {
Random prng(299792458ull);
BucketTestUnsignedInterval(2, 100000, 0, 1, 3, &prng);
BucketTestUnsignedInterval(7, 100000, 1, 14, 3, &prng);
BucketTestUnsignedInterval(11, 100000, 1000, 1010, 3, &prng);
BucketTestUnsignedInterval(100, 100000, 0, 99, 3, &prng);
BucketTestUnsignedInterval(2, 100000, 0, 4294967295, 3, &prng);
BucketTestUnsignedInterval(17, 100000, 455, 2147484110, 3, &prng);
// 99.7% of all samples will be within 3 standard deviations of the mean,
// but since we test 1000 buckets we allow an interval of 4 sigma.
BucketTestUnsignedInterval(1000, 1000000, 0, 2147483999, 4, &prng);
}
TEST(RandomNumberGeneratorTest, UniformSignedInterval) {
Random prng(66260695729ull);
BucketTestSignedInterval(2, 100000, 0, 1, 3, &prng);
BucketTestSignedInterval(7, 100000, -2, 4, 3, &prng);
BucketTestSignedInterval(11, 100000, 1000, 1010, 3, &prng);
BucketTestSignedInterval(100, 100000, 0, 99, 3, &prng);
BucketTestSignedInterval(2, 100000, std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::max(), 3, &prng);
BucketTestSignedInterval(17, 100000, -1073741826, 1073741829, 3, &prng);
// 99.7% of all samples will be within 3 standard deviations of the mean,
// but since we test 1000 buckets we allow an interval of 4 sigma.
BucketTestSignedInterval(1000, 1000000, -352, 2147483647, 4, &prng);
}
// The range of the random numbers is divided into bucket_count intervals
// of consecutive numbers. Check that approximately equally many numbers
// from each inteval are generated.
void BucketTestFloat(unsigned int bucket_count,
unsigned int samples,
int sigma_level,
Random* prng) {
ASSERT_GE(bucket_count, 2u);
std::vector<unsigned int> buckets(bucket_count, 0);
for (unsigned int i = 0; i < samples; i++) {
uint32_t sample = bucket_count * prng->Rand<float>();
EXPECT_LE(0u, sample);
EXPECT_GE(bucket_count - 1, sample);
buckets[sample]++;
}
for (unsigned int i = 0; i < bucket_count; i++) {
// Expect the result to be within 3 standard deviations of the mean,
// or more generally, within sigma_level standard deviations of the mean.
double mean = static_cast<double>(samples) / bucket_count;
EXPECT_NEAR(buckets[i], mean, sigma_level * sqrt(mean));
}
}
TEST(RandomNumberGeneratorTest, UniformFloatInterval) {
Random prng(1380648813ull);
BucketTestFloat(100, 100000, 3, &prng);
// 99.7% of all samples will be within 3 standard deviations of the mean,
// but since we test 1000 buckets we allow an interval of 4 sigma.
// BucketTestSignedInterval(1000, 1000000, -352, 2147483647, 4, &prng);
}
TEST(RandomNumberGeneratorTest, SignedHasSameBitPattern) {
Random prng_signed(66738480ull), prng_unsigned(66738480ull);
for (int i = 0; i < 1000; i++) {
signed int s = prng_signed.Rand<signed int>();
unsigned int u = prng_unsigned.Rand<unsigned int>();
EXPECT_EQ(u, static_cast<unsigned int>(s));
}
for (int i = 0; i < 1000; i++) {
int16_t s = prng_signed.Rand<int16_t>();
uint16_t u = prng_unsigned.Rand<uint16_t>();
EXPECT_EQ(u, static_cast<uint16_t>(s));
}
for (int i = 0; i < 1000; i++) {
signed char s = prng_signed.Rand<signed char>();
unsigned char u = prng_unsigned.Rand<unsigned char>();
EXPECT_EQ(u, static_cast<unsigned char>(s));
}
}
TEST(RandomNumberGeneratorTest, Gaussian) {
const int kN = 100000;
const int kBuckets = 100;
const double kMean = 49;
const double kStddev = 10;
Random prng(1256637061);
std::vector<unsigned int> buckets(kBuckets, 0);
for (int i = 0; i < kN; i++) {
int index = prng.Gaussian(kMean, kStddev) + 0.5;
if (index >= 0 && index < kBuckets) {
buckets[index]++;
}
}
const double kPi = 3.14159265358979323846;
const double kScale = 1 / (kStddev * sqrt(2.0 * kPi));
const double kDiv = -2.0 * kStddev * kStddev;
for (int n = 0; n < kBuckets; ++n) {
// Use Simpsons rule to estimate the probability that a random gaussian
// sample is in the interval [n-0.5, n+0.5].
double f_left = kScale * exp((n - kMean - 0.5) * (n - kMean - 0.5) / kDiv);
double f_mid = kScale * exp((n - kMean) * (n - kMean) / kDiv);
double f_right = kScale * exp((n - kMean + 0.5) * (n - kMean + 0.5) / kDiv);
double normal_dist = (f_left + 4 * f_mid + f_right) / 6;
// Expect the number of samples to be within 3 standard deviations
// (rounded up) of the expected number of samples in the bucket.
EXPECT_NEAR(buckets[n], kN * normal_dist, 3 * sqrt(kN * normal_dist) + 1);
}
}
} // namespace webrtc
|
{
"language": "C++"
}
|
// 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.
#ifndef MOJO_PUBLIC_CPP_BINDINGS_MAP_TRAITS_H_
#define MOJO_PUBLIC_CPP_BINDINGS_MAP_TRAITS_H_
#include "mojo/public/cpp/bindings/lib/template_util.h"
namespace mojo {
// This must be specialized for any type |T| to be serialized/deserialized as
// a mojom map.
//
// Usually you would like to do a partial specialization for a map template.
// Imagine you want to specialize it for CustomMap<>, you need to implement:
//
// template <typename K, typename V>
// struct MapTraits<CustomMap<K, V>> {
// using Key = K;
// using Value = V;
//
// // These two methods are optional. Please see comments in struct_traits.h
// // Note that unlike with StructTraits, IsNull() is called *twice* during
// // serialization for MapTraits.
// static bool IsNull(const CustomMap<K, V>& input);
// static void SetToNull(CustomMap<K, V>* output);
//
// static size_t GetSize(const CustomMap<K, V>& input);
//
// static CustomConstIterator GetBegin(const CustomMap<K, V>& input);
// static CustomIterator GetBegin(CustomMap<K, V>& input);
//
// static void AdvanceIterator(CustomConstIterator& iterator);
// static void AdvanceIterator(CustomIterator& iterator);
//
// static const K& GetKey(CustomIterator& iterator);
// static const K& GetKey(CustomConstIterator& iterator);
//
// static V& GetValue(CustomIterator& iterator);
// static const V& GetValue(CustomConstIterator& iterator);
//
// // Returning false results in deserialization failure and causes the
// // message pipe receiving it to be disconnected. |IK| and |IV| are
// // separate input key/value template parameters that allows for the
// // the key/value types to be forwarded.
// template <typename IK, typename IV>
// static bool Insert(CustomMap<K, V>& input,
// IK&& key,
// IV&& value);
//
// static void SetToEmpty(CustomMap<K, V>* output);
// };
//
template <typename T>
struct MapTraits {
static_assert(internal::AlwaysFalse<T>::value,
"Cannot find the mojo::MapTraits specialization. Did you "
"forget to include the corresponding header file?");
};
} // namespace mojo
#endif // MOJO_PUBLIC_CPP_BINDINGS_MAP_TRAITS_H_
|
{
"language": "C++"
}
|
/*=============================================================================
Copyright (c) 2001-2008 Joel de Guzman
Copyright (c) 2001-2008 Hartmut Kaiser
http://spirit.sourceforge.net/
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_DEPRECATED_INCLUDE_TYPEOF_DYNAMIC
#define BOOST_SPIRIT_DEPRECATED_INCLUDE_TYPEOF_DYNAMIC
#include <boost/version.hpp>
#if BOOST_VERSION >= 103800
#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__)
# pragma message ("Warning: This header is deprecated. Please use: boost/spirit/include/classic_typeof.hpp")
#elif defined(__GNUC__) || defined(__HP_aCC) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
# warning "This header is deprecated. Please use: boost/spirit/include/classic_typeof.hpp"
#endif
#endif
#if !defined(BOOST_SPIRIT_USE_OLD_NAMESPACE)
#define BOOST_SPIRIT_USE_OLD_NAMESPACE
#endif
#include <boost/spirit/include/classic_typeof.hpp>
#endif
|
{
"language": "C++"
}
|
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// 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_UNITS_MAGNETIC_FLUX_DERIVED_DIMENSION_HPP
#define BOOST_UNITS_MAGNETIC_FLUX_DERIVED_DIMENSION_HPP
#include <boost/units/derived_dimension.hpp>
#include <boost/units/physical_dimensions/length.hpp>
#include <boost/units/physical_dimensions/mass.hpp>
#include <boost/units/physical_dimensions/time.hpp>
#include <boost/units/physical_dimensions/current.hpp>
namespace boost {
namespace units {
/// derived dimension for magnetic flux : L^2 M T^-2 I^-1
typedef derived_dimension<length_base_dimension,2,
mass_base_dimension,1,
time_base_dimension,-2,
current_base_dimension,-1>::type magnetic_flux_dimension;
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_MAGNETIC_FLUX_DERIVED_DIMENSION_HPP
|
{
"language": "C++"
}
|
/*
* 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.
*/
/*
* Copyright (C) 2016 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/metrics.hh>
#include "types.hh"
#include "tracing/trace_keyspace_helper.hh"
#include "tracing/tracing_backend_registry.hh"
#include "cql3/statements/batch_statement.hh"
#include "cql3/statements/modification_statement.hh"
#include "cql3/query_processor.hh"
#include "cql3/cql_config.hh"
#include "types/set.hh"
#include "types/map.hh"
namespace tracing {
using namespace std::chrono_literals;
static logging::logger tlogger("trace_keyspace_helper");
const sstring trace_keyspace_helper::KEYSPACE_NAME("system_traces");
const sstring trace_keyspace_helper::SESSIONS("sessions");
const sstring trace_keyspace_helper::SESSIONS_TIME_IDX("sessions_time_idx");
const sstring trace_keyspace_helper::EVENTS("events");
const sstring trace_keyspace_helper::NODE_SLOW_QUERY_LOG("node_slow_log");
const sstring trace_keyspace_helper::NODE_SLOW_QUERY_LOG_TIME_IDX("node_slow_log_time_idx");
timeout_config tracing_db_timeout_config {
5s, 5s, 5s, 5s, 5s, 5s, 5s,
};
struct trace_keyspace_backend_sesssion_state final : public backend_session_state_base {
int64_t last_nanos = 0;
semaphore write_sem {1};
virtual ~trace_keyspace_backend_sesssion_state() {}
};
trace_keyspace_helper::trace_keyspace_helper(tracing& tr)
: i_tracing_backend_helper(tr)
, _dummy_query_state(service::client_state::for_internal_calls(), empty_service_permit())
, _sessions(KEYSPACE_NAME, SESSIONS,
sprint("CREATE TABLE IF NOT EXISTS %s.%s ("
"session_id uuid,"
"command text,"
"client inet,"
"coordinator inet,"
"duration int,"
"parameters map<text, text>,"
"request text,"
"started_at timestamp,"
"request_size int,"
"response_size int,"
"PRIMARY KEY ((session_id))) "
"WITH default_time_to_live = 86400", KEYSPACE_NAME, SESSIONS),
sprint("INSERT INTO %s.%s ("
"session_id,"
"command,"
"client,"
"coordinator,"
"duration,"
"parameters,"
"request,"
"started_at,"
"request_size,"
"response_size) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
"USING TTL ?", KEYSPACE_NAME, SESSIONS))
, _sessions_time_idx(KEYSPACE_NAME, SESSIONS_TIME_IDX,
sprint("CREATE TABLE IF NOT EXISTS %s.%s ("
"minute timestamp,"
"started_at timestamp,"
"session_id uuid,"
"PRIMARY KEY (minute, started_at, session_id)) "
"WITH default_time_to_live = 86400", KEYSPACE_NAME, SESSIONS_TIME_IDX),
sprint("INSERT INTO %s.%s ("
"minute,"
"started_at,"
"session_id) VALUES (?, ?, ?) "
"USING TTL ?", KEYSPACE_NAME, SESSIONS_TIME_IDX))
, _events(KEYSPACE_NAME, EVENTS,
sprint("CREATE TABLE IF NOT EXISTS %s.%s ("
"session_id uuid,"
"event_id timeuuid,"
"activity text,"
"source inet,"
"source_elapsed int,"
"thread text,"
"scylla_parent_id bigint,"
"scylla_span_id bigint,"
"PRIMARY KEY ((session_id), event_id)) "
"WITH default_time_to_live = 86400", KEYSPACE_NAME, EVENTS),
sprint("INSERT INTO %s.%s ("
"session_id, "
"event_id, "
"activity, "
"source, "
"source_elapsed, "
"thread,"
"scylla_parent_id,"
"scylla_span_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
"USING TTL ?", KEYSPACE_NAME, EVENTS))
, _slow_query_log(KEYSPACE_NAME, NODE_SLOW_QUERY_LOG,
sprint("CREATE TABLE IF NOT EXISTS %s.%s ("
"node_ip inet,"
"shard int,"
"session_id uuid,"
"date timestamp,"
"start_time timeuuid,"
"command text,"
"duration int,"
"parameters map<text, text>,"
"source_ip inet,"
"table_names set<text>,"
"username text,"
"PRIMARY KEY (start_time, node_ip, shard)) "
"WITH default_time_to_live = 86400", KEYSPACE_NAME, NODE_SLOW_QUERY_LOG),
sprint("INSERT INTO %s.%s ("
"node_ip,"
"shard,"
"session_id,"
"date,"
"start_time,"
"command,"
"duration,"
"parameters,"
"source_ip,"
"table_names,"
"username) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
"USING TTL ?", KEYSPACE_NAME, NODE_SLOW_QUERY_LOG))
, _slow_query_log_time_idx(KEYSPACE_NAME, NODE_SLOW_QUERY_LOG_TIME_IDX,
sprint("CREATE TABLE IF NOT EXISTS %s.%s ("
"minute timestamp,"
"started_at timestamp,"
"session_id uuid,"
"start_time timeuuid,"
"node_ip inet,"
"shard int,"
"PRIMARY KEY (minute, started_at, session_id)) "
"WITH default_time_to_live = 86400", KEYSPACE_NAME, NODE_SLOW_QUERY_LOG_TIME_IDX),
sprint("INSERT INTO %s.%s ("
"minute,"
"started_at,"
"session_id,"
"start_time,"
"node_ip,"
"shard) VALUES (?, ?, ?, ?, ?, ?)"
"USING TTL ?", KEYSPACE_NAME, NODE_SLOW_QUERY_LOG_TIME_IDX))
{
namespace sm = seastar::metrics;
_metrics.add_group("tracing_keyspace_helper", {
sm::make_derive("tracing_errors", [this] { return _stats.tracing_errors; },
sm::description("Counts a number of errors during writing to a system_traces keyspace. "
"One error may cause one or more tracing records to be lost.")),
sm::make_derive("bad_column_family_errors", [this] { return _stats.bad_column_family_errors; },
sm::description("Counts a number of times write failed due to one of the tables in the system_traces keyspace has an incompatible schema. "
"One error may result one or more tracing records to be lost. "
"Non-zero value indicates that the administrator has to take immediate steps to fix the corresponding schema. "
"The appropriate error message will be printed in the syslog.")),
});
}
future<> trace_keyspace_helper::start() {
return table_helper::setup_keyspace(KEYSPACE_NAME, "2", _dummy_query_state, { &_sessions, &_sessions_time_idx, &_events, &_slow_query_log, &_slow_query_log_time_idx });
}
void trace_keyspace_helper::write_one_session_records(lw_shared_ptr<one_session_records> records) {
// Future is waited on indirectly in `stop()` (via `_pending_writes`).
(void)with_gate(_pending_writes, [this, records = std::move(records)] {
auto num_records = records->size();
return this->flush_one_session_mutations(std::move(records)).finally([this, num_records] { _local_tracing.write_complete(num_records); });
}).handle_exception([this] (auto ep) {
try {
++_stats.tracing_errors;
std::rethrow_exception(ep);
} catch (exceptions::overloaded_exception&) {
tlogger.warn("Too many nodes are overloaded to save trace events");
} catch (bad_column_family& e) {
if (_stats.bad_column_family_errors++ % bad_column_family_message_period == 0) {
tlogger.warn("Tracing is enabled but {}", e.what());
}
} catch (std::logic_error& e) {
tlogger.error(e.what());
} catch (...) {
// TODO: Handle some more exceptions maybe?
}
}).discard_result();
}
void trace_keyspace_helper::write_records_bulk(records_bulk& bulk) {
tlogger.trace("Writing {} sessions", bulk.size());
std::for_each(bulk.begin(), bulk.end(), [this] (records_bulk::value_type& one_session_records_ptr) {
write_one_session_records(std::move(one_session_records_ptr));
});
}
cql3::query_options trace_keyspace_helper::make_session_mutation_data(const one_session_records& session_records) {
const session_record& record = session_records.session_rec;
auto millis_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(record.started_at.time_since_epoch()).count();
std::vector<std::pair<data_value, data_value>> parameters_values_vector;
parameters_values_vector.reserve(record.parameters.size());
std::for_each(record.parameters.begin(), record.parameters.end(), [¶meters_values_vector] (auto& val_pair) { parameters_values_vector.emplace_back(val_pair.first, val_pair.second); });
auto my_map_type = map_type_impl::get_instance(utf8_type, utf8_type, true);
std::vector<cql3::raw_value> values {
cql3::raw_value::make_value(uuid_type->decompose(session_records.session_id)),
cql3::raw_value::make_value(utf8_type->decompose(type_to_string(record.command))),
cql3::raw_value::make_value(inet_addr_type->decompose(record.client.addr())),
cql3::raw_value::make_value(inet_addr_type->decompose(utils::fb_utilities::get_broadcast_address().addr())),
cql3::raw_value::make_value(int32_type->decompose(elapsed_to_micros(record.elapsed))),
cql3::raw_value::make_value(make_map_value(my_map_type, map_type_impl::native_type(std::move(parameters_values_vector))).serialize()),
cql3::raw_value::make_value(utf8_type->decompose(record.request)),
cql3::raw_value::make_value(timestamp_type->decompose(millis_since_epoch)),
cql3::raw_value::make_value(int32_type->decompose((int32_t)(record.request_size))),
cql3::raw_value::make_value(int32_type->decompose((int32_t)(record.response_size))),
cql3::raw_value::make_value(int32_type->decompose((int32_t)(session_records.ttl.count())))
};
return cql3::query_options(cql3::default_cql_config,
db::consistency_level::ANY, tracing_db_timeout_config, std::nullopt, std::move(values), false, cql3::query_options::specific_options::DEFAULT, cql_serialization_format::latest());
}
cql3::query_options trace_keyspace_helper::make_session_time_idx_mutation_data(const one_session_records& session_records) {
auto started_at_duration = session_records.session_rec.started_at.time_since_epoch();
// timestamp in minutes when the query began
auto minutes_in_millis = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration_cast<std::chrono::minutes>(started_at_duration)).count();
// timestamp when the query began
auto millis_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(started_at_duration).count();
std::vector<cql3::raw_value> values {
cql3::raw_value::make_value(timestamp_type->decompose(minutes_in_millis)),
cql3::raw_value::make_value(timestamp_type->decompose(millis_since_epoch)),
cql3::raw_value::make_value(uuid_type->decompose(session_records.session_id)),
cql3::raw_value::make_value(int32_type->decompose(int32_t(session_records.ttl.count())))
};
return cql3::query_options(cql3::default_cql_config,
db::consistency_level::ANY, tracing_db_timeout_config, std::nullopt, std::move(values), false, cql3::query_options::specific_options::DEFAULT, cql_serialization_format::latest());
}
cql3::query_options trace_keyspace_helper::make_slow_query_mutation_data(const one_session_records& session_records, const utils::UUID& start_time_id) {
const session_record& record = session_records.session_rec;
auto millis_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(record.started_at.time_since_epoch()).count();
// query command is stored on a parameters map with a 'query' key
auto query_str_it = record.parameters.find("query");
if (query_str_it == record.parameters.end()) {
throw std::logic_error("No \"query\" parameter set for a session requesting a slow_query_log record");
}
// parameters map
std::vector<std::pair<data_value, data_value>> parameters_values_vector;
parameters_values_vector.reserve(record.parameters.size());
std::for_each(record.parameters.begin(), record.parameters.end(), [¶meters_values_vector] (auto& val_pair) { parameters_values_vector.emplace_back(val_pair.first, val_pair.second); });
auto my_map_type = map_type_impl::get_instance(utf8_type, utf8_type, true);
// set of tables involved in this query
std::vector<data_value> tables_names_vector;
tables_names_vector.reserve(record.tables.size());
std::for_each(record.tables.begin(), record.tables.end(), [&tables_names_vector] (auto& val) { tables_names_vector.emplace_back(val); });
auto my_set_type = set_type_impl::get_instance(utf8_type, true);
std::vector<cql3::raw_value> values({
cql3::raw_value::make_value(inet_addr_type->decompose(utils::fb_utilities::get_broadcast_address().addr())),
cql3::raw_value::make_value(int32_type->decompose((int32_t)(this_shard_id()))),
cql3::raw_value::make_value(uuid_type->decompose(session_records.session_id)),
cql3::raw_value::make_value(timestamp_type->decompose(millis_since_epoch)),
cql3::raw_value::make_value(timeuuid_type->decompose(start_time_id)),
cql3::raw_value::make_value(utf8_type->decompose(query_str_it->second)),
cql3::raw_value::make_value(int32_type->decompose(elapsed_to_micros(record.elapsed))),
cql3::raw_value::make_value(make_map_value(my_map_type, map_type_impl::native_type(std::move(parameters_values_vector))).serialize()),
cql3::raw_value::make_value(inet_addr_type->decompose(record.client.addr())),
cql3::raw_value::make_value(make_set_value(my_set_type, set_type_impl::native_type(std::move(tables_names_vector))).serialize()),
cql3::raw_value::make_value(utf8_type->decompose(record.username)),
cql3::raw_value::make_value(int32_type->decompose((int32_t)(record.slow_query_record_ttl.count())))
});
return cql3::query_options(cql3::default_cql_config,
db::consistency_level::ANY, tracing_db_timeout_config, std::nullopt, std::move(values), false, cql3::query_options::specific_options::DEFAULT, cql_serialization_format::latest());
}
cql3::query_options trace_keyspace_helper::make_slow_query_time_idx_mutation_data(const one_session_records& session_records, const utils::UUID& start_time_id) {
auto started_at_duration = session_records.session_rec.started_at.time_since_epoch();
// timestamp in minutes when the query began
auto minutes_in_millis = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration_cast<std::chrono::minutes>(started_at_duration)).count();
// timestamp when the query began
auto millis_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(started_at_duration).count();
std::vector<cql3::raw_value> values({
cql3::raw_value::make_value(timestamp_type->decompose(minutes_in_millis)),
cql3::raw_value::make_value(timestamp_type->decompose(millis_since_epoch)),
cql3::raw_value::make_value(uuid_type->decompose(session_records.session_id)),
cql3::raw_value::make_value(timeuuid_type->decompose(start_time_id)),
cql3::raw_value::make_value(inet_addr_type->decompose(utils::fb_utilities::get_broadcast_address().addr())),
cql3::raw_value::make_value(int32_type->decompose(int32_t(this_shard_id()))),
cql3::raw_value::make_value(int32_type->decompose(int32_t(session_records.session_rec.slow_query_record_ttl.count())))
});
return cql3::query_options(cql3::default_cql_config,
db::consistency_level::ANY, tracing_db_timeout_config, std::nullopt, std::move(values), false, cql3::query_options::specific_options::DEFAULT, cql_serialization_format::latest());
}
std::vector<cql3::raw_value> trace_keyspace_helper::make_event_mutation_data(one_session_records& session_records, const event_record& record) {
auto backend_state_ptr = static_cast<trace_keyspace_backend_sesssion_state*>(session_records.backend_state_ptr.get());
std::vector<cql3::raw_value> values({
cql3::raw_value::make_value(uuid_type->decompose(session_records.session_id)),
cql3::raw_value::make_value(timeuuid_type->decompose(utils::UUID_gen::get_time_UUID(table_helper::make_monotonic_UUID_tp(backend_state_ptr->last_nanos, record.event_time_point)))),
cql3::raw_value::make_value(utf8_type->decompose(record.message)),
cql3::raw_value::make_value(inet_addr_type->decompose(utils::fb_utilities::get_broadcast_address().addr())),
cql3::raw_value::make_value(int32_type->decompose(elapsed_to_micros(record.elapsed))),
cql3::raw_value::make_value(utf8_type->decompose(_local_tracing.get_thread_name())),
cql3::raw_value::make_value(long_type->decompose(int64_t(session_records.parent_id.get_id()))),
cql3::raw_value::make_value(long_type->decompose(int64_t(session_records.my_span_id.get_id()))),
cql3::raw_value::make_value(int32_type->decompose((int32_t)(session_records.ttl.count())))
});
return values;
}
future<> trace_keyspace_helper::apply_events_mutation(lw_shared_ptr<one_session_records> records, std::deque<event_record>& events_records) {
if (events_records.empty()) {
return now();
}
return _events.cache_table_info(_dummy_query_state).then([this, records, &events_records] {
tlogger.trace("{}: storing {} events records: parent_id {} span_id {}", records->session_id, events_records.size(), records->parent_id, records->my_span_id);
std::vector<cql3::statements::batch_statement::single_statement> modifications(events_records.size(), cql3::statements::batch_statement::single_statement(_events.insert_stmt(), false));
std::vector<std::vector<cql3::raw_value>> values;
auto& qp = cql3::get_local_query_processor();
values.reserve(events_records.size());
std::for_each(events_records.begin(), events_records.end(), [&values, all_records = records, this] (event_record& one_event_record) { values.emplace_back(make_event_mutation_data(*all_records, one_event_record)); });
return do_with(
cql3::query_options::make_batch_options(cql3::query_options(cql3::default_cql_config, db::consistency_level::ANY, tracing_db_timeout_config, std::nullopt, std::vector<cql3::raw_value>{}, false, cql3::query_options::specific_options::DEFAULT, cql_serialization_format::latest()), std::move(values)),
cql3::statements::batch_statement(cql3::statements::batch_statement::type::UNLOGGED, std::move(modifications), cql3::attributes::none(), qp.get_cql_stats()),
[this] (auto& batch_options, auto& batch) {
return batch.execute(service::get_storage_proxy().local(), _dummy_query_state, batch_options).then([] (shared_ptr<cql_transport::messages::result_message> res) { return now(); });
}
);
});
}
future<> trace_keyspace_helper::flush_one_session_mutations(lw_shared_ptr<one_session_records> records) {
// grab events records available so far
return do_with(std::move(records->events_recs), [this, records] (std::deque<event_record>& events_records) {
records->events_recs.clear();
// Check if a session's record is ready before handling events' records.
//
// New event's records and a session's record may become ready while a
// mutation with the current events' records is being written. We don't want
// to allow the situation when a session's record is written before the last
// event record from the same session.
bool session_record_is_ready = records->session_rec.ready();
// From this point on - all new data will have to be handled in the next write event
records->data_consumed();
// We want to serialize the creation of events mutations in order to ensure
// that mutations for events that were created first are going to be
// created first too.
auto backend_state_ptr = static_cast<trace_keyspace_backend_sesssion_state*>(records->backend_state_ptr.get());
semaphore& write_sem = backend_state_ptr->write_sem;
return with_semaphore(write_sem, 1, [this, records, session_record_is_ready, &events_records] {
return apply_events_mutation(records, events_records).then([this, session_record_is_ready, records] {
if (session_record_is_ready) {
// if session is finished - store a session and a session time index entries
tlogger.trace("{}: going to store a session event", records->session_id);
return _sessions.insert(_dummy_query_state, make_session_mutation_data, std::ref(*records)).then([this, records] {
tlogger.trace("{}: going to store a {} entry", records->session_id, _sessions_time_idx.name());
return _sessions_time_idx.insert(_dummy_query_state, make_session_time_idx_mutation_data, std::ref(*records));
}).then([this, records] {
if (!records->do_log_slow_query) {
return now();
}
// if slow query log is requested - store a slow query log and a slow query log time index entries
auto start_time_id = utils::UUID_gen::get_time_UUID(table_helper::make_monotonic_UUID_tp(_slow_query_last_nanos, records->session_rec.started_at));
tlogger.trace("{}: going to store a slow query event", records->session_id);
return _slow_query_log.insert(_dummy_query_state, make_slow_query_mutation_data, std::ref(*records), start_time_id).then([this, records, start_time_id] {
tlogger.trace("{}: going to store a {} entry", records->session_id, _slow_query_log_time_idx.name());
return _slow_query_log_time_idx.insert(_dummy_query_state, make_slow_query_time_idx_mutation_data, std::ref(*records), start_time_id);
});
});
} else {
return now();
}
});
}).finally([records] {});
});
}
std::unique_ptr<backend_session_state_base> trace_keyspace_helper::allocate_session_state() const {
return std::make_unique<trace_keyspace_backend_sesssion_state>();
}
void register_tracing_keyspace_backend(backend_registry& tbr) {
tbr.register_backend<trace_keyspace_helper>("trace_keyspace_helper");
}
}
|
{
"language": "C++"
}
|
#include "fancy_index.hpp"
#include "stdio.h"
#include "stdlib.h"
/**
* malloc and return a new range from 0 to n. The caller assumes ownership
* of the memory, which must be `free`d.
*
**/
static int*
range(int n)
{
int i;
int* r = (int*) malloc(n * sizeof(int));
if (r == NULL) { fprintf(stderr, "malloc failure in file '%s' in line %i\n", __FILE__, __LINE__); exit(1); }
for (i = 0; i < n; i++) {
r[i] = i;
}
return r;
}
/**
* Numpy-like "fancy indexing" of a 2D array
*
* The equivalent python code for this function is
*
* >>> out = A[indx, indy]
*
* where
* A.shape == (nx, ny),
* indx.shape == (nindx,)
* indy.shape == (nindy,)
*
*
* The reason for writing this function in C is that from cython, we can't
* call the numpy fancy indexing without acquiring the GIL, which means it
* can't be used inside a prange construct
**/
void
fancy_index2d(const float* A, int nx, int ny,
const int* indx, int nindx, const int* indy, int nindy,
float* out)
{
int i, ii, j, jj;
int* indx_ = (int*) indx;
int* indy_ = (int*) indy;
if (indx == NULL) { indx_ = range(nx); nindx = nx; }
if (indy == NULL) { indy_ = range(ny); nindy = ny; }
for (ii = 0; ii < nindx; ii++) {
i = indx_[ii];
for (jj = 0; jj < nindy; jj++) {
j = indy_[jj];
out[ii*nindy + jj] = A[i*ny + j];
}
}
if (indx == NULL) { free(indx_); }
if (indy == NULL) { free(indy_); }
}
|
{
"language": "C++"
}
|
/*
Copyright (c) 2014 Aerys
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "minko/file/AnyASSIMPParser.hpp"
namespace Assimp
{
class IRRImporter;
}
namespace minko
{
namespace file
{
template <>
class AnyASSIMPParser<Assimp::IRRImporter> : public AbstractASSIMPParser
{
public:
typedef std::shared_ptr<AnyASSIMPParser<Assimp::IRRImporter>> Ptr;
public:
virtual ~AnyASSIMPParser() { }
static
Ptr
create();
virtual
void
provideLoaders(Assimp::Importer& importer);
private:
AnyASSIMPParser() { }
};
using IRRParser = AnyASSIMPParser<Assimp::IRRImporter>;
}
}
|
{
"language": "C++"
}
|
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000-2005.
// Use, modification and distribution are subject to 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).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_REMOVE_EXTENT_HPP_INCLUDED
#define BOOST_TT_REMOVE_EXTENT_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <cstddef> // size_t
namespace boost {
template <class T> struct remove_extent{ typedef T type; };
#if !defined(BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS)
template <typename T, std::size_t N> struct remove_extent<T[N]> { typedef T type; };
template <typename T, std::size_t N> struct remove_extent<T const[N]> { typedef T const type; };
template <typename T, std::size_t N> struct remove_extent<T volatile [N]> { typedef T volatile type; };
template <typename T, std::size_t N> struct remove_extent<T const volatile [N]> { typedef T const volatile type; };
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) && !defined(__IBMCPP__) && !BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840))
template <typename T> struct remove_extent<T[]> { typedef T type; };
template <typename T> struct remove_extent<T const[]> { typedef T const type; };
template <typename T> struct remove_extent<T volatile[]> { typedef T volatile type; };
template <typename T> struct remove_extent<T const volatile[]> { typedef T const volatile type; };
#endif
#endif
} // namespace boost
#endif // BOOST_TT_REMOVE_BOUNDS_HPP_INCLUDED
|
{
"language": "C++"
}
|
#include <functional>
#include "stat.hpp"
using namespace std;
int nUniquePoints(const vector<double> &points)
{
int up = 0;
for(vector<double>::const_iterator vb(points.begin()), vi(vb), ve(points.end()); vi!=ve; vi++)
if ((vi == vb) || (*(vi-1) != *vi))
up++;
return up;
}
void samplingFactor(const vector<double> &points, int nPoints, vector<double> &result)
{
result.clear();
for (vector<double>::const_iterator pi(points.begin()), pe(points.end());;) {
const double &ax = *pi;
result.push_back(ax);
if (++pi==pe)
break;
if (*pi == ax)
continue;
if (*pi != ax) {
// We could write this faster, but we don't want to run into problems with rounding
double div = (*pi - ax) / nPoints;
for (int i=1; i < nPoints; i++)
result.push_back(ax + i*div);
}
}
}
void samplingFactor(const map<double, double> &points, int nPoints, vector<double> &result)
{
result.clear();
for (map<double, double>::const_iterator pi(points.begin()), pe(points.end());;) {
const double &ax = (*pi).first;
result.push_back(ax);
if (++pi==pe)
break;
// We could write this faster, but we don't want to run into problems with rounding floats
const double &div = ((*pi).first - ax) / nPoints;
for (int i=1; i < nPoints; i++)
result.push_back(ax + i*div);
}
}
void samplingMinimal(const map<double, double> &points, int nPoints, vector<double> &result)
{
result.clear();
if (nPoints<=points.size()) {
for (map<double, double>::const_iterator pi(points.begin()), pe(points.end()); pi != pe; pi++)
result.push_back((*pi).first);
}
else
samplingFixed(points, nPoints, result);
}
void samplingMinimal(const vector<double> &points, int nPoints, vector<double> &result)
{
int nUnique = nUniquePoints(points);
if (nPoints<=nUnique)
result = points;
else
samplingFixed(points, nPoints, result);
}
void samplingFixed(const vector<double> &points, int nPoints, vector<double> &result)
{
int nUnique = nUniquePoints(points);
result.clear();
const double &ineach = double(nPoints - nUnique) / double(nUnique-1);
double inthis = 0.0;
for (vector<double>::const_iterator pi(points.begin()), pe(points.end());;) {
double ax = *pi;
result.push_back(ax);
if (++pi==pe)
break;
if (*pi != ax) {
inthis += ineach;
if (inthis >= 1.0) {
const double &dif = (*pi - ax) / (int(floor(inthis))+1);
while (inthis > 0.5) {
result.push_back(ax += dif);
inthis -= 1.0;
}
}
}
}
}
void samplingFixed(const map<double, double> &points, int nPoints, vector<double> &result)
{
result.clear();
const double &ineach = float(nPoints - points.size()) / float(points.size()-1);
double inthis = 0.0;
for (map<double, double>::const_iterator pi(points.begin()), pe(points.end());;) {
double ax = (*pi).first;
result.push_back(ax);
if (++pi==pe)
break;
inthis += ineach;
if (inthis >= 0.5) {
const double &dif = ((*pi).first - ax) / (int(floor(inthis))+1);
while (inthis > 0.5) {
result.push_back(ax += dif);
inthis -= 1.0;
}
}
}
}
void samplingUniform(const vector<double> &points, int nPoints, vector<double> &result)
{
result.clear();
const double &fi = points.front();
const double &rg = (points.back()-fi) / (nPoints-1);
for (int i = 0; i<nPoints; i++)
result.push_back(fi + i*rg);
}
void samplingUniform(const map<double, double> &points, int nPoints, vector<double> &result)
{
result.clear();
const double &fi = (*points.begin()).first;
map<double, double>::const_iterator pe(points.end());
pe--;
const double &rg = ((*pe).first-fi) / (nPoints-1);
for (int i = 0; i<nPoints; i++)
result.push_back(fi + i*rg);
}
bool comp1st(const pair<double, double> &x1, const pair<double, double> &x2)
{ return x1.first < x2.first; }
void vector2weighted(const vector<pair<double, double> > &points, vector<TXYW> &weighted)
{
if (points.empty())
throw StatException("lwr/loess: empty sample");
weighted.clear();
vector<pair<double, double> > myPoints = points;
sort(myPoints.begin(), myPoints.end(), comp1st);
vector<pair<double, double> >::const_iterator mpi(myPoints.begin()), mpe(myPoints.end());
weighted.push_back(TXYW((*mpi).first, (*mpi).second));
while(++mpi != mpe) {
TXYW &last = weighted.back();
if ((*mpi).first == last.x) {
last.y += (*mpi).second;
last.w += 1.0;
}
else {
if (last.w > 1e-6)
last.y /= last.w;
weighted.push_back(TXYW((*mpi).first, (*mpi).second));
}
}
TXYW &last = weighted.back();
if (last.w > 1e-6)
last.y /= last.w;
}
void loess(const vector<double> &refpoints, const vector<TXYW> &points, const float &windowProp, vector<pair<double, double> > &result)
{
result.clear();
typedef vector<TXYW>::const_iterator iterator;
iterator lowedge = points.begin();
iterator highedge = points.end();
iterator from;
iterator to;
double nPoints = 0;
for(from = points.begin(); from != highedge; nPoints += (*(from++)).w);
double needpoints = windowProp <= 1.0 ? nPoints * windowProp : windowProp;
bool stopWindow = needpoints >= nPoints;
if (stopWindow) {
from = lowedge;
to = highedge;
}
else
for(from = to = lowedge; (to != highedge) && (needpoints>0); needpoints -= (*(to++)).w);
for(vector<double>::const_iterator rpi(refpoints.begin()), rpe(refpoints.end()); rpi != rpe; rpi++) {
const double &refx = *rpi;
/* Adjust the window */
if (!stopWindow) {
// adjust the top end so that the window includes the reference point
// (note that the last point included is to-1, so this one must be >= refx)
for(; (to != highedge) && (refx > (*(to-1)).x); needpoints -= (*(to++)).w);
const int diffto = (to == highedge ? (to-1)->x : to->x) - refx;
// adjust the bottom end as high as it goes but so that the window still covers at least needpoints points
for(; (from != to) && (diffto < refx - (*from).x) && (needpoints + (*from).w < 0); needpoints += (*(from++)).w);
while ((to!=highedge) && ((*to).x - refx < refx - (*from).x)) {
// 'to' is not at the high edge and to's point is closer that from's, so include it
needpoints -= (*(to++)).w;
// adjust the bottom end as high as it goes but so that the window still covers at least needpoints points
for(; (from != to) && (needpoints + (*from).w < 0); needpoints += (*(from++)).w);
}
stopWindow = (to==highedge);
}
/* Determine the window half-width */
double h = abs(refx - (*from).x);
const double h2 = abs((*(to-1)).x - refx);
if (h2 > h)
h = h2;
h *= 1.1;
/* Iterate through the window */
double Sx = 0.0, Sy = 0.0, Sxx = 0.0, Syy = 0.0, Sxy = 0.0, Sw = 0.0, Swx = 0.0, Swxx = 0.0;
double n = 0.0;
for (iterator ii = from; ii != to; ii++) {
const double &x = (*ii).x;
const double &y = (*ii).y;
// compute the weight based on the distance
double w = abs(refx - x) / h;
w = 1 - w*w*w;
w = w*w*w;
// and multiply it by the point's given weight
w *= (*ii).w;
n += w;
Sx += w * x;
Sxx += w * x * x;
Sy += w * y;
Syy += w * y * y;
Sxy += w * x * y;
Sw += w * w;
Swx += w * w * x;
Swxx += w * w * x * x;
}
if (n==0) {
result.push_back(pair<double, double>(Sy, 0));
continue;
}
const double mu_x = Sx / n;
const double mu_y = Sy / n;
const double sigma_x2 = (Sxx - mu_x * Sx) / n;
if (sigma_x2 < 1e-20) {
result.push_back(pair<double, double>(Sy, 0));
continue;
}
const double sigma_y2 = (Syy - mu_y * Sy) / n;
const double sigma_xy = (Sxy - Sx * Sy / n) / n;
const double sigma_y_x = sigma_y2 - sigma_xy * sigma_xy / sigma_x2;
const double dist_x = refx - mu_x;
const double y = mu_y + sigma_xy / sigma_x2 * dist_x;
double var_y = sigma_y_x / n / n * (Sw + dist_x * dist_x / sigma_x2 / sigma_x2 * (Swxx + mu_x * mu_x * Sw - 2 * mu_x * Swx));
if ((var_y < 0) && (var_y > -1e-6))
var_y = 0;
else
var_y = sqrt(var_y);
result.push_back(pair<double, double>(y, var_y));
}
}
void loess(const vector<double> &refpoints, const vector<pair<double, double> > &points, const float &windowProp, vector<pair<double, double> > &result)
{
vector<TXYW> weighted;
vector2weighted(points, weighted);
loess(refpoints, weighted, windowProp, result);
}
void loess(const vector<double> &refpoints, const map<double, double> &points, const float &windowProp, vector<pair<double, double> > &result)
{
vector<TXYW> opoints;
for(map<double, double>::const_iterator pi(points.begin()), pe(points.end()); pi != pe; pi++)
opoints.push_back(TXYW((*pi).first, (*pi).second));
loess(refpoints, opoints, windowProp, result);
}
void lwr(const vector<double> &refpoints, const vector<TXYW> &points, const float &smoothFactor, vector<pair<double, double> > &result)
{
result.clear();
typedef vector<TXYW>::const_iterator iterator;
float tot_w = 0.0;
{
const_ITERATE(vector<TXYW>, pi, points)
tot_w += (*pi).w;
}
const float p25 = 0.25 * tot_w;
const float p75 = 0.75 * tot_w;
float x25, x75;
tot_w = 0;
{
vector<TXYW>::const_iterator pi(points.begin()), pe(points.end());
for(; (pi!=pe) && (tot_w<p25); tot_w += (*pi).w, pi++);
const float &x1 = (*(pi-1)).x;
x25 = x1 + ((*pi).x-x1) * (p25 - tot_w + (*pi).w) / (*pi).w;
if (tot_w >= p75)
throw StatException("not enough data to compute 25th and 75th percentile");
for(; (pi!=pe) && (tot_w<p75); tot_w += (*pi).w, pi++);
const float &x2 = (*(pi-1)).x;
x75 = x2 + ((*pi).x-x2) * (p75 - tot_w + (*pi).w) / (*pi).w;
}
const float sigma = smoothFactor * (x75-x25);
const_ITERATE(vector<double>, ri, refpoints) {
const double &refx = *ri;
double Sx = 0.0, Sy = 0.0, Sxx = 0.0, Syy = 0.0, Sxy = 0.0, Sw = 0.0, Swx = 0.0, Swxx = 0.0;
double n = 0.0;
for (vector<TXYW>::const_iterator ii(points.begin()), ie(points.end()); ii != ie; ii++) {
const double &x = (*ii).x;
const double &y = (*ii).y;
// compute the weight based on the distance and the point's given weight
const double dx = x - *ri;
double w = (*ii).w * exp(- dx*dx / (sigma*sigma));
n += w;
Sx += w * x;
Sxx += w * x * x;
Sy += w * y;
Syy += w * y * y;
Sxy += w * x * y;
Sw += w * w;
Swx += w * w * x;
Swxx += w * w * x * x;
}
if (n==0) {
result.push_back(pair<double, double>(Sy, 0));
continue;
}
const double mu_x = Sx / n;
const double mu_y = Sy / n;
const double sigma_x2 = (Sxx - mu_x * Sx) / n;
if (sigma_x2 < 1e-20) {
result.push_back(pair<double, double>(Sy, 0));
continue;
}
const double sigma_y2 = (Syy - mu_y * Sy) / n;
const double sigma_xy = (Sxy - Sx * Sy / n) / n;
const double sigma_y_x = sigma_y2 - sigma_xy * sigma_xy / sigma_x2;
const double dist_x = refx - mu_x;
const double y = mu_y + sigma_xy / sigma_x2 * dist_x;
double var_y = sigma_y_x / n / n * (Sw + dist_x * dist_x / sigma_x2 / sigma_x2 * (Swxx + mu_x * mu_x * Sw - 2 * mu_x * Swx));
if ((var_y < 0) && (var_y > -1e-6))
var_y = 0;
else
var_y = sqrt(var_y);
result.push_back(pair<double, double>(y, var_y));
}
}
void lwr(const vector<double> &refpoints, const vector<pair<double, double> > &points, const float &smoothFactor, vector<pair<double, double> > &result)
{
vector<TXYW> weighted;
vector2weighted(points, weighted);
lwr(refpoints, weighted, smoothFactor, result);
}
void lwr(const vector<double> &refpoints, const map<double, double> &points, const float &smoothFactor, vector<pair<double, double> > &result)
{
vector<TXYW> opoints;
for(map<double, double>::const_iterator pi(points.begin()), pe(points.end()); pi != pe; pi++)
opoints.push_back(TXYW((*pi).first, (*pi).second));
lwr(refpoints, opoints, smoothFactor, result);
}
|
{
"language": "C++"
}
|
#ifndef BOOST_MPL_SET_SET50_HPP_INCLUDED
#define BOOST_MPL_SET_SET50_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
// Copyright David Abrahams 2003-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#if !defined(BOOST_MPL_PREPROCESSING_MODE)
# include <boost/mpl/set/set40.hpp>
#endif
#include <boost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE)
# define BOOST_MPL_PREPROCESSED_HEADER set50.hpp
# include <boost/mpl/set/aux_/include_preprocessed.hpp>
#else
# include <boost/preprocessor/iterate.hpp>
namespace boost { namespace mpl {
# define BOOST_PP_ITERATION_PARAMS_1 \
(3,(41, 50, <boost/mpl/set/aux_/numbered.hpp>))
# include BOOST_PP_ITERATE()
}}
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_SET_SET50_HPP_INCLUDED
|
{
"language": "C++"
}
|
/*
* Copyright (c) 2012, Michael Lehn, Klaus Pototzky
*
* 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.
*/
#ifndef CXXLAPACK_INTERFACE_UNMLQ_H
#define CXXLAPACK_INTERFACE_UNMLQ_H 1
#include <cxxstd/complex.h>
namespace cxxlapack {
template <typename IndexType>
IndexType
unmlq(char side,
char trans,
IndexType m,
IndexType n,
IndexType k,
std::complex<float > *A,
IndexType ldA,
const std::complex<float > *tau,
std::complex<float > *C,
IndexType ldC,
std::complex<float > *work,
IndexType lWork);
template <typename IndexType>
IndexType
unmlq(char side,
char trans,
IndexType m,
IndexType n,
IndexType k,
std::complex<double> *A,
IndexType ldA,
const std::complex<double> *tau,
std::complex<double> *C,
IndexType ldC,
std::complex<double> *work,
IndexType lWork);
} // namespace cxxlapack
#endif // CXXLAPACK_INTERFACE_UNMLQ_H
|
{
"language": "C++"
}
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include "CToastNotification.hpp"
namespace s3d
{
ISiv3DToastNotification* ISiv3DToastNotification::Create()
{
return new CToastNotification;
}
}
|
{
"language": "C++"
}
|
//== INCLUDES =================================================================
#include <fstream>
#include <limits>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/writer/VTKWriter.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/Utils/color_cast.hh>
//=== NAMESPACES ==============================================================
namespace OpenMesh {
namespace IO {
//=== INSTANTIATE =============================================================
_VTKWriter_ __VTKWriterinstance;
_VTKWriter_& VTKWriter() { return __VTKWriterinstance; }
//=== IMPLEMENTATION ==========================================================
_VTKWriter_::_VTKWriter_() { IOManager().register_module(this); }
//-----------------------------------------------------------------------------
bool _VTKWriter_::write(const std::string& _filename, BaseExporter& _be, Options _opt, std::streamsize _precision) const
{
std::ofstream out(_filename.c_str());
if (!out) {
omerr() << "[VTKWriter] : cannot open file " << _filename << std::endl;
return false;
}
return write(out, _be, _opt, _precision);
}
//-----------------------------------------------------------------------------
bool _VTKWriter_::write(std::ostream& _out, BaseExporter& _be, Options _opt, std::streamsize _precision) const
{
Vec3f v, n;
Vec2f t;
VertexHandle vh;
OpenMesh::Vec3f c;
OpenMesh::Vec4f cA;
// check exporter features
if (!check(_be, _opt)) {
return false;
}
// check writer features
if (!_opt.is_empty()) {
omlog() << "[VTKWriter] : writer does not support any options\n";
return false;
}
omlog() << "[VTKWriter] : write file\n";
_out.precision(_precision);
std::vector<VertexHandle> vhandles;
size_t polygon_table_size = 0;
size_t nf = _be.n_faces();
for (size_t i = 0; i < nf; ++i) {
polygon_table_size += _be.get_vhandles(FaceHandle(int(i)), vhandles);
}
polygon_table_size += nf;
// header
_out << "# vtk DataFile Version 3.0\n";
_out << "Generated by OpenMesh\n";
_out << "ASCII\n";
_out << "DATASET POLYDATA\n";
// points
_out << "POINTS " << _be.n_vertices() << " float\n";
size_t nv = _be.n_vertices();
for (size_t i = 0; i < nv; ++i) {
Vec3f v = _be.point(VertexHandle(int(i)));
_out << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';
}
// faces
_out << "POLYGONS " << nf << ' ' << polygon_table_size << '\n';
for (size_t i = 0; i < nf; ++i) {
_be.get_vhandles(FaceHandle(int(i)), vhandles);
_out << vhandles.size() << ' ';
for (size_t j = 0; j < vhandles.size(); ++j) {
_out << " " << vhandles[j].idx();
}
_out << '\n';
}
return true;
}
//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
|
{
"language": "C++"
}
|
/*
* replay.c
*
* Copyright (c) 2010-2015 Institute for System Programming
* of the Russian Academy of Sciences.
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
*/
#include "qemu-common.h"
#include "sysemu/replay.h"
#include "replay-internal.h"
#include "qemu/timer.h"
#include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "qemu/error-report.h"
/* Current version of the replay mechanism.
Increase it when file format changes. */
#define REPLAY_VERSION 0xe02002
/* Size of replay log header */
#define HEADER_SIZE (sizeof(uint32_t) + sizeof(uint64_t))
ReplayMode replay_mode = REPLAY_MODE_NONE;
/* Name of replay file */
static char *replay_filename;
ReplayState replay_state;
static GSList *replay_blockers;
bool replay_next_event_is(int event)
{
bool res = false;
/* nothing to skip - not all instructions used */
if (replay_state.instructions_count != 0) {
assert(replay_data_kind == EVENT_INSTRUCTION);
return event == EVENT_INSTRUCTION;
}
while (true) {
if (event == replay_data_kind) {
res = true;
}
switch (replay_data_kind) {
case EVENT_SHUTDOWN:
replay_finish_event();
qemu_system_shutdown_request();
break;
default:
/* clock, time_t, checkpoint and other events */
return res;
}
}
return res;
}
uint64_t replay_get_current_step(void)
{
return cpu_get_icount_raw();
}
int replay_get_instructions(void)
{
int res = 0;
replay_mutex_lock();
if (replay_next_event_is(EVENT_INSTRUCTION)) {
res = replay_state.instructions_count;
}
replay_mutex_unlock();
return res;
}
void replay_account_executed_instructions(void)
{
if (replay_mode == REPLAY_MODE_PLAY) {
replay_mutex_lock();
if (replay_state.instructions_count > 0) {
int count = (int)(replay_get_current_step()
- replay_state.current_step);
replay_state.instructions_count -= count;
replay_state.current_step += count;
if (replay_state.instructions_count == 0) {
assert(replay_data_kind == EVENT_INSTRUCTION);
replay_finish_event();
/* Wake up iothread. This is required because
timers will not expire until clock counters
will be read from the log. */
qemu_notify_event();
}
}
replay_mutex_unlock();
}
}
bool replay_exception(void)
{
if (replay_mode == REPLAY_MODE_RECORD) {
replay_save_instructions();
replay_mutex_lock();
replay_put_event(EVENT_EXCEPTION);
replay_mutex_unlock();
return true;
} else if (replay_mode == REPLAY_MODE_PLAY) {
bool res = replay_has_exception();
if (res) {
replay_mutex_lock();
replay_finish_event();
replay_mutex_unlock();
}
return res;
}
return true;
}
bool replay_has_exception(void)
{
bool res = false;
if (replay_mode == REPLAY_MODE_PLAY) {
replay_account_executed_instructions();
replay_mutex_lock();
res = replay_next_event_is(EVENT_EXCEPTION);
replay_mutex_unlock();
}
return res;
}
bool replay_interrupt(void)
{
if (replay_mode == REPLAY_MODE_RECORD) {
replay_save_instructions();
replay_mutex_lock();
replay_put_event(EVENT_INTERRUPT);
replay_mutex_unlock();
return true;
} else if (replay_mode == REPLAY_MODE_PLAY) {
bool res = replay_has_interrupt();
if (res) {
replay_mutex_lock();
replay_finish_event();
replay_mutex_unlock();
}
return res;
}
return true;
}
bool replay_has_interrupt(void)
{
bool res = false;
if (replay_mode == REPLAY_MODE_PLAY) {
replay_account_executed_instructions();
replay_mutex_lock();
res = replay_next_event_is(EVENT_INTERRUPT);
replay_mutex_unlock();
}
return res;
}
void replay_shutdown_request(void)
{
if (replay_mode == REPLAY_MODE_RECORD) {
replay_mutex_lock();
replay_put_event(EVENT_SHUTDOWN);
replay_mutex_unlock();
}
}
bool replay_checkpoint(ReplayCheckpoint checkpoint)
{
bool res = false;
assert(EVENT_CHECKPOINT + checkpoint <= EVENT_CHECKPOINT_LAST);
replay_save_instructions();
if (!replay_file) {
return true;
}
replay_mutex_lock();
if (replay_mode == REPLAY_MODE_PLAY) {
if (replay_next_event_is(EVENT_CHECKPOINT + checkpoint)) {
replay_finish_event();
} else if (replay_data_kind != EVENT_ASYNC) {
res = false;
goto out;
}
replay_read_events(checkpoint);
/* replay_read_events may leave some unread events.
Return false if not all of the events associated with
checkpoint were processed */
res = replay_data_kind != EVENT_ASYNC;
} else if (replay_mode == REPLAY_MODE_RECORD) {
replay_put_event(EVENT_CHECKPOINT + checkpoint);
replay_save_events(checkpoint);
res = true;
}
out:
replay_mutex_unlock();
return res;
}
static void replay_enable(const char *fname, int mode)
{
const char *fmode = NULL;
assert(!replay_file);
switch (mode) {
case REPLAY_MODE_RECORD:
fmode = "wb";
break;
case REPLAY_MODE_PLAY:
fmode = "rb";
break;
default:
fprintf(stderr, "Replay: internal error: invalid replay mode\n");
exit(1);
}
atexit(replay_finish);
replay_mutex_init();
replay_file = fopen(fname, fmode);
if (replay_file == NULL) {
fprintf(stderr, "Replay: open %s: %s\n", fname, strerror(errno));
exit(1);
}
replay_filename = g_strdup(fname);
replay_mode = mode;
replay_data_kind = -1;
replay_state.instructions_count = 0;
replay_state.current_step = 0;
/* skip file header for RECORD and check it for PLAY */
if (replay_mode == REPLAY_MODE_RECORD) {
fseek(replay_file, HEADER_SIZE, SEEK_SET);
} else if (replay_mode == REPLAY_MODE_PLAY) {
unsigned int version = replay_get_dword();
if (version != REPLAY_VERSION) {
fprintf(stderr, "Replay: invalid input log file version\n");
exit(1);
}
/* go to the beginning */
fseek(replay_file, HEADER_SIZE, SEEK_SET);
replay_fetch_data_kind();
}
replay_init_events();
}
void replay_configure(QemuOpts *opts)
{
const char *fname;
const char *rr;
ReplayMode mode = REPLAY_MODE_NONE;
rr = qemu_opt_get(opts, "rr");
if (!rr) {
/* Just enabling icount */
return;
} else if (!strcmp(rr, "record")) {
mode = REPLAY_MODE_RECORD;
} else if (!strcmp(rr, "replay")) {
mode = REPLAY_MODE_PLAY;
} else {
error_report("Invalid icount rr option: %s", rr);
exit(1);
}
fname = qemu_opt_get(opts, "rrfile");
if (!fname) {
error_report("File name not specified for replay");
exit(1);
}
replay_enable(fname, mode);
}
void replay_start(void)
{
if (replay_mode == REPLAY_MODE_NONE) {
return;
}
if (replay_blockers) {
error_report("Record/replay: %s",
error_get_pretty(replay_blockers->data));
exit(1);
}
if (!use_icount) {
error_report("Please enable icount to use record/replay");
exit(1);
}
/* Timer for snapshotting will be set up here. */
replay_enable_events();
}
void replay_finish(void)
{
if (replay_mode == REPLAY_MODE_NONE) {
return;
}
replay_save_instructions();
/* finalize the file */
if (replay_file) {
if (replay_mode == REPLAY_MODE_RECORD) {
/* write end event */
replay_put_event(EVENT_END);
/* write header */
fseek(replay_file, 0, SEEK_SET);
replay_put_dword(REPLAY_VERSION);
}
fclose(replay_file);
replay_file = NULL;
}
if (replay_filename) {
g_free(replay_filename);
replay_filename = NULL;
}
replay_finish_events();
replay_mutex_destroy();
}
void replay_add_blocker(Error *reason)
{
replay_blockers = g_slist_prepend(replay_blockers, reason);
}
|
{
"language": "C++"
}
|
/*
Copyright 2010 Kevin Ottens <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SOLID_BACKENDS_UDEV_DEVICEINTERFACE_H
#define SOLID_BACKENDS_UDEV_DEVICEINTERFACE_H
#include <solid-lite/ifaces/deviceinterface.h>
#include "udevdevice.h"
#include <QObject>
#include <QStringList>
namespace Solid
{
namespace Backends
{
namespace UDev
{
class DeviceInterface : public QObject, virtual public Solid::Ifaces::DeviceInterface
{
Q_OBJECT
Q_INTERFACES(Solid::Ifaces::DeviceInterface)
public:
DeviceInterface(UDevDevice *device);
~DeviceInterface() override;
protected:
UDevDevice *m_device;
};
}
}
}
#endif
|
{
"language": "C++"
}
|
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkStream_DEFINED
#define SkStream_DEFINED
#include "include/core/SkData.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkScalar.h"
#include "include/private/SkTo.h"
#include <memory.h>
class SkStream;
class SkStreamRewindable;
class SkStreamSeekable;
class SkStreamAsset;
class SkStreamMemory;
/**
* SkStream -- abstraction for a source of bytes. Subclasses can be backed by
* memory, or a file, or something else.
*
* NOTE:
*
* Classic "streams" APIs are sort of async, in that on a request for N
* bytes, they may return fewer than N bytes on a given call, in which case
* the caller can "try again" to get more bytes, eventually (modulo an error)
* receiving their total N bytes.
*
* Skia streams behave differently. They are effectively synchronous, and will
* always return all N bytes of the request if possible. If they return fewer
* (the read() call returns the number of bytes read) then that means there is
* no more data (at EOF or hit an error). The caller should *not* call again
* in hopes of fulfilling more of the request.
*/
class SK_API SkStream {
public:
virtual ~SkStream() {}
SkStream() {}
/**
* Attempts to open the specified file as a stream, returns nullptr on failure.
*/
static std::unique_ptr<SkStreamAsset> MakeFromFile(const char path[]);
/** Reads or skips size number of bytes.
* If buffer == NULL, skip size bytes, return how many were skipped.
* If buffer != NULL, copy size bytes into buffer, return how many were copied.
* @param buffer when NULL skip size bytes, otherwise copy size bytes into buffer
* @param size the number of bytes to skip or copy
* @return the number of bytes actually read.
*/
virtual size_t read(void* buffer, size_t size) = 0;
/** Skip size number of bytes.
* @return the actual number bytes that could be skipped.
*/
size_t skip(size_t size) {
return this->read(nullptr, size);
}
/**
* Attempt to peek at size bytes.
* If this stream supports peeking, copy min(size, peekable bytes) into
* buffer, and return the number of bytes copied.
* If the stream does not support peeking, or cannot peek any bytes,
* return 0 and leave buffer unchanged.
* The stream is guaranteed to be in the same visible state after this
* call, regardless of success or failure.
* @param buffer Must not be NULL, and must be at least size bytes. Destination
* to copy bytes.
* @param size Number of bytes to copy.
* @return The number of bytes peeked/copied.
*/
virtual size_t peek(void* /*buffer*/, size_t /*size*/) const { return 0; }
/** Returns true when all the bytes in the stream have been read.
* This may return true early (when there are no more bytes to be read)
* or late (after the first unsuccessful read).
*/
virtual bool isAtEnd() const = 0;
bool SK_WARN_UNUSED_RESULT readS8(int8_t*);
bool SK_WARN_UNUSED_RESULT readS16(int16_t*);
bool SK_WARN_UNUSED_RESULT readS32(int32_t*);
bool SK_WARN_UNUSED_RESULT readU8(uint8_t* i) { return this->readS8((int8_t*)i); }
bool SK_WARN_UNUSED_RESULT readU16(uint16_t* i) { return this->readS16((int16_t*)i); }
bool SK_WARN_UNUSED_RESULT readU32(uint32_t* i) { return this->readS32((int32_t*)i); }
bool SK_WARN_UNUSED_RESULT readBool(bool* b) {
uint8_t i;
if (!this->readU8(&i)) { return false; }
*b = (i != 0);
return true;
}
bool SK_WARN_UNUSED_RESULT readScalar(SkScalar*);
bool SK_WARN_UNUSED_RESULT readPackedUInt(size_t*);
//SkStreamRewindable
/** Rewinds to the beginning of the stream. Returns true if the stream is known
* to be at the beginning after this call returns.
*/
virtual bool rewind() { return false; }
/** Duplicates this stream. If this cannot be done, returns NULL.
* The returned stream will be positioned at the beginning of its data.
*/
std::unique_ptr<SkStream> duplicate() const {
return std::unique_ptr<SkStream>(this->onDuplicate());
}
/** Duplicates this stream. If this cannot be done, returns NULL.
* The returned stream will be positioned the same as this stream.
*/
std::unique_ptr<SkStream> fork() const {
return std::unique_ptr<SkStream>(this->onFork());
}
//SkStreamSeekable
/** Returns true if this stream can report it's current position. */
virtual bool hasPosition() const { return false; }
/** Returns the current position in the stream. If this cannot be done, returns 0. */
virtual size_t getPosition() const { return 0; }
/** Seeks to an absolute position in the stream. If this cannot be done, returns false.
* If an attempt is made to seek past the end of the stream, the position will be set
* to the end of the stream.
*/
virtual bool seek(size_t /*position*/) { return false; }
/** Seeks to an relative offset in the stream. If this cannot be done, returns false.
* If an attempt is made to move to a position outside the stream, the position will be set
* to the closest point within the stream (beginning or end).
*/
virtual bool move(long /*offset*/) { return false; }
//SkStreamAsset
/** Returns true if this stream can report it's total length. */
virtual bool hasLength() const { return false; }
/** Returns the total length of the stream. If this cannot be done, returns 0. */
virtual size_t getLength() const { return 0; }
//SkStreamMemory
/** Returns the starting address for the data. If this cannot be done, returns NULL. */
//TODO: replace with virtual const SkData* getData()
virtual const void* getMemoryBase() { return nullptr; }
private:
virtual SkStream* onDuplicate() const { return nullptr; }
virtual SkStream* onFork() const { return nullptr; }
SkStream(SkStream&&) = delete;
SkStream(const SkStream&) = delete;
SkStream& operator=(SkStream&&) = delete;
SkStream& operator=(const SkStream&) = delete;
};
/** SkStreamRewindable is a SkStream for which rewind and duplicate are required. */
class SK_API SkStreamRewindable : public SkStream {
public:
bool rewind() override = 0;
std::unique_ptr<SkStreamRewindable> duplicate() const {
return std::unique_ptr<SkStreamRewindable>(this->onDuplicate());
}
private:
SkStreamRewindable* onDuplicate() const override = 0;
};
/** SkStreamSeekable is a SkStreamRewindable for which position, seek, move, and fork are required. */
class SK_API SkStreamSeekable : public SkStreamRewindable {
public:
std::unique_ptr<SkStreamSeekable> duplicate() const {
return std::unique_ptr<SkStreamSeekable>(this->onDuplicate());
}
bool hasPosition() const override { return true; }
size_t getPosition() const override = 0;
bool seek(size_t position) override = 0;
bool move(long offset) override = 0;
std::unique_ptr<SkStreamSeekable> fork() const {
return std::unique_ptr<SkStreamSeekable>(this->onFork());
}
private:
SkStreamSeekable* onDuplicate() const override = 0;
SkStreamSeekable* onFork() const override = 0;
};
/** SkStreamAsset is a SkStreamSeekable for which getLength is required. */
class SK_API SkStreamAsset : public SkStreamSeekable {
public:
bool hasLength() const override { return true; }
size_t getLength() const override = 0;
std::unique_ptr<SkStreamAsset> duplicate() const {
return std::unique_ptr<SkStreamAsset>(this->onDuplicate());
}
std::unique_ptr<SkStreamAsset> fork() const {
return std::unique_ptr<SkStreamAsset>(this->onFork());
}
private:
SkStreamAsset* onDuplicate() const override = 0;
SkStreamAsset* onFork() const override = 0;
};
/** SkStreamMemory is a SkStreamAsset for which getMemoryBase is required. */
class SK_API SkStreamMemory : public SkStreamAsset {
public:
const void* getMemoryBase() override = 0;
std::unique_ptr<SkStreamMemory> duplicate() const {
return std::unique_ptr<SkStreamMemory>(this->onDuplicate());
}
std::unique_ptr<SkStreamMemory> fork() const {
return std::unique_ptr<SkStreamMemory>(this->onFork());
}
private:
SkStreamMemory* onDuplicate() const override = 0;
SkStreamMemory* onFork() const override = 0;
};
class SK_API SkWStream {
public:
virtual ~SkWStream();
SkWStream() {}
/** Called to write bytes to a SkWStream. Returns true on success
@param buffer the address of at least size bytes to be written to the stream
@param size The number of bytes in buffer to write to the stream
@return true on success
*/
virtual bool write(const void* buffer, size_t size) = 0;
virtual void flush();
virtual size_t bytesWritten() const = 0;
// helpers
bool write8(U8CPU value) {
uint8_t v = SkToU8(value);
return this->write(&v, 1);
}
bool write16(U16CPU value) {
uint16_t v = SkToU16(value);
return this->write(&v, 2);
}
bool write32(uint32_t v) {
return this->write(&v, 4);
}
bool writeText(const char text[]) {
SkASSERT(text);
return this->write(text, strlen(text));
}
bool newline() { return this->write("\n", strlen("\n")); }
bool writeDecAsText(int32_t);
bool writeBigDecAsText(int64_t, int minDigits = 0);
bool writeHexAsText(uint32_t, int minDigits = 0);
bool writeScalarAsText(SkScalar);
bool writeBool(bool v) { return this->write8(v); }
bool writeScalar(SkScalar);
bool writePackedUInt(size_t);
bool writeStream(SkStream* input, size_t length);
/**
* This returns the number of bytes in the stream required to store
* 'value'.
*/
static int SizeOfPackedUInt(size_t value);
private:
SkWStream(const SkWStream&) = delete;
SkWStream& operator=(const SkWStream&) = delete;
};
class SK_API SkNullWStream : public SkWStream {
public:
SkNullWStream() : fBytesWritten(0) {}
bool write(const void* , size_t n) override { fBytesWritten += n; return true; }
void flush() override {}
size_t bytesWritten() const override { return fBytesWritten; }
private:
size_t fBytesWritten;
};
////////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
/** A stream that wraps a C FILE* file stream. */
class SK_API SkFILEStream : public SkStreamAsset {
public:
/** Initialize the stream by calling sk_fopen on the specified path.
* This internal stream will be closed in the destructor.
*/
explicit SkFILEStream(const char path[] = nullptr);
/** Initialize the stream with an existing C FILE stream.
* The current position of the C FILE stream will be considered the
* beginning of the SkFILEStream.
* The C FILE stream will be closed in the destructor.
*/
explicit SkFILEStream(FILE* file);
~SkFILEStream() override;
static std::unique_ptr<SkFILEStream> Make(const char path[]) {
std::unique_ptr<SkFILEStream> stream(new SkFILEStream(path));
return stream->isValid() ? std::move(stream) : nullptr;
}
/** Returns true if the current path could be opened. */
bool isValid() const { return fFILE != nullptr; }
/** Close this SkFILEStream. */
void close();
size_t read(void* buffer, size_t size) override;
bool isAtEnd() const override;
bool rewind() override;
std::unique_ptr<SkStreamAsset> duplicate() const {
return std::unique_ptr<SkStreamAsset>(this->onDuplicate());
}
size_t getPosition() const override;
bool seek(size_t position) override;
bool move(long offset) override;
std::unique_ptr<SkStreamAsset> fork() const {
return std::unique_ptr<SkStreamAsset>(this->onFork());
}
size_t getLength() const override;
private:
explicit SkFILEStream(std::shared_ptr<FILE>, size_t size, size_t offset);
explicit SkFILEStream(std::shared_ptr<FILE>, size_t size, size_t offset, size_t originalOffset);
SkStreamAsset* onDuplicate() const override;
SkStreamAsset* onFork() const override;
std::shared_ptr<FILE> fFILE;
// My own council will I keep on sizes and offsets.
size_t fSize;
size_t fOffset;
size_t fOriginalOffset;
typedef SkStreamAsset INHERITED;
};
class SK_API SkMemoryStream : public SkStreamMemory {
public:
SkMemoryStream();
/** We allocate (and free) the memory. Write to it via getMemoryBase() */
SkMemoryStream(size_t length);
/** If copyData is true, the stream makes a private copy of the data. */
SkMemoryStream(const void* data, size_t length, bool copyData = false);
/** Creates the stream to read from the specified data */
SkMemoryStream(sk_sp<SkData> data);
/** Returns a stream with a copy of the input data. */
static std::unique_ptr<SkMemoryStream> MakeCopy(const void* data, size_t length);
/** Returns a stream with a bare pointer reference to the input data. */
static std::unique_ptr<SkMemoryStream> MakeDirect(const void* data, size_t length);
/** Returns a stream with a shared reference to the input data. */
static std::unique_ptr<SkMemoryStream> Make(sk_sp<SkData> data);
/** Resets the stream to the specified data and length,
just like the constructor.
if copyData is true, the stream makes a private copy of the data
*/
virtual void setMemory(const void* data, size_t length,
bool copyData = false);
/** Replace any memory buffer with the specified buffer. The caller
must have allocated data with sk_malloc or sk_realloc, since it
will be freed with sk_free.
*/
void setMemoryOwned(const void* data, size_t length);
sk_sp<SkData> asData() const { return fData; }
void setData(sk_sp<SkData> data);
void skipToAlign4();
const void* getAtPos();
size_t read(void* buffer, size_t size) override;
bool isAtEnd() const override;
size_t peek(void* buffer, size_t size) const override;
bool rewind() override;
std::unique_ptr<SkMemoryStream> duplicate() const {
return std::unique_ptr<SkMemoryStream>(this->onDuplicate());
}
size_t getPosition() const override;
bool seek(size_t position) override;
bool move(long offset) override;
std::unique_ptr<SkMemoryStream> fork() const {
return std::unique_ptr<SkMemoryStream>(this->onFork());
}
size_t getLength() const override;
const void* getMemoryBase() override;
private:
SkMemoryStream* onDuplicate() const override;
SkMemoryStream* onFork() const override;
sk_sp<SkData> fData;
size_t fOffset;
typedef SkStreamMemory INHERITED;
};
/////////////////////////////////////////////////////////////////////////////////////////////
class SK_API SkFILEWStream : public SkWStream {
public:
SkFILEWStream(const char path[]);
~SkFILEWStream() override;
/** Returns true if the current path could be opened.
*/
bool isValid() const { return fFILE != nullptr; }
bool write(const void* buffer, size_t size) override;
void flush() override;
void fsync();
size_t bytesWritten() const override;
private:
FILE* fFILE;
typedef SkWStream INHERITED;
};
class SK_API SkDynamicMemoryWStream : public SkWStream {
public:
SkDynamicMemoryWStream() = default;
SkDynamicMemoryWStream(SkDynamicMemoryWStream&&);
SkDynamicMemoryWStream& operator=(SkDynamicMemoryWStream&&);
~SkDynamicMemoryWStream() override;
bool write(const void* buffer, size_t size) override;
size_t bytesWritten() const override;
bool read(void* buffer, size_t offset, size_t size);
/** More efficient version of read(dst, 0, bytesWritten()). */
void copyTo(void* dst) const;
bool writeToStream(SkWStream* dst) const;
/** Equivalent to copyTo() followed by reset(), but may save memory use. */
void copyToAndReset(void* dst);
/** Equivalent to writeToStream() followed by reset(), but may save memory use. */
bool writeToAndReset(SkWStream* dst);
/** Equivalent to writeToStream() followed by reset(), but may save memory use.
When the dst is also a SkDynamicMemoryWStream, the implementation is constant time. */
bool writeToAndReset(SkDynamicMemoryWStream* dst);
/** Prepend this stream to dst, resetting this. */
void prependToAndReset(SkDynamicMemoryWStream* dst);
/** Return the contents as SkData, and then reset the stream. */
sk_sp<SkData> detachAsData();
/** Reset, returning a reader stream with the current content. */
std::unique_ptr<SkStreamAsset> detachAsStream();
/** Reset the stream to its original, empty, state. */
void reset();
void padToAlign4();
private:
struct Block;
Block* fHead = nullptr;
Block* fTail = nullptr;
size_t fBytesWrittenBeforeTail = 0;
#ifdef SK_DEBUG
void validate() const;
#else
void validate() const {}
#endif
// For access to the Block type.
friend class SkBlockMemoryStream;
friend class SkBlockMemoryRefCnt;
typedef SkWStream INHERITED;
};
#endif
|
{
"language": "C++"
}
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/chain/protocol/operations.hpp>
#include <graphene/chain/protocol/transaction.hpp>
namespace graphene { namespace app {
void operation_get_impacted_accounts(
const graphene::chain::operation& op,
boost::container::flat_set<graphene::chain::account_id_type>& result );
void transaction_get_impacted_accounts(
const graphene::chain::transaction& tx,
boost::container::flat_set<graphene::chain::account_id_type>& result );
} } // graphene::app
|
{
"language": "C++"
}
|
/*
__________
_____ __ __\______ \_____ _______ ______ ____ _______
/ \ | | \| ___/\__ \ \_ __ \/ ___/_/ __ \\_ __ \
| Y Y \| | /| | / __ \_| | \/\___ \ \ ___/ | | \/
|__|_| /|____/ |____| (____ /|__| /____ > \___ >|__|
\/ \/ \/ \/
Copyright (C) 2004-2013 Ingo Berg
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MU_PARSER_INT_H
#define MU_PARSER_INT_H
#include "muParserBase.h"
#include <vector>
/** \file
\brief Definition of a parser using integer value.
*/
namespace mu
{
/** \brief Mathematical expressions parser.
This version of the parser handles only integer numbers. It disables the built in operators thus it is
slower than muParser. Integer values are stored in the double value_type and converted if needed.
*/
class ParserInt : public ParserBase
{
private:
static int Round(value_type v) { return (int)(v + ((v>=0) ? 0.5 : -0.5) ); };
static value_type Abs(value_type);
static value_type Sign(value_type);
static value_type Ite(value_type, value_type, value_type);
// !! The unary Minus is a MUST, otherwise you cant use negative signs !!
static value_type UnaryMinus(value_type);
// Functions with variable number of arguments
static value_type Sum(const value_type* a_afArg, int a_iArgc); // sum
static value_type Min(const value_type* a_afArg, int a_iArgc); // minimum
static value_type Max(const value_type* a_afArg, int a_iArgc); // maximum
// binary operator callbacks
static value_type Add(value_type v1, value_type v2);
static value_type Sub(value_type v1, value_type v2);
static value_type Mul(value_type v1, value_type v2);
static value_type Div(value_type v1, value_type v2);
static value_type Mod(value_type v1, value_type v2);
static value_type Pow(value_type v1, value_type v2);
static value_type Shr(value_type v1, value_type v2);
static value_type Shl(value_type v1, value_type v2);
static value_type LogAnd(value_type v1, value_type v2);
static value_type LogOr(value_type v1, value_type v2);
static value_type And(value_type v1, value_type v2);
static value_type Or(value_type v1, value_type v2);
static value_type Xor(value_type v1, value_type v2);
static value_type Less(value_type v1, value_type v2);
static value_type Greater(value_type v1, value_type v2);
static value_type LessEq(value_type v1, value_type v2);
static value_type GreaterEq(value_type v1, value_type v2);
static value_type Equal(value_type v1, value_type v2);
static value_type NotEqual(value_type v1, value_type v2);
static value_type Not(value_type v1);
static int IsHexVal(const char_type* a_szExpr, int *a_iPos, value_type *a_iVal);
static int IsBinVal(const char_type* a_szExpr, int *a_iPos, value_type *a_iVal);
static int IsVal (const char_type* a_szExpr, int *a_iPos, value_type *a_iVal);
/** \brief A facet class used to change decimal and thousands separator. */
template<class TChar>
class change_dec_sep : public std::numpunct<TChar>
{
public:
explicit change_dec_sep(char_type cDecSep, char_type cThousandsSep = 0, int nGroup = 3)
:std::numpunct<TChar>()
,m_cDecPoint(cDecSep)
,m_cThousandsSep(cThousandsSep)
,m_nGroup(nGroup)
{}
protected:
virtual char_type do_decimal_point() const
{
return m_cDecPoint;
}
virtual char_type do_thousands_sep() const
{
return m_cThousandsSep;
}
virtual std::string do_grouping() const
{
// fix for issue 4: https://code.google.com/p/muparser/issues/detail?id=4
// courtesy of Jens Bartsch
// original code:
// return std::string(1, (char)m_nGroup);
// new code:
return std::string(1, (char)(m_cThousandsSep > 0 ? m_nGroup : CHAR_MAX));
}
private:
int m_nGroup;
char_type m_cDecPoint;
char_type m_cThousandsSep;
};
public:
ParserInt();
virtual void InitFun();
virtual void InitOprt();
virtual void InitConst();
virtual void InitCharSets();
};
} // namespace mu
#endif
|
{
"language": "C++"
}
|
/*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
* Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero>
* Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org>
* Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/// \addtogroup realmd
/// @{
/// \file
#ifndef _REALMLIST_H
#define _REALMLIST_H
#include "Common.h"
struct RealmBuildInfo
{
int build;
int major_version;
int minor_version;
int bugfix_version;
int hotfix_version;
};
RealmBuildInfo const* FindBuildInfo(uint16 _build);
typedef std::set<uint32> RealmBuilds;
/// Storage object for a realm
struct Realm
{
std::string address;
uint8 icon;
RealmFlags realmflags; // realmflags
uint8 timezone;
uint32 m_ID;
AccountTypes allowedSecurityLevel; // current allowed join security level (show as locked for not fit accounts)
float populationLevel;
RealmBuilds realmbuilds; // list of supported builds (updated in DB by mangosd)
RealmBuildInfo realmBuildInfo; // build info for show version in list
};
/// Storage object for the list of realms on the server
class RealmList
{
public:
typedef std::map<std::string, Realm> RealmMap;
static RealmList& Instance();
RealmList();
~RealmList() {}
void Initialize(uint32 updateInterval);
void UpdateIfNeed();
RealmMap::const_iterator begin() const { return m_realms.begin(); }
RealmMap::const_iterator end() const { return m_realms.end(); }
uint32 size() const { return m_realms.size(); }
private:
void UpdateRealms(bool init);
void UpdateRealm( uint32 ID, const std::string& name, const std::string& address, uint32 port, uint8 icon, RealmFlags realmflags, uint8 timezone, AccountTypes allowedSecurityLevel, float popu, const std::string& builds);
private:
RealmMap m_realms; ///< Internal map of realms
uint32 m_UpdateInterval;
time_t m_NextUpdateTime;
};
#define sRealmList RealmList::Instance()
#endif
/// @}
|
{
"language": "C++"
}
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#pragma once
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Documentation for the API is available at https://renderdoc.org/docs/in_application_api.html
//
#if !defined(RENDERDOC_NO_STDINT)
#include <stdint.h>
#endif
#if defined(WIN32)
#define RENDERDOC_CC __cdecl
#elif defined(__linux__)
#define RENDERDOC_CC
#elif defined(__APPLE__)
#define RENDERDOC_CC
#else
#error "Unknown platform"
#endif
#ifdef __cplusplus
extern "C" {
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////
// Constants not used directly in below API
// This is a GUID/magic value used for when applications pass a path where shader debug
// information can be found to match up with a stripped shader.
// the define can be used like so: const GUID RENDERDOC_ShaderDebugMagicValue =
// RENDERDOC_ShaderDebugMagicValue_value
#define RENDERDOC_ShaderDebugMagicValue_struct \
{ \
0xeab25520, 0x6670, 0x4865, 0x84, 0x29, 0x6c, 0x8, 0x51, 0x54, 0x00, 0xff \
}
// as an alternative when you want a byte array (assuming x86 endianness):
#define RENDERDOC_ShaderDebugMagicValue_bytearray \
{ \
0x20, 0x55, 0xb2, 0xea, 0x70, 0x66, 0x65, 0x48, 0x84, 0x29, 0x6c, 0x8, 0x51, 0x54, 0x00, 0xff \
}
// truncated version when only a uint64_t is available (e.g. Vulkan tags):
#define RENDERDOC_ShaderDebugMagicValue_truncated 0x48656670eab25520ULL
//////////////////////////////////////////////////////////////////////////////////////////////////
// RenderDoc capture options
//
typedef enum {
// Allow the application to enable vsync
//
// Default - enabled
//
// 1 - The application can enable or disable vsync at will
// 0 - vsync is force disabled
eRENDERDOC_Option_AllowVSync = 0,
// Allow the application to enable fullscreen
//
// Default - enabled
//
// 1 - The application can enable or disable fullscreen at will
// 0 - fullscreen is force disabled
eRENDERDOC_Option_AllowFullscreen = 1,
// Record API debugging events and messages
//
// Default - disabled
//
// 1 - Enable built-in API debugging features and records the results into
// the capture, which is matched up with events on replay
// 0 - no API debugging is forcibly enabled
eRENDERDOC_Option_APIValidation = 2,
eRENDERDOC_Option_DebugDeviceMode = 2, // deprecated name of this enum
// Capture CPU callstacks for API events
//
// Default - disabled
//
// 1 - Enables capturing of callstacks
// 0 - no callstacks are captured
eRENDERDOC_Option_CaptureCallstacks = 3,
// When capturing CPU callstacks, only capture them from drawcalls.
// This option does nothing without the above option being enabled
//
// Default - disabled
//
// 1 - Only captures callstacks for drawcall type API events.
// Ignored if CaptureCallstacks is disabled
// 0 - Callstacks, if enabled, are captured for every event.
eRENDERDOC_Option_CaptureCallstacksOnlyDraws = 4,
// Specify a delay in seconds to wait for a debugger to attach, after
// creating or injecting into a process, before continuing to allow it to run.
//
// 0 indicates no delay, and the process will run immediately after injection
//
// Default - 0 seconds
//
eRENDERDOC_Option_DelayForDebugger = 5,
// Verify any writes to mapped buffers, by checking the memory after the
// bounds of the returned pointer to detect any modification.
//
// Default - disabled
//
// 1 - Verify any writes to mapped buffers
// 0 - No verification is performed, and overwriting bounds may cause
// crashes or corruption in RenderDoc
eRENDERDOC_Option_VerifyMapWrites = 6,
// Hooks any system API calls that create child processes, and injects
// RenderDoc into them recursively with the same options.
//
// Default - disabled
//
// 1 - Hooks into spawned child processes
// 0 - Child processes are not hooked by RenderDoc
eRENDERDOC_Option_HookIntoChildren = 7,
// By default RenderDoc only includes resources in the final capture necessary
// for that frame, this allows you to override that behaviour.
//
// Default - disabled
//
// 1 - all live resources at the time of capture are included in the capture
// and available for inspection
// 0 - only the resources referenced by the captured frame are included
eRENDERDOC_Option_RefAllResources = 8,
// By default RenderDoc skips saving initial states for resources where the
// previous contents don't appear to be used, assuming that writes before
// reads indicate previous contents aren't used.
//
// Default - disabled
//
// 1 - initial contents at the start of each captured frame are saved, even if
// they are later overwritten or cleared before being used.
// 0 - unless a read is detected, initial contents will not be saved and will
// appear as black or empty data.
eRENDERDOC_Option_SaveAllInitials = 9,
// In APIs that allow for the recording of command lists to be replayed later,
// RenderDoc may choose to not capture command lists before a frame capture is
// triggered, to reduce overheads. This means any command lists recorded once
// and replayed many times will not be available and may cause a failure to
// capture.
//
// Note this is only true for APIs where multithreading is difficult or
// discouraged. Newer APIs like Vulkan and D3D12 will ignore this option
// and always capture all command lists since the API is heavily oriented
// around it and the overheads have been reduced by API design.
//
// 1 - All command lists are captured from the start of the application
// 0 - Command lists are only captured if their recording begins during
// the period when a frame capture is in progress.
eRENDERDOC_Option_CaptureAllCmdLists = 10,
// Mute API debugging output when the API validation mode option is enabled
//
// Default - enabled
//
// 1 - Mute any API debug messages from being displayed or passed through
// 0 - API debugging is displayed as normal
eRENDERDOC_Option_DebugOutputMute = 11,
} RENDERDOC_CaptureOption;
// Sets an option that controls how RenderDoc behaves on capture.
//
// Returns 1 if the option and value are valid
// Returns 0 if either is invalid and the option is unchanged
typedef int(RENDERDOC_CC *pRENDERDOC_SetCaptureOptionU32)(RENDERDOC_CaptureOption opt, uint32_t val);
typedef int(RENDERDOC_CC *pRENDERDOC_SetCaptureOptionF32)(RENDERDOC_CaptureOption opt, float val);
// Gets the current value of an option as a uint32_t
//
// If the option is invalid, 0xffffffff is returned
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetCaptureOptionU32)(RENDERDOC_CaptureOption opt);
// Gets the current value of an option as a float
//
// If the option is invalid, -FLT_MAX is returned
typedef float(RENDERDOC_CC *pRENDERDOC_GetCaptureOptionF32)(RENDERDOC_CaptureOption opt);
typedef enum {
// '0' - '9' matches ASCII values
eRENDERDOC_Key_0 = 0x30,
eRENDERDOC_Key_1 = 0x31,
eRENDERDOC_Key_2 = 0x32,
eRENDERDOC_Key_3 = 0x33,
eRENDERDOC_Key_4 = 0x34,
eRENDERDOC_Key_5 = 0x35,
eRENDERDOC_Key_6 = 0x36,
eRENDERDOC_Key_7 = 0x37,
eRENDERDOC_Key_8 = 0x38,
eRENDERDOC_Key_9 = 0x39,
// 'A' - 'Z' matches ASCII values
eRENDERDOC_Key_A = 0x41,
eRENDERDOC_Key_B = 0x42,
eRENDERDOC_Key_C = 0x43,
eRENDERDOC_Key_D = 0x44,
eRENDERDOC_Key_E = 0x45,
eRENDERDOC_Key_F = 0x46,
eRENDERDOC_Key_G = 0x47,
eRENDERDOC_Key_H = 0x48,
eRENDERDOC_Key_I = 0x49,
eRENDERDOC_Key_J = 0x4A,
eRENDERDOC_Key_K = 0x4B,
eRENDERDOC_Key_L = 0x4C,
eRENDERDOC_Key_M = 0x4D,
eRENDERDOC_Key_N = 0x4E,
eRENDERDOC_Key_O = 0x4F,
eRENDERDOC_Key_P = 0x50,
eRENDERDOC_Key_Q = 0x51,
eRENDERDOC_Key_R = 0x52,
eRENDERDOC_Key_S = 0x53,
eRENDERDOC_Key_T = 0x54,
eRENDERDOC_Key_U = 0x55,
eRENDERDOC_Key_V = 0x56,
eRENDERDOC_Key_W = 0x57,
eRENDERDOC_Key_X = 0x58,
eRENDERDOC_Key_Y = 0x59,
eRENDERDOC_Key_Z = 0x5A,
// leave the rest of the ASCII range free
// in case we want to use it later
eRENDERDOC_Key_NonPrintable = 0x100,
eRENDERDOC_Key_Divide,
eRENDERDOC_Key_Multiply,
eRENDERDOC_Key_Subtract,
eRENDERDOC_Key_Plus,
eRENDERDOC_Key_F1,
eRENDERDOC_Key_F2,
eRENDERDOC_Key_F3,
eRENDERDOC_Key_F4,
eRENDERDOC_Key_F5,
eRENDERDOC_Key_F6,
eRENDERDOC_Key_F7,
eRENDERDOC_Key_F8,
eRENDERDOC_Key_F9,
eRENDERDOC_Key_F10,
eRENDERDOC_Key_F11,
eRENDERDOC_Key_F12,
eRENDERDOC_Key_Home,
eRENDERDOC_Key_End,
eRENDERDOC_Key_Insert,
eRENDERDOC_Key_Delete,
eRENDERDOC_Key_PageUp,
eRENDERDOC_Key_PageDn,
eRENDERDOC_Key_Backspace,
eRENDERDOC_Key_Tab,
eRENDERDOC_Key_PrtScrn,
eRENDERDOC_Key_Pause,
eRENDERDOC_Key_Max,
} RENDERDOC_InputButton;
// Sets which key or keys can be used to toggle focus between multiple windows
//
// If keys is NULL or num is 0, toggle keys will be disabled
typedef void(RENDERDOC_CC *pRENDERDOC_SetFocusToggleKeys)(RENDERDOC_InputButton *keys, int num);
// Sets which key or keys can be used to capture the next frame
//
// If keys is NULL or num is 0, captures keys will be disabled
typedef void(RENDERDOC_CC *pRENDERDOC_SetCaptureKeys)(RENDERDOC_InputButton *keys, int num);
typedef enum {
// This single bit controls whether the overlay is enabled or disabled globally
eRENDERDOC_Overlay_Enabled = 0x1,
// Show the average framerate over several seconds as well as min/max
eRENDERDOC_Overlay_FrameRate = 0x2,
// Show the current frame number
eRENDERDOC_Overlay_FrameNumber = 0x4,
// Show a list of recent captures, and how many captures have been made
eRENDERDOC_Overlay_CaptureList = 0x8,
// Default values for the overlay mask
eRENDERDOC_Overlay_Default = (eRENDERDOC_Overlay_Enabled | eRENDERDOC_Overlay_FrameRate |
eRENDERDOC_Overlay_FrameNumber | eRENDERDOC_Overlay_CaptureList),
// Enable all bits
eRENDERDOC_Overlay_All = ~0U,
// Disable all bits
eRENDERDOC_Overlay_None = 0,
} RENDERDOC_OverlayBits;
// returns the overlay bits that have been set
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetOverlayBits)();
// sets the overlay bits with an and & or mask
typedef void(RENDERDOC_CC *pRENDERDOC_MaskOverlayBits)(uint32_t And, uint32_t Or);
// this function will attempt to shut down RenderDoc.
//
// Note: that this will only work correctly if done immediately after
// the dll is loaded, before any API work happens. RenderDoc will remove its
// injected hooks and shut down. Behaviour is undefined if this is called
// after any API functions have been called.
typedef void(RENDERDOC_CC *pRENDERDOC_Shutdown)();
// This function will unload RenderDoc's crash handler.
//
// If you use your own crash handler and don't want RenderDoc's handler to
// intercede, you can call this function to unload it and any unhandled
// exceptions will pass to the next handler.
typedef void(RENDERDOC_CC *pRENDERDOC_UnloadCrashHandler)();
// Sets the capture file path template
//
// pathtemplate is a UTF-8 string that gives a template for how captures will be named
// and where they will be saved.
//
// Any extension is stripped off the path, and captures are saved in the directory
// specified, and named with the filename and the frame number appended. If the
// directory does not exist it will be created, including any parent directories.
//
// If pathtemplate is NULL, the template will remain unchanged
//
// Example:
//
// SetCaptureFilePathTemplate("my_captures/example");
//
// Capture #1 -> my_captures/example_frame123.rdc
// Capture #2 -> my_captures/example_frame456.rdc
typedef void(RENDERDOC_CC *pRENDERDOC_SetCaptureFilePathTemplate)(const char *pathtemplate);
// returns the current capture path template, see SetCaptureFileTemplate above, as a UTF-8 string
typedef const char *(RENDERDOC_CC *pRENDERDOC_GetCaptureFilePathTemplate)();
// DEPRECATED: compatibility for code compiled against pre-1.1.2 headers.
typedef void(RENDERDOC_CC *pRENDERDOC_SetLogFilePathTemplate)(const char *pathtemplate);
typedef const char *(RENDERDOC_CC *pRENDERDOC_GetLogFilePathTemplate)();
// returns the number of captures that have been made
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetNumCaptures)();
// This function returns the details of a capture, by index. New captures are added
// to the end of the list.
//
// filename will be filled with the absolute path to the capture file, as a UTF-8 string
// pathlength will be written with the length in bytes of the filename string
// timestamp will be written with the time of the capture, in seconds since the Unix epoch
//
// Any of the parameters can be NULL and they'll be skipped.
//
// The function will return 1 if the capture index is valid, or 0 if the index is invalid
// If the index is invalid, the values will be unchanged
//
// Note: when captures are deleted in the UI they will remain in this list, so the
// capture path may not exist anymore.
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetCapture)(uint32_t idx, char *filename,
uint32_t *pathlength, uint64_t *timestamp);
// returns 1 if the RenderDoc UI is connected to this application, 0 otherwise
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_IsTargetControlConnected)();
// DEPRECATED: compatibility for code compiled against pre-1.1.1 headers.
// This was renamed to IsTargetControlConnected in API 1.1.1, the old typedef is kept here for
// backwards compatibility with old code, it is castable either way since it's ABI compatible
// as the same function pointer type.
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_IsRemoteAccessConnected)();
// This function will launch the Replay UI associated with the RenderDoc library injected
// into the running application.
//
// if connectTargetControl is 1, the Replay UI will be launched with a command line parameter
// to connect to this application
// cmdline is the rest of the command line, as a UTF-8 string. E.g. a captures to open
// if cmdline is NULL, the command line will be empty.
//
// returns the PID of the replay UI if successful, 0 if not successful.
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_LaunchReplayUI)(uint32_t connectTargetControl,
const char *cmdline);
// RenderDoc can return a higher version than requested if it's backwards compatible,
// this function returns the actual version returned. If a parameter is NULL, it will be
// ignored and the others will be filled out.
typedef void(RENDERDOC_CC *pRENDERDOC_GetAPIVersion)(int *major, int *minor, int *patch);
//////////////////////////////////////////////////////////////////////////
// Capturing functions
//
// A device pointer is a pointer to the API's root handle.
//
// This would be an ID3D11Device, HGLRC/GLXContext, ID3D12Device, etc
typedef void *RENDERDOC_DevicePointer;
// A window handle is the OS's native window handle
//
// This would be an HWND, GLXDrawable, etc
typedef void *RENDERDOC_WindowHandle;
// A helper macro for Vulkan, where the device handle cannot be used directly.
//
// Passing the VkInstance to this macro will return the RENDERDOC_DevicePointer to use.
//
// Specifically, the value needed is the dispatch table pointer, which sits as the first
// pointer-sized object in the memory pointed to by the VkInstance. Thus we cast to a void** and
// indirect once.
#define RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(inst) (*((void **)(inst)))
// This sets the RenderDoc in-app overlay in the API/window pair as 'active' and it will
// respond to keypresses. Neither parameter can be NULL
typedef void(RENDERDOC_CC *pRENDERDOC_SetActiveWindow)(RENDERDOC_DevicePointer device,
RENDERDOC_WindowHandle wndHandle);
// capture the next frame on whichever window and API is currently considered active
typedef void(RENDERDOC_CC *pRENDERDOC_TriggerCapture)();
// capture the next N frames on whichever window and API is currently considered active
typedef void(RENDERDOC_CC *pRENDERDOC_TriggerMultiFrameCapture)(uint32_t numFrames);
// When choosing either a device pointer or a window handle to capture, you can pass NULL.
// Passing NULL specifies a 'wildcard' match against anything. This allows you to specify
// any API rendering to a specific window, or a specific API instance rendering to any window,
// or in the simplest case of one window and one API, you can just pass NULL for both.
//
// In either case, if there are two or more possible matching (device,window) pairs it
// is undefined which one will be captured.
//
// Note: for headless rendering you can pass NULL for the window handle and either specify
// a device pointer or leave it NULL as above.
// Immediately starts capturing API calls on the specified device pointer and window handle.
//
// If there is no matching thing to capture (e.g. no supported API has been initialised),
// this will do nothing.
//
// The results are undefined (including crashes) if two captures are started overlapping,
// even on separate devices and/oror windows.
typedef void(RENDERDOC_CC *pRENDERDOC_StartFrameCapture)(RENDERDOC_DevicePointer device,
RENDERDOC_WindowHandle wndHandle);
// Returns whether or not a frame capture is currently ongoing anywhere.
//
// This will return 1 if a capture is ongoing, and 0 if there is no capture running
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_IsFrameCapturing)();
// Ends capturing immediately.
//
// This will return 1 if the capture succeeded, and 0 if there was an error capturing.
typedef uint32_t(RENDERDOC_CC *pRENDERDOC_EndFrameCapture)(RENDERDOC_DevicePointer device,
RENDERDOC_WindowHandle wndHandle);
//////////////////////////////////////////////////////////////////////////////////////////////////
// RenderDoc API versions
//
// RenderDoc uses semantic versioning (http://semver.org/).
//
// MAJOR version is incremented when incompatible API changes happen.
// MINOR version is incremented when functionality is added in a backwards-compatible manner.
// PATCH version is incremented when backwards-compatible bug fixes happen.
//
// Note that this means the API returned can be higher than the one you might have requested.
// e.g. if you are running against a newer RenderDoc that supports 1.0.1, it will be returned
// instead of 1.0.0. You can check this with the GetAPIVersion entry point
typedef enum {
eRENDERDOC_API_Version_1_0_0 = 10000, // RENDERDOC_API_1_0_0 = 1 00 00
eRENDERDOC_API_Version_1_0_1 = 10001, // RENDERDOC_API_1_0_1 = 1 00 01
eRENDERDOC_API_Version_1_0_2 = 10002, // RENDERDOC_API_1_0_2 = 1 00 02
eRENDERDOC_API_Version_1_1_0 = 10100, // RENDERDOC_API_1_1_0 = 1 01 00
eRENDERDOC_API_Version_1_1_1 = 10101, // RENDERDOC_API_1_1_1 = 1 01 01
eRENDERDOC_API_Version_1_1_2 = 10102, // RENDERDOC_API_1_1_2 = 1 01 02
} RENDERDOC_Version;
// API version changelog:
//
// 1.0.0 - initial release
// 1.0.1 - Bugfix: IsFrameCapturing() was returning false for captures that were triggered
// by keypress or TriggerCapture, instead of Start/EndFrameCapture.
// 1.0.2 - Refactor: Renamed eRENDERDOC_Option_DebugDeviceMode to eRENDERDOC_Option_APIValidation
// 1.1.0 - Add feature: TriggerMultiFrameCapture(). Backwards compatible with 1.0.x since the new
// function pointer is added to the end of the struct, the original layout is identical
// 1.1.1 - Refactor: Renamed remote access to target control (to better disambiguate from remote
// replay/remote server concept in replay UI)
// 1.1.2 - Refactor: Renamed "log file" in function names to just capture, to clarify that these
// are captures and not debug logging files. This is the first API version in the v1.0
// branch.
// eRENDERDOC_API_Version_1_1_0
typedef struct
{
pRENDERDOC_GetAPIVersion GetAPIVersion;
pRENDERDOC_SetCaptureOptionU32 SetCaptureOptionU32;
pRENDERDOC_SetCaptureOptionF32 SetCaptureOptionF32;
pRENDERDOC_GetCaptureOptionU32 GetCaptureOptionU32;
pRENDERDOC_GetCaptureOptionF32 GetCaptureOptionF32;
pRENDERDOC_SetFocusToggleKeys SetFocusToggleKeys;
pRENDERDOC_SetCaptureKeys SetCaptureKeys;
pRENDERDOC_GetOverlayBits GetOverlayBits;
pRENDERDOC_MaskOverlayBits MaskOverlayBits;
pRENDERDOC_Shutdown Shutdown;
pRENDERDOC_UnloadCrashHandler UnloadCrashHandler;
pRENDERDOC_SetLogFilePathTemplate SetLogFilePathTemplate;
pRENDERDOC_GetLogFilePathTemplate GetLogFilePathTemplate;
pRENDERDOC_GetNumCaptures GetNumCaptures;
pRENDERDOC_GetCapture GetCapture;
pRENDERDOC_TriggerCapture TriggerCapture;
pRENDERDOC_IsRemoteAccessConnected IsRemoteAccessConnected;
pRENDERDOC_LaunchReplayUI LaunchReplayUI;
pRENDERDOC_SetActiveWindow SetActiveWindow;
pRENDERDOC_StartFrameCapture StartFrameCapture;
pRENDERDOC_IsFrameCapturing IsFrameCapturing;
pRENDERDOC_EndFrameCapture EndFrameCapture;
pRENDERDOC_TriggerMultiFrameCapture TriggerMultiFrameCapture;
} RENDERDOC_API_1_1_0;
typedef RENDERDOC_API_1_1_0 RENDERDOC_API_1_0_0;
typedef RENDERDOC_API_1_1_0 RENDERDOC_API_1_0_1;
typedef RENDERDOC_API_1_1_0 RENDERDOC_API_1_0_2;
// although this structure is identical to RENDERDOC_API_1_1_0, the member
// IsRemoteAccessConnected was renamed to IsTargetControlConnected. So that
// old code can still compile with a new header, we must declare a new struct
// type. It can be casted back and forth though, so we will still return a
// pointer to this type for all previous API versions - the above struct is
// purely legacy for compilation compatibility
// eRENDERDOC_API_Version_1_1_1
typedef struct
{
pRENDERDOC_GetAPIVersion GetAPIVersion;
pRENDERDOC_SetCaptureOptionU32 SetCaptureOptionU32;
pRENDERDOC_SetCaptureOptionF32 SetCaptureOptionF32;
pRENDERDOC_GetCaptureOptionU32 GetCaptureOptionU32;
pRENDERDOC_GetCaptureOptionF32 GetCaptureOptionF32;
pRENDERDOC_SetFocusToggleKeys SetFocusToggleKeys;
pRENDERDOC_SetCaptureKeys SetCaptureKeys;
pRENDERDOC_GetOverlayBits GetOverlayBits;
pRENDERDOC_MaskOverlayBits MaskOverlayBits;
pRENDERDOC_Shutdown Shutdown;
pRENDERDOC_UnloadCrashHandler UnloadCrashHandler;
pRENDERDOC_SetLogFilePathTemplate SetLogFilePathTemplate;
pRENDERDOC_GetLogFilePathTemplate GetLogFilePathTemplate;
pRENDERDOC_GetNumCaptures GetNumCaptures;
pRENDERDOC_GetCapture GetCapture;
pRENDERDOC_TriggerCapture TriggerCapture;
pRENDERDOC_IsTargetControlConnected IsTargetControlConnected;
pRENDERDOC_LaunchReplayUI LaunchReplayUI;
pRENDERDOC_SetActiveWindow SetActiveWindow;
pRENDERDOC_StartFrameCapture StartFrameCapture;
pRENDERDOC_IsFrameCapturing IsFrameCapturing;
pRENDERDOC_EndFrameCapture EndFrameCapture;
pRENDERDOC_TriggerMultiFrameCapture TriggerMultiFrameCapture;
} RENDERDOC_API_1_1_1;
// similarly to above, we renamed Get/SetLogFilePathTemplate to Get/SetCaptureFilePathTemplate.
// We thus declare a new struct so that code that was referencing the RENDERDOC_API_1_1_1 struct
// can still compile without changes, but new code will use the new struct members
// eRENDERDOC_API_Version_1_1_2
typedef struct
{
pRENDERDOC_GetAPIVersion GetAPIVersion;
pRENDERDOC_SetCaptureOptionU32 SetCaptureOptionU32;
pRENDERDOC_SetCaptureOptionF32 SetCaptureOptionF32;
pRENDERDOC_GetCaptureOptionU32 GetCaptureOptionU32;
pRENDERDOC_GetCaptureOptionF32 GetCaptureOptionF32;
pRENDERDOC_SetFocusToggleKeys SetFocusToggleKeys;
pRENDERDOC_SetCaptureKeys SetCaptureKeys;
pRENDERDOC_GetOverlayBits GetOverlayBits;
pRENDERDOC_MaskOverlayBits MaskOverlayBits;
pRENDERDOC_Shutdown Shutdown;
pRENDERDOC_UnloadCrashHandler UnloadCrashHandler;
pRENDERDOC_SetCaptureFilePathTemplate SetCaptureFilePathTemplate;
pRENDERDOC_GetCaptureFilePathTemplate GetCaptureFilePathTemplate;
pRENDERDOC_GetNumCaptures GetNumCaptures;
pRENDERDOC_GetCapture GetCapture;
pRENDERDOC_TriggerCapture TriggerCapture;
pRENDERDOC_IsTargetControlConnected IsTargetControlConnected;
pRENDERDOC_LaunchReplayUI LaunchReplayUI;
pRENDERDOC_SetActiveWindow SetActiveWindow;
pRENDERDOC_StartFrameCapture StartFrameCapture;
pRENDERDOC_IsFrameCapturing IsFrameCapturing;
pRENDERDOC_EndFrameCapture EndFrameCapture;
pRENDERDOC_TriggerMultiFrameCapture TriggerMultiFrameCapture;
} RENDERDOC_API_1_1_2;
//////////////////////////////////////////////////////////////////////////////////////////////////
// RenderDoc API entry point
//
// This entry point can be obtained via GetProcAddress/dlsym if RenderDoc is available.
//
// The name is the same as the typedef - "RENDERDOC_GetAPI"
//
// This function is not thread safe, and should not be called on multiple threads at once.
// Ideally, call this once as early as possible in your application's startup, before doing
// any API work, since some configuration functionality etc has to be done also before
// initialising any APIs.
//
// Parameters:
// version is a single value from the RENDERDOC_Version above.
//
// outAPIPointers will be filled out with a pointer to the corresponding struct of function
// pointers.
//
// Returns:
// 1 - if the outAPIPointers has been filled with a pointer to the API struct requested
// 0 - if the requested version is not supported or the arguments are invalid.
//
typedef int(RENDERDOC_CC *pRENDERDOC_GetAPI)(RENDERDOC_Version version, void **outAPIPointers);
#ifdef __cplusplus
} // extern "C"
#endif
|
{
"language": "C++"
}
|
/**
* Copyright (c) 2017-present, Facebook, Inc.
* 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.
*/
#pragma once
#include <utility>
#include "pybind_helper.h"
#include "python_options_utils_cpp.h"
#include "circular_queue.h"
#include "copier.hh"
#include "common.h"
template <typename _Data>
class HistT {
public:
using Data = _Data;
using State = typename Data::State;
using DataPrepareReturn = decltype(std::declval<Data>().Prepare(SeqInfo()));
private:
std::unique_ptr<CircularQueue<Data>> _h;
public:
HistT() { }
HistT(const HistT<Data> &other) {
_h.reset(new CircularQueue<Data>(*other._h));
}
void InitHist(int len) {
_h.reset(new CircularQueue<Data>(len));
}
void Restart() {
// Cannot clear history, For game whose reward is only revealed in the end,
// clear history will lead to even sparser reward (since for a long trajectory,
// the state with the reward will appear only in the end).
// _h->clear();
}
DataPrepareReturn Prepare(const SeqInfo &seq) {
// we move the history forward.
return _h->GetRoom().Prepare(seq);
}
// Note that these two will be called after .Push, so we need to retrieve them from .newest().
// TODO: Make them consistent.
int size() const { return _h->size(); }
std::vector<Data> &v() { return _h->v(); }
const std::vector<Data> &v() const { return _h->v(); }
// oldest = 0, newest = _h->maxlen() - 1
Data &oldest(int i = 0) { return _h->get_from_push(_h->maxlen() - i - 1); }
const Data &oldest(int i = 0) const { return _h->get_from_push(_h->maxlen() - i - 1); }
Data &newest(int i = 0) {
// std::cout << "[" << _h->get_from_push(i).id << "] newest(" << i << ")" << std::endl;
return _h->get_from_push(i);
}
const Data &newest(int i = 0) const { return _h->get_from_push(i); }
REGISTER_PYBIND;
};
namespace elf {
template <typename State>
void CopyToMem(const std::vector<CopyItemT<State>> &copier, const std::vector<HistT<State> *> &batch) {
if (batch.empty()) return;
size_t batchsize = batch.size();
size_t overall_hist_len = batch[0]->size();
for (const auto& item: copier) {
size_t capacity = item.Capacity(batch[0]->newest());
size_t hist_len = capacity / batchsize;
size_t min_hist_len = std::min(hist_len, overall_hist_len);
char *p = item.ptr();
// std::cout << "key = " << item.key << ". p = " << std::hex << (void *)p << std::dec << " min_hist_len = " << min_hist_len << std::endl;
//
for (size_t t = 0; t < min_hist_len; ++t) {
for (auto* s: batch) {
const State &state = s->newest(min_hist_len - t - 1);
p = item.CopyToMem(state, p);
}
}
if (hist_len > overall_hist_len) {
// Fill them with the oldest hist.
for (size_t i = overall_hist_len; i < hist_len; ++i) {
for (auto *s: batch) {
const State &state = s->newest(min_hist_len - 1);
p = item.CopyToMem(state, p);
}
}
}
}
}
template <typename State>
void CopyFromMem(const std::vector<CopyItemT<State>> &copier, std::vector<HistT<State> *> &batch) {
if (batch.empty()) return;
size_t batchsize = batch.size();
size_t overall_hist_len = batch[0]->size();
for (const auto& item: copier) {
size_t capacity = item.Capacity(batch[0]->newest());
size_t hist_len = capacity / batchsize;
size_t min_hist_len = std::min(hist_len, overall_hist_len);
const char *p = item.ptr();
for (size_t t = 0; t < min_hist_len; ++t) {
for (auto* s: batch) {
State &state = s->newest(min_hist_len - t - 1);
p = item.CopyFromMem(state, p);
}
}
}
}
}
|
{
"language": "C++"
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D_h
#define vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D_h
#ifndef __VTK_WRAP__
#include "vtkOpenGLVolumeLookupTable.h"
#include "vtkNew.h"
// Forward declarations
class vtkOpenGLRenderWindow;
/**
* \brief 2D Transfer function container for label map mask gradient opacity.
*
* Manages the texture fetched by the fragment shader when TransferFunction2D
* mode is active. Update() assumes the vtkImageData instance used as source
* is of type VTK_FLOAT and has 1 component (vtkVolumeProperty ensures this
* is the case when the function is set).
*
* \sa vtkVolumeProperty::SetLabelGradientOpacity
*/
class vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D : public vtkOpenGLVolumeLookupTable
{
public:
vtkTypeMacro(vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D, vtkOpenGLVolumeLookupTable);
void PrintSelf(ostream& os, vtkIndent indent) override;
static vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D* New();
protected:
vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D();
/**
* Update the internal texture object using the 2D image data
*/
void InternalUpdate(vtkObject* func, int blendMode, double sampleDistance, double unitDistance,
int filterValue) override;
/**
* Compute the ideal texture size based on the number of labels and transfer
* functions in the label map.
*/
void ComputeIdealTextureSize(
vtkObject* func, int& width, int& height, vtkOpenGLRenderWindow* renWin) override;
private:
vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D(const vtkOpenGLVolumeLookupTable&) = delete;
vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D& operator=(
const vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D&) = delete;
};
#endif // __VTK_WRAP__
#endif // vtkOpenGLVolumeMaskTransferFunction2D_h
// VTK-HeaderTest-Exclude: vtkOpenGLVolumeMaskGradientOpacityTransferFunction2D.h
|
{
"language": "C++"
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "UnitTestingReporter.h"
#include <ScriptCanvas/Execution/RuntimeComponent.h>
#include <AzTest/AzTest.h>
#define SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_EQ(LHS, RHS)\
EXPECT_EQ(LHS, RHS) << report.data();
#define SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_NE(LHS, RHS)\
EXPECT_NE(LHS, RHS) << report.data();
#define SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_GT(LHS, RHS)\
EXPECT_GT(LHS, RHS) << report.data();
#define SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_GE(LHS, RHS)\
EXPECT_GE(LHS, RHS) << report.data();
#define SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_LT(LHS, RHS)\
EXPECT_LT(LHS, RHS) << report.data();
#define SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_LE(LHS, RHS)\
EXPECT_LE(LHS, RHS) << report.data();
namespace ScriptCanvas
{
namespace UnitTesting
{
Reporter::Reporter()
: m_graphId{}
, m_entityId{}
{}
Reporter::Reporter(const RuntimeComponent& graph)
{
SetGraph(graph);
}
Reporter::~Reporter()
{
Reset();
}
void Reporter::Checkpoint(const Report& report)
{
if (m_isReportFinished)
return;
m_checkpoints.push_back(report);
}
const AZStd::vector<Report>& Reporter::GetCheckpoints() const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_checkpoints;
}
const AZStd::vector<Report>& Reporter::GetFailure() const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_failures;
}
const AZ::EntityId& Reporter::GetGraphId() const
{
return m_graphId;
}
const AZStd::vector<Report>& Reporter::GetSuccess() const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_successes;
}
bool Reporter::IsActivated() const
{
return m_graphIsActivated;
}
bool Reporter::IsComplete() const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_graphIsComplete;
}
bool Reporter::IsDeactivated() const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_graphIsDeactivated;
}
bool Reporter::IsErrorFree() const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_graphIsErrorFree;
}
bool Reporter::IsReportFinished() const
{
return m_isReportFinished;
}
void Reporter::FinishReport()
{
AZ_Assert(!m_isReportFinished, "the report is already finished");
m_isReportFinished = true;
}
void Reporter::FinishReport(const RuntimeComponent& graph)
{
AZ_Assert(!m_isReportFinished, "the report is already finished");
Bus::Handler::BusDisconnect(m_graphId);
AZ::EntityBus::Handler::BusDisconnect(m_entityId);
m_graphIsErrorFree = !graph.IsInErrorState();
m_isReportFinished = true;
}
bool Reporter::operator==(const Reporter& other) const
{
AZ_Assert(m_isReportFinished, "the report must be finished before evaluation");
return m_graphIsActivated == other.m_graphIsActivated
&& m_graphIsDeactivated == other.m_graphIsDeactivated
&& m_graphIsComplete == other.m_graphIsComplete
&& m_graphIsErrorFree == other.m_graphIsErrorFree
&& m_isReportFinished == other.m_isReportFinished
&& m_failures == other.m_failures
&& m_successes == other.m_successes;
}
void Reporter::OnEntityActivated(const AZ::EntityId& entity)
{
AZ_Assert(m_entityId == entity, "this reporter is listening to the wrong entity");
if (m_isReportFinished)
return;
m_graphIsActivated = true;
}
void Reporter::OnEntityDeactivated(const AZ::EntityId& entity)
{
AZ_Assert(m_entityId == entity, "this reporter is listening to the wrong entity");
if (m_isReportFinished)
return;
m_graphIsDeactivated = true;
}
void Reporter::Reset()
{
if (m_graphId.IsValid())
{
Bus::Handler::BusDisconnect();
}
if (m_entityId.IsValid())
{
AZ::EntityBus::Handler::BusDisconnect();
}
m_graphIsActivated = false;
m_graphIsComplete = false;
m_graphIsErrorFree = false;
m_isReportFinished = false;
m_graphId = AZ::EntityId{};
m_failures.clear();
m_failures.clear();
}
void Reporter::SetGraph(const RuntimeComponent& graph)
{
Reset();
m_graphId = graph.GetUniqueId();
m_entityId = graph.GetEntityId();
Bus::Handler::BusConnect(m_graphId);
AZ::EntityBus::Handler::BusConnect(m_entityId);
}
// Handler
void Reporter::MarkComplete(const Report& report)
{
if (m_isReportFinished)
return;
if (m_graphIsComplete)
{
AddFailure(AZStd::string::format("MarkComplete was called twice. %s", report.data()));
}
else
{
m_graphIsComplete = true;
}
}
void Reporter::AddFailure(const Report& report)
{
if (m_isReportFinished)
return;
m_failures.push_back(report);
Checkpoint(AZStd::string::format("AddFailure: %s", report.data()));
}
void Reporter::AddSuccess(const Report& report)
{
if (m_isReportFinished)
return;
m_successes.push_back(report);
Checkpoint(AZStd::string::format("AddSuccess: %s", report.data()));
}
void Reporter::ExpectFalse(const bool value, const Report& report)
{
EXPECT_FALSE(value) << report.data();
Checkpoint(AZStd::string::format("ExpectFalse: %s", report.data()));
}
void Reporter::ExpectTrue(const bool value, const Report& report)
{
EXPECT_TRUE(value) << report.data();
Checkpoint(AZStd::string::format("ExpectTrue: %s", report.data()));
}
void Reporter::ExpectEqualNumber(const Data::NumberType lhs, const Data::NumberType rhs, const Report& report)
{
EXPECT_NEAR(lhs, rhs, 0.001) << report.data();
Checkpoint(AZStd::string::format("ExpectEqualNumber: %s", report.data()));
}
void Reporter::ExpectNotEqualNumber(const Data::NumberType lhs, const Data::NumberType rhs, const Report& report)
{
EXPECT_NE(lhs, rhs) << report.data();
Checkpoint(AZStd::string::format("ExpectNotEqualNumber: %s", report.data()));
}
SCRIPT_CANVAS_UNIT_TEST_EQUALITY_OVERLOAD_IMPLEMENTATIONS(Reporter, ExpectEqual, SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_EQ)
SCRIPT_CANVAS_UNIT_TEST_EQUALITY_OVERLOAD_IMPLEMENTATIONS(Reporter, ExpectNotEqual, SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_NE)
SCRIPT_CANVAS_UNIT_TEST_COMPARE_OVERLOAD_IMPLEMENTATIONS(Reporter, ExpectGreaterThan, SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_GT)
SCRIPT_CANVAS_UNIT_TEST_COMPARE_OVERLOAD_IMPLEMENTATIONS(Reporter, ExpectGreaterThanEqual, SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_GE)
SCRIPT_CANVAS_UNIT_TEST_COMPARE_OVERLOAD_IMPLEMENTATIONS(Reporter, ExpectLessThan, SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_LT)
SCRIPT_CANVAS_UNIT_TEST_COMPARE_OVERLOAD_IMPLEMENTATIONS(Reporter, ExpectLessThanEqual, SCRIPT_CANVAS_UNIT_TEST_REPORTER_EXPECT_LE)
} // namespace UnitTesting
} // namespace ScriptCanvas
|
{
"language": "C++"
}
|
/***************************************************************************
* @file The code is for the exercises in C++ Primmer 5th Edition
* @author Yue Wang
* @date 23 DEC 2013
* @remark
***************************************************************************/
//
// Exercise 12.10:
// Explain whether the following call to the process function defined on page
// 464 is correct. If not, how would you correct the call?
// correct.
#include <iostream>
#include <memory>
void process(std::shared_ptr<int> ptr)
{
std::cout << "inside the process function:" << ptr.use_count() << "\n";
}
int main()
{
std::shared_ptr<int> p(new int(42));
process(std::shared_ptr<int>(p));
/**
* codes below shows how the reference count change.
*/
std::cout << p.use_count() << "\n";
auto q = p;
std::cout << p.use_count() << "\n";
std::cout << "the int p now points to is:" << *p << "\n";
return 0;
}
|
{
"language": "C++"
}
|
/* Copyright (C) 2000-2012 by George Williams */
/*
* 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.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <fontforge-config.h>
#include "gdraw.h"
#include "ggadgetP.h"
#include "gkeysym.h"
#include "gwidget.h"
#include "ustring.h"
static Color GRowColLabelBg = 0xc0c0c0;
static void GRowColSelected(GRowCol *l) {
GEvent e;
e.type = et_controlevent;
e.w = l->g.base;
e.u.control.subtype = et_listselected;
e.u.control.g = &l->g;
e.u.control.u.list.from_mouse = false;
if ( l->g.handle_controlevent != NULL )
(l->g.handle_controlevent)(&l->g,&e);
else
GDrawPostEvent(&e);
}
static void GRowColDoubleClick(GRowCol *l) {
GEvent e;
e.type = et_controlevent;
e.w = l->g.base;
e.u.control.subtype = et_listdoubleclick;
e.u.control.g = &l->g;
if ( l->g.handle_controlevent != NULL )
(l->g.handle_controlevent)(&l->g,&e);
else
GDrawPostEvent(&e);
}
static int GRowColAlphaCompare(const void *v1, const void *v2) {
GTextInfo * const *pt1 = v1, * const *pt2 = v2;
return( GTextInfoCompare(*pt1,*pt2));
}
static void GRowColOrderIt(GRowCol *grc) {
if ( grc->order_entries ) {
/* Sort each entry left to right then top to bottom (1 2 3/4 5 6/...) */
qsort(grc->ti,grc->rows*grc->cols,sizeof(GTextInfo *),grc->orderer);
if ( grc->backwards ) {
int i;
GTextInfo *ti;
for ( i=0; i<grc->ltot/2; ++i ) {
ti = grc->ti[i];
grc->ti[i] = grc->ti[grc->ltot-1-i];
grc->ti[grc->ltot-1-i] = ti;
}
}
} else {
/* Sort each row, top to bottom (1 8 5/2 7 3/...) */
qsort(grc->ti,grc->rows,sizeof(GTextInfo *)*grc->cols,grc->orderer);
if ( grc->backwards ) {
int i;
GTextInfo **ti;
ti = gmalloc(grc->cols*sizeof(GTextInfo *));
for ( i=0; i<grc->rows/2; ++i ) {
memcpy(ti,grc->ti+(i*grc->cols),grc->cols*sizeof(GTextInfo *));
memcpy(grc->ti+(i*grc->cols),grc->ti+((grc->rows-1-i)*grc->cols),grc->cols*sizeof(GTextInfo *));
memcpy(grc->ti+((grc->rows-1-i)*grc->cols),ti,grc->cols*sizeof(GTextInfo *));
}
free(ti);
}
}
}
static void GRowColClearSel(GRowCol *grc) {
int i;
for ( i=0; i<grc->ltot; ++i )
grc->ti[i]->selected = false;
}
static int GRowColAnyOtherSels(GRowCol *grc, int pos) {
int i;
for ( i=0; i<grc->ltot; ++i )
if ( grc->ti[i]->selected && i!=pos )
return( true );
return( false );
}
static int32 GRowColGetFirstSelPos(GGadget *g) {
int i;
GRowCol *grc = (GRowCol *) g;
for ( i=0; i<grc->ltot; ++i )
if ( grc->ti[i]->selected )
return( i );
return( -1 );
}
static void GRowColSelect(GGadget *g, int32 pos, int32 sel) {
GRowCol *grc = (GRowCol *) g;
GRowColClearSel(grc);
if ( pos>=grc->ltot || pos<0 )
return;
if ( grc->ltot>0 ) {
grc->ti[pos]->selected = sel;
_ggadget_redraw(g);
}
}
static void GRowColSelectOne(GGadget *g, int32 pos) {
GRowCol *grc = (GRowCol *) g;
GRowColClearSel(grc);
if ( pos>=grc->ltot ) pos = grc->ltot-1;
if ( pos<0 ) pos = 0;
if ( grc->ltot>0 ) {
grc->ti[pos]->selected = true;
_ggadget_redraw(g);
}
}
static int32 GRowColIsItemSelected(GGadget *g, int32 pos) {
GRowCol *grc = (GRowCol *) g;
if ( pos>=grc->ltot )
return( false );
if ( pos<0 )
return( false );
if ( grc->ltot>0 )
return( grc->ti[pos]->selected );
return( false );
}
static int GRowColIndexFromPos(GRowCol *grc,int y) {
int i, height;
y -= grc->g.inner.y;
if ( y<0 ) y=0;
if ( y>=grc->g.inner.height ) y = grc->g.inner.height-1;
for ( i=grc->loff, height=0; i<grc->ltot; ++i ) {
int temp = GTextInfoGetHeight(grc->g.base,grc->ti[i],grc->font);
if ( height+temp>y )
break;
height += temp;
}
if ( i==grc->ltot )
return( -1 );
if ( grc->ti[i]->disabled )
return( -1 );
return( i );
}
static void GRowColScrollBy(GRowCol *grc,int loff,int xoff) {
int top = GRowColTopInWindow(grc,grc->ltot-1);
int ydiff, i;
if ( grc->loff + loff < 0 )
loff = -grc->loff;
else if ( grc->loff + loff > top )
loff = top-grc->loff;
if ( xoff+grc->xoff<0 )
xoff = -grc->xoff;
else if ( xoff+grc->xoff+grc->g.inner.width > grc->xmax ) {
xoff = grc->xmax-grc->g.inner.width-grc->xoff;
if ( xoff<0 ) xoff = 0;
}
if ( loff == 0 && xoff==0 )
return;
ydiff = 0;
if ( loff>0 ) {
for ( i=0; i<loff && ydiff<grc->g.inner.height; ++i )
ydiff += GTextInfoGetHeight(grc->g.base,grc->ti[i+grc->loff],grc->font);
} else if ( loff<0 ) {
for ( i=loff; i<0 && -ydiff<grc->g.inner.height; ++i )
ydiff -= GTextInfoGetHeight(grc->g.base,grc->ti[i+grc->loff],grc->font);
}
if ( !GDrawIsVisible(grc->g.base))
return;
GDrawForceUpdate(grc->g.base);
grc->loff += loff; grc->xoff += xoff;
if ( ydiff>=grc->g.inner.height || -ydiff >= grc->g.inner.height )
_ggadget_redraw(&grc->g);
else if ( ydiff!=0 || xoff!=0 )
GDrawScroll(grc->g.base,&grc->g.inner,xoff,ydiff);
if ( loff!=0 )
GScrollBarSetPos(&grc->vsb->g,grc->loff);
}
static int GRowColFindPosition(GRowCol *grc,unichar_t *text) {
GTextInfo temp, *ptemp=&temp;
int i, order;
if ( grc->orderer!=NULL ) {
memset(&temp,'\0',sizeof(temp));
temp.text = text;
/* I don't think I need to write a binary search here... */
for ( i=0; i<grc->ltot; ++i ) {
order = (grc->orderer)(&ptemp,&grc->ti[i]);
if (( order<= 0 && !grc->backwards ) || ( order>=0 && grc->backwards ))
return( i );
}
return( 0 );
} else {
for ( i=0; i<grc->ltot; ++i ) {
if (u_strmatch(text,grc->ti[i]->text)==0 )
return( i );
}
}
return( 0 );
}
static int GRowColAdjustPos(GGadget *g,int pos) {
GRowCol *grc = (GRowCol *) g;
int newoff = grc->loff;
if ( pos<grc->loff ) {
if (( newoff = pos-1)<0 ) newoff = 0;
if ( GRowColLinesInWindow(grc,newoff)<2 )
newoff = pos;
} else if ( pos >= grc->loff + GRowColLinesInWindow(grc,grc->loff) ) {
newoff = GRowColTopInWindow(grc,pos);
if ( pos!=grc->ltot-1 && GRowColLinesInWindow(grc,newoff+1)>=2 )
++newoff;
}
return( newoff );
}
static void GRowColShowPos(GGadget *g,int pos) {
GRowCol *grc = (GRowCol *) g;
int newoff = GRowColAdjustPos(g,pos);
if ( newoff!=grc->loff )
GRowColScrollBy(grc,newoff-grc->loff,0);
}
static void GRowColScrollToText(GGadget *g,unichar_t *text,int sel) {
GRowCol *grc = (GRowCol *) g;
int pos;
pos = GRowColFindPosition(grc,text);
if ( sel && pos<grc->ltot ) {
GRowColClearSel(grc);
if ( grc->exactly_one || u_strmatch(text,grc->ti[pos]->text)==0 )
grc->ti[pos]->selected = true;
}
grc->loff = GRowColAdjustPos(g,pos);
_ggadget_redraw(g);
}
static void GRowColSetOrderer(GGadget *g,int (*orderer)(const void *, const void *)) {
GRowCol *grc = (GRowCol *) g;
grc->orderer = orderer;
if ( orderer!=NULL ) {
GRowColOrderIt(grc);
GRowColScrollBy(grc,-grc->loff,-grc->xoff);
_ggadget_redraw(&grc->g);
}
}
static int growcol_scroll(GGadget *g, GEvent *event);
static void GRowColCheckSB(GRowCol *grc) {
if ( GRowColLinesInWindow(grc,0)<grc->ltot ) {
if ( grc->vsb==NULL ) {
GGadgetData gd;
memset(&gd,'\0',sizeof(gd));
gd.pos.y = grc->g.r.y; gd.pos.height = grc->g.r.height;
gd.pos.width = GDrawPointsToPixels(grc->g.base,_GScrollBar_Width);
gd.pos.x = grc->g.r.x+grc->g.r.width - gd.pos.width;
gd.flags = gg_visible|gg_enabled|gg_pos_in_pixels|gg_sb_vert|gg_pos_use0;
gd.handle_controlevent = growcol_scroll;
grc->vsb = (GScrollBar *) GScrollBarCreate(grc->g.base,&gd,grc);
grc->vsb->g.contained = true;
gd.pos.width += GDrawPointsToPixels(grc->g.base,1);
grc->g.r.width -= gd.pos.width;
grc->g.inner.width -= gd.pos.width;
}
GScrollBarSetBounds(&grc->vsb->g,0,grc->ltot-1,GRowColLinesInWindow(grc,0));
GScrollBarSetPos(&grc->vsb->g,grc->loff);
} else {
if ( grc->vsb!=NULL ) {
int wid = grc->vsb->g.r.width + GDrawPointsToPixels(grc->g.base,1);
(grc->vsb->g.funcs->destroy)(&grc->vsb->g);
grc->vsb = NULL;
grc->g.r.width += wid;
grc->g.inner.width += wid;
}
}
}
static int GRowColFindXMax(GRowCol *grc) {
int i, width=0, temp;
for ( i=0; i<grc->ltot; ++i ) {
temp = GTextInfoGetWidth(grc->g.base,grc->ti[i],grc->font);
if ( temp>width ) width=temp;
}
grc->xmax = width;
return( width );
}
static void GRowColSetList(GGadget *g,GTextInfo **ti,int docopy) {
GRowCol *grc = (GRowCol *) g;
int same;
GTextInfoArrayFree(grc->ti);
if ( docopy || ti==NULL )
ti = GTextInfoArrayCopy(ti);
grc->ti = ti;
grc->ltot = GTextInfoArrayCount(ti);
if ( grc->orderer!=NULL )
GRowColOrderIt(grc);
grc->loff = grc->xoff = 0;
grc->hmax = GTextInfoGetMaxHeight(g->base,ti,grc->font,&same);
grc->sameheight = same;
GRowColCheckSB(grc);
_ggadget_redraw(&grc->g);
}
static void GRowColClear(GGadget *g) {
GRowColSetList(g,NULL,true);
}
static GTextInfo **GRowColGetList(GGadget *g,int32 *len) {
GRowCol *grc = (GRowCol *) g;
if ( len!=NULL ) *len = grc->ltot;
return( grc->ti );
}
static GTextInfo *GRowColGetListItem(GGadget *g,int32 pos) {
GRowCol *grc = (GRowCol *) g;
if ( pos<0 || pos>=grc->ltot )
return( NULL );
return(grc->ti[pos]);
}
static int growcol_expose(GWindow pixmap, GGadget *g, GEvent *event) {
GRowCol *grc = (GRowCol *) g;
GRect old1, old2;
Color fg, dfg;
int y, l, ymax, i;
if ( g->state == gs_invisible )
return( false );
GDrawPushClip(pixmap,&g->r,&old1);
GBoxDrawBackground(pixmap,&g->r,g->box, g->state,false);
if ( g->box->border_type!=bt_none ||
(g->box->flags&(box_foreground_border_inner|box_foreground_border_outer|box_active_border_inner))!=0 ) {
GBoxDrawBorder(pixmap,&g->r,g->box,g->state,false);
GDrawPushClip(pixmap,&g->inner,&old2);
}
fg = g->state==gs_disabled?g->box->disabled_foreground:g->box->main_foreground;
dfg = g->box->disabled_foreground;
y = g->inner.y;
ymax = g->inner.y+g->inner.height;
if ( ymax>event->u.expose.rect.y+event->u.expose.rect.height )
ymax = event->u.expose.rect.y+event->u.expose.rect.height;
if ( grc->labels!=NULL ) {
if ( y+grc->fh > event->u.expose.rect.y ) {
GRect r;
r = g->inner; r.height = fh;
GDrawFillRect(pixmap,&r,GRowColLabelBg);
for ( i=0; i<grc->cols; ++i ) {
GTextInfoDraw(pixmap,g->inner.x+grc->colx[i]+grc->hpad-grc->xoff,y,grc->labels[i],
grc->font,dfg,g->box->active_border
g->inner.y+g->inner.height);
}
}
y += grc->fh;
if ( grc->hrules )
GDrawDrawLine(pixmap,g->inner.x,y-1,g->inner.x+g->inner.width,y-1,fg);
}
for ( l = grc->loff; y<ymax && l<grc->rows; ++l ) {
if ( y+grc->fh > event->u.expose.rect.y ) {
for ( i=0; i<grc->cols; ++i ) {
if ( l!=grc->tfr || i!=grc->tfc ) {
GTextInfo *ti = grc->ti[l*grc->cols+i];
GTextInfoDraw(pixmap,g->inner.x+grc->colx[i]-grc->xoff+grc->hpad,y,ti,
grc->font,dfg,g->box->active_border,
g->inner.y+g->inner.height);
} else {
/* now we can draw the text field */
grc->tf->dontdraw = false;
(grc->tf->g.gfuncs->handle_expose)(pixmap,&grc->tf->g,event);
grc->tf->dontdraw = true;
}
}
}
y += grc->fh;
if ( grc->hrules )
GDrawDrawLine(pixmap,g->inner.x,y-1,g->inner.x+g->inner.width,y-1,fg);
}
if ( grc->vrules ) {
for ( i=1; i<grc->cols; ++i )
GDrawDrawLine(pixmap,grc->colx[i]-grc->xoff,g->inner.y,
grc->colx[i]-grc->xoff,g->inner.y+g->inner.height,fg);
}
if ( g->box->border_type!=bt_none ||
(g->box->flags&(box_foreground_border_inner|box_foreground_border_outer|box_active_border_inner))!=0 )
GDrawPopClip(pixmap,&old2);
GDrawPopClip(pixmap,&old1);
return( true );
}
static void growcol_scroll_selbymouse(GGadget *g, GEvent *event) {
int loff=0, xoff=0, pos;
GRowCol *grc = (GRowCol *) (g->data);
if ( event->u.mouse.y<grc->g.inner.y ) {
if ( grc->loff>0 ) loff = -1;
} else if ( event->u.mouse.y >= grc->g.inner.y+grc->g.inner.height ) {
int top = GRowColTopInWindow(grc,grc->ltot-1);
if ( grc->loff<top ) loff = 1;
}
if ( event->u.mouse.x<grc->g.inner.x ) {
xoff = -GDrawPointsToPixels(grc->g.base,6);
} else if ( event->u.mouse.x >= grc->g.inner.x+grc->g.inner.width ) {
xoff = GDrawPointsToPixels(grc->g.base,6);
}
GRowColScrollBy(grc,loff,xoff);
pos = GRowColIndexFromPos(grc,event->u.mouse.y);
if ( pos==-1 || pos == grc->end )
/* Do Nothing, nothing selectable */;
else if ( !grc->multiple_sel ) {
GRowColClearSel(grc);
grc->ti[pos]->selected = true;
grc->start = grc->end = pos;
_ggadget_redraw(&grc->g);
} else {
GRowColExpandSelection(grc,pos);
grc->end = pos;
_ggadget_redraw(&grc->g);
}
}
static int growcol_mouse(GGadget *g, GEvent *event) {
GRowCol *grc = (GRowCol *) g;
int pos;
if ( !g->takes_input || (g->state!=gs_active && g->state!=gs_enabled && g->state!=gs_focused))
return( false );
if ( event->type == et_crossing )
return( false );
if ( event->type==et_mousemove && !grc->pressed && !grc->parentpressed ) {
if ( GGadgetWithin(g,event->u.mouse.x,event->u.mouse.y) && g->popup_msg )
GGadgetPreparePopup(g->base,g->popup_msg);
return( true );
} else if ( event->type==et_mouseup && grc->parentpressed &&
!GGadgetInnerWithin(&grc->g,event->u.mouse.x,event->u.mouse.y)) {
grc->parentpressed = false;
GDrawPointerUngrab(GDrawGetDisplayOfWindow(grc->g.base));
} else if ( event->type==et_mousemove && grc->parentpressed &&
GGadgetInnerWithin(&grc->g,event->u.mouse.x,event->u.mouse.y)) {
if ( grc->pressed == NULL )
grc->pressed = GDrawRequestTimer(g->base,GRowColScrollTime,GRowColScrollTime,NULL);
GDrawPointerUngrab(GDrawGetDisplayOfWindow(grc->g.base));
grc->parentpressed = false;
growcol_scroll_selbymouse(grc,event);
return( true );
} else if ( event->type==et_mousemove && grc->pressed ) {
growcol_scroll_selbymouse(grc,event);
return( true );
} else if ( event->type==et_mousedown ) {
if ( grc->pressed == NULL )
grc->pressed = GDrawRequestTimer(g->base,GRowColScrollTime,GRowColScrollTime,NULL);
pos = GRowColIndexFromPos(grc,event->u.mouse.y);
if ( pos==-1 )
return( true ); /* Do Nothing, nothing selectable */
else if ( !grc->exactly_one && grc->ti[pos]->selected &&
(event->u.mouse.state&(ksm_control|ksm_shift))) {
grc->ti[pos]->selected = false;
} else if ( !grc->multiple_sel ||
!(event->u.mouse.state&(ksm_control|ksm_shift))) {
GRowColClearSel(grc);
grc->ti[pos]->selected = true;
grc->start = grc->end = pos;
} else if ( event->u.mouse.state&ksm_control ) {
grc->ti[pos]->selected = !grc->ti[pos]->selected;
grc->start = grc->end = pos;
} else if ( event->u.mouse.state&ksm_shift ) {
GRowColExpandSelection(grc,pos);
}
_ggadget_redraw(&grc->g);
} else if ( event->type==et_mouseup && grc->pressed ) {
GDrawCancelTimer(grc->pressed); grc->pressed = NULL;
if ( GGadgetInnerWithin(&grc->g,event->u.mouse.x,event->u.mouse.y) ) {
growcol_scroll_selbymouse(grc,event);
if ( event->u.mouse.clicks==2 )
GRowColDoubleClick(grc);
else
GRowColSelected(grc);
}
} else
return( false );
return( true );
}
static int growcol_key(GGadget *g, GEvent *event) {
GRowCol *grc = (GRowCol *) g;
uint16 keysym = event->u.chr.keysym;
int sofar_pos = grc->sofar_pos;
int loff, xoff, sel=-1;
int refresh = false;
if ( event->type == et_charup )
return( false );
if ( !g->takes_input || (g->state!=gs_enabled && g->state!=gs_active && g->state!=gs_focused ))
return(false );
if ( grc->ispopup && event->u.chr.keysym == GK_Return ) {
GRowColDoubleClick(grc);
return( true );
}
if ( event->u.chr.keysym == GK_Return || event->u.chr.keysym == GK_Tab ||
event->u.chr.keysym == GK_BackTab || event->u.chr.keysym == GK_Escape )
return( false );
GDrawCancelTimer(grc->enduser); grc->enduser = NULL; grc->sofar_pos = 0;
loff = 0x80000000; xoff = 0x80000000; sel = -1;
if ( keysym == GK_Home || keysym == GK_KP_Home || keysym == GK_Begin || keysym == GK_KP_Begin ) {
loff = -grc->loff;
xoff = -grc->xoff;
sel = 0;
} else if ( keysym == GK_End || keysym == GK_KP_End ) {
loff = GRowColTopInWindow(grc,grc->ltot-1)-grc->loff;
xoff = -grc->xoff;
sel = grc->ltot-1;
} else if ( keysym == GK_Up || keysym == GK_KP_Up ) {
if (( sel = GRowColGetFirstSelPos(&grc->g)-1 )<0 ) {
/*if ( grc->loff!=0 ) loff = -1; else loff = 0;*/
sel = 0;
}
} else if ( keysym == GK_Down || keysym == GK_KP_Down ) {
if (( sel = GRowColGetFirstSelPos(&grc->g))!= -1 )
++sel;
else
/*if ( grc->loff + GRowColLinesInWindow(grc,grc->loff)<grc->ltot ) loff = 1; else loff = 0;*/
sel = 0;
} else if ( keysym == GK_Left || keysym == GK_KP_Left ) {
xoff = -GDrawPointsToPixels(grc->g.base,6);
} else if ( keysym == GK_Right || keysym == GK_KP_Right ) {
xoff = GDrawPointsToPixels(grc->g.base,6);
} else if ( keysym == GK_Page_Up || keysym == GK_KP_Page_Up ) {
loff = GRowColTopInWindow(grc,grc->loff);
if ( loff == grc->loff ) /* Normally we leave one line in window from before, except if only one line fits */
loff = GRowColTopInWindow(grc,grc->loff-1);
loff -= grc->loff;
if (( sel = GRowColGetFirstSelPos(&grc->g))!= -1 ) {
if (( sel += loff )<0 ) sel = 0;
}
} else if ( keysym == GK_Page_Down || keysym == GK_KP_Page_Down ) {
loff = GRowColLinesInWindow(grc,grc->loff)-1;
if ( loff<=0 ) loff = 1;
if ( loff + grc->loff >= grc->ltot )
loff = GRowColTopInWindow(grc,grc->ltot-1)-grc->loff;
if (( sel = GRowColGetFirstSelPos(&grc->g))!= -1 ) {
if (( sel += loff )>=grc->ltot ) sel = grc->ltot-1;
}
} else if ( keysym == GK_BackSpace && grc->orderer ) {
/* ordered lists may be reversed by typing backspace */
grc->backwards = !grc->backwards;
GRowColOrderIt(grc);
sel = GRowColGetFirstSelPos(&grc->g);
if ( sel!=-1 ) {
int top = GRowColTopInWindow(grc,grc->ltot-1);
grc->loff = sel-1;
if ( grc->loff > top )
grc->loff = top;
if ( sel-1<0 )
grc->loff = 0;
}
GScrollBarSetPos(&grc->vsb->g,grc->loff);
_ggadget_redraw(&grc->g);
return( true );
} else if ( event->u.chr.chars[0]!='\0' && grc->orderer ) {
int len = u_strlen(event->u.chr.chars);
if ( sofar_pos+len >= grc->sofar_max ) {
if ( grc->sofar_max == 0 )
grc->sofar = malloc((grc->sofar_max = len+10) * sizeof(unichar_t));
else
grc->sofar = realloc(grc->sofar,(grc->sofar_max = sofar_pos+len+10)*sizeof(unichar_t));
}
u_strcpy(grc->sofar+sofar_pos,event->u.chr.chars);
grc->sofar_pos = sofar_pos + len;
sel = GRowColFindPosition(grc,grc->sofar);
grc->enduser = GDrawRequestTimer(grc->g.base,GRowColTypeTime,0,NULL);
}
if ( loff==0x80000000 && sel>=0 ) {
if ( sel>=grc->ltot ) sel = grc->ltot-1;
if ( sel<grc->loff ) loff = sel-grc->loff;
else if ( sel>=grc->loff+GRowColLinesInWindow(grc,grc->loff) )
loff = sel-(grc->loff+GRowColLinesInWindow(grc,grc->loff)-1);
} else
sel = -1;
if ( sel!=-1 ) {
int wassel = grc->ti[sel]->selected;
refresh = GRowColAnyOtherSels(grc,sel) || !wassel;
GRowColSelectOne(&grc->g,sel);
if ( refresh )
GRowColSelected(grc);
}
if ( loff!=0x80000000 || xoff!=0x80000000 ) {
if ( loff==0x80000000 ) loff = 0;
if ( xoff==0x80000000 ) xoff = 0;
GRowColScrollBy(grc,loff,xoff);
}
if ( refresh )
_ggadget_redraw(g);
if ( loff!=0x80000000 || xoff!=0x80000000 || sel!=-1 )
return( true );
return( false );
}
static int growcol_timer(GGadget *g, GEvent *event) {
GRowCol *grc = (GRowCol *) g;
if ( event->u.timer.timer == grc->enduser ) {
grc->enduser = NULL;
grc->sofar_pos = 0;
return( true );
} else if ( event->u.timer.timer == grc->pressed ) {
GEvent e;
e.type = et_mousemove;
GDrawGetPointerPosition(g->base,&e);
if ( e.u.mouse.x<g->inner.x || e.u.mouse.y <g->inner.y ||
e.u.mouse.x >= g->inner.x + g->inner.width ||
e.u.mouse.y >= g->inner.y + g->inner.height )
growcol_scroll_selbymouse(grc,&e);
return( true );
}
return( false );
}
static int growcol_scroll(GGadget *g, GEvent *event) {
int loff = 0;
enum sb sbt = event->u.control.u.sb.type;
GRowCol *grc = (GRowCol *) g;
if ( sbt==et_sb_top )
loff = -grc->loff;
else if ( sbt==et_sb_bottom )
loff = GRowColTopInWindow(grc,grc->ltot-1)-grc->loff;
else if ( sbt==et_sb_up ) {
if ( grc->loff!=0 ) loff = -1; else loff = 0;
} else if ( sbt==et_sb_down ) {
if ( grc->loff + GRowColLinesInWindow(grc,grc->loff)<grc->ltot ) loff = 1; else loff = 0;
} else if ( sbt==et_sb_uppage ) {
loff = GRowColTopInWindow(grc,grc->loff);
if ( loff == grc->loff ) /* Normally we leave one line in window from before, except if only one line fits */
loff = GRowColTopInWindow(grc,grc->loff-1);
loff -= grc->loff;
} else if ( sbt==et_sb_downpage ) {
loff = GRowColLinesInWindow(grc,grc->loff)-1;
if ( loff<=0 ) loff = 1;
if ( loff + grc->loff >= grc->ltot )
loff = GRowColTopInWindow(grc,grc->ltot-1)-grc->loff;
} else /* if ( sbt==et_sb_thumb || sbt==et_sb_thumbrelease ) */ {
loff = event->u.control.u.sb.pos - grc->loff;
}
GRowColScrollBy(grc,loff,0);
return( true );
}
static void GRowCol_destroy(GGadget *g) {
GRowCol *grc = (GRowCol *) g;
if ( grc==NULL )
return;
GDrawCancelTimer(grc->enduser);
GDrawCancelTimer(grc->pressed);
if ( grc->freeti )
GTextInfoArrayFree(grc->ti);
free(grc->sofar);
if ( grc->vsb!=NULL )
(grc->vsb->g.funcs->destroy)(&grc->vsb->g);
_ggadget_destroy(g);
}
static void GRowColSetFont(GGadget *g,FontInstance *new) {
GRowCol *b = (GRowCol *) g;
b->font = new;
}
static FontInstance *GRowColGetFont(GGadget *g) {
GRowCol *b = (GRowCol *) g;
return( b->font );
}
static void growcol_redraw(GGadget *g) {
GRowCol *grc = (GRowCol *) g;
if ( grc->vsb!=NULL )
_ggadget_redraw((GGadget *) (grc->vsb));
_ggadget_redraw(g);
}
static void growcol_move(GGadget *g, int32 x, int32 y ) {
GRowCol *grc = (GRowCol *) g;
if ( grc->vsb!=NULL )
_ggadget_move((GGadget *) (grc->vsb),x+(grc->vsb->g.r.x-g->r.x),y);
_ggadget_move(g,x,y);
}
static void growcol_resize(GGadget *g, int32 width, int32 height ) {
GRowCol *grc = (GRowCol *) g;
if ( grc->vsb!=NULL ) {
int oldwidth = grc->vsb->g.r.x+grc->vsb->g.r.width-g->r.x;
_ggadget_move((GGadget *) (grc->vsb),grc->vsb->g.r.x+width-oldwidth,grc->vsb->g.r.y);
_ggadget_resize(g,width-(oldwidth-g->r.width), height);
_ggadget_resize((GGadget *) (grc->vsb),grc->vsb->g.r.width,height);
} else
_ggadget_resize(g,width,height);
}
static GRect *growcol_getsize(GGadget *g, GRect *r ) {
GRowCol *grc = (GRowCol *) g;
_ggadget_getsize(g,r);
if ( grc->vsb!=NULL )
r->width = grc->vsb->g.r.x+grc->vsb->g.r.width-g->r.x;
return( r );
}
static void growcol_setvisible(GGadget *g, int visible ) {
GRowCol *grc = (GRowCol *) g;
if ( grc->vsb!=NULL ) _ggadget_setvisible(&grc->vsb->g,visible);
_ggadget_setvisible(g,visible);
}
static void growcol_setenabled(GGadget *g, int enabled ) {
GRowCol *grc = (GRowCol *) g;
if ( grc->vsb!=NULL ) _ggadget_setenabled(&grc->vsb->g,enabled);
_ggadget_setenabled(g,enabled);
}
struct gfuncs GRowCol_funcs = {
0,
sizeof(struct gfuncs),
growcol_expose,
growcol_mouse,
growcol_key,
NULL,
NULL,
growcol_timer,
NULL,
growcol_redraw,
growcol_move,
growcol_resize,
growcol_setvisible,
growcol_setenabled,
growcol_getsize,
_ggadget_getinnersize,
GRowCol_destroy,
NULL,
NULL,
NULL,
NULL,
NULL,
GRowColSetFont,
GRowColGetFont,
GRowColClear,
GRowColSetList,
GRowColGetList,
GRowColGetListItem,
GRowColSelect,
GRowColSelectOne,
GRowColIsItemSelected,
GRowColGetFirstSelPos,
GRowColShowPos,
GRowColScrollToText,
GRowColSetOrderer,
NULL,
NULL,
NULL,
NULL
};
static GBox list_box = { bt_lowered, bs_rect, 2, 2, 3, box_foreground_border_outer, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static FontInstance *list_font = NULL;
static int growcol_inited = false;
static void GRowColInit() {
list_box.main_background = 0xc0c0c0;
list_font = _GGadgetInitDefaultBox("GRowCol.",&list_box,NULL);
growcol_inited = true;
}
static void GRowColFit(GRowCol *grc) {
int width=0, height=0;
int bp = GBoxBorderWidth(grc->g.base,grc->g.box);
int i;
/* can't deal with eliptical scrolling lists nor diamond ones. Just rects and roundrects */
GRowColFindXMax(grc);
if ( grc->g.r.width==0 ) {
if ( width==0 ) width = GDrawPointsToPixels(grc->g.base,100);
width += GDrawPointsToPixels(grc->g.base,_GScrollBar_Width) +
GDrawPointsToPixels(grc->g.base,1);
grc->g.r.width = width + 2*bp;
}
if ( grc->g.r.height==0 ) {
for ( i=0; i<grc->ltot && i<5; ++i ) {
height += GTextInfoGetHeight(grc->g.base,grc->ti[i],grc->font);
}
if ( i<5 ) {
int as, ds, ld;
GDrawWindowFontMetrics(grc->g.base,grc->font,&as, &ds, &ld);
height += (5-i)*(as+ds);
}
grc->g.r.height = height + 2*bp;
}
grc->g.inner = grc->g.r;
grc->g.inner.x += bp; grc->g.inner.y += bp;
grc->g.inner.width -= 2*bp; grc->g.inner.height -= 2*bp;
GRowColCheckSB(grc);
}
static GRowCol *_GRowColCreate(GRowCol *grc, struct gwindow *base, GGadgetData *gd,void *data, GBox *def) {
int same;
if ( !growcol_inited )
GRowColInit();
grc->g.funcs = &GRowCol_funcs;
_GGadget_Create(&grc->g,base,gd,data,def);
grc->font = list_font;
grc->g.takes_input = grc->g.takes_keyboard = true; grc->g.focusable = true;
if ( !(gd->flags & gg_list_internal ) ) {
grc->ti = GTextInfoArrayFromList(gd->u.list,&grc->ltot);
grc->freeti = true;
} else {
grc->ti = (GTextInfo **) (gd->u.list);
grc->ltot = GTextInfoArrayCount(grc->ti);
}
grc->hmax = GTextInfoGetMaxHeight(grc->g.base,grc->ti,grc->font,&same);
grc->sameheight = same;
if ( gd->flags & gg_list_alphabetic ) {
grc->orderer = GRowColAlphaCompare;
GRowColOrderIt(grc);
}
grc->start = grc->end = -1;
if ( gd->flags & gg_list_multiplesel )
grc->multiple_sel = true;
else if ( gd->flags & gg_list_exactlyone ) {
int sel = GRowColGetFirstSelPos(&grc->g);
grc->exactly_one = true;
if ( sel==-1 ) sel = 0;
GRowColClearSel(grc);
if ( grc->ltot>0 ) grc->ti[sel]->selected = true;
}
GRowColFit(grc);
_GGadget_FinalPosition(&grc->g,base,gd);
if ( gd->flags & gg_group_end )
_GGadgetCloseGroup(&grc->g);
GWidgetIndicateFocusGadget(&grc->g);
return( grc );
}
GGadget *GRowColCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GRowCol *grc = _GRowColCreate(calloc(1,sizeof(GRowCol)),base,gd,data,&list_box);
return( &grc->g );
}
|
{
"language": "C++"
}
|
/** @file
VBIOS DXE policy definitions
Copyright (c) 2019 Intel Corporation. All rights reserved. <BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _VBIOS_DXE_CONFIG_H_
#define _VBIOS_DXE_CONFIG_H_
#pragma pack(push, 1)
#define VBIOS_DXE_CONFIG_REVISION 1
/**
This data structure includes Switchable Graphics VBIOS configuration.
If Switchable Graphics/Hybrid Gfaphics feature is not supported, all the policies in this configuration block can be ignored.
The data elements should be initialized by a Platform Module.\n
<b>Revision 1</b>:
- Initial version.
**/
typedef struct {
CONFIG_BLOCK_HEADER Header; ///< Offset 0-27 Config Block Header
UINT8 LoadVbios : 1; ///< Offset 28:0 :This field is used to describe if the dGPU VBIOS needs to be loaded: <b>0=Not load</b>, 1=Load
UINT8 ExecuteVbios : 1; ///< Offset 28:1 :This field is used to describe if the dGPU VBIOS need to be executed: <b>0=Not execute</b>, 1=Execute
/**
Offset 28:2 :
This field is used to identify the source location of dGPU VBIOS\n
<b>1 = secondary display device VBIOS Source is PCI Card</b>\n
0 = secondary display device VBIOS Source is FW Volume\n
**/
UINT8 VbiosSource : 1;
UINT8 RsvdBits0 : 5; ///< Offset 28:3 Reserved for future use
UINT8 Rsvd[3]; ///< Offset 29 : Reserved for DWORD alignment
} VBIOS_DXE_CONFIG;
#pragma pack(pop)
#endif // _VBIOS_DXE_CONFIG_H_
|
{
"language": "C++"
}
|
/*
* <one line to give the program's name and a brief idea of what it does.>
* Copyright (C) 2016 <copyright holder> <email>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef CAMERA_H
#define CAMERA_H
#include "myslam/common_include.h"
namespace myslam
{
// Pinhole RGBD camera model
class Camera
{
public:
typedef std::shared_ptr<Camera> Ptr;
float fx_, fy_, cx_, cy_, depth_scale_;
Camera();
Camera ( float fx, float fy, float cx, float cy, float depth_scale=0 ) :
fx_ ( fx ), fy_ ( fy ), cx_ ( cx ), cy_ ( cy ), depth_scale_ ( depth_scale )
{}
// coordinate transform: world, camera, pixel
Vector3d world2camera( const Vector3d& p_w, const SE3& T_c_w );
Vector3d camera2world( const Vector3d& p_c, const SE3& T_c_w );
Vector2d camera2pixel( const Vector3d& p_c );
Vector3d pixel2camera( const Vector2d& p_p, double depth=1 );
Vector3d pixel2world ( const Vector2d& p_p, const SE3& T_c_w, double depth=1 );
Vector2d world2pixel ( const Vector3d& p_w, const SE3& T_c_w );
};
}
#endif // CAMERA_H
|
{
"language": "C++"
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Chocolatey" file="IChocolateyGuiCacheService.cs">
// Copyright 2017 - Present Chocolatey Software, LLC
// Copyright 2014 - 2017 Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ChocolateyGui.Common.Services
{
public interface IChocolateyGuiCacheService
{
void PurgeIcons();
void PurgeOutdatedPackages();
}
}
|
{
"language": "C++"
}
|
// Copyright 2004, 2005 The Trustees of Indiana University.
// Use, modification and distribution is subject to 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)
// Authors: Nick Edmonds
// Andrew Lumsdaine
#ifndef BOOST_GRAPH_MESH_GENERATOR_HPP
#define BOOST_GRAPH_MESH_GENERATOR_HPP
#include <iterator>
#include <utility>
#include <boost/assert.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost {
template<typename Graph>
class mesh_iterator
{
typedef typename graph_traits<Graph>::directed_category directed_category;
typedef typename graph_traits<Graph>::vertices_size_type
vertices_size_type;
BOOST_STATIC_CONSTANT
(bool,
is_undirected = (is_base_and_derived<undirected_tag,
directed_category>::value
|| is_same<undirected_tag, directed_category>::value));
public:
typedef std::input_iterator_tag iterator_category;
typedef std::pair<vertices_size_type, vertices_size_type> value_type;
typedef const value_type& reference;
typedef const value_type* pointer;
typedef void difference_type;
mesh_iterator()
: x(0), y(0), done(true) { }
// Vertices are numbered in row-major order
// Assumes directed
mesh_iterator(vertices_size_type x, vertices_size_type y,
bool toroidal = true)
: x(x), y(y), n(x*y), source(0), target(1), current(0,1),
toroidal(toroidal), done(false)
{ BOOST_ASSERT(x > 1 && y > 1); }
reference operator*() const { return current; }
pointer operator->() const { return ¤t; }
mesh_iterator& operator++()
{
if (is_undirected) {
if (!toroidal) {
if (target == source + 1)
if (source < x * (y - 1))
target = source + x;
else {
source++;
target = (source % x) < x - 1 ? source + 1 : source + x;
if (target > n)
done = true;
}
else if (target == source + x) {
source++;
target = (source % x) < x - 1 ? source + 1 : source + x;
}
} else {
if (target == source + 1 || target == source - (source % x))
target = (source + x) % n;
else if (target == (source + x) % n) {
if (source == n - 1)
done = true;
else {
source++;
target = (source % x) < (x - 1) ? source + 1 : source - (source % x);
}
}
}
} else { // Directed
if ( !toroidal ) {
if (target == source - x)
target = source % x > 0 ? source - 1 : source + 1;
else if (target == source - 1)
if ((source % x) < (x - 1))
target = source + 1;
else if (source < x * (y - 1))
target = source + x;
else {
done = true;
}
else if (target == source + 1)
if (source < x * (y - 1))
target = source + x;
else {
source++;
target = source - x;
}
else if (target == source + x) {
source++;
target = (source >= x) ? source - x : source - 1;
}
} else {
if (source == n - 1 && target == (source + x) % n)
done = true;
else if (target == source - 1 || target == source + x - 1)
target = (source + x) % n;
else if (target == source + 1 || target == source - (source % x))
target = (source - x + n) % n;
else if (target == (source - x + n) % n)
target = (source % x > 0) ? source - 1 : source + x - 1;
else if (target == (source + x) % n) {
source++;
target = (source % x) < (x - 1) ? source + 1 : source - (source % x);
}
}
}
current.first = source;
current.second = target;
return *this;
}
mesh_iterator operator++(int)
{
mesh_iterator temp(*this);
++(*this);
return temp;
}
bool operator==(const mesh_iterator& other) const
{
return done == other.done;
}
bool operator!=(const mesh_iterator& other) const
{ return !(*this == other); }
private:
vertices_size_type x,y;
vertices_size_type n;
vertices_size_type source;
vertices_size_type target;
value_type current;
bool toroidal;
bool done;
};
} // end namespace boost
#endif // BOOST_GRAPH_MESH_GENERATOR_HPP
|
{
"language": "C++"
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> GenerateFactors(int n)
{
std::vector<int> factors;
factors.push_back(1);
factors.push_back(n);
for(int i = 2; i * i <= n; ++i)
{
if(n % i == 0)
{
factors.push_back(i);
if(i * i != n)
factors.push_back(n / i);
}
}
std::sort(factors.begin(), factors.end());
return factors;
}
int main()
{
const int SampleNumbers[] = {3135, 45, 60, 81};
for(size_t i = 0; i < sizeof(SampleNumbers) / sizeof(int); ++i)
{
std::vector<int> factors = GenerateFactors(SampleNumbers[i]);
std::cout << "Factors of " << SampleNumbers[i] << " are:\n";
std::copy(factors.begin(), factors.end(), std::ostream_iterator<int>(std::cout, "\n"));
std::cout << std::endl;
}
}
|
{
"language": "C++"
}
|
/*
* Copyright (C) 2015 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "UIScriptController.h"
#include "JSUIScriptController.h"
#include "UIScriptContext.h"
#include <JavaScriptCore/JSValueRef.h>
namespace WTR {
UIScriptController::UIScriptController(UIScriptContext& context)
: m_context(&context)
{
}
void UIScriptController::contextDestroyed()
{
m_context = nullptr;
}
void UIScriptController::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
{
setProperty(context, windowObject, "uiController", this, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
}
JSClassRef UIScriptController::wrapperClass()
{
return JSUIScriptController::uIScriptControllerClass();
}
#if !PLATFORM(COCOA)
void UIScriptController::doAsyncTask(JSValueRef)
{
}
#endif
void UIScriptController::setWillBeginZoomingCallback(JSValueRef callback)
{
m_context->registerCallback(callback, CallbackTypeWillBeginZooming);
platformSetWillBeginZoomingCallback();
}
JSValueRef UIScriptController::willBeginZoomingCallback() const
{
return m_context->callbackWithID(CallbackTypeWillBeginZooming);
}
void UIScriptController::setDidEndZoomingCallback(JSValueRef callback)
{
m_context->registerCallback(callback, CallbackTypeDidEndZooming);
platformSetDidEndZoomingCallback();
}
JSValueRef UIScriptController::didEndZoomingCallback() const
{
return m_context->callbackWithID(CallbackTypeDidEndZooming);
}
void UIScriptController::setDidEndScrollingCallback(JSValueRef callback)
{
m_context->registerCallback(callback, CallbackTypeDidEndScrolling);
platformSetDidEndScrollingCallback();
}
JSValueRef UIScriptController::didEndScrollingCallback() const
{
return m_context->callbackWithID(CallbackTypeDidEndScrolling);
}
void UIScriptController::setDidShowKeyboardCallback(JSValueRef callback)
{
m_context->registerCallback(callback, CallbackTypeDidShowKeyboard);
platformSetDidShowKeyboardCallback();
}
JSValueRef UIScriptController::didShowKeyboardCallback() const
{
return m_context->callbackWithID(CallbackTypeDidShowKeyboard);
}
void UIScriptController::setDidHideKeyboardCallback(JSValueRef callback)
{
m_context->registerCallback(callback, CallbackTypeDidHideKeyboard);
platformSetDidHideKeyboardCallback();
}
JSValueRef UIScriptController::didHideKeyboardCallback() const
{
return m_context->callbackWithID(CallbackTypeDidHideKeyboard);
}
#if !PLATFORM(IOS)
void UIScriptController::zoomToScale(double, JSValueRef)
{
}
void UIScriptController::touchDownAtPoint(long x, long y, long touchCount, JSValueRef)
{
}
void UIScriptController::liftUpAtPoint(long x, long y, long touchCount, JSValueRef)
{
}
void UIScriptController::singleTapAtPoint(long x, long y, JSValueRef)
{
}
void UIScriptController::doubleTapAtPoint(long x, long y, JSValueRef)
{
}
void UIScriptController::dragFromPointToPoint(long startX, long startY, long endX, long endY, double durationSeconds, JSValueRef callback)
{
}
void UIScriptController::typeCharacterUsingHardwareKeyboard(JSStringRef, JSValueRef)
{
}
void UIScriptController::keyUpUsingHardwareKeyboard(JSStringRef, JSValueRef)
{
}
void UIScriptController::keyDownUsingHardwareKeyboard(JSStringRef, JSValueRef)
{
}
void UIScriptController::keyboardAccessoryBarNext()
{
}
void UIScriptController::keyboardAccessoryBarPrevious()
{
}
double UIScriptController::zoomScale() const
{
return 1;
}
double UIScriptController::minimumZoomScale() const
{
return 1;
}
double UIScriptController::maximumZoomScale() const
{
return 1;
}
JSObjectRef UIScriptController::contentVisibleRect() const
{
return nullptr;
}
bool UIScriptController::forceIPadStyleZoomOnInputFocus() const
{
return false;
}
void UIScriptController::setForceIPadStyleZoomOnInputFocus(bool)
{
}
void UIScriptController::platformSetWillBeginZoomingCallback()
{
}
void UIScriptController::platformSetDidEndZoomingCallback()
{
}
void UIScriptController::platformSetDidEndScrollingCallback()
{
}
void UIScriptController::platformSetDidShowKeyboardCallback()
{
}
void UIScriptController::platformSetDidHideKeyboardCallback()
{
}
void UIScriptController::platformClearAllCallbacks()
{
}
#endif
void UIScriptController::uiScriptComplete(JSStringRef result)
{
m_context->requestUIScriptCompletion(result);
platformClearAllCallbacks();
}
}
|
{
"language": "C++"
}
|
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// 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_UNITS_LUMINOUS_FLUX_DERIVED_DIMENSION_HPP
#define BOOST_UNITS_LUMINOUS_FLUX_DERIVED_DIMENSION_HPP
#include <boost/units/derived_dimension.hpp>
#include <boost/units/physical_dimensions/luminous_intensity.hpp>
#include <boost/units/physical_dimensions/solid_angle.hpp>
namespace boost {
namespace units {
/// derived dimension for luminous flux : I QS
typedef derived_dimension<luminous_intensity_base_dimension,1,
solid_angle_base_dimension,1>::type luminous_flux_dimension;
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_LUMINOUS_FLUX_DERIVED_DIMENSION_HPP
|
{
"language": "C++"
}
|
/**
* Copyright (C) 2019-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <vector>
#include "mongo/base/string_data.h"
namespace mongo {
/**
* Allow components a way to tell the watchdog what to watch.
*/
void registerWatchdogPath(StringData path);
/**
* Get list of registered watchdog paths.
*/
std::vector<std::string>& getWatchdogPaths();
} // namespace mongo
|
{
"language": "C++"
}
|
/*==========================================================================*/
/*
FILE DESCRIPTION: Rate main
AUTHOR: Kildor
GROUP: The NULL workgroup
PROJECT: Contact`s rate
PART: Main
VERSION: 1.0
CREATED: 20.12.2006 23:11:41
EMAIL: [email protected]
WWW: http://kildor.miranda.im
COPYRIGHT: (C) 2006 The NULL workgroup. All Rights Reserved.
*/
/*--------------------------------------------------------------------------*/
/*
Copyright (C) 2006 The NULL workgroup
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "stdafx.h"
static HANDLE hExtraIcon = nullptr;
struct CMPlugin : public PLUGIN<CMPlugin>
{
CMPlugin();
int Load() override;
}
g_plugin;
///////////////////////////////////////////////////////////////////////////////
PLUGININFOEX pluginInfoEx =
{
sizeof(PLUGININFOEX),
__PLUGIN_NAME,
PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM),
__DESCRIPTION,
__AUTHOR,
__COPYRIGHT,
__AUTHORWEB,
UNICODE_AWARE,
// {45230488-977B-405B-856D-EA276D7083B7}
{0x45230488, 0x977b, 0x405b, {0x85, 0x6d, 0xea, 0x27, 0x6d, 0x70, 0x83, 0xb7}}
};
CMPlugin::CMPlugin() :
PLUGIN<CMPlugin>("Rate", pluginInfoEx)
{}
///////////////////////////////////////////////////////////////////////////////
static void setExtraIcon(MCONTACT hContact, int bRate = -1, BOOL clear = TRUE)
{
if (hContact == NULL)
return;
if (bRate < 0)
bRate = db_get_b(hContact, "CList", "Rate", 0);
const char *icon = nullptr;
switch (bRate) {
case 1: icon = "rate_low"; break;
case 2: icon = "rate_medium"; break;
case 3: icon = "rate_high"; break;
}
if (icon != nullptr || clear)
ExtraIcon_SetIconByName(hExtraIcon, hContact, icon);
}
///////////////////////////////////////////////////////////////////////////////
static IconItem iconList[] =
{
{ LPGEN("Rate high"), "rate_high", IDI_RATEHI },
{ LPGEN("Rate medium"), "rate_medium", IDI_RATEME },
{ LPGEN("Rate low"), "rate_low", IDI_RATELO },
};
int onModulesLoaded(WPARAM, LPARAM)
{
// Set initial value for all contacts
for (auto &hContact : Contacts())
setExtraIcon(hContact, -1, FALSE);
return 0;
}
int onContactSettingChanged(WPARAM hContact, LPARAM lParam)
{
DBCONTACTWRITESETTING *cws = (DBCONTACTWRITESETTING*)lParam;
if (hContact != NULL && !strcmp(cws->szModule, "CList") && !strcmp(cws->szSetting, "Rate"))
setExtraIcon(hContact, cws->value.type == DBVT_DELETED ? 0 : cws->value.bVal);
return 0;
}
int CMPlugin::Load()
{
HookEvent(ME_SYSTEM_MODULESLOADED, onModulesLoaded);
HookEvent(ME_DB_CONTACT_SETTINGCHANGED, onContactSettingChanged);
// IcoLib support
g_plugin.registerIcon(LPGEN("Contact rate"), iconList);
// Extra icon support
hExtraIcon = ExtraIcon_RegisterIcolib("contact_rate", LPGEN("Contact rate"), "rate_high");
return 0;
}
|
{
"language": "C++"
}
|
// This is core/vgui/vgui_find.cxx
//:
// \file
// \author fsm
// \brief See vgui_find.h for a description of this file.
#include "vgui_find.h"
#include "vgui/vgui_tableau.h"
// Does a depth-first search for the first tableau whose type_name()
// method returns the given std::string. Returns 0 if no tableau is found.
vgui_tableau_sptr
vgui_find_by_type_name(vgui_tableau_sptr const & start, std::string const & tn, bool direction_down)
{
if (!start)
return nullptr;
if (start->type_name() == tn)
return start;
std::vector<vgui_tableau_sptr> tt;
if (direction_down)
start->get_children(&tt); // get all children.
else
start->get_parents(&tt); // get all parents.
for (unsigned int i = 0; i < tt.size(); ++i)
{
vgui_tableau_sptr t = vgui_find_by_type_name(tt[i], tn, direction_down);
if (t)
return t; // found one.
}
return nullptr; // not found.
}
vgui_tableau_sptr
vgui_find_by_name(vgui_tableau_sptr const & start, std::string const & name, bool direction_down)
{
if (!start)
return nullptr;
if (start->name() == name)
return start;
std::vector<vgui_tableau_sptr> tt;
if (direction_down)
start->get_children(&tt); // get all children.
else
start->get_parents(&tt); // get all parents.
for (unsigned int i = 0; i < tt.size(); ++i)
{
vgui_tableau_sptr t = vgui_find_by_name(tt[i], name, direction_down);
if (t)
return t; // found one.
}
return nullptr; // not found.
}
|
{
"language": "C++"
}
|
// Boost.Range ATL Extension
//
// Copyright Shunsuke Sogame 2005-2006.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// #include <pstade/vodka/drink.hpp>
#include <boost/test/test_tools.hpp>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define BOOST_LIB_NAME boost_test_exec_monitor
#include <boost/config/auto_link.hpp>
#define BOOST_RANGE_DETAIL_MICROSOFT_TEST
#include <boost/range/atl.hpp> // can be placed first
#include <map>
#include <string>
#include <boost/concept_check.hpp>
#include <boost/mpl/if.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/distance.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/foreach.hpp>
#include <atlbase.h> // for ATL3 CSimpleArray/CSimpleValArray
#if !(_ATL_VER < 0x0700)
#include <atlcoll.h>
#include <cstringt.h>
#include <atlsimpstr.h>
#include <atlstr.h>
#endif
namespace brdm = boost::range_detail_microsoft;
#if !(_ATL_VER < 0x0700)
template< class ArrayT, class SampleRange >
bool test_init_auto_ptr_array(ArrayT& arr, SampleRange& sample)
{
typedef typename boost::range_iterator<SampleRange>::type iter_t;
for (iter_t it = boost::begin(sample), last = boost::end(sample); it != last; ++it) {
arr.Add(*it); // moves ownership
}
return boost::distance(arr) == boost::distance(sample);
}
template< class ListT, class SampleRange >
bool test_init_auto_ptr_list(ListT& lst, SampleRange& sample)
{
typedef typename boost::range_iterator<SampleRange>::type iter_t;
typedef typename boost::range_value<SampleRange>::type val_t;
for (iter_t it = boost::begin(sample), last = boost::end(sample); it != last; ++it) {
lst.AddTail(*it); // moves ownership
}
return boost::distance(lst) == boost::distance(sample);
}
// Workaround:
// CRBTree provides no easy access function, but yes, it is the range!
//
template< class AtlMapT, class KeyT, class MappedT >
bool test_atl_map_has(AtlMapT& map, const KeyT& k, const MappedT m)
{
typedef typename boost::range_iterator<AtlMapT>::type iter_t;
for (iter_t it = boost::begin(map), last = boost::end(map); it != last; ++it) {
if (it->m_key == k && it->m_value == m)
return true;
}
return false;
}
template< class AtlMapT, class MapT >
bool test_atl_map(AtlMapT& map, const MapT& sample)
{
typedef typename boost::range_iterator<AtlMapT>::type iter_t;
typedef typename boost::range_const_iterator<MapT>::type siter_t;
bool result = true;
result = result && (boost::distance(map) == boost::distance(sample));
if (!result)
return false;
{
for (iter_t it = boost::begin(map), last = boost::end(map); it != last; ++it) {
result = result && brdm::test_find_key_and_mapped(sample, std::make_pair(it->m_key, it->m_value));
}
}
{
for (siter_t it = boost::begin(sample), last = boost::end(sample); it != last; ++it) {
result = result && (test_atl_map_has)(map, it->first, it->second);
}
}
return result;
}
template< class MapT, class SampleMap >
bool test_init_atl_multimap(MapT& map, const SampleMap& sample)
{
typedef typename boost::range_const_iterator<SampleMap>::type iter_t;
for (iter_t it = boost::const_begin(sample), last = boost::const_end(sample); it != last; ++it) {
map.Insert(it->first, it->second);
}
return boost::distance(map) == boost::distance(sample);
}
// arrays
//
template< class Range >
void test_CAtlArray(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef ATL::CAtlArray<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, val_t *>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, val_t const*>::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_array(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class ValT, class Range >
void test_CAutoPtrArray(Range& sample)
{
typedef ValT val_t;
typedef ATL::CAutoPtrArray<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, boost::indirect_iterator< ATL::CAutoPtr<val_t> *> >::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, boost::indirect_iterator< ATL::CAutoPtr<val_t> const*> >::value ));
rng_t rng;
BOOST_CHECK( ::test_init_auto_ptr_array(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class I, class Range >
void test_CInterfaceArray(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef ATL::CInterfaceArray<I> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, ATL::CComQIPtr<I> * >::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, ATL::CComQIPtr<I> const* >::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_array(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
// lists
//
template< class Range >
void test_CAtlList(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef ATL::CAtlList<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter< rng_t, brdm::list_iterator<rng_t, val_t> >::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter < rng_t, brdm::list_iterator<rng_t const, val_t const> >::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_list(rng, sample) );
BOOST_CHECK( brdm::test_bidirectional(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class ValT, class Range >
void test_CAutoPtrList(Range& sample)
{
typedef ValT val_t;
typedef ATL::CAutoPtrList<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter< rng_t, boost::indirect_iterator< brdm::list_iterator<rng_t, ATL::CAutoPtr<val_t> > > >::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter < rng_t, boost::indirect_iterator< brdm::list_iterator<rng_t const, ATL::CAutoPtr<val_t> const> > >::value ));
rng_t rng;
BOOST_CHECK( ::test_init_auto_ptr_list(rng, sample) );
BOOST_CHECK( brdm::test_bidirectional(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class ValT, class Range >
void test_CHeapPtrList(const Range& sample)
{
typedef ValT val_t;
typedef ATL::CHeapPtrList<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter< rng_t, boost::indirect_iterator< brdm::list_iterator<rng_t, ATL::CHeapPtr<val_t> > > >::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter < rng_t, boost::indirect_iterator< brdm::list_iterator<rng_t const, ATL::CHeapPtr<val_t> const> > >::value ));
rng_t rng;
BOOST_CHECK( ::test_init_auto_ptr_list(rng, sample) );
BOOST_CHECK( brdm::test_bidirectional(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class I, class Range >
void test_CInterfaceList(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef ATL::CInterfaceList<I> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter< rng_t, brdm::list_iterator<rng_t, ATL::CComQIPtr<I> > >::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter < rng_t, brdm::list_iterator<rng_t const, ATL::CComQIPtr<I> const> >::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_list(rng, sample) );
BOOST_CHECK( brdm::test_bidirectional(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
// strings
//
template< class Range >
void test_CSimpleStringT(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef typename boost::mpl::if_< boost::is_same<val_t, char>,
ATL::CAtlStringA,
ATL::CAtlStringW
>::type derived_t;
typedef ATL::CSimpleStringT<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, typename rng_t::PXSTR>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, typename rng_t::PCXSTR>::value ));
derived_t drng;
rng_t& rng = drng;
BOOST_CHECK( brdm::test_init_string(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
// BOOST_CHECK( brdm::test_emptiness(rng) ); no default constructible
}
template< int n, class Range >
void test_CFixedStringT(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef typename boost::mpl::if_< boost::is_same<val_t, char>,
ATL::CAtlStringA,
ATL::CAtlStringW
>::type base_t;
typedef ATL::CFixedStringT<base_t, n> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, typename rng_t::PXSTR>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, typename rng_t::PCXSTR>::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_string(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class Range >
void test_CStringT(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef typename boost::mpl::if_< boost::is_same<val_t, char>,
ATL::CAtlStringA, // == CStringT<char, X>
ATL::CAtlStringW // == CStringT<wchar_t, X>
>::type rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, typename rng_t::PXSTR>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, typename rng_t::PCXSTR>::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_string(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class Range >
void test_CStaticString(const Range& sample)
{
#if !defined(BOOST_RANGE_ATL_NO_TEST_UNDOCUMENTED_RANGE)
{
typedef ATL::CStaticString<char, 20> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, char const *>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, char const *>::value ));
rng_t rng("hello static string");
BOOST_CHECK( *(boost::begin(rng)+4) == 'o' );
BOOST_CHECK( *(boost::end(rng)-3) == 'i' );
}
{
typedef ATL::CStaticString<wchar_t, 40> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, wchar_t const *>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, wchar_t const *>::value ));
rng_t rng(L"hello static string");
BOOST_CHECK( *(boost::begin(rng)+4) == L'o' );
BOOST_CHECK( *(boost::end(rng)-3) == L'i' );
}
#endif
(void)sample; // unused
}
#endif // !(_ATL_VER < 0x0700)
template< class Range >
void test_CComBSTR(const Range& sample)
{
typedef ATL::CComBSTR rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, OLECHAR *>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, OLECHAR const*>::value ));
rng_t rng(OLESTR("hello CComBSTR range!"));
BOOST_CHECK( brdm::test_equals(rng, std::string("hello CComBSTR range!")) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
(void)sample; // unused
}
// simples
//
template< class Range >
void test_CSimpleArray(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef ATL::CSimpleArray<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, val_t *>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, val_t const*>::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_array(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
template< class Range >
void test_CSimpleMap(const Range& sample)
{
#if !defined(BOOST_RANGE_ATL_NO_TEST_UNDOCUMENTED_RANGE)
typedef ATL::CSimpleMap<int, double> rng_t;
rng_t rng;
rng.Add(3, 3.0);
rng.Add(4, 2.0);
BOOST_CHECK( boost::begin(rng)->get<0>() == 3.0 );
BOOST_CHECK( (boost::end(rng)-1)->get<1>() == 2.0 );
#endif
(void)sample; // unused
}
template< class Range >
void test_CSimpleValArray(const Range& sample)
{
typedef typename boost::range_value<Range>::type val_t;
typedef ATL::CSimpleArray<val_t> rng_t;
BOOST_STATIC_ASSERT(( brdm::test_mutable_iter<rng_t, val_t *>::value ));
BOOST_STATIC_ASSERT(( brdm::test_const_iter <rng_t, val_t const*>::value ));
rng_t rng;
BOOST_CHECK( brdm::test_init_array(rng, sample) );
BOOST_CHECK( brdm::test_random_access(rng) );
BOOST_CHECK( brdm::test_emptiness(rng) );
}
// maps
//
template< class MapT >
void test_CAtlMap(const MapT& sample)
{
typedef typename MapT::key_type k_t;
typedef typename MapT::mapped_type m_t;
typedef ATL::CAtlMap<k_t, m_t> rng_t;
rng_t rng;
boost::function_requires< boost::ForwardRangeConcept<rng_t> >();
BOOST_CHECK( brdm::test_init_map(rng, sample) );
BOOST_CHECK( ::test_atl_map(rng, sample) );
}
template< class MapT >
void test_CRBTree(const MapT& sample)
{
typedef typename MapT::key_type k_t;
typedef typename MapT::mapped_type m_t;
typedef ATL::CRBMap<k_t, m_t> derived_t;
typedef ATL::CRBTree<k_t, m_t> rng_t;
derived_t drng;
rng_t& rng = drng;
boost::function_requires< boost::BidirectionalRangeConcept<rng_t> >();
BOOST_CHECK( brdm::test_init_map(drng, sample) );
BOOST_CHECK( ::test_atl_map(rng, sample) );
}
template< class MapT >
void test_CRBMap(const MapT& sample)
{
typedef typename MapT::key_type k_t;
typedef typename MapT::mapped_type m_t;
typedef ATL::CRBMap<k_t, m_t> rng_t;
rng_t rng;
boost::function_requires< boost::BidirectionalRangeConcept<rng_t> >();
BOOST_CHECK( brdm::test_init_map(rng, sample) );
BOOST_CHECK( ::test_atl_map(rng, sample) );
}
template< class MapT >
void test_CRBMultiMap(const MapT& sample)
{
typedef typename MapT::key_type k_t;
typedef typename MapT::mapped_type m_t;
typedef ATL::CRBMultiMap<k_t, m_t> rng_t;
rng_t rng;
boost::function_requires< boost::BidirectionalRangeConcept<rng_t> >();
BOOST_CHECK( ::test_init_atl_multimap(rng, sample) );
BOOST_CHECK( ::test_atl_map(rng, sample) );
}
// main test
//
void test_atl()
{
// ordinary ranges
//
{
std::string sample("rebecca judy and mary whiteberry chat monchy");
#if !(_ATL_VER < 0x0700)
::test_CAtlArray(sample);
::test_CAtlList(sample);
::test_CSimpleStringT(sample);
::test_CFixedStringT<44>(sample);
::test_CStringT(sample);
::test_CStaticString(sample);
#endif
::test_CComBSTR(sample);
::test_CSimpleArray(sample);
::test_CSimpleMap(sample);
::test_CSimpleValArray(sample);
}
{
std::wstring sample(L"rebecca judy and mary whiteberry chat monchy");
#if !(_ATL_VER < 0x0700)
::test_CAtlArray(sample);
::test_CAtlList(sample);
::test_CSimpleStringT(sample);
::test_CFixedStringT<44>(sample);
::test_CStringT(sample);
::test_CStaticString(sample);
#endif
::test_CComBSTR(sample);
::test_CSimpleArray(sample);
::test_CSimpleMap(sample);
::test_CSimpleValArray(sample);
}
// pointer ranges
//
#if !(_ATL_VER < 0x0700)
{
typedef ATL::CAutoPtr<int> ptr_t;
ptr_t
ptr0(new int(3)), ptr1(new int(4)), ptr2(new int(5)), ptr3(new int(4)),
ptr4(new int(1)), ptr5(new int(2)), ptr6(new int(4)), ptr7(new int(0));
ptr_t ptrs[8] = {
ptr0, ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7
};
boost::iterator_range< ptr_t * > workaround(ptrs, ptrs+8);
::test_CAutoPtrArray<int>(workaround);
}
{
typedef ATL::CAutoPtr<int> ptr_t;
ptr_t
ptr0(new int(3)), ptr1(new int(4)), ptr2(new int(5)), ptr3(new int(4)),
ptr4(new int(1)), ptr5(new int(2)), ptr6(new int(4)), ptr7(new int(0));
ptr_t ptrs[8] = {
ptr0, ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7
};
boost::iterator_range< ptr_t * > workaround(ptrs, ptrs+8);
::test_CAutoPtrList<int>(workaround);
}
{
typedef ATL::CHeapPtr<int> ptr_t;
ptr_t ptrs[5]; {
ptrs[0].AllocateBytes(sizeof(int));
ptrs[1].AllocateBytes(sizeof(int));
ptrs[2].AllocateBytes(sizeof(int));
ptrs[3].AllocateBytes(sizeof(int));
ptrs[4].AllocateBytes(sizeof(int));
}
boost::iterator_range< ptr_t * > workaround(ptrs, ptrs+5);
::test_CHeapPtrList<int>(workaround);
}
{
typedef ATL::CComQIPtr<IDispatch> ptr_t;
ptr_t ptrs[8];
boost::iterator_range< ptr_t * > workaround(ptrs, ptrs+8);
::test_CInterfaceArray<IDispatch>(workaround);
::test_CInterfaceList<IDispatch>(workaround);
}
#endif
// maps
//
{
#if !(_ATL_VER < 0x0700)
std::map<int, std::string> sample; {
sample[0] = "hello";
sample[1] = "range";
sample[2] = "atl";
sample[3] = "mfc";
sample[4] = "collections";
}
::test_CAtlMap(sample);
::test_CRBTree(sample);
::test_CRBMap(sample);
::test_CRBMultiMap(sample);
#endif
}
} // test_atl
#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;
test_suite *
init_unit_test_suite(int argc, char* argv[])
{
test_suite *test = BOOST_TEST_SUITE("ATL Range Test Suite");
test->add(BOOST_TEST_CASE(&test_atl));
(void)argc, (void)argv; // unused
return test;
}
|
{
"language": "C++"
}
|
// unitrayDlg.h : header file
//
#if !defined(AFX_UNITRAYDLG_H__DE84CD38_DB2D_49F0_A688_65B7168154AA__INCLUDED_)
#define AFX_UNITRAYDLG_H__DE84CD38_DB2D_49F0_A688_65B7168154AA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CUnitrayDlg dialog
class CUnitrayDlg : public CDialog
{
// Construction
public:
CUnitrayDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CUnitrayDlg)
enum { IDD = IDD_UNITRAY_DIALOG };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CUnitrayDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CUnitrayDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_UNITRAYDLG_H__DE84CD38_DB2D_49F0_A688_65B7168154AA__INCLUDED_)
|
{
"language": "C++"
}
|
/****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CC_PU_PARTICLE_3D_ON_RANDOM_OBSERVER_H__
#define __CC_PU_PARTICLE_3D_ON_RANDOM_OBSERVER_H__
#include "base/CCRef.h"
#include "math/CCMath.h"
#include "extensions/Particle3D/PU/CCPUObserver.h"
#include <vector>
#include <string>
NS_CC_BEGIN
struct PUParticle3D;
class PUParticleSystem3D;
class CC_DLL PUOnRandomObserver : public PUObserver
{
public:
// Constants
static const float DEFAULT_THRESHOLD;
static PUOnRandomObserver* create();
/** See ParticleObserver::_preProcessParticles()
*/
virtual void preUpdateObserver(float deltaTime) override;
/** See ParticleObserver::_processParticle()
*/
virtual void updateObserver(PUParticle3D *particle, float deltaTime, bool firstParticle) override;
/**
*/
virtual bool observe (PUParticle3D* particle, float timeElapsed) override;
/**
*/
float getThreshold(void) const {return _threshold;};
void setThreshold(float threshold){_threshold = threshold;};
virtual void copyAttributesTo (PUObserver* observer) override;
CC_CONSTRUCTOR_ACCESS:
PUOnRandomObserver(void);
virtual ~PUOnRandomObserver(void) {};
protected:
float _threshold; // Value between 0..1
};
NS_CC_END
#endif
|
{
"language": "C++"
}
|
/*
* Copyright (C) 2010 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSNPObject.h"
#include "JSNPMethod.h"
#include "NPJSObject.h"
#include "NPRuntimeObjectMap.h"
#include "NPRuntimeUtilities.h"
#include <JavaScriptCore/Error.h>
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/JSLock.h>
#include <JavaScriptCore/ObjectPrototype.h>
#include <WebCore/IdentifierRep.h>
#include <wtf/text/WTFString.h>
using namespace JSC;
using namespace WebCore;
namespace WebKit {
static NPIdentifier npIdentifierFromIdentifier(const Identifier& identifier)
{
return static_cast<NPIdentifier>(IdentifierRep::get(identifier.ustring().utf8().data()));
}
const ClassInfo JSNPObject::s_info = { "NPObject", &JSObjectWithGlobalObject::s_info, 0, 0 };
JSNPObject::JSNPObject(JSGlobalObject* globalObject, NPRuntimeObjectMap* objectMap, NPObject* npObject)
: JSObjectWithGlobalObject(globalObject, createStructure(globalObject->globalData(), globalObject->objectPrototype()))
, m_objectMap(objectMap)
, m_npObject(npObject)
{
ASSERT(inherits(&s_info));
// We should never have an NPJSObject inside a JSNPObject.
ASSERT(!NPJSObject::isNPJSObject(m_npObject));
retainNPObject(m_npObject);
}
JSNPObject::~JSNPObject()
{
if (!m_npObject)
return;
m_objectMap->jsNPObjectDestroyed(this);
releaseNPObject(m_npObject);
}
void JSNPObject::invalidate()
{
ASSERT(m_npObject);
releaseNPObject(m_npObject);
m_npObject = 0;
}
JSValue JSNPObject::callMethod(ExecState* exec, NPIdentifier methodName)
{
if (!m_npObject)
return throwInvalidAccessError(exec);
size_t argumentCount = exec->argumentCount();
Vector<NPVariant, 8> arguments(argumentCount);
// Convert all arguments to NPVariants.
for (size_t i = 0; i < argumentCount; ++i)
m_objectMap->convertJSValueToNPVariant(exec, exec->argument(i), arguments[i]);
// Calling NPClass::invoke will call into plug-in code, and there's no telling what the plug-in can do.
// (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until
// the call has finished.
NPRuntimeObjectMap::PluginProtector protector(m_objectMap);
bool returnValue;
NPVariant result;
VOID_TO_NPVARIANT(result);
{
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly);
returnValue = m_npObject->_class->invoke(m_npObject, methodName, arguments.data(), argumentCount, &result);
NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec);
}
// Release all arguments;
for (size_t i = 0; i < argumentCount; ++i)
releaseNPVariantValue(&arguments[i]);
if (!returnValue)
throwError(exec, createError(exec, "Error calling method on NPObject."));
JSValue propertyValue = m_objectMap->convertNPVariantToJSValue(exec, globalObject(), result);
releaseNPVariantValue(&result);
return propertyValue;
}
JSC::JSValue JSNPObject::callObject(JSC::ExecState* exec)
{
if (!m_npObject)
return throwInvalidAccessError(exec);
size_t argumentCount = exec->argumentCount();
Vector<NPVariant, 8> arguments(argumentCount);
// Convert all arguments to NPVariants.
for (size_t i = 0; i < argumentCount; ++i)
m_objectMap->convertJSValueToNPVariant(exec, exec->argument(i), arguments[i]);
// Calling NPClass::invokeDefault will call into plug-in code, and there's no telling what the plug-in can do.
// (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until
// the call has finished.
NPRuntimeObjectMap::PluginProtector protector(m_objectMap);
bool returnValue;
NPVariant result;
VOID_TO_NPVARIANT(result);
{
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly);
returnValue = m_npObject->_class->invokeDefault(m_npObject, arguments.data(), argumentCount, &result);
NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec);
}
// Release all arguments;
for (size_t i = 0; i < argumentCount; ++i)
releaseNPVariantValue(&arguments[i]);
if (!returnValue)
throwError(exec, createError(exec, "Error calling method on NPObject."));
JSValue propertyValue = m_objectMap->convertNPVariantToJSValue(exec, globalObject(), result);
releaseNPVariantValue(&result);
return propertyValue;
}
JSValue JSNPObject::callConstructor(ExecState* exec)
{
if (!m_npObject)
return throwInvalidAccessError(exec);
size_t argumentCount = exec->argumentCount();
Vector<NPVariant, 8> arguments(argumentCount);
// Convert all arguments to NPVariants.
for (size_t i = 0; i < argumentCount; ++i)
m_objectMap->convertJSValueToNPVariant(exec, exec->argument(i), arguments[i]);
// Calling NPClass::construct will call into plug-in code, and there's no telling what the plug-in can do.
// (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until
// the call has finished.
NPRuntimeObjectMap::PluginProtector protector(m_objectMap);
bool returnValue;
NPVariant result;
VOID_TO_NPVARIANT(result);
{
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly);
returnValue = m_npObject->_class->construct(m_npObject, arguments.data(), argumentCount, &result);
NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec);
}
if (!returnValue)
throwError(exec, createError(exec, "Error calling method on NPObject."));
JSValue value = m_objectMap->convertNPVariantToJSValue(exec, globalObject(), result);
releaseNPVariantValue(&result);
return value;
}
static EncodedJSValue JSC_HOST_CALL callNPJSObject(ExecState* exec)
{
JSObject* object = exec->callee();
ASSERT(object->inherits(&JSNPObject::s_info));
return JSValue::encode(static_cast<JSNPObject*>(object)->callObject(exec));
}
JSC::CallType JSNPObject::getCallData(JSC::CallData& callData)
{
if (!m_npObject || !m_npObject->_class->invokeDefault)
return CallTypeNone;
callData.native.function = callNPJSObject;
return CallTypeHost;
}
static EncodedJSValue JSC_HOST_CALL constructWithConstructor(ExecState* exec)
{
JSObject* constructor = exec->callee();
ASSERT(constructor->inherits(&JSNPObject::s_info));
return JSValue::encode(static_cast<JSNPObject*>(constructor)->callConstructor(exec));
}
ConstructType JSNPObject::getConstructData(ConstructData& constructData)
{
if (!m_npObject || !m_npObject->_class->construct)
return ConstructTypeNone;
constructData.native.function = constructWithConstructor;
return ConstructTypeHost;
}
bool JSNPObject::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
if (!m_npObject) {
throwInvalidAccessError(exec);
return false;
}
NPIdentifier npIdentifier = npIdentifierFromIdentifier(propertyName);
// First, check if the NPObject has a property with this name.
if (m_npObject->_class->hasProperty && m_npObject->_class->hasProperty(m_npObject, npIdentifier)) {
slot.setCustom(this, propertyGetter);
return true;
}
// Second, check if the NPObject has a method with this name.
if (m_npObject->_class->hasMethod && m_npObject->_class->hasMethod(m_npObject, npIdentifier)) {
slot.setCustom(this, methodGetter);
return true;
}
return false;
}
bool JSNPObject::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
if (!m_npObject) {
throwInvalidAccessError(exec);
return false;
}
NPIdentifier npIdentifier = npIdentifierFromIdentifier(propertyName);
// First, check if the NPObject has a property with this name.
if (m_npObject->_class->hasProperty && m_npObject->_class->hasProperty(m_npObject, npIdentifier)) {
PropertySlot slot;
slot.setCustom(this, propertyGetter);
descriptor.setDescriptor(slot.getValue(exec, propertyName), DontDelete);
return true;
}
// Second, check if the NPObject has a method with this name.
if (m_npObject->_class->hasMethod && m_npObject->_class->hasMethod(m_npObject, npIdentifier)) {
PropertySlot slot;
slot.setCustom(this, methodGetter);
descriptor.setDescriptor(slot.getValue(exec, propertyName), DontDelete | ReadOnly);
return true;
}
return false;
}
void JSNPObject::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot&)
{
if (!m_npObject) {
throwInvalidAccessError(exec);
return;
}
NPIdentifier npIdentifier = npIdentifierFromIdentifier(propertyName);
if (!m_npObject->_class->hasProperty || !m_npObject->_class->hasProperty(m_npObject, npIdentifier)) {
// FIXME: Should we throw an exception here?
return;
}
if (!m_npObject->_class->setProperty)
return;
NPVariant variant;
m_objectMap->convertJSValueToNPVariant(exec, value, variant);
// Calling NPClass::setProperty will call into plug-in code, and there's no telling what the plug-in can do.
// (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until
// the call has finished.
NPRuntimeObjectMap::PluginProtector protector(m_objectMap);
{
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly);
m_npObject->_class->setProperty(m_npObject, npIdentifier, &variant);
NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec);
// FIXME: Should we throw an exception if setProperty returns false?
}
releaseNPVariantValue(&variant);
}
void JSNPObject::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNameArray, EnumerationMode mode)
{
if (!m_npObject) {
throwInvalidAccessError(exec);
return;
}
if (!NP_CLASS_STRUCT_VERSION_HAS_ENUM(m_npObject->_class) || !m_npObject->_class->enumerate)
return;
NPIdentifier* identifiers = 0;
uint32_t identifierCount = 0;
// Calling NPClass::enumerate will call into plug-in code, and there's no telling what the plug-in can do.
// (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until
// the call has finished.
NPRuntimeObjectMap::PluginProtector protector(m_objectMap);
{
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly);
// FIXME: Should we throw an exception if enumerate returns false?
if (!m_npObject->_class->enumerate(m_npObject, &identifiers, &identifierCount))
return;
NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec);
}
for (uint32_t i = 0; i < identifierCount; ++i) {
IdentifierRep* identifierRep = static_cast<IdentifierRep*>(identifiers[i]);
Identifier identifier;
if (identifierRep->isString()) {
const char* string = identifierRep->string();
int length = strlen(string);
identifier = Identifier(exec, String::fromUTF8WithLatin1Fallback(string, length).impl());
} else
identifier = Identifier::from(exec, identifierRep->number());
propertyNameArray.add(identifier);
}
npnMemFree(identifiers);
}
JSValue JSNPObject::propertyGetter(ExecState* exec, JSValue slotBase, const Identifier& propertyName)
{
JSNPObject* thisObj = static_cast<JSNPObject*>(asObject(slotBase));
if (!thisObj->m_npObject)
return throwInvalidAccessError(exec);
if (!thisObj->m_npObject->_class->getProperty)
return jsUndefined();
NPVariant result;
VOID_TO_NPVARIANT(result);
// Calling NPClass::getProperty will call into plug-in code, and there's no telling what the plug-in can do.
// (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until
// the call has finished.
NPRuntimeObjectMap::PluginProtector protector(thisObj->m_objectMap);
bool returnValue;
{
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly);
NPIdentifier npIdentifier = npIdentifierFromIdentifier(propertyName);
returnValue = thisObj->m_npObject->_class->getProperty(thisObj->m_npObject, npIdentifier, &result);
NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec);
}
if (!returnValue)
return jsUndefined();
JSValue propertyValue = thisObj->m_objectMap->convertNPVariantToJSValue(exec, thisObj->globalObject(), result);
releaseNPVariantValue(&result);
return propertyValue;
}
JSValue JSNPObject::methodGetter(ExecState* exec, JSValue slotBase, const Identifier& methodName)
{
JSNPObject* thisObj = static_cast<JSNPObject*>(asObject(slotBase));
if (!thisObj->m_npObject)
return throwInvalidAccessError(exec);
NPIdentifier npIdentifier = npIdentifierFromIdentifier(methodName);
return new (exec) JSNPMethod(exec, thisObj->globalObject(), methodName, npIdentifier);
}
JSObject* JSNPObject::throwInvalidAccessError(ExecState* exec)
{
return throwError(exec, createReferenceError(exec, "Trying to access object from destroyed plug-in."));
}
} // namespace WebKit
|
{
"language": "C++"
}
|
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Alec Jacobson <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "writeWRL.h"
#include <iostream>
#include <fstream>
template <typename DerivedV, typename DerivedF>
IGL_INLINE bool igl::writeWRL(
const std::string & str,
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F)
{
using namespace std;
using namespace Eigen;
assert(V.cols() == 3 && "V should have 3 columns");
assert(F.cols() == 3 && "F should have 3 columns");
ofstream s(str);
if(!s.is_open())
{
cerr<<"IOError: writeWRL() could not open "<<str<<endl;
return false;
}
// Append column of -1 to F
Matrix<typename DerivedF::Scalar,Dynamic,4> FF(F.rows(),4);
FF.leftCols(3) = F;
FF.col(3).setConstant(-1);
s<<R"(#VRML V2.0 utf8
DEF default Transform {
translation 0 0 0
children [
Shape {
geometry DEF default-FACES IndexedFaceSet {
ccw TRUE
)"<<
V.format(
IOFormat(
FullPrecision,
DontAlignCols,
" ",",\n","","",
"coord DEF default-COORD Coordinate { point [ \n","]\n}\n"))<<
FF.format(
IOFormat(
FullPrecision,
DontAlignCols,
",","\n","","",
"coordIndex [ \n"," ]\n"))<<
"}\n}\n]\n}\n";
return true;
}
// write mesh and colors-by-vertex to an ascii off file
template <typename DerivedV, typename DerivedF, typename DerivedC>
IGL_INLINE bool igl::writeWRL(
const std::string & str,
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
const Eigen::PlainObjectBase<DerivedC> & C)
{
using namespace std;
using namespace Eigen;
assert(V.cols() == 3 && "V should have 3 columns");
assert(F.cols() == 3 && "F should have 3 columns");
ofstream s(str);
if(!s.is_open())
{
cerr<<"IOError: writeWRL() could not open "<<str<<endl;
return false;
}
// Append column of -1 to F
Matrix<typename DerivedF::Scalar,Dynamic,4> FF(F.rows(),4);
FF.leftCols(3) = F;
FF.col(3).setConstant(-1);
//Check if RGB values are in the range [0..1] or [0..255]
double rgbScale = (C.maxCoeff() <= 1.0)?1.0:1.0/255.0;
Eigen::MatrixXd RGB = rgbScale * C;
s<<R"(#VRML V2.0 utf8
DEF default Transform {
translation 0 0 0
children [
Shape {
geometry DEF default-FACES IndexedFaceSet {
ccw TRUE
)"<<
V.format(
IOFormat(
FullPrecision,
DontAlignCols,
" ",",\n","","",
"coord DEF default-COORD Coordinate { point [ \n","]\n}\n"))<<
FF.format(
IOFormat(
FullPrecision,
DontAlignCols,
",","\n","","",
"coordIndex [ \n"," ]\n"))<<
RGB.format(
IOFormat(
FullPrecision,
DontAlignCols,
",","\n","","",
"colorPerVertex TRUE\ncolor Color { color [ \n"," ] }\n"))<<
"}\n}\n]\n}\n";
return true;
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template bool igl::writeWRL<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&);
// generated by autoexplicit.sh
template bool igl::writeWRL<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&);
// generated by autoexplicit.sh
template bool igl::writeWRL<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&);
// generated by autoexplicit.sh
template bool igl::writeWRL<Eigen::Matrix<double, 8, 3, 0, 8, 3>, Eigen::Matrix<int, 12, 3, 0, 12, 3> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 8, 3, 0, 8, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, 12, 3, 0, 12, 3> > const&);
template bool igl::writeWRL<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&);
template bool igl::writeWRL<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&);
#endif
|
{
"language": "C++"
}
|
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// 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.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_AGGREGATE_FILTER_HPP_INCLUDED
#define BOOST_IOSTREAMS_AGGREGATE_FILTER_HPP_INCLUDED
#if defined(_MSC_VER)
# pragma once
#endif
#include <algorithm> // copy, min.
#include <boost/assert.hpp>
#include <iterator> // back_inserter
#include <vector>
#include <boost/iostreams/constants.hpp> // default_device_buffer_size
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/detail/char_traits.hpp>
#include <boost/iostreams/detail/ios.hpp> // openmode, streamsize.
#include <boost/iostreams/pipeline.hpp>
#include <boost/iostreams/read.hpp> // check_eof
#include <boost/iostreams/write.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/type_traits/is_convertible.hpp>
// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // MSVC.
namespace boost { namespace iostreams {
//
// Template name: aggregate_filter.
// Template parameters:
// Ch - The character type.
// Alloc - The allocator type.
// Description: Utility for defining DualUseFilters which filter an
// entire stream at once. To use, override the protected virtual
// member do_filter.
// Note: This filter should not be copied while it is in use.
//
template<typename Ch, typename Alloc = std::allocator<Ch> >
class aggregate_filter {
public:
typedef Ch char_type;
struct category
: dual_use,
filter_tag,
multichar_tag,
closable_tag
{ };
aggregate_filter() : ptr_(0), state_(0) { }
virtual ~aggregate_filter() { }
template<typename Source>
std::streamsize read(Source& src, char_type* s, std::streamsize n)
{
using namespace std;
BOOST_ASSERT(!(state_ & f_write));
state_ |= f_read;
if (!(state_ & f_eof))
do_read(src);
std::streamsize amt =
(std::min)(n, static_cast<std::streamsize>(data_.size() - ptr_));
if (amt) {
BOOST_IOSTREAMS_CHAR_TRAITS(char_type)::copy(s, &data_[ptr_], amt);
ptr_ += amt;
}
return detail::check_eof(amt);
}
template<typename Sink>
std::streamsize write(Sink&, const char_type* s, std::streamsize n)
{
BOOST_ASSERT(!(state_ & f_read));
state_ |= f_write;
data_.insert(data_.end(), s, s + n);
return n;
}
template<typename Sink>
void close(Sink& sink, BOOST_IOS::openmode which)
{
if ((state_ & f_read) != 0 && which == BOOST_IOS::in)
close_impl();
if ((state_ & f_write) != 0 && which == BOOST_IOS::out) {
try {
vector_type filtered;
do_filter(data_, filtered);
do_write(
sink, &filtered[0],
static_cast<std::streamsize>(filtered.size())
);
} catch (...) {
close_impl();
throw;
}
close_impl();
}
}
protected:
typedef std::vector<Ch, Alloc> vector_type;
typedef typename vector_type::size_type size_type;
private:
virtual void do_filter(const vector_type& src, vector_type& dest) = 0;
virtual void do_close() { }
template<typename Source>
void do_read(Source& src)
{
using std::streamsize;
vector_type data;
while (true) {
const std::streamsize size = default_device_buffer_size;
Ch buf[size];
std::streamsize amt;
if ((amt = boost::iostreams::read(src, buf, size)) == -1)
break;
data.insert(data.end(), buf, buf + amt);
}
do_filter(data, data_);
state_ |= f_eof;
}
template<typename Sink>
void do_write(Sink& sink, const char_type* s, std::streamsize n)
{
typedef typename iostreams::category_of<Sink>::type category;
typedef is_convertible<category, output> can_write;
do_write(sink, s, n, can_write());
}
template<typename Sink>
void do_write(Sink& sink, const char_type* s, std::streamsize n, mpl::true_)
{ iostreams::write(sink, s, n); }
template<typename Sink>
void do_write(Sink&, const char_type*, std::streamsize, mpl::false_) { }
void close_impl()
{
data_.clear();
ptr_ = 0;
state_ = 0;
do_close();
}
enum flag_type {
f_read = 1,
f_write = f_read << 1,
f_eof = f_write << 1
};
// Note: typically will not be copied while vector contains data.
vector_type data_;
size_type ptr_;
int state_;
};
BOOST_IOSTREAMS_PIPABLE(aggregate_filter, 1)
} } // End namespaces iostreams, boost.
#include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC.
#endif // #ifndef BOOST_IOSTREAMS_AGGREGATE_FILTER_HPP_INCLUDED
|
{
"language": "C++"
}
|
#ifndef BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
#define BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/push_back_fwd.hpp>
#include <boost/mpl/aux_/config/typeof.hpp>
#if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES)
# include <boost/mpl/vector/aux_/item.hpp>
# include <boost/mpl/vector/aux_/tag.hpp>
namespace boost { namespace mpl {
template<>
struct push_back_impl< aux::vector_tag >
{
template< typename Vector, typename T > struct apply
{
typedef v_item<T,Vector,0> type;
};
};
}}
#endif
#endif // BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
|
{
"language": "C++"
}
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to 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_GEOMETRY_ALGORITHMS_DETAIL_FOR_EACH_RANGE_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_FOR_EACH_RANGE_HPP
#include <boost/mpl/assert.hpp>
#include <boost/concept/requires.hpp>
#include <boost/range.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tag_cast.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/util/add_const_if_c.hpp>
#include <boost/geometry/views/box_view.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace for_each
{
template <typename Range, typename Actor>
struct fe_range_range
{
static inline void apply(Range & range, Actor & actor)
{
actor.apply(range);
}
};
template <typename Polygon, typename Actor>
struct fe_range_polygon
{
static inline void apply(Polygon & polygon, Actor & actor)
{
actor.apply(exterior_ring(polygon));
// TODO: If some flag says true, also do the inner rings.
// for convex hull, it's not necessary
}
};
template <typename Box, typename Actor>
struct fe_range_box
{
static inline void apply(Box & box, Actor & actor)
{
actor.apply(box_view<typename boost::remove_const<Box>::type>(box));
}
};
template <typename Multi, typename Actor, typename SinglePolicy>
struct fe_range_multi
{
static inline void apply(Multi & multi, Actor & actor)
{
for ( typename boost::range_iterator<Multi>::type
it = boost::begin(multi); it != boost::end(multi); ++it)
{
SinglePolicy::apply(*it, actor);
}
}
};
}} // namespace detail::for_each
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template
<
typename Geometry,
typename Actor,
typename Tag = typename tag<Geometry>::type
>
struct for_each_range
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_OR_NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE
, (types<Geometry>)
);
};
template <typename Linestring, typename Actor>
struct for_each_range<Linestring, Actor, linestring_tag>
: detail::for_each::fe_range_range<Linestring, Actor>
{};
template <typename Ring, typename Actor>
struct for_each_range<Ring, Actor, ring_tag>
: detail::for_each::fe_range_range<Ring, Actor>
{};
template <typename Polygon, typename Actor>
struct for_each_range<Polygon, Actor, polygon_tag>
: detail::for_each::fe_range_polygon<Polygon, Actor>
{};
template <typename Box, typename Actor>
struct for_each_range<Box, Actor, box_tag>
: detail::for_each::fe_range_box<Box, Actor>
{};
template <typename MultiPoint, typename Actor>
struct for_each_range<MultiPoint, Actor, multi_point_tag>
: detail::for_each::fe_range_range<MultiPoint, Actor>
{};
template <typename Geometry, typename Actor>
struct for_each_range<Geometry, Actor, multi_linestring_tag>
: detail::for_each::fe_range_multi
<
Geometry,
Actor,
detail::for_each::fe_range_range
<
typename add_const_if_c
<
boost::is_const<Geometry>::value,
typename boost::range_value<Geometry>::type
>::type,
Actor
>
>
{};
template <typename Geometry, typename Actor>
struct for_each_range<Geometry, Actor, multi_polygon_tag>
: detail::for_each::fe_range_multi
<
Geometry,
Actor,
detail::for_each::fe_range_polygon
<
typename add_const_if_c
<
boost::is_const<Geometry>::value,
typename boost::range_value<Geometry>::type
>::type,
Actor
>
>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
namespace detail
{
template <typename Geometry, typename Actor>
inline void for_each_range(Geometry const& geometry, Actor & actor)
{
dispatch::for_each_range
<
Geometry const,
Actor
>::apply(geometry, actor);
}
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_FOR_EACH_RANGE_HPP
|
{
"language": "C++"
}
|
/*
* Active Directory Services Lightweight Directory Provider C
*
* Copyright 2017 Alex Henrie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include "windef.h"
#include "winbase.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(adsldpc);
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, void *reserved)
{
TRACE("(%p, %u, %p)\n", instance, reason, reserved);
switch (reason)
{
case DLL_WINE_PREATTACH:
return FALSE; /* prefer native version */
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(instance);
break;
}
return TRUE;
}
|
{
"language": "C++"
}
|
// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL1.2
// expected-no-diagnostics
void f1(double da) {
double d;
(void) 1.0;
}
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
void f2(void) {
double d;
(void) 1.0;
}
#pragma OPENCL EXTENSION cl_khr_fp64 : disable
void f3(void) {
double d;
}
|
{
"language": "C++"
}
|
//
// FilesystemConfiguration.cpp
//
// Library: Util
// Package: Configuration
// Module: FilesystemConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Util/FilesystemConfiguration.h"
#include "Poco/File.h"
#include "Poco/Path.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/StringTokenizer.h"
#include "Poco/FileStream.h"
using Poco::Path;
using Poco::File;
using Poco::DirectoryIterator;
using Poco::StringTokenizer;
namespace Poco {
namespace Util {
FilesystemConfiguration::FilesystemConfiguration(const std::string& path):
_path(path)
{
_path.makeDirectory();
}
FilesystemConfiguration::~FilesystemConfiguration()
{
}
void FilesystemConfiguration::clear()
{
File regDir(_path);
regDir.remove(true);
}
bool FilesystemConfiguration::getRaw(const std::string& key, std::string& value) const
{
Path p(keyToPath(key));
p.setFileName("data");
File f(p);
if (f.exists())
{
value.reserve((std::string::size_type) f.getSize());
Poco::FileInputStream istr(p.toString());
int c = istr.get();
while (c != std::char_traits<char>::eof())
{
value += (char) c;
c = istr.get();
}
return true;
}
else return false;
}
void FilesystemConfiguration::setRaw(const std::string& key, const std::string& value)
{
Path p(keyToPath(key));
File dir(p);
dir.createDirectories();
p.setFileName("data");
Poco::FileOutputStream ostr(p.toString());
ostr.write(value.data(), (std::streamsize) value.length());
}
void FilesystemConfiguration::enumerate(const std::string& key, Keys& range) const
{
Path p(keyToPath(key));
File dir(p);
if (!dir.exists())
{
return;
}
DirectoryIterator it(p);
DirectoryIterator end;
while (it != end)
{
if (it->isDirectory())
range.push_back(it.name());
++it;
}
}
void FilesystemConfiguration::removeRaw(const std::string& key)
{
Path p(keyToPath(key));
File dir(p);
if (dir.exists())
{
dir.remove(true);
}
}
Path FilesystemConfiguration::keyToPath(const std::string& key) const
{
Path result(_path);
StringTokenizer tokenizer(key, ".", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
for (const auto& tok: tokenizer)
{
result.pushDirectory(tok);
}
return result;
}
} } // namespace Poco::Util
|
{
"language": "C++"
}
|
#pragma once
#ifndef NTSTATUS
typedef __success(return >= 0) LONG NTSTATUS;
#endif
#define VERSIONHELPERAPI inline bool
#define _WIN32_WINNT_NT4 0x0400
#define _WIN32_WINNT_WIN2K 0x0500
#define _WIN32_WINNT_WINXP 0x0501
#define _WIN32_WINNT_WS03 0x0502
#define _WIN32_WINNT_WIN6 0x0600
#define _WIN32_WINNT_VISTA 0x0600
#define _WIN32_WINNT_WS08 0x0600
#define _WIN32_WINNT_LONGHORN 0x0600
#define _WIN32_WINNT_WIN7 0x0601
#define _WIN32_WINNT_WIN8 0x0602
#define _WIN32_WINNT_WINBLUE 0x0603
#define _WIN32_WINNT_WIN10 0x0A00
typedef NTSTATUS(NTAPI* fnRtlGetVersion)(PRTL_OSVERSIONINFOEXW lpVersionInformation);
enum eVerShort
{
WinUnsupported, // Unsupported OS
WinXP, // Windows XP
Win7, // Windows 7
Win8, // Windows 8
Win8Point1, // Windows 8.1
Win10, // Windows 10
Win10AU, // Windows 10 Anniversary update
Win10CU, // Windows 10 Creators update
Win10FC, // Windows 10 Fall Creators update
};
struct WinVersion
{
eVerShort ver = WinUnsupported;
RTL_OSVERSIONINFOEXW native;
};
inline WinVersion& WinVer()
{
static WinVersion g_WinVer;
return g_WinVer;
}
inline void InitVersion()
{
auto& g_WinVer = WinVer();
g_WinVer.native.dwOSVersionInfoSize = sizeof(g_WinVer.native);
auto RtlGetVersion = (fnRtlGetVersion)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion");
if (RtlGetVersion)
RtlGetVersion(&g_WinVer.native);
if (g_WinVer.native.dwMajorVersion != 0)
{
auto fullver = (g_WinVer.native.dwMajorVersion << 8) | g_WinVer.native.dwMinorVersion;
switch (fullver)
{
case _WIN32_WINNT_WIN10:
if (g_WinVer.native.dwBuildNumber >= 16299)
g_WinVer.ver = Win10FC;
else if (g_WinVer.native.dwBuildNumber >= 15063)
g_WinVer.ver = Win10CU;
else if (g_WinVer.native.dwBuildNumber >= 14393)
g_WinVer.ver = Win10AU;
else if (g_WinVer.native.dwBuildNumber >= 10586)
g_WinVer.ver = Win10;
break;
case _WIN32_WINNT_WINBLUE:
g_WinVer.ver = Win8Point1;
break;
case _WIN32_WINNT_WIN8:
g_WinVer.ver = Win8;
break;
case _WIN32_WINNT_WIN7:
g_WinVer.ver = Win7;
break;
case _WIN32_WINNT_WINXP:
g_WinVer.ver = WinXP;
break;
default:
g_WinVer.ver = WinUnsupported;
}
}
}
VERSIONHELPERAPI
IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor, DWORD dwBuild)
{
auto& g_WinVer = WinVer();
if (g_WinVer.native.dwMajorVersion != 0)
{
if (g_WinVer.native.dwMajorVersion > wMajorVersion)
return true;
else if (g_WinVer.native.dwMajorVersion < wMajorVersion)
return false;
if (g_WinVer.native.dwMinorVersion > wMinorVersion)
return true;
else if (g_WinVer.native.dwMinorVersion < wMinorVersion)
return false;
if (g_WinVer.native.wServicePackMajor > wServicePackMajor)
return true;
else if (g_WinVer.native.wServicePackMajor < wServicePackMajor)
return false;
if (g_WinVer.native.dwBuildNumber >= dwBuild)
return true;
}
return false;
}
VERSIONHELPERAPI
IsWindowsXPOrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 0);
}
VERSIONHELPERAPI
IsWindowsXPSP1OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 1, 0);
}
VERSIONHELPERAPI
IsWindowsXPSP2OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 2, 0);
}
VERSIONHELPERAPI
IsWindowsXPSP3OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 3, 0);
}
VERSIONHELPERAPI
IsWindowsVistaOrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 0);
}
VERSIONHELPERAPI
IsWindowsVistaSP1OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 1, 0);
}
VERSIONHELPERAPI
IsWindowsVistaSP2OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 2, 0);
}
VERSIONHELPERAPI
IsWindows7OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0, 0);
}
VERSIONHELPERAPI
IsWindows7SP1OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 1, 0);
}
VERSIONHELPERAPI
IsWindows8OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0, 0);
}
VERSIONHELPERAPI
IsWindows8Point1OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINBLUE), LOBYTE(_WIN32_WINNT_WINBLUE), 0, 0);
}
VERSIONHELPERAPI
IsWindows10OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0, 0);
}
VERSIONHELPERAPI
IsWindows10AnniversaryOrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0, 14393);
}
VERSIONHELPERAPI
IsWindows10CreatorsOrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0, 15063);
}
VERSIONHELPERAPI
IsWindows10FallCreatorsOrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0, 16299);
}
VERSIONHELPERAPI
IsWindowsServer()
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0,{ 0 }, 0, 0, 0, VER_NT_WORKSTATION };
DWORDLONG const dwlConditionMask = VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL);
return !VerifyVersionInfoW(&osvi, VER_PRODUCT_TYPE, dwlConditionMask);
}
|
{
"language": "C++"
}
|
/*
* Scriptographer
*
* This file is part of Scriptographer, a Scripting Plugin for Adobe Illustrator
* http://scriptographer.org/
*
* Copyright (c) 2002-2010, Juerg Lehni
* http://scratchdisk.com/
*
* All rights reserved. See LICENSE file for details.
*/
#include "stdHeaders.h"
#include "ScriptographerEngine.h"
#include "aiGlobals.h"
#include "com_scriptographer_ai_PlacedSymbol.h"
/*
* com.scriptographer.ai.PlacedSymbol
*/
/*
* int nativeCreate(int symbolHandle, com.scriptographer.ai.Matrix matrix)
*/
JNIEXPORT jint JNICALL Java_com_scriptographer_ai_PlacedSymbol_nativeCreate(
JNIEnv *env, jclass cls, jint symbolHandle, jobject matrix) {
try {
short paintOrder;
AIArtHandle artInsert = Item_getInsertionPoint(&paintOrder);
AIRealMatrix mx;
gEngine->convertMatrix(env, kArtboardCoordinates, kCurrentCoordinates,
matrix, &mx);
// harden the matrix as symbols use hard matrixes internaly
sAIHardSoft->AIRealMatrixHarden(&mx);
AIArtHandle res = NULL;
sAISymbol->NewInstanceWithTransform((AIPatternHandle) symbolHandle, &mx,
paintOrder, artInsert, &res);
return (jint) res;
} EXCEPTION_CONVERT(env);
return 0;
}
/*
* int nativeGetSymbol()
*/
JNIEXPORT jint JNICALL Java_com_scriptographer_ai_PlacedSymbol_nativeGetSymbol(
JNIEnv *env, jobject obj) {
try {
AIArtHandle art = gEngine->getArtHandle(env, obj);
AIPatternHandle symbol = NULL;
sAISymbol->GetSymbolPatternOfSymbolArt(art, &symbol);
return (jint) symbol;
} EXCEPTION_CONVERT(env);
return 0;
}
/*
* void setSymbol(com.scriptographer.ai.Symbol symbol)
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_PlacedSymbol_setSymbol(
JNIEnv *env, jobject obj, jobject symbol) {
try {
AIArtHandle art = gEngine->getArtHandle(env, obj, true);
gEngine->getPatternHandle(env, symbol);
sAISymbol->SetSymbolPatternOfSymbolArt(art, symbol);
} EXCEPTION_CONVERT(env);
}
/*
* com.scriptographer.ai.Matrix getMatrix()
*/
JNIEXPORT jobject JNICALL Java_com_scriptographer_ai_PlacedSymbol_getMatrix(
JNIEnv *env, jobject obj) {
try {
AIArtHandle art = gEngine->getArtHandle(env, obj);
AIRealMatrix mx;
sAISymbol->GetSoftTransformOfSymbolArt(art, &mx);
// Flip the scaleY value to reflect orientation of PlacedFile
mx.d = -mx.d;
return gEngine->convertMatrix(env, kCurrentCoordinates,
kArtboardCoordinates, &mx);
} EXCEPTION_CONVERT(env);
return NULL;
}
/*
* void setMatrix(com.scriptographer.ai.Matrix matrix)
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_PlacedSymbol_setMatrix(
JNIEnv *env, jobject obj, jobject matrix) {
try {
AIArtHandle art = gEngine->getArtHandle(env, obj, true);
AIRealMatrix mx;
gEngine->convertMatrix(env, kArtboardCoordinates, kCurrentCoordinates,
matrix, &mx);
// Flip the scaleY value to reflect orientation of PlacedFile
mx.d = -mx.d;
sAISymbol->SetSoftTransformOfSymbolArt(art, &mx);
} EXCEPTION_CONVERT(env);
}
/*
* com.scriptographer.ai.Item embed()
*/
JNIEXPORT jobject JNICALL Java_com_scriptographer_ai_PlacedSymbol_embed(
JNIEnv *env, jobject obj) {
try {
AIArtHandle art = gEngine->getArtHandle(env, obj);
AIArtHandle embedded = NULL;
if (sAISymbol->BreakLinkToSymbol(art, kPlaceAbove, art, &embedded))
throw new StringException("Unable to embed symbol item.");
return gEngine->wrapArtHandle(env, embedded, NULL, true);
} EXCEPTION_CONVERT(env);
return NULL;
}
|
{
"language": "C++"
}
|
//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.
//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 UUID_7E7AB138196311E0907B246CDFD72085
#define UUID_7E7AB138196311E0907B246CDFD72085
#include <boost/qvm/deduce_scalar.hpp>
#include <boost/qvm/vec_traits.hpp>
#include <boost/qvm/static_assert.hpp>
namespace
boost
{
namespace
qvm
{
template <class T,int D>
struct vec;
namespace
qvm_detail
{
template <class V,int D,
int VD=vec_traits<V>::dim>
struct
deduce_vec_default
{
typedef vec<typename vec_traits<V>::scalar_type,D> type;
};
template <class V,int D>
struct
deduce_vec_default<V,D,D>
{
typedef V type;
};
}
template <class V,int Dim=vec_traits<V>::dim>
struct
deduce_vec
{
BOOST_QVM_STATIC_ASSERT(is_vec<V>::value);
typedef typename qvm_detail::deduce_vec_default<V,Dim>::type type;
};
namespace
qvm_detail
{
template <class A,class B,int D,
bool VA=is_vec<A>::value,
bool VB=is_vec<B>::value,
int AD=vec_traits<A>::dim,
int BD=vec_traits<B>::dim>
struct
deduce_v2_default
{
typedef vec<
typename deduce_scalar<
typename scalar<A>::type,
typename scalar<B>::type>::type,
D> type;
};
template <class V,int D>
struct
deduce_v2_default<V,V,D,true,true,D,D>
{
typedef V type;
};
}
template <class A,class B,int D>
struct
deduce_vec2
{
BOOST_QVM_STATIC_ASSERT(is_vec<A>::value || is_vec<B>::value);
typedef typename qvm_detail::deduce_v2_default<A,B,D>::type type;
};
}
}
#endif
|
{
"language": "C++"
}
|
//
// detail/impl/win_iocp_handle_service.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected])
//
// 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_ASIO_DETAIL_IMPL_WIN_IOCP_HANDLE_SERVICE_IPP
#define BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_HANDLE_SERVICE_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_IOCP)
#include <boost/asio/detail/win_iocp_handle_service.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
class win_iocp_handle_service::overlapped_wrapper
: public OVERLAPPED
{
public:
explicit overlapped_wrapper(boost::system::error_code& ec)
{
Internal = 0;
InternalHigh = 0;
Offset = 0;
OffsetHigh = 0;
// Create a non-signalled manual-reset event, for GetOverlappedResult.
hEvent = ::CreateEvent(0, TRUE, FALSE, 0);
if (hEvent)
{
// As documented in GetQueuedCompletionStatus, setting the low order
// bit of this event prevents our synchronous writes from being treated
// as completion port events.
*reinterpret_cast<DWORD_PTR*>(&hEvent) |= 1;
}
else
{
DWORD last_error = ::GetLastError();
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
}
}
~overlapped_wrapper()
{
if (hEvent)
{
::CloseHandle(hEvent);
}
}
};
win_iocp_handle_service::win_iocp_handle_service(
boost::asio::io_service& io_service)
: iocp_service_(boost::asio::use_service<win_iocp_io_service>(io_service)),
mutex_(),
impl_list_(0)
{
}
void win_iocp_handle_service::shutdown_service()
{
// Close all implementations, causing all operations to complete.
boost::asio::detail::mutex::scoped_lock lock(mutex_);
implementation_type* impl = impl_list_;
while (impl)
{
close_for_destruction(*impl);
impl = impl->next_;
}
}
void win_iocp_handle_service::construct(
win_iocp_handle_service::implementation_type& impl)
{
impl.handle_ = INVALID_HANDLE_VALUE;
impl.safe_cancellation_thread_id_ = 0;
// Insert implementation into linked list of all implementations.
boost::asio::detail::mutex::scoped_lock lock(mutex_);
impl.next_ = impl_list_;
impl.prev_ = 0;
if (impl_list_)
impl_list_->prev_ = &impl;
impl_list_ = &impl;
}
void win_iocp_handle_service::move_construct(
win_iocp_handle_service::implementation_type& impl,
win_iocp_handle_service::implementation_type& other_impl)
{
impl.handle_ = other_impl.handle_;
other_impl.handle_ = INVALID_HANDLE_VALUE;
impl.safe_cancellation_thread_id_ = other_impl.safe_cancellation_thread_id_;
other_impl.safe_cancellation_thread_id_ = 0;
// Insert implementation into linked list of all implementations.
boost::asio::detail::mutex::scoped_lock lock(mutex_);
impl.next_ = impl_list_;
impl.prev_ = 0;
if (impl_list_)
impl_list_->prev_ = &impl;
impl_list_ = &impl;
}
void win_iocp_handle_service::move_assign(
win_iocp_handle_service::implementation_type& impl,
win_iocp_handle_service& other_service,
win_iocp_handle_service::implementation_type& other_impl)
{
close_for_destruction(impl);
if (this != &other_service)
{
// Remove implementation from linked list of all implementations.
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (impl_list_ == &impl)
impl_list_ = impl.next_;
if (impl.prev_)
impl.prev_->next_ = impl.next_;
if (impl.next_)
impl.next_->prev_= impl.prev_;
impl.next_ = 0;
impl.prev_ = 0;
}
impl.handle_ = other_impl.handle_;
other_impl.handle_ = INVALID_HANDLE_VALUE;
impl.safe_cancellation_thread_id_ = other_impl.safe_cancellation_thread_id_;
other_impl.safe_cancellation_thread_id_ = 0;
if (this != &other_service)
{
// Insert implementation into linked list of all implementations.
boost::asio::detail::mutex::scoped_lock lock(other_service.mutex_);
impl.next_ = other_service.impl_list_;
impl.prev_ = 0;
if (other_service.impl_list_)
other_service.impl_list_->prev_ = &impl;
other_service.impl_list_ = &impl;
}
}
void win_iocp_handle_service::destroy(
win_iocp_handle_service::implementation_type& impl)
{
close_for_destruction(impl);
// Remove implementation from linked list of all implementations.
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (impl_list_ == &impl)
impl_list_ = impl.next_;
if (impl.prev_)
impl.prev_->next_ = impl.next_;
if (impl.next_)
impl.next_->prev_= impl.prev_;
impl.next_ = 0;
impl.prev_ = 0;
}
boost::system::error_code win_iocp_handle_service::assign(
win_iocp_handle_service::implementation_type& impl,
const native_handle_type& handle, boost::system::error_code& ec)
{
if (is_open(impl))
{
ec = boost::asio::error::already_open;
return ec;
}
if (iocp_service_.register_handle(handle, ec))
return ec;
impl.handle_ = handle;
ec = boost::system::error_code();
return ec;
}
boost::system::error_code win_iocp_handle_service::close(
win_iocp_handle_service::implementation_type& impl,
boost::system::error_code& ec)
{
if (is_open(impl))
{
BOOST_ASIO_HANDLER_OPERATION(("handle", &impl, "close"));
if (!::CloseHandle(impl.handle_))
{
DWORD last_error = ::GetLastError();
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
}
else
{
ec = boost::system::error_code();
}
impl.handle_ = INVALID_HANDLE_VALUE;
impl.safe_cancellation_thread_id_ = 0;
}
else
{
ec = boost::system::error_code();
}
return ec;
}
boost::system::error_code win_iocp_handle_service::cancel(
win_iocp_handle_service::implementation_type& impl,
boost::system::error_code& ec)
{
if (!is_open(impl))
{
ec = boost::asio::error::bad_descriptor;
return ec;
}
BOOST_ASIO_HANDLER_OPERATION(("handle", &impl, "cancel"));
if (FARPROC cancel_io_ex_ptr = ::GetProcAddress(
::GetModuleHandleA("KERNEL32"), "CancelIoEx"))
{
// The version of Windows supports cancellation from any thread.
typedef BOOL (WINAPI* cancel_io_ex_t)(HANDLE, LPOVERLAPPED);
cancel_io_ex_t cancel_io_ex = (cancel_io_ex_t)cancel_io_ex_ptr;
if (!cancel_io_ex(impl.handle_, 0))
{
DWORD last_error = ::GetLastError();
if (last_error == ERROR_NOT_FOUND)
{
// ERROR_NOT_FOUND means that there were no operations to be
// cancelled. We swallow this error to match the behaviour on other
// platforms.
ec = boost::system::error_code();
}
else
{
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
}
}
else
{
ec = boost::system::error_code();
}
}
else if (impl.safe_cancellation_thread_id_ == 0)
{
// No operations have been started, so there's nothing to cancel.
ec = boost::system::error_code();
}
else if (impl.safe_cancellation_thread_id_ == ::GetCurrentThreadId())
{
// Asynchronous operations have been started from the current thread only,
// so it is safe to try to cancel them using CancelIo.
if (!::CancelIo(impl.handle_))
{
DWORD last_error = ::GetLastError();
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
}
else
{
ec = boost::system::error_code();
}
}
else
{
// Asynchronous operations have been started from more than one thread,
// so cancellation is not safe.
ec = boost::asio::error::operation_not_supported;
}
return ec;
}
size_t win_iocp_handle_service::do_write(
win_iocp_handle_service::implementation_type& impl, boost::uint64_t offset,
const boost::asio::const_buffer& buffer, boost::system::error_code& ec)
{
if (!is_open(impl))
{
ec = boost::asio::error::bad_descriptor;
return 0;
}
// A request to write 0 bytes on a handle is a no-op.
if (boost::asio::buffer_size(buffer) == 0)
{
ec = boost::system::error_code();
return 0;
}
overlapped_wrapper overlapped(ec);
if (ec)
{
return 0;
}
// Write the data.
overlapped.Offset = offset & 0xFFFFFFFF;
overlapped.OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
BOOL ok = ::WriteFile(impl.handle_,
boost::asio::buffer_cast<LPCVOID>(buffer),
static_cast<DWORD>(boost::asio::buffer_size(buffer)), 0, &overlapped);
if (!ok)
{
DWORD last_error = ::GetLastError();
if (last_error != ERROR_IO_PENDING)
{
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
return 0;
}
}
// Wait for the operation to complete.
DWORD bytes_transferred = 0;
ok = ::GetOverlappedResult(impl.handle_,
&overlapped, &bytes_transferred, TRUE);
if (!ok)
{
DWORD last_error = ::GetLastError();
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
return 0;
}
ec = boost::system::error_code();
return bytes_transferred;
}
void win_iocp_handle_service::start_write_op(
win_iocp_handle_service::implementation_type& impl, boost::uint64_t offset,
const boost::asio::const_buffer& buffer, operation* op)
{
update_cancellation_thread_id(impl);
iocp_service_.work_started();
if (!is_open(impl))
{
iocp_service_.on_completion(op, boost::asio::error::bad_descriptor);
}
else if (boost::asio::buffer_size(buffer) == 0)
{
// A request to write 0 bytes on a handle is a no-op.
iocp_service_.on_completion(op);
}
else
{
DWORD bytes_transferred = 0;
op->Offset = offset & 0xFFFFFFFF;
op->OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
BOOL ok = ::WriteFile(impl.handle_,
boost::asio::buffer_cast<LPCVOID>(buffer),
static_cast<DWORD>(boost::asio::buffer_size(buffer)),
&bytes_transferred, op);
DWORD last_error = ::GetLastError();
if (!ok && last_error != ERROR_IO_PENDING
&& last_error != ERROR_MORE_DATA)
{
iocp_service_.on_completion(op, last_error, bytes_transferred);
}
else
{
iocp_service_.on_pending(op);
}
}
}
size_t win_iocp_handle_service::do_read(
win_iocp_handle_service::implementation_type& impl, boost::uint64_t offset,
const boost::asio::mutable_buffer& buffer, boost::system::error_code& ec)
{
if (!is_open(impl))
{
ec = boost::asio::error::bad_descriptor;
return 0;
}
// A request to read 0 bytes on a stream handle is a no-op.
if (boost::asio::buffer_size(buffer) == 0)
{
ec = boost::system::error_code();
return 0;
}
overlapped_wrapper overlapped(ec);
if (ec)
{
return 0;
}
// Read some data.
overlapped.Offset = offset & 0xFFFFFFFF;
overlapped.OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
BOOL ok = ::ReadFile(impl.handle_,
boost::asio::buffer_cast<LPVOID>(buffer),
static_cast<DWORD>(boost::asio::buffer_size(buffer)), 0, &overlapped);
if (!ok)
{
DWORD last_error = ::GetLastError();
if (last_error != ERROR_IO_PENDING && last_error != ERROR_MORE_DATA)
{
if (last_error == ERROR_HANDLE_EOF)
{
ec = boost::asio::error::eof;
}
else
{
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
}
return 0;
}
}
// Wait for the operation to complete.
DWORD bytes_transferred = 0;
ok = ::GetOverlappedResult(impl.handle_,
&overlapped, &bytes_transferred, TRUE);
if (!ok)
{
DWORD last_error = ::GetLastError();
if (last_error == ERROR_HANDLE_EOF)
{
ec = boost::asio::error::eof;
}
else
{
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
}
return 0;
}
ec = boost::system::error_code();
return bytes_transferred;
}
void win_iocp_handle_service::start_read_op(
win_iocp_handle_service::implementation_type& impl, boost::uint64_t offset,
const boost::asio::mutable_buffer& buffer, operation* op)
{
update_cancellation_thread_id(impl);
iocp_service_.work_started();
if (!is_open(impl))
{
iocp_service_.on_completion(op, boost::asio::error::bad_descriptor);
}
else if (boost::asio::buffer_size(buffer) == 0)
{
// A request to read 0 bytes on a handle is a no-op.
iocp_service_.on_completion(op);
}
else
{
DWORD bytes_transferred = 0;
op->Offset = offset & 0xFFFFFFFF;
op->OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
BOOL ok = ::ReadFile(impl.handle_,
boost::asio::buffer_cast<LPVOID>(buffer),
static_cast<DWORD>(boost::asio::buffer_size(buffer)),
&bytes_transferred, op);
DWORD last_error = ::GetLastError();
if (!ok && last_error != ERROR_IO_PENDING
&& last_error != ERROR_MORE_DATA)
{
iocp_service_.on_completion(op, last_error, bytes_transferred);
}
else
{
iocp_service_.on_pending(op);
}
}
}
void win_iocp_handle_service::update_cancellation_thread_id(
win_iocp_handle_service::implementation_type& impl)
{
if (impl.safe_cancellation_thread_id_ == 0)
impl.safe_cancellation_thread_id_ = ::GetCurrentThreadId();
else if (impl.safe_cancellation_thread_id_ != ::GetCurrentThreadId())
impl.safe_cancellation_thread_id_ = ~DWORD(0);
}
void win_iocp_handle_service::close_for_destruction(implementation_type& impl)
{
if (is_open(impl))
{
BOOST_ASIO_HANDLER_OPERATION(("handle", &impl, "close"));
::CloseHandle(impl.handle_);
impl.handle_ = INVALID_HANDLE_VALUE;
impl.safe_cancellation_thread_id_ = 0;
}
}
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_HANDLE_SERVICE_IPP
|
{
"language": "C++"
}
|
#ifdef USE_OPENCV
#include <string>
#include <vector>
#include "boost/scoped_ptr.hpp"
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layers/data_layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
using boost::scoped_ptr;
template <typename TypeParam>
class DataLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
DataLayerTest()
: backend_(DataParameter_DB_LEVELDB),
blob_top_data_(new Blob<Dtype>()),
blob_top_label_(new Blob<Dtype>()),
seed_(1701) {}
virtual void SetUp() {
filename_.reset(new string());
MakeTempDir(filename_.get());
*filename_ += "/db";
blob_top_vec_.push_back(blob_top_data_);
blob_top_vec_.push_back(blob_top_label_);
}
// Fill the DB with data: if unique_pixels, each pixel is unique but
// all images are the same; else each image is unique but all pixels within
// an image are the same.
void Fill(const bool unique_pixels, DataParameter_DB backend) {
backend_ = backend;
LOG(INFO) << "Using temporary dataset " << *filename_;
scoped_ptr<db::DB> db(db::GetDB(backend));
db->Open(*filename_, db::NEW);
scoped_ptr<db::Transaction> txn(db->NewTransaction());
for (int i = 0; i < 5; ++i) {
Datum datum;
datum.set_label(i);
datum.set_channels(2);
datum.set_height(3);
datum.set_width(4);
std::string* data = datum.mutable_data();
for (int j = 0; j < 24; ++j) {
int datum = unique_pixels ? j : i;
data->push_back(static_cast<uint8_t>(datum));
}
stringstream ss;
ss << i;
string out;
CHECK(datum.SerializeToString(&out));
txn->Put(ss.str(), out);
}
txn->Commit();
db->Close();
}
void TestRead() {
const Dtype scale = 3;
LayerParameter param;
param.set_phase(TRAIN);
DataParameter* data_param = param.mutable_data_param();
data_param->set_batch_size(5);
data_param->set_source(filename_->c_str());
data_param->set_backend(backend_);
TransformationParameter* transform_param =
param.mutable_transform_param();
transform_param->set_scale(scale);
DataLayer<Dtype> layer(param);
layer.SetUp(blob_bottom_vec_, blob_top_vec_);
EXPECT_EQ(blob_top_data_->num(), 5);
EXPECT_EQ(blob_top_data_->channels(), 2);
EXPECT_EQ(blob_top_data_->height(), 3);
EXPECT_EQ(blob_top_data_->width(), 4);
EXPECT_EQ(blob_top_label_->num(), 5);
EXPECT_EQ(blob_top_label_->channels(), 1);
EXPECT_EQ(blob_top_label_->height(), 1);
EXPECT_EQ(blob_top_label_->width(), 1);
for (int iter = 0; iter < 100; ++iter) {
layer.Forward(blob_bottom_vec_, blob_top_vec_);
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, blob_top_label_->cpu_data()[i]);
}
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 24; ++j) {
EXPECT_EQ(scale * i, blob_top_data_->cpu_data()[i * 24 + j])
<< "debug: iter " << iter << " i " << i << " j " << j;
}
}
}
}
void TestReshape(DataParameter_DB backend) {
const int num_inputs = 5;
// Save data of varying shapes.
LOG(INFO) << "Using temporary dataset " << *filename_;
scoped_ptr<db::DB> db(db::GetDB(backend));
db->Open(*filename_, db::NEW);
scoped_ptr<db::Transaction> txn(db->NewTransaction());
for (int i = 0; i < num_inputs; ++i) {
Datum datum;
datum.set_label(i);
datum.set_channels(2);
datum.set_height(i % 2 + 1);
datum.set_width(i % 4 + 1);
std::string* data = datum.mutable_data();
const int data_size = datum.channels() * datum.height() * datum.width();
for (int j = 0; j < data_size; ++j) {
data->push_back(static_cast<uint8_t>(j));
}
stringstream ss;
ss << i;
string out;
CHECK(datum.SerializeToString(&out));
txn->Put(ss.str(), out);
}
txn->Commit();
db->Close();
// Load and check data of various shapes.
LayerParameter param;
param.set_phase(TEST);
DataParameter* data_param = param.mutable_data_param();
data_param->set_batch_size(1);
data_param->set_source(filename_->c_str());
data_param->set_backend(backend);
DataLayer<Dtype> layer(param);
layer.SetUp(blob_bottom_vec_, blob_top_vec_);
EXPECT_EQ(blob_top_data_->num(), 1);
EXPECT_EQ(blob_top_data_->channels(), 2);
EXPECT_EQ(blob_top_label_->num(), 1);
EXPECT_EQ(blob_top_label_->channels(), 1);
EXPECT_EQ(blob_top_label_->height(), 1);
EXPECT_EQ(blob_top_label_->width(), 1);
for (int iter = 0; iter < num_inputs; ++iter) {
layer.Forward(blob_bottom_vec_, blob_top_vec_);
EXPECT_EQ(blob_top_data_->height(), iter % 2 + 1);
EXPECT_EQ(blob_top_data_->width(), iter % 4 + 1);
EXPECT_EQ(iter, blob_top_label_->cpu_data()[0]);
const int channels = blob_top_data_->channels();
const int height = blob_top_data_->height();
const int width = blob_top_data_->width();
for (int c = 0; c < channels; ++c) {
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
const int idx = (c * height + h) * width + w;
EXPECT_EQ(idx, static_cast<int>(blob_top_data_->cpu_data()[idx]))
<< "debug: iter " << iter << " c " << c
<< " h " << h << " w " << w;
}
}
}
}
}
void TestReadCrop(Phase phase) {
const Dtype scale = 3;
LayerParameter param;
param.set_phase(phase);
Caffe::set_random_seed(1701);
DataParameter* data_param = param.mutable_data_param();
data_param->set_batch_size(5);
data_param->set_source(filename_->c_str());
data_param->set_backend(backend_);
TransformationParameter* transform_param =
param.mutable_transform_param();
transform_param->set_scale(scale);
transform_param->set_crop_size(1);
DataLayer<Dtype> layer(param);
layer.SetUp(blob_bottom_vec_, blob_top_vec_);
EXPECT_EQ(blob_top_data_->num(), 5);
EXPECT_EQ(blob_top_data_->channels(), 2);
EXPECT_EQ(blob_top_data_->height(), 1);
EXPECT_EQ(blob_top_data_->width(), 1);
EXPECT_EQ(blob_top_label_->num(), 5);
EXPECT_EQ(blob_top_label_->channels(), 1);
EXPECT_EQ(blob_top_label_->height(), 1);
EXPECT_EQ(blob_top_label_->width(), 1);
for (int iter = 0; iter < 2; ++iter) {
layer.Forward(blob_bottom_vec_, blob_top_vec_);
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, blob_top_label_->cpu_data()[i]);
}
int num_with_center_value = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 2; ++j) {
const Dtype center_value = scale * (j ? 17 : 5);
num_with_center_value +=
(center_value == blob_top_data_->cpu_data()[i * 2 + j]);
// At TEST time, check that we always get center value.
if (phase == caffe::TEST) {
EXPECT_EQ(center_value, this->blob_top_data_->cpu_data()[i * 2 + j])
<< "debug: iter " << iter << " i " << i << " j " << j;
}
}
}
// At TRAIN time, check that we did not get the center crop all 10 times.
// (This check fails with probability 1-1/12^10 in a correct
// implementation, so we call set_random_seed.)
if (phase == caffe::TRAIN) {
EXPECT_LT(num_with_center_value, 10);
}
}
}
void TestReadCropTrainSequenceSeeded() {
LayerParameter param;
param.set_phase(TRAIN);
DataParameter* data_param = param.mutable_data_param();
data_param->set_batch_size(5);
data_param->set_source(filename_->c_str());
data_param->set_backend(backend_);
TransformationParameter* transform_param =
param.mutable_transform_param();
transform_param->set_crop_size(1);
transform_param->set_mirror(true);
// Get crop sequence with Caffe seed 1701.
Caffe::set_random_seed(seed_);
vector<vector<Dtype> > crop_sequence;
{
DataLayer<Dtype> layer1(param);
layer1.SetUp(blob_bottom_vec_, blob_top_vec_);
for (int iter = 0; iter < 2; ++iter) {
layer1.Forward(blob_bottom_vec_, blob_top_vec_);
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, blob_top_label_->cpu_data()[i]);
}
vector<Dtype> iter_crop_sequence;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 2; ++j) {
iter_crop_sequence.push_back(
blob_top_data_->cpu_data()[i * 2 + j]);
}
}
crop_sequence.push_back(iter_crop_sequence);
}
} // destroy 1st data layer and unlock the db
// Get crop sequence after reseeding Caffe with 1701.
// Check that the sequence is the same as the original.
Caffe::set_random_seed(seed_);
DataLayer<Dtype> layer2(param);
layer2.SetUp(blob_bottom_vec_, blob_top_vec_);
for (int iter = 0; iter < 2; ++iter) {
layer2.Forward(blob_bottom_vec_, blob_top_vec_);
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, blob_top_label_->cpu_data()[i]);
}
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 2; ++j) {
EXPECT_EQ(crop_sequence[iter][i * 2 + j],
blob_top_data_->cpu_data()[i * 2 + j])
<< "debug: iter " << iter << " i " << i << " j " << j;
}
}
}
}
void TestReadCropTrainSequenceUnseeded() {
LayerParameter param;
param.set_phase(TRAIN);
DataParameter* data_param = param.mutable_data_param();
data_param->set_batch_size(5);
data_param->set_source(filename_->c_str());
data_param->set_backend(backend_);
TransformationParameter* transform_param =
param.mutable_transform_param();
transform_param->set_crop_size(1);
transform_param->set_mirror(true);
// Get crop sequence with Caffe seed 1701, srand seed 1701.
Caffe::set_random_seed(seed_);
srand(seed_);
vector<vector<Dtype> > crop_sequence;
{
DataLayer<Dtype> layer1(param);
layer1.SetUp(blob_bottom_vec_, blob_top_vec_);
for (int iter = 0; iter < 2; ++iter) {
layer1.Forward(blob_bottom_vec_, blob_top_vec_);
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, blob_top_label_->cpu_data()[i]);
}
vector<Dtype> iter_crop_sequence;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 2; ++j) {
iter_crop_sequence.push_back(
blob_top_data_->cpu_data()[i * 2 + j]);
}
}
crop_sequence.push_back(iter_crop_sequence);
}
} // destroy 1st data layer and unlock the db
// Get crop sequence continuing from previous Caffe RNG state; reseed
// srand with 1701. Check that the sequence differs from the original.
srand(seed_);
DataLayer<Dtype> layer2(param);
layer2.SetUp(blob_bottom_vec_, blob_top_vec_);
for (int iter = 0; iter < 2; ++iter) {
layer2.Forward(blob_bottom_vec_, blob_top_vec_);
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, blob_top_label_->cpu_data()[i]);
}
int num_sequence_matches = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 2; ++j) {
num_sequence_matches += (crop_sequence[iter][i * 2 + j] ==
blob_top_data_->cpu_data()[i * 2 + j]);
}
}
EXPECT_LT(num_sequence_matches, 10);
}
}
virtual ~DataLayerTest() { delete blob_top_data_; delete blob_top_label_; }
DataParameter_DB backend_;
shared_ptr<string> filename_;
Blob<Dtype>* const blob_top_data_;
Blob<Dtype>* const blob_top_label_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
int seed_;
};
TYPED_TEST_CASE(DataLayerTest, TestDtypesAndDevices);
#ifdef USE_LEVELDB
TYPED_TEST(DataLayerTest, TestReadLevelDB) {
const bool unique_pixels = false; // all pixels the same; images different
this->Fill(unique_pixels, DataParameter_DB_LEVELDB);
this->TestRead();
}
TYPED_TEST(DataLayerTest, TestReshapeLevelDB) {
this->TestReshape(DataParameter_DB_LEVELDB);
}
TYPED_TEST(DataLayerTest, TestReadCropTrainLevelDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LEVELDB);
this->TestReadCrop(TRAIN);
}
// Test that the sequence of random crops is consistent when using
// Caffe::set_random_seed.
TYPED_TEST(DataLayerTest, TestReadCropTrainSequenceSeededLevelDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LEVELDB);
this->TestReadCropTrainSequenceSeeded();
}
// Test that the sequence of random crops differs across iterations when
// Caffe::set_random_seed isn't called (and seeds from srand are ignored).
TYPED_TEST(DataLayerTest, TestReadCropTrainSequenceUnseededLevelDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LEVELDB);
this->TestReadCropTrainSequenceUnseeded();
}
TYPED_TEST(DataLayerTest, TestReadCropTestLevelDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LEVELDB);
this->TestReadCrop(TEST);
}
#endif // USE_LEVELDB
#ifdef USE_LMDB
TYPED_TEST(DataLayerTest, TestReadLMDB) {
const bool unique_pixels = false; // all pixels the same; images different
this->Fill(unique_pixels, DataParameter_DB_LMDB);
this->TestRead();
}
TYPED_TEST(DataLayerTest, TestReshapeLMDB) {
this->TestReshape(DataParameter_DB_LMDB);
}
TYPED_TEST(DataLayerTest, TestReadCropTrainLMDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LMDB);
this->TestReadCrop(TRAIN);
}
// Test that the sequence of random crops is consistent when using
// Caffe::set_random_seed.
TYPED_TEST(DataLayerTest, TestReadCropTrainSequenceSeededLMDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LMDB);
this->TestReadCropTrainSequenceSeeded();
}
// Test that the sequence of random crops differs across iterations when
// Caffe::set_random_seed isn't called (and seeds from srand are ignored).
TYPED_TEST(DataLayerTest, TestReadCropTrainSequenceUnseededLMDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LMDB);
this->TestReadCropTrainSequenceUnseeded();
}
TYPED_TEST(DataLayerTest, TestReadCropTestLMDB) {
const bool unique_pixels = true; // all images the same; pixels different
this->Fill(unique_pixels, DataParameter_DB_LMDB);
this->TestReadCrop(TEST);
}
#endif // USE_LMDB
} // namespace caffe
#endif // USE_OPENCV
|
{
"language": "C++"
}
|
#include <vector>
#include "caffe/layers/exp_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void ExpLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
NeuronLayer<Dtype>::LayerSetUp(bottom, top);
const Dtype base = this->layer_param_.exp_param().base();
if (base != Dtype(-1)) {
CHECK_GT(base, 0) << "base must be strictly positive.";
}
// If base == -1, interpret the base as e and set log_base = 1 exactly.
// Otherwise, calculate its log explicitly.
const Dtype log_base = (base == Dtype(-1)) ? Dtype(1) : log(base);
CHECK(!isnan(log_base))
<< "NaN result: log(base) = log(" << base << ") = " << log_base;
CHECK(!isinf(log_base))
<< "Inf result: log(base) = log(" << base << ") = " << log_base;
const Dtype input_scale = this->layer_param_.exp_param().scale();
const Dtype input_shift = this->layer_param_.exp_param().shift();
inner_scale_ = log_base * input_scale;
outer_scale_ = (input_shift == Dtype(0)) ? Dtype(1) :
( (base != Dtype(-1)) ? pow(base, input_shift) : exp(input_shift) );
}
template <typename Dtype>
void ExpLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const int count = bottom[0]->count();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
if (inner_scale_ == Dtype(1)) {
caffe_exp(count, bottom_data, top_data);
} else {
caffe_cpu_scale(count, inner_scale_, bottom_data, top_data);
caffe_exp(count, top_data, top_data);
}
if (outer_scale_ != Dtype(1)) {
caffe_scal(count, outer_scale_, top_data);
}
}
template <typename Dtype>
void ExpLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (!propagate_down[0]) { return; }
const int count = bottom[0]->count();
const Dtype* top_data = top[0]->cpu_data();
const Dtype* top_diff = top[0]->cpu_diff();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
caffe_mul(count, top_data, top_diff, bottom_diff);
if (inner_scale_ != Dtype(1)) {
caffe_scal(count, inner_scale_, bottom_diff);
}
}
#ifdef CPU_ONLY
STUB_GPU(ExpLayer);
#endif
INSTANTIATE_CLASS(ExpLayer);
REGISTER_LAYER_CLASS(Exp);
} // namespace caffe
|
{
"language": "C++"
}
|
// Copyright (C) 2003, Fernando Luis Cacciola Carballal.
//
// Use, modification, and distribution is subject to 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)
//
// See http://www.boost.org/libs/optional for documentation.
//
// You are welcome to contact the author at:
// [email protected]
//
#ifndef BOOST_OPTIONAL_FLC_19NOV2002_HPP
#define BOOST_OPTIONAL_FLC_19NOV2002_HPP
#include "boost/optional/optional.hpp"
#endif
|
{
"language": "C++"
}
|
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
/* This header provides common string manipulation support, such as UTF-8,
* portable conversion from/to string...
*
* It is an internal header that must not be exposed.
*/
namespace Json {
/// Converts a unicode code-point to UTF-8.
static inline std::string codePointToUTF8(unsigned int cp) {
std::string result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f) {
result.resize(1);
result[0] = static_cast<char>(cp);
} else if (cp <= 0x7FF) {
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
} else if (cp <= 0xFFFF) {
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
} else if (cp <= 0x10FFFF) {
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
/// Returns true if ch is a control character (in range [0,32[).
static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
enum {
/// Constant that specify the size of the buffer that must be passed to
/// uintToString.
uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
};
// Defines a char buffer for use with uintToString().
typedef char UIntToStringBuffer[uintToStringBufferSize];
/** Converts an unsigned integer to string.
* @param value Unsigned interger to convert to string
* @param current Input/Output string buffer.
* Must have at least uintToStringBufferSize chars free.
*/
static inline void uintToString(LargestUInt value, char *¤t) {
*--current = 0;
do {
*--current = char(value % 10) + '0';
value /= 10;
} while (value != 0);
}
/** Change ',' to '.' everywhere in buffer.
*
* We had a sophisticated way, but it did not work in WinCE.
* @see https://github.com/open-source-parsers/jsoncpp/pull/9
*/
static inline void fixNumericLocale(char* begin, char* end) {
while (begin < end) {
if (*begin == ',') {
*begin = '.';
}
++begin;
}
}
} // namespace Json {
#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
// vim: et ts=2 sts=2 sw=2 tw=0
|
{
"language": "C++"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.