hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2eca8e68d67c0ff7a35d70c4ff559b6050eed058 | 38,853 | cpp | C++ | WebLayoutCore/Source/WebCore/platform/graphics/cairo/CairoOperations.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2020-05-25T16:06:49.000Z | 2020-05-25T16:06:49.000Z | WebLayoutCore/Source/WebCore/platform/graphics/cairo/CairoOperations.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | null | null | null | WebLayoutCore/Source/WebCore/platform/graphics/cairo/CairoOperations.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2018-07-10T10:53:18.000Z | 2018-07-10T10:53:18.000Z | /*
* Copyright (C) 2006 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008, 2009 Dirk Schulze <krit@webkit.org>
* Copyright (C) 2008 Nuanti Ltd.
* Copyright (C) 2009 Brent Fulgham <bfulgham@webkit.org>
* Copyright (C) 2010, 2011 Igalia S.L.
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
* Copyright (C) 2012, Intel Corporation
*
* 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. ``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
* 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 "CairoOperations.h"
#if USE(CAIRO)
#include "DrawErrorUnderline.h"
#include "FloatConversion.h"
#include "FloatRect.h"
#include "GraphicsContext.h"
#include "GraphicsContextPlatformPrivateCairo.h"
#include "Image.h"
#include "Path.h"
#include "PlatformContextCairo.h"
#include "PlatformPathCairo.h"
#include <algorithm>
#include <cairo.h>
namespace WebCore {
namespace Cairo {
static inline void fillRectWithColor(cairo_t* cr, const FloatRect& rect, const Color& color)
{
if (!color.isVisible() && cairo_get_operator(cr) == CAIRO_OPERATOR_OVER)
return;
setSourceRGBAFromColor(cr, color);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill(cr);
}
enum PathDrawingStyle {
Fill = 1,
Stroke = 2,
FillAndStroke = Fill + Stroke
};
static inline void drawPathShadow(PlatformContextCairo& platformContext, const GraphicsContextState& contextState, GraphicsContext& targetContext, PathDrawingStyle drawingStyle)
{
ShadowBlur& shadow = platformContext.shadowBlur();
if (shadow.type() == ShadowBlur::NoShadow)
return;
// Calculate the extents of the rendered solid paths.
cairo_t* cairoContext = platformContext.cr();
std::unique_ptr<cairo_path_t, void(*)(cairo_path_t*)> path(cairo_copy_path(cairoContext), [](cairo_path_t* path) {
cairo_path_destroy(path);
});
FloatRect solidFigureExtents;
double x0 = 0;
double x1 = 0;
double y0 = 0;
double y1 = 0;
if (drawingStyle & Stroke) {
cairo_stroke_extents(cairoContext, &x0, &y0, &x1, &y1);
solidFigureExtents = FloatRect(x0, y0, x1 - x0, y1 - y0);
}
if (drawingStyle & Fill) {
cairo_fill_extents(cairoContext, &x0, &y0, &x1, &y1);
FloatRect fillExtents(x0, y0, x1 - x0, y1 - y0);
solidFigureExtents.unite(fillExtents);
}
GraphicsContext* shadowContext = shadow.beginShadowLayer(targetContext, solidFigureExtents);
if (!shadowContext)
return;
cairo_t* cairoShadowContext = shadowContext->platformContext()->cr();
// It's important to copy the context properties to the new shadow
// context to preserve things such as the fill rule and stroke width.
copyContextProperties(cairoContext, cairoShadowContext);
if (drawingStyle & Fill) {
cairo_save(cairoShadowContext);
cairo_append_path(cairoShadowContext, path.get());
shadowContext->platformContext()->prepareForFilling(contextState, PlatformContextCairo::NoAdjustment);
cairo_fill(cairoShadowContext);
cairo_restore(cairoShadowContext);
}
if (drawingStyle & Stroke) {
cairo_append_path(cairoShadowContext, path.get());
shadowContext->platformContext()->prepareForStroking(contextState, PlatformContextCairo::DoNotPreserveAlpha);
cairo_stroke(cairoShadowContext);
}
// The original path may still be hanging around on the context and endShadowLayer
// will take care of properly creating a path to draw the result shadow. We remove the path
// temporarily and then restore it.
// See: https://bugs.webkit.org/show_bug.cgi?id=108897
cairo_new_path(cairoContext);
shadow.endShadowLayer(targetContext);
cairo_append_path(cairoContext, path.get());
}
static inline void fillCurrentCairoPath(PlatformContextCairo& platformContext, const GraphicsContextState& contextState)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
platformContext.prepareForFilling(contextState, PlatformContextCairo::AdjustPatternForGlobalAlpha);
cairo_fill(cr);
cairo_restore(cr);
}
static inline void adjustFocusRingColor(Color& color)
{
#if !PLATFORM(GTK)
// Force the alpha to 50%. This matches what the Mac does with outline rings.
color = Color(makeRGBA(color.red(), color.green(), color.blue(), 127));
#else
UNUSED_PARAM(color);
#endif
}
static inline void adjustFocusRingLineWidth(float& width)
{
#if PLATFORM(GTK)
width = 2;
#else
UNUSED_PARAM(width);
#endif
}
static inline StrokeStyle focusRingStrokeStyle()
{
#if PLATFORM(GTK)
return DottedStroke;
#else
return SolidStroke;
#endif
}
static bool mustUseShadowBlur(PlatformContextCairo& platformContext, const GraphicsContextState& state)
{
// We can't avoid ShadowBlur if the shadow has blur.
if (state.shadowColor.isVisible() && state.shadowBlur)
return true;
// We can avoid ShadowBlur and optimize, since we're not drawing on a
// canvas and box shadows are affected by the transformation matrix.
if (!state.shadowsIgnoreTransforms)
return false;
// We can avoid ShadowBlur, since there are no transformations to apply to the canvas.
if (State::getCTM(platformContext).isIdentity())
return false;
// Otherwise, no chance avoiding ShadowBlur.
return true;
}
static void drawGlyphsToContext(cairo_t* context, cairo_scaled_font_t* scaledFont, double syntheticBoldOffset, const Vector<cairo_glyph_t>& glyphs)
{
cairo_matrix_t originalTransform;
if (syntheticBoldOffset)
cairo_get_matrix(context, &originalTransform);
cairo_set_scaled_font(context, scaledFont);
cairo_show_glyphs(context, glyphs.data(), glyphs.size());
if (syntheticBoldOffset) {
cairo_translate(context, syntheticBoldOffset, 0);
cairo_show_glyphs(context, glyphs.data(), glyphs.size());
cairo_set_matrix(context, &originalTransform);
}
}
static void drawGlyphsShadow(PlatformContextCairo& platformContext, const GraphicsContextState& state, const FloatPoint& point, cairo_scaled_font_t* scaledFont, double syntheticBoldOffset, const Vector<cairo_glyph_t>& glyphs, GraphicsContext& targetContext)
{
ShadowBlur& shadow = platformContext.shadowBlur();
if (!(state.textDrawingMode & TextModeFill) || shadow.type() == ShadowBlur::NoShadow)
return;
if (!mustUseShadowBlur(platformContext, state)) {
// Optimize non-blurry shadows, by just drawing text without the ShadowBlur.
cairo_t* context = platformContext.cr();
cairo_save(context);
FloatSize shadowOffset(state.shadowOffset);
cairo_translate(context, shadowOffset.width(), shadowOffset.height());
setSourceRGBAFromColor(context, state.shadowColor);
drawGlyphsToContext(context, scaledFont, syntheticBoldOffset, glyphs);
cairo_restore(context);
return;
}
cairo_text_extents_t extents;
cairo_scaled_font_glyph_extents(scaledFont, glyphs.data(), glyphs.size(), &extents);
FloatRect fontExtentsRect(point.x() + extents.x_bearing, point.y() + extents.y_bearing, extents.width, extents.height);
if (GraphicsContext* shadowContext = shadow.beginShadowLayer(targetContext, fontExtentsRect)) {
drawGlyphsToContext(shadowContext->platformContext()->cr(), scaledFont, syntheticBoldOffset, glyphs);
shadow.endShadowLayer(targetContext);
}
}
static bool cairoSurfaceHasAlpha(cairo_surface_t* surface)
{
return cairo_surface_get_content(surface) != CAIRO_CONTENT_COLOR;
}
// FIXME: Fix GraphicsContext::computeLineBoundsAndAntialiasingModeForText()
// to be a static public function that operates on CTM and strokeThickness
// arguments instead of using an underlying GraphicsContext object.
FloatRect computeLineBoundsAndAntialiasingModeForText(PlatformContextCairo& platformContext, const FloatPoint& point, float width, bool printing, Color& color, float strokeThickness)
{
FloatPoint origin = point;
float thickness = std::max(strokeThickness, 0.5f);
if (printing)
return FloatRect(origin, FloatSize(width, thickness));
AffineTransform transform = Cairo::State::getCTM(platformContext);
// Just compute scale in x dimension, assuming x and y scales are equal.
float scale = transform.b() ? sqrtf(transform.a() * transform.a() + transform.b() * transform.b()) : transform.a();
if (scale < 1.0) {
// This code always draws a line that is at least one-pixel line high,
// which tends to visually overwhelm text at small scales. To counter this
// effect, an alpha is applied to the underline color when text is at small scales.
static const float minimumUnderlineAlpha = 0.4f;
float shade = scale > minimumUnderlineAlpha ? scale : minimumUnderlineAlpha;
color = color.colorWithAlphaMultipliedBy(shade);
}
FloatPoint devicePoint = transform.mapPoint(point);
// Visual overflow might occur here due to integral roundf/ceilf. visualOverflowForDecorations adjusts the overflow value for underline decoration.
FloatPoint deviceOrigin = FloatPoint(roundf(devicePoint.x()), ceilf(devicePoint.y()));
if (auto inverse = transform.inverse())
origin = inverse.value().mapPoint(deviceOrigin);
return FloatRect(origin, FloatSize(width, thickness));
};
// FIXME: Replace once GraphicsContext::dashedLineCornerWidthForStrokeWidth()
// is refactored as a static public function.
static float dashedLineCornerWidthForStrokeWidth(float strokeWidth, const GraphicsContextState& state)
{
float thickness = state.strokeThickness;
return state.strokeStyle == DottedStroke ? thickness : std::min(2.0f * thickness, std::max(thickness, strokeWidth / 3.0f));
}
// FIXME: Replace once GraphicsContext::dashedLinePatternWidthForStrokeWidth()
// is refactored as a static public function.
static float dashedLinePatternWidthForStrokeWidth(float strokeWidth, const GraphicsContextState& state)
{
float thickness = state.strokeThickness;
return state.strokeStyle == DottedStroke ? thickness : std::min(3.0f * thickness, std::max(thickness, strokeWidth / 3.0f));
}
// FIXME: Replace once GraphicsContext::dashedLinePatternOffsetForPatternAndStrokeWidth()
// is refactored as a static public function.
static float dashedLinePatternOffsetForPatternAndStrokeWidth(float patternWidth, float strokeWidth)
{
// Pattern starts with full fill and ends with the empty fill.
// 1. Let's start with the empty phase after the corner.
// 2. Check if we've got odd or even number of patterns and whether they fully cover the line.
// 3. In case of even number of patterns and/or remainder, move the pattern start position
// so that the pattern is balanced between the corners.
float patternOffset = patternWidth;
int numberOfSegments = std::floor(strokeWidth / patternWidth);
bool oddNumberOfSegments = numberOfSegments % 2;
float remainder = strokeWidth - (numberOfSegments * patternWidth);
if (oddNumberOfSegments && remainder)
patternOffset -= remainder / 2.0f;
else if (!oddNumberOfSegments) {
if (remainder)
patternOffset += patternOffset - (patternWidth + remainder) / 2.0f;
else
patternOffset += patternWidth / 2.0f;
}
return patternOffset;
}
// FIXME: Replace once GraphicsContext::centerLineAndCutOffCorners()
// is refactored as a static public function.
static Vector<FloatPoint> centerLineAndCutOffCorners(bool isVerticalLine, float cornerWidth, FloatPoint point1, FloatPoint point2)
{
// Center line and cut off corners for pattern painting.
if (isVerticalLine) {
float centerOffset = (point2.x() - point1.x()) / 2.0f;
point1.move(centerOffset, cornerWidth);
point2.move(-centerOffset, -cornerWidth);
} else {
float centerOffset = (point2.y() - point1.y()) / 2.0f;
point1.move(cornerWidth, centerOffset);
point2.move(-cornerWidth, -centerOffset);
}
return { point1, point2 };
}
namespace State {
void setStrokeThickness(PlatformContextCairo& platformContext, float strokeThickness)
{
cairo_set_line_width(platformContext.cr(), strokeThickness);
}
void setStrokeStyle(PlatformContextCairo& platformContext, StrokeStyle strokeStyle)
{
static const double dashPattern[] = { 5.0, 5.0 };
static const double dotPattern[] = { 1.0, 1.0 };
cairo_t* cr = platformContext.cr();
switch (strokeStyle) {
case NoStroke:
// FIXME: is it the right way to emulate NoStroke?
cairo_set_line_width(cr, 0);
break;
case SolidStroke:
case DoubleStroke:
case WavyStroke:
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=94110 - Needs platform support.
cairo_set_dash(cr, 0, 0, 0);
break;
case DottedStroke:
cairo_set_dash(cr, dotPattern, 2, 0);
break;
case DashedStroke:
cairo_set_dash(cr, dashPattern, 2, 0);
break;
}
}
void setGlobalAlpha(PlatformContextCairo& platformContext, float alpha)
{
platformContext.setGlobalAlpha(alpha);
}
void setCompositeOperation(PlatformContextCairo& platformContext, CompositeOperator compositeOperation, BlendMode blendMode)
{
cairo_set_operator(platformContext.cr(), toCairoOperator(compositeOperation, blendMode));
}
void setShouldAntialias(PlatformContextCairo& platformContext, bool enable)
{
// When true, use the default Cairo backend antialias mode (usually this
// enables standard 'grayscale' antialiasing); false to explicitly disable
// antialiasing.
cairo_set_antialias(platformContext.cr(), enable ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
}
void setImageInterpolationQuality(PlatformContextCairo& platformContext, InterpolationQuality quality)
{
platformContext.setImageInterpolationQuality(quality);
}
void setCTM(PlatformContextCairo& platformContext, const AffineTransform& transform)
{
const cairo_matrix_t matrix = toCairoMatrix(transform);
cairo_set_matrix(platformContext.cr(), &matrix);
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->setCTM(transform);
}
AffineTransform getCTM(PlatformContextCairo& platformContext)
{
cairo_matrix_t m;
cairo_get_matrix(platformContext.cr(), &m);
return AffineTransform(m.xx, m.yx, m.xy, m.yy, m.x0, m.y0);
}
void setShadowValues(PlatformContextCairo& platformContext, const FloatSize& radius, const FloatSize& offset, const Color& color, bool ignoreTransforms)
{
// Cairo doesn't support shadows natively, they are drawn manually in the draw* functions using ShadowBlur.
platformContext.shadowBlur().setShadowValues(radius, offset, color, ignoreTransforms);
}
void clearShadow(PlatformContextCairo& platformContext)
{
platformContext.shadowBlur().clear();
}
IntRect getClipBounds(PlatformContextCairo& platformContext)
{
double x1, x2, y1, y2;
cairo_clip_extents(platformContext.cr(), &x1, &y1, &x2, &y2);
return enclosingIntRect(FloatRect(x1, y1, x2 - x1, y2 - y1));
}
FloatRect roundToDevicePixels(PlatformContextCairo& platformContext, const FloatRect& rect)
{
FloatRect result;
double x = rect.x();
double y = rect.y();
cairo_t* cr = platformContext.cr();
cairo_user_to_device(cr, &x, &y);
x = round(x);
y = round(y);
cairo_device_to_user(cr, &x, &y);
result.setX(narrowPrecisionToFloat(x));
result.setY(narrowPrecisionToFloat(y));
// We must ensure width and height are at least 1 (or -1) when
// we're given float values in the range between 0 and 1 (or -1 and 0).
double width = rect.width();
double height = rect.height();
cairo_user_to_device_distance(cr, &width, &height);
if (width > -1 && width < 0)
width = -1;
else if (width > 0 && width < 1)
width = 1;
else
width = round(width);
if (height > -1 && height < 0)
height = -1;
else if (height > 0 && height < 1)
height = 1;
else
height = round(height);
cairo_device_to_user_distance(cr, &width, &height);
result.setWidth(narrowPrecisionToFloat(width));
result.setHeight(narrowPrecisionToFloat(height));
return result;
}
bool isAcceleratedContext(PlatformContextCairo& platformContext)
{
return cairo_surface_get_type(cairo_get_target(platformContext.cr())) == CAIRO_SURFACE_TYPE_GL;
}
} // namespace State
void setLineCap(PlatformContextCairo& platformContext, LineCap lineCap)
{
cairo_line_cap_t cairoCap;
switch (lineCap) {
case ButtCap:
cairoCap = CAIRO_LINE_CAP_BUTT;
break;
case RoundCap:
cairoCap = CAIRO_LINE_CAP_ROUND;
break;
case SquareCap:
cairoCap = CAIRO_LINE_CAP_SQUARE;
break;
}
cairo_set_line_cap(platformContext.cr(), cairoCap);
}
void setLineDash(PlatformContextCairo& platformContext, const DashArray& dashes, float dashOffset)
{
if (std::all_of(dashes.begin(), dashes.end(), [](auto& dash) { return !dash; }))
cairo_set_dash(platformContext.cr(), 0, 0, 0);
else
cairo_set_dash(platformContext.cr(), dashes.data(), dashes.size(), dashOffset);
}
void setLineJoin(PlatformContextCairo& platformContext, LineJoin lineJoin)
{
cairo_line_join_t cairoJoin;
switch (lineJoin) {
case MiterJoin:
cairoJoin = CAIRO_LINE_JOIN_MITER;
break;
case RoundJoin:
cairoJoin = CAIRO_LINE_JOIN_ROUND;
break;
case BevelJoin:
cairoJoin = CAIRO_LINE_JOIN_BEVEL;
break;
}
cairo_set_line_join(platformContext.cr(), cairoJoin);
}
void setMiterLimit(PlatformContextCairo& platformContext, float miterLimit)
{
cairo_set_miter_limit(platformContext.cr(), miterLimit);
}
void fillRect(PlatformContextCairo& platformContext, const FloatRect& rect, const GraphicsContextState& contextState, GraphicsContext& targetContext)
{
cairo_t* cr = platformContext.cr();
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
drawPathShadow(platformContext, contextState, targetContext, Fill);
fillCurrentCairoPath(platformContext, contextState);
}
void fillRect(PlatformContextCairo& platformContext, const FloatRect& rect, const Color& color, bool hasShadow, GraphicsContext& targetContext)
{
if (hasShadow)
platformContext.shadowBlur().drawRectShadow(targetContext, FloatRoundedRect(rect));
fillRectWithColor(platformContext.cr(), rect, color);
}
void fillRect(PlatformContextCairo& platformContext, const FloatRect& rect, cairo_pattern_t* platformPattern)
{
cairo_t* cr = platformContext.cr();
cairo_set_source(cr, platformPattern);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill(cr);
}
void fillRoundedRect(PlatformContextCairo& platformContext, const FloatRoundedRect& rect, const Color& color, bool hasShadow, GraphicsContext& targetContext)
{
if (hasShadow)
platformContext.shadowBlur().drawRectShadow(targetContext, rect);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
Path path;
path.addRoundedRect(rect);
appendWebCorePathToCairoContext(cr, path);
setSourceRGBAFromColor(cr, color);
cairo_fill(cr);
cairo_restore(cr);
}
void fillRectWithRoundedHole(PlatformContextCairo& platformContext, const FloatRect& rect, const FloatRoundedRect& roundedHoleRect, const GraphicsContextState& contextState, GraphicsContext& targetContext)
{
// FIXME: this should leverage the specified color.
if (mustUseShadowBlur(platformContext, contextState))
platformContext.shadowBlur().drawInsetShadow(targetContext, rect, roundedHoleRect);
Path path;
path.addRect(rect);
if (!roundedHoleRect.radii().isZero())
path.addRoundedRect(roundedHoleRect);
else
path.addRect(roundedHoleRect.rect());
cairo_t* cr = platformContext.cr();
cairo_save(cr);
setPathOnCairoContext(platformContext.cr(), path.platformPath()->context());
fillCurrentCairoPath(platformContext, contextState);
cairo_restore(cr);
}
void fillPath(PlatformContextCairo& platformContext, const Path& path, const GraphicsContextState& contextState, GraphicsContext& targetContext)
{
cairo_t* cr = platformContext.cr();
setPathOnCairoContext(cr, path.platformPath()->context());
drawPathShadow(platformContext, contextState, targetContext, Fill);
fillCurrentCairoPath(platformContext, contextState);
}
void strokeRect(PlatformContextCairo& platformContext, const FloatRect& rect, float lineWidth, const GraphicsContextState& contextState, GraphicsContext& targetContext)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_set_line_width(cr, lineWidth);
drawPathShadow(platformContext, contextState, targetContext, Stroke);
platformContext.prepareForStroking(contextState);
cairo_stroke(cr);
cairo_restore(cr);
}
void strokePath(PlatformContextCairo& platformContext, const Path& path, const GraphicsContextState& contextState, GraphicsContext& targetContext)
{
cairo_t* cr = platformContext.cr();
setPathOnCairoContext(cr, path.platformPath()->context());
drawPathShadow(platformContext, contextState, targetContext, Stroke);
platformContext.prepareForStroking(contextState);
cairo_stroke(cr);
}
void clearRect(PlatformContextCairo& platformContext, const FloatRect& rect)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
cairo_fill(cr);
cairo_restore(cr);
}
void drawGlyphs(PlatformContextCairo& platformContext, const GraphicsContextState& state, const FloatPoint& point, cairo_scaled_font_t* scaledFont, double syntheticBoldOffset, const Vector<cairo_glyph_t>& glyphs, float xOffset, GraphicsContext& targetContext)
{
drawGlyphsShadow(platformContext, state, point, scaledFont, syntheticBoldOffset, glyphs, targetContext);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
if (state.textDrawingMode & TextModeFill) {
platformContext.prepareForFilling(state, PlatformContextCairo::AdjustPatternForGlobalAlpha);
drawGlyphsToContext(cr, scaledFont, syntheticBoldOffset, glyphs);
}
// Prevent running into a long computation within cairo. If the stroke width is
// twice the size of the width of the text we will not ask cairo to stroke
// the text as even one single stroke would cover the full wdth of the text.
// See https://bugs.webkit.org/show_bug.cgi?id=33759.
if (state.textDrawingMode & TextModeStroke && state.strokeThickness < 2 * xOffset) {
platformContext.prepareForStroking(state);
cairo_set_line_width(cr, state.strokeThickness);
// This may disturb the CTM, but we are going to call cairo_restore soon after.
cairo_set_scaled_font(cr, scaledFont);
cairo_glyph_path(cr, glyphs.data(), glyphs.size());
cairo_stroke(cr);
}
cairo_restore(cr);
}
void drawNativeImage(PlatformContextCairo& platformContext, cairo_surface_t* surface, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator compositeOperator, BlendMode blendMode, ImageOrientation orientation, GraphicsContext& targetContext)
{
platformContext.save();
// Set the compositing operation.
if (compositeOperator == CompositeSourceOver && blendMode == BlendModeNormal && !cairoSurfaceHasAlpha(surface))
Cairo::State::setCompositeOperation(platformContext, CompositeCopy, BlendModeNormal);
else
Cairo::State::setCompositeOperation(platformContext, compositeOperator, blendMode);
FloatRect dst = destRect;
if (orientation != DefaultImageOrientation) {
// ImageOrientation expects the origin to be at (0, 0).
Cairo::translate(platformContext, dst.x(), dst.y());
dst.setLocation(FloatPoint());
Cairo::concatCTM(platformContext, orientation.transformFromDefault(dst.size()));
if (orientation.usesWidthAsHeight()) {
// The destination rectangle will have its width and height already reversed for the orientation of
// the image, as it was needed for page layout, so we need to reverse it back here.
dst = FloatRect(dst.x(), dst.y(), dst.height(), dst.width());
}
}
platformContext.drawSurfaceToContext(surface, dst, srcRect, targetContext);
platformContext.restore();
}
void drawPattern(PlatformContextCairo& platformContext, cairo_surface_t* surface, const IntSize& size, const FloatRect& destRect, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, CompositeOperator compositeOperator, BlendMode blendMode)
{
// FIXME: Investigate why the size has to be passed in as an IntRect.
drawPatternToCairoContext(platformContext.cr(), surface, size, tileRect, patternTransform, phase, toCairoOperator(compositeOperator, blendMode), destRect);
}
void drawRect(PlatformContextCairo& platformContext, const FloatRect& rect, float borderThickness, const GraphicsContextState& state)
{
// FIXME: how should borderThickness be used?
UNUSED_PARAM(borderThickness);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
fillRectWithColor(cr, rect, state.fillColor);
if (state.strokeStyle != NoStroke) {
setSourceRGBAFromColor(cr, state.strokeColor);
FloatRect r(rect);
r.inflate(-.5f);
cairo_rectangle(cr, r.x(), r.y(), r.width(), r.height());
cairo_set_line_width(cr, 1.0); // borderThickness?
cairo_stroke(cr);
}
cairo_restore(cr);
}
void drawLine(PlatformContextCairo& platformContext, const FloatPoint& point1, const FloatPoint& point2, const GraphicsContextState& state)
{
bool isVerticalLine = (point1.x() + state.strokeThickness == point2.x());
float strokeWidth = isVerticalLine ? point2.y() - point1.y() : point2.x() - point1.x();
if (!state.strokeThickness || !strokeWidth)
return;
cairo_t* cairoContext = platformContext.cr();
float cornerWidth = 0;
bool drawsDashedLine = state.strokeStyle == DottedStroke || state.strokeStyle == DashedStroke;
if (drawsDashedLine) {
cairo_save(cairoContext);
// Figure out end points to ensure we always paint corners.
cornerWidth = dashedLineCornerWidthForStrokeWidth(strokeWidth, state);
if (isVerticalLine) {
fillRectWithColor(cairoContext, FloatRect(point1.x(), point1.y(), state.strokeThickness, cornerWidth), state.strokeColor);
fillRectWithColor(cairoContext, FloatRect(point1.x(), point2.y() - cornerWidth, state.strokeThickness, cornerWidth), state.strokeColor);
} else {
fillRectWithColor(cairoContext, FloatRect(point1.x(), point1.y(), cornerWidth, state.strokeThickness), state.strokeColor);
fillRectWithColor(cairoContext, FloatRect(point2.x() - cornerWidth, point1.y(), cornerWidth, state.strokeThickness), state.strokeColor);
}
strokeWidth -= 2 * cornerWidth;
float patternWidth = dashedLinePatternWidthForStrokeWidth(strokeWidth, state);
// Check if corner drawing sufficiently covers the line.
if (strokeWidth <= patternWidth + 1) {
cairo_restore(cairoContext);
return;
}
float patternOffset = dashedLinePatternOffsetForPatternAndStrokeWidth(patternWidth, strokeWidth);
const double dashedLine[2] = { static_cast<double>(patternWidth), static_cast<double>(patternWidth) };
cairo_set_dash(cairoContext, dashedLine, 2, patternOffset);
} else {
setSourceRGBAFromColor(cairoContext, state.strokeColor);
if (state.strokeThickness < 1)
cairo_set_line_width(cairoContext, 1);
}
auto centeredPoints = centerLineAndCutOffCorners(isVerticalLine, cornerWidth, point1, point2);
auto p1 = centeredPoints[0];
auto p2 = centeredPoints[1];
if (state.shouldAntialias)
cairo_set_antialias(cairoContext, CAIRO_ANTIALIAS_NONE);
cairo_new_path(cairoContext);
cairo_move_to(cairoContext, p1.x(), p1.y());
cairo_line_to(cairoContext, p2.x(), p2.y());
cairo_stroke(cairoContext);
if (drawsDashedLine)
cairo_restore(cairoContext);
if (state.shouldAntialias)
cairo_set_antialias(cairoContext, CAIRO_ANTIALIAS_DEFAULT);
}
void drawLinesForText(PlatformContextCairo& platformContext, const FloatPoint& point, const DashArray& widths, bool printing, bool doubleUnderlines, const Color& color, float strokeThickness)
{
Color modifiedColor = color;
FloatRect bounds = computeLineBoundsAndAntialiasingModeForText(platformContext, point, widths.last(), printing, modifiedColor, strokeThickness);
Vector<FloatRect, 4> dashBounds;
ASSERT(!(widths.size() % 2));
dashBounds.reserveInitialCapacity(dashBounds.size() / 2);
for (size_t i = 0; i < widths.size(); i += 2)
dashBounds.append(FloatRect(FloatPoint(bounds.x() + widths[i], bounds.y()), FloatSize(widths[i+1] - widths[i], bounds.height())));
if (doubleUnderlines) {
// The space between double underlines is equal to the height of the underline
for (size_t i = 0; i < widths.size(); i += 2)
dashBounds.append(FloatRect(FloatPoint(bounds.x() + widths[i], bounds.y() + 2 * bounds.height()), FloatSize(widths[i+1] - widths[i], bounds.height())));
}
cairo_t* cr = platformContext.cr();
cairo_save(cr);
for (auto& dash : dashBounds)
fillRectWithColor(cr, dash, modifiedColor);
cairo_restore(cr);
}
void drawLineForDocumentMarker(PlatformContextCairo& platformContext, const FloatPoint& origin, float width, GraphicsContext::DocumentMarkerLineStyle style)
{
if (style != GraphicsContext::DocumentMarkerSpellingLineStyle
&& style != GraphicsContext::DocumentMarkerGrammarLineStyle)
return;
cairo_t* cr = platformContext.cr();
cairo_save(cr);
if (style == GraphicsContext::DocumentMarkerSpellingLineStyle)
cairo_set_source_rgb(cr, 1, 0, 0);
else if (style == GraphicsContext::DocumentMarkerGrammarLineStyle)
cairo_set_source_rgb(cr, 0, 1, 0);
drawErrorUnderline(cr, origin.x(), origin.y(), width, cMisspellingLineThickness);
cairo_restore(cr);
}
void drawEllipse(PlatformContextCairo& platformContext, const FloatRect& rect, const GraphicsContextState& state)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
float yRadius = .5 * rect.height();
float xRadius = .5 * rect.width();
cairo_translate(cr, rect.x() + xRadius, rect.y() + yRadius);
cairo_scale(cr, xRadius, yRadius);
cairo_arc(cr, 0., 0., 1., 0., 2 * piFloat);
cairo_restore(cr);
if (state.fillColor.isVisible()) {
setSourceRGBAFromColor(cr, state.fillColor);
cairo_fill_preserve(cr);
}
if (state.strokeStyle != NoStroke) {
setSourceRGBAFromColor(cr, state.strokeColor);
cairo_set_line_width(cr, state.strokeThickness);
cairo_stroke(cr);
} else
cairo_new_path(cr);
}
void drawFocusRing(PlatformContextCairo& platformContext, const Path& path, float width, const Color& color)
{
// FIXME: We should draw paths that describe a rectangle with rounded corners
// so as to be consistent with how we draw rectangular focus rings.
Color ringColor = color;
adjustFocusRingColor(ringColor);
adjustFocusRingLineWidth(width);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
cairo_push_group(cr);
appendWebCorePathToCairoContext(cr, path);
setSourceRGBAFromColor(cr, ringColor);
cairo_set_line_width(cr, width);
Cairo::State::setStrokeStyle(platformContext, focusRingStrokeStyle());
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_stroke_preserve(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
cairo_fill(cr);
cairo_pop_group_to_source(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_paint(cr);
cairo_restore(cr);
}
void drawFocusRing(PlatformContextCairo& platformContext, const Vector<FloatRect>& rects, float width, const Color& color)
{
Path path;
#if PLATFORM(GTK)
for (const auto& rect : rects)
path.addRect(rect);
#else
unsigned rectCount = rects.size();
int radius = (width - 1) / 2;
Path subPath;
for (unsigned i = 0; i < rectCount; ++i) {
if (i > 0)
subPath.clear();
subPath.addRoundedRect(rects[i], FloatSize(radius, radius));
path.addPath(subPath, AffineTransform());
}
#endif
drawFocusRing(platformContext, path, width, color);
}
void save(PlatformContextCairo& platformContext)
{
platformContext.save();
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->save();
}
void restore(PlatformContextCairo& platformContext)
{
platformContext.restore();
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->restore();
}
void translate(PlatformContextCairo& platformContext, float x, float y)
{
cairo_translate(platformContext.cr(), x, y);
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->translate(x, y);
}
void rotate(PlatformContextCairo& platformContext, float angleInRadians)
{
cairo_rotate(platformContext.cr(), angleInRadians);
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->rotate(angleInRadians);
}
void scale(PlatformContextCairo& platformContext, const FloatSize& size)
{
cairo_scale(platformContext.cr(), size.width(), size.height());
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->scale(size);
}
void concatCTM(PlatformContextCairo& platformContext, const AffineTransform& transform)
{
const cairo_matrix_t matrix = toCairoMatrix(transform);
cairo_transform(platformContext.cr(), &matrix);
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->concatCTM(transform);
}
void beginTransparencyLayer(PlatformContextCairo& platformContext, float opacity)
{
cairo_push_group(platformContext.cr());
platformContext.layers().append(opacity);
}
void endTransparencyLayer(PlatformContextCairo& platformContext)
{
cairo_t* cr = platformContext.cr();
cairo_pop_group_to_source(cr);
cairo_paint_with_alpha(cr, platformContext.layers().takeLast());
}
void clip(PlatformContextCairo& platformContext, const FloatRect& rect)
{
cairo_t* cr = platformContext.cr();
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
// The rectangular clip function is traditionally not expected to
// antialias. If we don't force antialiased clipping here,
// edge fringe artifacts may occur at the layer edges
// when a transformation is applied to the GraphicsContext
// while drawing the transformed layer.
cairo_antialias_t savedAntialiasRule = cairo_get_antialias(cr);
cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
cairo_clip(cr);
cairo_set_fill_rule(cr, savedFillRule);
cairo_set_antialias(cr, savedAntialiasRule);
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->clip(rect);
}
void clipOut(PlatformContextCairo& platformContext, const FloatRect& rect)
{
cairo_t* cr = platformContext.cr();
double x1, y1, x2, y2;
cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
cairo_clip(cr);
cairo_set_fill_rule(cr, savedFillRule);
}
void clipOut(PlatformContextCairo& platformContext, const Path& path)
{
cairo_t* cr = platformContext.cr();
double x1, y1, x2, y2;
cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
appendWebCorePathToCairoContext(cr, path);
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
cairo_clip(cr);
cairo_set_fill_rule(cr, savedFillRule);
}
void clipPath(PlatformContextCairo& platformContext, const Path& path, WindRule clipRule)
{
cairo_t* cr = platformContext.cr();
if (!path.isNull())
setPathOnCairoContext(cr, path.platformPath()->context());
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, clipRule == RULE_EVENODD ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
cairo_clip(cr);
cairo_set_fill_rule(cr, savedFillRule);
if (auto* graphicsContextPrivate = platformContext.graphicsContextPrivate())
graphicsContextPrivate->clip(path);
}
void clipToImageBuffer(PlatformContextCairo& platformContext, Image& image, const FloatRect& destRect)
{
RefPtr<cairo_surface_t> surface = image.nativeImageForCurrentFrame();
if (surface)
platformContext.pushImageMask(surface.get(), destRect);
}
} // namespace Cairo
} // namespace WebCore
#endif // USE(CAIRO)
| 38.166012 | 280 | 0.725581 | [
"object",
"vector",
"transform",
"solid"
] |
2ed0e589c0cffe45bfc4a1e5e5c01eb36cf385bd | 9,502 | hpp | C++ | src/ibeo_8l_sdk/src/ibeosdk/datablocks/snippets/ObjectScala.hpp | tomcamp0228/ibeo_ros2 | ff56c88d6e82440ae3ce4de08f2745707c354604 | [
"MIT"
] | 1 | 2020-06-19T11:01:49.000Z | 2020-06-19T11:01:49.000Z | src/ibeo_8l_sdk/src/ibeosdk/datablocks/snippets/ObjectScala.hpp | tomcamp0228/ibeo_ros2 | ff56c88d6e82440ae3ce4de08f2745707c354604 | [
"MIT"
] | null | null | null | src/ibeo_8l_sdk/src/ibeosdk/datablocks/snippets/ObjectScala.hpp | tomcamp0228/ibeo_ros2 | ff56c88d6e82440ae3ce4de08f2745707c354604 | [
"MIT"
] | 2 | 2020-06-19T11:01:48.000Z | 2020-10-29T03:07:14.000Z | //======================================================================
/*! \file ObjectScala.hpp
*
* \copydoc Copyright
* \author Jan Christian Dittmer (jcd)
* \date Jan 17, 2014
*///-------------------------------------------------------------------
#ifndef IBEOSDK_OBJECTSCALA_HPP_SEEN
#define IBEOSDK_OBJECTSCALA_HPP_SEEN
//======================================================================
#include <ibeosdk/misc/WinCompatibility.hpp>
#include <ibeosdk/ObjectBasic.hpp>
#include <ibeosdk/Point2d.hpp>
#include <ibeosdk/PointSigma2d.hpp>
#include <ibeosdk/datablocks/snippets/Snippet.hpp>
#include <vector>
#include <iostream>
#include <cmath>
//======================================================================
namespace ibeosdk {
//======================================================================
class ObjectScala : public ibeosdk::Snippet {
public:
enum Flags {
Flag_Stationary = 0x01, ///< Stationary model if set.
Flag_Mobile = 0x02, ///< Mobile, can only be set if object tracked by dynamic model.
Flag_MotionModelValidated = 0x04 ///< Motion model validated, is true if object is validated according to motion model.
}; // Flags
public:
ObjectScala();
ObjectScala(const ObjectScala& other);
ObjectScala& operator= (const ObjectScala& other);
virtual ~ObjectScala();
public:
virtual std::streamsize getSerializedSize() const;
virtual bool deserialize(std::istream& is);
virtual bool serialize(std::ostream& os) const;
public:
UINT16 getObjectId() const { return m_id; }
UINT16 getObjectAge() const { return m_age; }
UINT16 getPredictionAge() const { return m_predictionAge; }
UINT16 getRelativeTimestamp() const { return m_relativeTimestamp; }
RefPointBoxLocation getRefPointBoxLocation() const { return m_referencePointLocation; }
Point2d getReferencePoint() const { return m_refPoint; }
PointSigma2d getReferencePointSigma() const { return m_refPointSigma; }
UINT16 getRefPointPosCorrCoeff() const { return m_referencePointPositionCorrCoeff; }
UINT16 getObjectPriority() const { return m_objectPriority; }
UINT16 getObjectExistenceMeasure() const { return m_objectExistenceMeasure; }
Point2d getClosestPoint() const { return m_closestPoint; }
Point2d getBoundingBoxCenter() const { return m_boundingBoxCenter; }
UINT16 getBoundingBoxWidth() const { return m_boundingBoxWidth; }
UINT16 getBoundingBoxLength() const { return m_boundingBoxLength; }
Point2d getObjectBoxCenter() const { return m_objectBoxCenter; }
UINT16 getObjectBoxSizeX() const { return m_objectBoxSizeX; }
UINT16 getObjectBoxSizeY() const { return m_objectBoxSizeY; }
INT16 getObjectBoxOrientation() const { return m_objectBoxOrientation; }
PointSigma2d getObjectBoxSizeSigma() const { return m_objectBoxSizeSigma; }
UINT16 getObjectBoxOrientationSigma() const { return m_objectBoxOrientationSigma; }
Point2d getAbsoluteVelocity() const { return m_absVelocity; }
PointSigma2d getAbsoluteVelocitySigma() const { return m_absVelSigma; }
Point2d getRelativeVelocity() const { return m_relVelocity; }
PointSigma2d getRelativeVelocitySigma() const { return m_relVelSigma; }
ObjectClass getClassification() const { return m_class; }
UINT8 getFlags() const { return m_flags; }
bool trackedByStationary() const {return (m_flags & Flag_Stationary) == Flag_Stationary; }
bool mobile() const {return (m_flags & Flag_Mobile) == Flag_Mobile; }
bool motionModelValidated() const {return (m_flags & Flag_MotionModelValidated) == Flag_MotionModelValidated; }
UINT16 getClassificationAge() const { return m_classAge; }
UINT16 getClassificationConfidence() const { return m_classConfidence; }
UINT16 getNumberOfContourPoints() const { return m_numContourPoints; }
const std::vector<Point2d>& getContourPoints() const { return m_contourPoints; }
std::vector<Point2d>& getContourPoints() { return m_contourPoints; }
public:
void setObjectId(const UINT16 id) { this->m_id = id; }
void setObjectAge(const UINT16 age) { this->m_age = age; }
void setPredictionAge(const UINT16 predictionAge) { this->m_predictionAge = predictionAge; }
void setRelativeTimestamp(const UINT16 relativeTimestamp) { this->m_relativeTimestamp = relativeTimestamp; }
void setRefPointBoxLocation(const RefPointBoxLocation newRefPtLocation) { m_referencePointLocation = newRefPtLocation; }
void setRefPoint(const Point2d refPoint) { this->m_refPoint = refPoint; }
void setRefPointSigma(const PointSigma2d refPointSigma) { this->m_refPointSigma = refPointSigma; }
void setReferencePointPositionCorrCoeff(const UINT16 corrCoeff) { this->m_referencePointPositionCorrCoeff = corrCoeff; }
void setObjectPriority(const UINT16 newObjPrio) { this->m_objectPriority = newObjPrio; }
void setObjectExistenceMeasure(const UINT16 newExistenceMeasure) { this->m_objectExistenceMeasure = newExistenceMeasure; }
void setClosestPoint(const Point2d newClosesPoint) { this->m_closestPoint = newClosesPoint; }
void setBoundingBoxCenter(const Point2d boundingBoxCenter) { this->m_boundingBoxCenter = boundingBoxCenter; }
void setBoundingBoxWidth(const UINT16 boundingBoxWidth) { this->m_boundingBoxWidth = boundingBoxWidth; }
void setBoundingBoxLength(const UINT16 boundingBoxLength) { this->m_boundingBoxLength = boundingBoxLength; }
void setObjectBoxCenter(const Point2d objectBoxCenter) { this->m_objectBoxCenter = objectBoxCenter; }
void setObjectBoxLength(const UINT16 objectBoxLength) { this->m_objectBoxSizeX = objectBoxLength; }
void setObjectBoxWidth(const UINT16 objectBoxWidth) { this->m_objectBoxSizeY = objectBoxWidth; }
void setObjectBoxOrientation(const INT16 objectBoxOrientation) { this->m_objectBoxOrientation = objectBoxOrientation; }
void setObjectBoxSizeSigma(const PointSigma2d newObjBoxSizeSigma) { this->m_objectBoxSizeSigma = newObjBoxSizeSigma; }
void setObjectBoxOrientationSigma(const UINT16 newOrientSigma) { this->m_objectBoxOrientationSigma = newOrientSigma; }
void setAbsVelocity(const Point2d absVelocity) { this->m_absVelocity = absVelocity; }
void setAbsVelSigma(const PointSigma2d absVelSigma) { this->m_absVelSigma = absVelSigma; }
void setRelVelocity(const Point2d relVelocity) { this->m_relVelocity = relVelocity; }
void setRelVelSigma(const PointSigma2d relVelSigma) { this->m_relVelSigma = relVelSigma; }
void setClass(const ObjectClass cl) { this->m_class = cl; }
void getFlags(const UINT8 newFlags) { this->m_flags = newFlags; }
void setTrackedByStationaryModel(const bool set = true)
{
m_flags=set ? UINT8(m_flags | UINT8(Flag_Stationary))
: UINT8(m_flags & ~UINT8(Flag_Stationary));
}
void setMobile(const bool set = true)
{
m_flags=set ? UINT8(m_flags | UINT8(Flag_Mobile))
: UINT8(m_flags & ~UINT8(Flag_Mobile));
}
void setMotionModelValidated(const bool set = true)
{
m_flags=set ? UINT8(m_flags | UINT8(Flag_MotionModelValidated))
: UINT8(m_flags & ~UINT8(Flag_MotionModelValidated));
}
void setClassAge(const UINT16 classAge) { this->m_classAge = classAge; }
void setClassCertainty(const UINT16 classConfidence) { this->m_classConfidence = classConfidence; }
void setNumContourPoints(const UINT16 numContourPoints)
{
if (numContourPoints!= contourIsInvalid) {
this->m_numContourPoints = numContourPoints;
this-> m_numContourPointsIsValid = true;
}
else {
this->m_numContourPoints = 1;
this-> m_numContourPointsIsValid = false;
}
}
void setNumCoutourPointsValid(const bool valid) { this->m_numContourPointsIsValid = valid; }
void setContourPoints(const std::vector<Point2d>& newContourPts) { this->m_contourPoints = newContourPts; }
public:
static float angle2rad(const INT16 ticks)
{
const UINT16 angleTicksPerRotation = 36000;
// (x < 0) ? ((x % N) + N) : x % N
return float(((ticks < 0) ? float((ticks % angleTicksPerRotation) + angleTicksPerRotation)
: float(ticks % angleTicksPerRotation))
* 2.f * M_PI / float(angleTicksPerRotation));
}
protected:
static const UINT16 contourIsInvalid;
protected:
UINT16 m_id;
UINT16 m_age;
UINT16 m_predictionAge;
UINT16 m_relativeTimestamp;
UINT8 m_reserved0;
RefPointBoxLocation m_referencePointLocation; // as UINT8
Point2d m_refPoint;
PointSigma2d m_refPointSigma;
UINT16 m_referencePointPositionCorrCoeff;
UINT16 m_objectPriority;
UINT16 m_objectExistenceMeasure;
Point2d m_closestPoint;
Point2d m_boundingBoxCenter;
UINT16 m_boundingBoxWidth; // y-value
UINT16 m_boundingBoxLength; // x-value
Point2d m_objectBoxCenter;
UINT16 m_objectBoxSizeX; // x-value
UINT16 m_objectBoxSizeY; // y-value
INT16 m_objectBoxOrientation; // angle in [deg/100].
PointSigma2d m_objectBoxSizeSigma;
UINT16 m_objectBoxOrientationSigma;
Point2d m_absVelocity;
PointSigma2d m_absVelSigma;
Point2d m_relVelocity;
PointSigma2d m_relVelSigma;
ObjectClass m_class; // as UINT8
UINT8 m_flags;
UINT16 m_classAge;
UINT16 m_classConfidence;
UINT16 m_numContourPoints;
bool m_numContourPointsIsValid;
std::vector<Point2d> m_contourPoints;
}; // ObjectScala
//======================================================================
std::ostream& operator<<(std::ostream& os, const ObjectScala& obj);
//======================================================================
}// namespace ibeosdk
//======================================================================
#endif // IBEOSDK_OBJECTSCALA_HPP_SEEN
//======================================================================
| 39.757322 | 123 | 0.722269 | [
"object",
"vector",
"model"
] |
2ee27daf9eb8b71a26adc94d885f5580e806134c | 9,571 | cxx | C++ | Source/vtkboneApplyBendingTest.cxx | Numerics88/vtkbone | 5a6ab2870679e9e7ea51926c34911607b9d85235 | [
"MIT"
] | 3 | 2017-04-04T04:59:22.000Z | 2022-03-13T11:22:40.000Z | Source/vtkboneApplyBendingTest.cxx | Numerics88/vtkbone | 5a6ab2870679e9e7ea51926c34911607b9d85235 | [
"MIT"
] | 5 | 2017-04-06T19:46:39.000Z | 2019-12-11T23:41:41.000Z | Source/vtkboneApplyBendingTest.cxx | Numerics88/vtkbone | 5a6ab2870679e9e7ea51926c34911607b9d85235 | [
"MIT"
] | 2 | 2017-04-29T20:54:57.000Z | 2017-04-29T22:28:10.000Z | #include "vtkboneApplyBendingTest.h"
#include "vtkboneSolverParameters.h"
#include "vtkboneConstraintCollection.h"
#include "vtkboneNodeSetsByGeometry.h"
#include "vtkboneVersion.h"
#include "vtkObjectFactory.h"
#include "vtkCharArray.h"
#include "vtkDoubleArray.h"
#include "vtkInformationVector.h"
#include "vtkInformation.h"
#include "vtkIdList.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationDoubleKey.h"
#include "vtkInformationDoubleVectorKey.h"
#include "vtkInformationStringKey.h"
#include "vtkInformationStringVectorKey.h"
#include "vtkDataSetAttributes.h"
#include "vtkSmartPointer.h"
#include <sstream>
vtkStandardNewMacro(vtkboneApplyBendingTest);
//----------------------------------------------------------------------------
vtkboneApplyBendingTest::vtkboneApplyBendingTest()
:
NeutralAxisAngle (1.5707963267948966), // pi/2
BendingAngle (0.017453292519943295) // One degree.
{
this->NeutralAxisOrigin[0] = 0;
this->NeutralAxisOrigin[1] = 0;
}
//----------------------------------------------------------------------------
vtkboneApplyBendingTest::~vtkboneApplyBendingTest()
{
}
//----------------------------------------------------------------------------
void vtkboneApplyBendingTest::PrintSelf (ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
this->PrintParameters(os,indent);
}
//----------------------------------------------------------------------------
void vtkboneApplyBendingTest::PrintParameters (ostream& os, vtkIndent indent)
{
os << indent << "NeutralAxisOrigin: " << this->NeutralAxisOrigin[0] << ", "
<< this->NeutralAxisOrigin[1] << "\n";
os << indent << "NeutralAxisAngle: " << this->NeutralAxisAngle << "\n";
os << indent << "BendingAngle: " << this->BendingAngle << "\n";
}
//----------------------------------------------------------------------------
int vtkboneApplyBendingTest::RequestData
(
vtkInformation * request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector
)
{
vtkboneApplyTestBase::RequestData(request, inputVector, outputVector);
// Only need output object: vtkboneApplyTestBase has already copied the input
// object to the output object (and added stuff).
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkboneFiniteElementModel *output = vtkboneFiniteElementModel::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (!output)
{
vtkErrorMacro("No output object.");
return 0;
}
return ((this->AddTopAndBottomConstraints(output) == VTK_OK) &&
(this->AddConvergenceSet(output) == VTK_OK) &&
(this->AddPostProcessingSets(output) == VTK_OK) &&
(this->AddInformation(output) == VTK_OK));
}
//----------------------------------------------------------------------------
int vtkboneApplyBendingTest::AddTopAndBottomConstraints
(
vtkboneFiniteElementModel* model
)
{
double bounds[6];
model->GetBounds(bounds);
// constrain bottom and top surfaces to move only in Z
model->ApplyBoundaryCondition(
"face_z0", this->DataFrameSense(0), 0, "bottom_fixed");
model->ApplyBoundaryCondition(
"face_z0", this->DataFrameSense(1), 0, "bottom_fixed");
model->ApplyBoundaryCondition(
"face_z1", this->DataFrameSense(0), 0, "top_fixed");
model->ApplyBoundaryCondition(
"face_z1", this->DataFrameSense(1), 0, "top_fixed");
double nao[2]; // Neutral Axis origin
nao[0] = this->NeutralAxisOrigin[0];
nao[1] = this->NeutralAxisOrigin[1];
// cout << "nao: " << nao[0] << ", " << nao[1] << "\n";
double nau[2]; // Neutral Axis unit vector
nau[0] = cos(this->NeutralAxisAngle);
nau[1] = sin(this->NeutralAxisAngle);
// cout << "nau: " << nau[0] << ", " << nau[1] << "\n";
double deflectionSlope = tan(this->BendingAngle/2.0);
// Top nodes bending constraint
{ // scope
vtkSmartPointer<vtkIdTypeArray> nodes = vtkSmartPointer<vtkIdTypeArray>::New();
vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
senses->SetName("SENSE");
vtkSmartPointer<vtkDoubleArray> values = vtkSmartPointer<vtkDoubleArray>::New();
values->SetName("VALUE");
vtkIdTypeArray* faceTopNodes = model->GetNodeSet("face_z1");
for (vtkIdType i=0; i < faceTopNodes->GetNumberOfTuples(); i++)
{
vtkIdType iNode = faceTopNodes->GetValue(i);
double* ptDataFrame = model->GetPoint(iNode);
double pt[2];
pt[0] = ptDataFrame[this->DataFrameSense(0)];
pt[1] = ptDataFrame[this->DataFrameSense(1)];
// cout << "pt: " << pt[0] << ", " << pt[1] << "\n";
nodes->InsertNextValue (iNode);
senses->InsertNextValue (this->DataFrameSense(2));
double dot_product = (pt[0]-nao[0])*nau[0] + (pt[1]-nao[1])*nau[1];
double projectionOntoLine[2];
projectionOntoLine[0] = nao[0] + dot_product*nau[0];
projectionOntoLine[1] = nao[1] + dot_product*nau[1];
// cout << "projectionOntoLine: " << projectionOntoLine[0] << ", " << projectionOntoLine[1] << "\n";
double normalVector[2];
normalVector[0] = pt[0] - projectionOntoLine[0];
normalVector[1] = pt[1] - projectionOntoLine[1];
// cout << "normalVector: " << normalVector[0] << ", " << normalVector[1] << "\n";
// z component of the cross-product
double distanceFromNeutralAxis = normalVector[0]*nau[1]
- normalVector[1]*nau[0];
// cout << "distanceFromNeutralAxis: " << distanceFromNeutralAxis << "\n";
values->InsertNextValue(deflectionSlope*distanceFromNeutralAxis);
}
model->ApplyBoundaryCondition(nodes, senses, values, "top_displacement");
} // scope
// Bottom nodes bending constraint
{ // scope
vtkSmartPointer<vtkIdTypeArray> nodes = vtkSmartPointer<vtkIdTypeArray>::New();
vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
senses->SetName("SENSE");
vtkSmartPointer<vtkDoubleArray> values = vtkSmartPointer<vtkDoubleArray>::New();
values->SetName("VALUE");
vtkIdTypeArray* faceTopNodes = model->GetNodeSet("face_z0");
for (vtkIdType i=0; i < faceTopNodes->GetNumberOfTuples(); i++)
{
vtkIdType iNode = faceTopNodes->GetValue(i);
double* ptDataFrame = model->GetPoint(iNode);
double pt[2];
pt[0] = ptDataFrame[this->DataFrameSense(0)];
pt[1] = ptDataFrame[this->DataFrameSense(1)];
// cout << "pt: " << pt[0] << ", " << pt[1] << "\n";
nodes->InsertNextValue (iNode);
senses->InsertNextValue (this->DataFrameSense(2));
double dot_product = (pt[0]-nao[0])*nau[0] + (pt[1]-nao[1])*nau[1];
double projectionOntoLine[2];
projectionOntoLine[0] = nao[0] + dot_product*nau[0];
projectionOntoLine[1] = nao[1] + dot_product*nau[1];
// cout << "projectionOntoLine: " << projectionOntoLine[0] << ", " << projectionOntoLine[1] << "\n";
double normalVector[2];
normalVector[0] = pt[0] - projectionOntoLine[0];
normalVector[1] = pt[1] - projectionOntoLine[1];
// cout << "normalVector: " << normalVector[0] << ", " << normalVector[1] << "\n";
// z component of the cross-product
double distanceFromNeutralAxis = normalVector[0]*nau[1]
- normalVector[1]*nau[0];
// cout << "distanceFromNeutralAxis: " << distanceFromNeutralAxis << "\n";
values->InsertNextValue(-deflectionSlope*distanceFromNeutralAxis);
}
model->ApplyBoundaryCondition(nodes, senses, values, "bottom_displacement");
} // scope
return VTK_OK;
}
//----------------------------------------------------------------------------
int vtkboneApplyBendingTest::AddConvergenceSet
(
vtkboneFiniteElementModel* model
)
{
return model->ConvergenceSetFromConstraint("top_displacement");
}
//----------------------------------------------------------------------------
int vtkboneApplyBendingTest::AddPostProcessingSets
(
vtkboneFiniteElementModel* model
)
{
vtkInformation* info = model->GetInformation();
vtkboneSolverParameters::POST_PROCESSING_NODE_SETS()->Append(info, "face_z1");
vtkboneSolverParameters::POST_PROCESSING_NODE_SETS()->Append(info, "face_z0");
vtkboneSolverParameters::POST_PROCESSING_ELEMENT_SETS()->Append(info, "face_z1");
vtkboneSolverParameters::POST_PROCESSING_ELEMENT_SETS()->Append(info, "face_z0");
double rotationCenter[3];
for (int i=0; i<3; ++i)
{
int testFrameSense = this->TestFrameSense(i);
if (testFrameSense < 2)
{ rotationCenter[i] = this->NeutralAxisOrigin[testFrameSense]; }
else
{
double bounds[6];
model->GetBounds(bounds);
rotationCenter[i] = (bounds[2*i] + bounds[2*i+1])/2;
}
}
vtkboneSolverParameters::ROTATION_CENTER()->Set(info, rotationCenter, 3);
return VTK_OK;
}
//----------------------------------------------------------------------------
int vtkboneApplyBendingTest::AddInformation
(
vtkboneFiniteElementModel* model
)
{
std::string history = std::string("Model created by vtkboneApplyBendingTest version ")
+ vtkboneVersion::GetVTKBONEVersion() + " .";
model->AppendHistory(history.c_str());
std::ostringstream comments;
comments << "vtkboneApplyBendingTest settings:\n\n";
vtkIndent indent;
vtkboneApplyTestBase::PrintParameters(comments, indent);
this->PrintParameters(comments, indent);
model->AppendLog(comments.str().c_str());
return VTK_OK;
}
| 38.748988 | 106 | 0.62167 | [
"object",
"vector",
"model"
] |
2ee49c2cf38b121f93fdc30e4f9ed86015a78447 | 4,971 | cpp | C++ | src/common/utilmatlib.cpp | vxsd/refraction | bb6def1feb6c2e5c94b2604ad55607ed380a2d7e | [
"MIT"
] | 14 | 2021-02-16T14:13:50.000Z | 2022-03-17T18:29:19.000Z | src/common/utilmatlib.cpp | undbsd/refraction | bb6def1feb6c2e5c94b2604ad55607ed380a2d7e | [
"MIT"
] | 7 | 2021-08-06T18:40:37.000Z | 2022-03-09T18:05:08.000Z | src/common/utilmatlib.cpp | undbsd/refraction | bb6def1feb6c2e5c94b2604ad55607ed380a2d7e | [
"MIT"
] | 2 | 2021-08-05T16:03:03.000Z | 2021-11-26T00:11:27.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
// C callable material system interface for the utils.
// und: fuck ton of winapi? or why there was a windows.h?
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/imaterialvar.h"
#include "utilmatlib.h"
#include "tier0/dbg.h"
#include "filesystem.h"
#include "materialsystem/materialsystem_config.h"
void LoadMaterialSystemInterface( CreateInterfaceFn fileSystemFactory )
{
// Already loaded
if( g_pMaterialSystem ) {
return;
}
// materialsystem.dll should be in the path, it's in bin along with vbsp.
const char *pDllName = "materialsystem.dll";
CSysModule *materialSystemDLLHInst;
materialSystemDLLHInst = g_pFullFileSystem->LoadModule( pDllName );
if( !materialSystemDLLHInst ) {
Error( "Can't load MaterialSystem.dll\n" );
}
CreateInterfaceFn clientFactory = Sys_GetFactory( materialSystemDLLHInst );
if( clientFactory ) {
g_pMaterialSystem = (IMaterialSystem *)clientFactory( MATERIAL_SYSTEM_INTERFACE_VERSION, NULL );
if( !g_pMaterialSystem ) {
Error( "Could not get the material system interface from materialsystem.dll (" __FILE__ ")" );
}
}
else {
Error( "Could not find factory interface in library MaterialSystem.dll" );
}
if( !g_pMaterialSystem->Init( "shaderapiempty.dll", 0, fileSystemFactory ) ) {
Error( "Could not start the empty shader (shaderapiempty.dll)!" );
}
// See valvesoftware/source-sdk-2013#200
g_pMaterialSystem->ModInit();
}
void InitMaterialSystem( const char *materialBaseDirPath, CreateInterfaceFn fileSystemFactory )
{
LoadMaterialSystemInterface( fileSystemFactory );
MaterialSystem_Config_t config;
g_pMaterialSystem->OverrideConfig( config, false );
}
void ShutdownMaterialSystem()
{
if( g_pMaterialSystem ) {
g_pMaterialSystem->Shutdown();
g_pMaterialSystem = NULL;
}
}
MaterialSystemMaterial_t FindMaterial( const char *materialName, bool *pFound, bool bComplain )
{
IMaterial *pMat = g_pMaterialSystem->FindMaterial( materialName, TEXTURE_GROUP_OTHER, bComplain );
MaterialSystemMaterial_t matHandle = pMat;
if( pFound ) {
*pFound = true;
if( IsErrorMaterial( pMat ) )
*pFound = false;
}
return matHandle;
}
void GetMaterialDimensions( MaterialSystemMaterial_t materialHandle, int *width, int *height )
{
PreviewImageRetVal_t retVal;
ImageFormat dummyImageFormat;
IMaterial *material = (IMaterial *)materialHandle;
bool translucent;
retVal = material->GetPreviewImageProperties( width, height, &dummyImageFormat, &translucent );
if( retVal != MATERIAL_PREVIEW_IMAGE_OK ) {
*width = 128;
*height = 128;
}
}
void GetMaterialReflectivity( MaterialSystemMaterial_t materialHandle, float *reflectivityVect )
{
IMaterial *material = (IMaterial *)materialHandle;
const IMaterialVar *reflectivityVar;
bool found;
reflectivityVar = material->FindVar( "$reflectivity", &found, false );
if( !found ) {
Vector tmp;
material->GetReflectivity( tmp );
VectorCopy( tmp.Base(), reflectivityVect );
}
else {
reflectivityVar->GetVecValue( reflectivityVect, 3 );
}
}
int GetMaterialShaderPropertyBool( MaterialSystemMaterial_t materialHandle, int propID )
{
IMaterial *material = (IMaterial *)materialHandle;
if( propID == UTILMATLIB_NEEDS_BUMPED_LIGHTMAPS ) {
return material->GetPropertyFlag( MATERIAL_PROPERTY_NEEDS_BUMPED_LIGHTMAPS );
}
if( propID == UTILMATLIB_NEEDS_LIGHTMAP ) {
return material->GetPropertyFlag( MATERIAL_PROPERTY_NEEDS_LIGHTMAP );
}
Assert( 0 );
return 0;
}
int GetMaterialShaderPropertyInt( MaterialSystemMaterial_t materialHandle, int propID )
{
IMaterial *material = (IMaterial *)materialHandle;
if( propID == UTILMATLIB_OPACITY ) {
if( material->IsTranslucent() ) {
return UTILMATLIB_TRANSLUCENT;
}
if( material->IsAlphaTested() ) {
return UTILMATLIB_ALPHATEST;
}
return UTILMATLIB_OPAQUE;
}
Assert( 0 );
return 0;
}
const char *GetMaterialVar( MaterialSystemMaterial_t materialHandle, const char *propertyName )
{
IMaterial *material = (IMaterial *)materialHandle;
IMaterialVar *var;
bool found;
var = material->FindVar( propertyName, &found, false );
if( found ) {
return var->GetStringValue();
}
else {
return NULL;
}
}
const char *GetMaterialShaderName( MaterialSystemMaterial_t materialHandle )
{
IMaterial *material = (IMaterial *)materialHandle;
return material->GetShaderName();
}
| 29.414201 | 106 | 0.675719 | [
"vector"
] |
2ee4f2ef6b43496b260b2281d6377d365a7f527a | 4,728 | hpp | C++ | checkers/engine/src/fuel/fuel.hpp | amreo/ructfe-2019 | 19064842acc57243f16143a85c06a5613378ebec | [
"MIT"
] | 23 | 2019-11-23T19:53:10.000Z | 2021-02-19T06:13:28.000Z | checkers/engine/src/fuel/fuel.hpp | amreo/ructfe-2019 | 19064842acc57243f16143a85c06a5613378ebec | [
"MIT"
] | 1 | 2019-11-30T16:10:52.000Z | 2019-12-01T15:23:39.000Z | checkers/engine/src/fuel/fuel.hpp | amreo/ructfe-2019 | 19064842acc57243f16143a85c06a5613378ebec | [
"MIT"
] | 3 | 2019-11-24T09:35:43.000Z | 2021-02-19T06:13:29.000Z | #ifndef HPP_FUEL
#define HPP_FUEL
#include <boost/serialization/access.hpp>
#include <queue>
#include <vector>
#include <memory>
#include <algorithm>
#include "piece.hpp"
#include "state.hpp"
#include "settings.hpp"
#include "piece_tree.hpp"
class fuel {
private:
state* d_root;
settings d_settings;
bool d_build_failure;
unsigned int d_num_keywords = 0;
public:
fuel(): fuel(settings()) {}
fuel(const settings& s)
: d_root(new state())
, d_settings(s)
, d_build_failure(false) {}
fuel& ignore_case() {
d_settings.set_ignore_case(true);
return *this;
}
fuel& without_overlaps() {
d_settings.set_without_overlaps(true);
return *this;
}
fuel& match_entire() {
d_settings.set_match_entire(true);
return *this;
}
void add(std::string keyword) {
if (keyword.empty())
return;
state* cur_state = d_root;
for (const auto& ch : keyword) {
cur_state = cur_state->add(ch);
}
cur_state->add_piece(keyword.size(), d_num_keywords++);
d_build_failure = false;
}
std::vector<piece> check(std::string text) {
if (!d_build_failure) {
build_failure();
}
size_t pos = 0;
state* cur_state = d_root;
std::vector<piece> collected_pieces;
for (auto c : text) {
if (d_settings.is_ignore_case()) {
c = std::tolower(c);
}
cur_state = find_state(cur_state, c);
store_piece(pos, cur_state, collected_pieces);
pos++;
}
if (d_settings.is_match_entire()) {
delete_partial_matches(text, collected_pieces);
}
if (d_settings.is_without_overlaps()) {
piece_tree tree(std::vector<piece>(collected_pieces.begin(), collected_pieces.end()));
auto tmp = tree.delete_overlaps(collected_pieces);
collected_pieces.swap(tmp);
}
return std::vector<piece>(collected_pieces);
}
private:
void delete_partial_matches(std::string& search_text, std::vector<piece>& collected_pieces) const {
size_t size = search_text.size();
std::vector<piece> remove_pieces;
for (const auto& p : collected_pieces) {
if ((p.start() == 0 || !std::isalpha(search_text.at(p.start() - 1))) &&
(p.end() + 1 == size || !std::isalpha(search_text.at(p.end() + 1)))) {
continue;
}
remove_pieces.push_back(p);
}
for (auto& p : remove_pieces) {
collected_pieces.erase(
std::find(collected_pieces.begin(), collected_pieces.end(), p)
);
}
}
state* find_state(state* cur_state, char c) const {
state* result = cur_state->next(c);
while (result == nullptr) {
cur_state = cur_state->failure();
result = cur_state->next(c);
}
return result;
}
void build_failure() {
std::queue<state*> q;
for (auto& depth_one_state : d_root->states()) {
depth_one_state->failure(d_root);
q.push(depth_one_state);
}
d_build_failure = true;
while (!q.empty()) {
auto cur_state = q.front();
for (const auto& transition : cur_state->transitions()) {
state* target_state = cur_state->next(transition);
q.push(target_state);
state* trace_failure_state = cur_state->failure();
while (trace_failure_state->next(transition) == nullptr) {
trace_failure_state = trace_failure_state->failure();
}
state* new_failure_state = trace_failure_state->next(transition);
target_state->failure(new_failure_state);
target_state->add_piece(new_failure_state->pieces());
}
q.pop();
}
}
void store_piece(size_t pos, state* cur_state, std::vector<piece>& collected_pieces) const {
auto pieces = cur_state->pieces();
if (!pieces.empty()) {
for (const auto& str : pieces) {
collected_pieces.push_back(piece(pos - str.first + 1, pos, str.second));
}
}
}
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & d_root;
ar & d_settings;
ar & d_build_failure;
ar & d_num_keywords;
}
};
#endif
| 26.413408 | 103 | 0.550761 | [
"vector"
] |
2ee8bd0a12c098898958ef852f525639fdb4ff7a | 1,302 | cpp | C++ | ABC/ABC104/C.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | ABC/ABC104/C.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | ABC/ABC104/C.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | //#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <sstream>
//#include <string>
//#include <vector>
//#include <map>
//#include <queue>
//#include <algorithm>
//
//#ifdef _DEBUG
//#define DMP(x) cerr << #x << ": " << x << "\n"
//#else
//#define DMP(x) ((void)0)
//#endif
//
//const int MOD = 1000000007, INF = 1111111111;
//using namespace std;
//typedef long long lint;
//
//struct prob {
// int bonus, num;
// };
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int D, G;
// cin >> D >> G;
//
// vector<prob> p(D);
// prob ptmp;
// for (int i = 0; i < D; i++) {
// cin >> ptmp.num >> ptmp.bonus;
// ptmp.bonus += (i + 1) * ptmp.num * 100;
// p[i] = ptmp;
// }
//
// int ans = INF, sum, cnt, tmp;
// for (int bit = 0b0; bit < (1 << D); bit++) {
//
// sum = 0, cnt = 0;
// for (int i = 0; i < D; i++) {
// if (bit & (1 << i)) {
// sum += p[i].bonus;
// cnt += p[i].num;
// }
// }
//
// if (sum >= G) {
// ans = min(ans, cnt);
// }
// else {
// for (int i = D - 1; i >= 0; i--) {
// if (!(bit & (1 << i))) {
// tmp = (G - sum - 1) / ((i + 1) * 100) + 1;
// if (tmp < p[i].num) {
// ans = min(ans, cnt + tmp);
// }
// break;
// }
// }
// }
//
// }
//
// cout << ans << "\n";
//
// return 0;
//} | 18.083333 | 49 | 0.440092 | [
"vector"
] |
2eeb298b761f0773116cf1a4cc0b5a0ff1dda0e9 | 14,450 | hpp | C++ | include/typecode.hpp | ferhatgec/typecode | 069566d367f41544d3017c0abeaa4c5d3653d732 | [
"MIT"
] | 2 | 2021-08-19T00:02:12.000Z | 2021-08-19T00:08:06.000Z | include/typecode.hpp | ferhatgec/typecode | 069566d367f41544d3017c0abeaa4c5d3653d732 | [
"MIT"
] | null | null | null | include/typecode.hpp | ferhatgec/typecode | 069566d367f41544d3017c0abeaa4c5d3653d732 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
// Distributed under the terms of the MIT License.
//
// TypeCode - An interpreter that introduces you.
//
// An example code:
// $%///*++;%////*++;///++++;///*++;///*+++;-%////*;$@/*+;+++;///;@
//
// Output:
// Languages:
// FlaScript
// Gretea
// C
// C++
// C++/CLI
// Python
//
// Branches:
// Computer Science
// Programming languages
// Programming languages and compilers
//
#ifndef TYPECODE_TYPECODE_HPP
#define TYPECODE_TYPECODE_HPP
#include <iostream>
#include <vector>
enum Tokens : char {
Lang = '$',
Branch = '@',
OS = '?',
Push = '+',
Push5 = '*',
Push10 = '/',
Push50 = '%',
Push100 = '-',
Print = ';'
};
class TypeCode {
// taken from https://dzone.com/articles/big-list-256-programming
std::vector<std::string> languages;
// taken from https://www.quora.com/What-are-the-branches-of-computer-science
std::vector<std::string> branches;
std::vector<std::string> operating_systems;
std::string data;
bool is_language, is_branch, is_os;
unsigned stack;
public:
std::vector<std::string> info_languages;
std::vector<std::string> info_branches;
std::vector<std::string> info_operating_systems;
public:
TypeCode() = default;
~TypeCode()= default;
void init(const std::string file_data) noexcept {
this->init_languages();
this->init_branches();
this->init_operating_systems();
for(auto& ch : file_data) {
// $+++++++;+++;$
//
// @+++++++++++++++;@
switch(ch) {
case Lang: {
this->is_language = !this->is_language;
break;
}
case Branch: {
this->is_branch = !this->is_branch;
break;
}
case OS: {
this->is_os = !this->is_os;
break;
}
case Push: {
++this->stack;
break;
}
case Push5: {
this->stack += 5;
break;
}
case Push10: {
this->stack += 10;
break;
}
case Push50: {
this->stack += 50;
break;
}
case Push100: {
this->stack += 100;
break;
}
case Print: {
if(this->is_branch && this->stack < this->branches.size()) {
this->info_branches.push_back(this->branches[this->stack]);
} else if(this->is_language && this->stack < this->languages.size()) {
this->info_languages.push_back(this->languages[this->stack]);
} else if(this->is_os && this->stack < this->operating_systems.size()) {
this->info_operating_systems.push_back(this->operating_systems[this->stack]);
} this->stack = 0;
break;
}
}
}
}
void init_languages() noexcept {
this->languages = {
"4th Dimension/4D",
"ABAP",
"ABC",
"ActionScript",
"Ada",
"Agilent VEE",
"Algol",
"Alice",
"Angelscript",
"Apex",
"APL",
"AppleScript",
"Arc",
"Arduino",
"ASP",
"AspectJ",
"Assembly",
"ATLAS",
"Augeas",
"AutoHotkey",
"AutoIt",
"AutoLISP",
"Automator",
"Avenue",
"Awk",
"Bash",
"(Visual) Basic",
"bc",
"BCPL",
"BETA",
"BlitzMax",
"Boo",
"Bourne Shell",
"Bro",
"C",
"C Shell",
"C#",
"C++",
"C++/CLI",
"C-Omega",
"Caml",
"Ceylon",
"CFML",
"cg",
"Ch",
"CHILL",
"CIL",
"CL (OS/400)",
"Clarion",
"Clean",
"Clipper",
"Clojure",
"CLU",
"COBOL",
"Cobra",
"CoffeeScript",
"ColdFusion",
"COMAL",
"Common Lisp",
"Coq",
"cT",
"Curl",
"D",
"Dart",
"DCL",
"DCPU-16 ASM",
"Delphi/Object Pascal",
"DiBOL",
"Dylan",
"E",
"eC",
"Ecl",
"ECMAScript",
"EGL",
"Eiffel",
"Elixir",
"Emacs Lisp",
"Erlang",
"Etoys",
"Euphoria",
"EXEC",
"F#",
"Factor",
"Falcon",
"Fancy",
"Fantom",
"Felix",
"FlaScript",
"Forth",
"Fortran",
"Fortress",
"(Visual) FoxPro",
"Gambas",
"GNU Octave",
"Go",
"Google AppsScript",
"Gosu",
"Gretea",
"Groovy",
"Haskell",
"haXe",
"Heron",
"HPL",
"HyperTalk",
"Icon",
"IDL",
"Inform",
"Informix-4GL",
"INTERCAL",
"Io",
"Ioke",
"J",
"J#",
"JADE",
"Java",
"Java FX Script",
"JavaScript",
"JScript",
"JScript.NET",
"Julia",
"Korn Shell",
"Kotlin",
"LabVIEW",
"Ladder Logic",
"Lasso",
"Limbo",
"Lingo",
"Lisp",
"Logo",
"Logtalk",
"LotusScript",
"LPC",
"Lua",
"Lustre",
"M4",
"MAD",
"Magic",
"Magik",
"Malbolge",
"MANTIS",
"Maple",
"Mathematica",
"MATLAB",
"Max/MSP",
"MAXScript",
"MEL",
"Mercury",
"Mirah",
"Miva",
"ML",
"Monkey",
"Modula-2",
"Modula-3",
"MOO",
"Moto",
"MS-DOS Batch",
"MUMPS",
"NATURAL",
"Nemerle",
"Nim",
"NQC",
"NSIS",
"Nu",
"NXT-G",
"Oberon",
"Object Rexx",
"Objective-C",
"Objective-J",
"OCaml",
"Occam",
"ooc",
"Opa",
"OpenCL",
"OpenEdge ABL",
"OPL",
"Oz",
"Paradox",
"Parrot",
"Pascal",
"Perl",
"PHP",
"Pike",
"PILOT",
"PL/I",
"PL/SQL",
"Pliant",
"PostScript",
"POV-Ray",
"PowerBasic",
"PowerScript",
"PowerShell",
"Processing",
"Prolog",
"Puppet",
"Pure Data",
"Python",
"Q",
"R",
"Racket",
"REALBasic",
"REBOL",
"Revolution",
"REXX",
"RPG (OS/400)",
"Ruby",
"Rust",
"S",
"S-PLUS",
"SAS",
"Sather",
"Scala",
"Scheme",
"Scilab",
"Scratch",
"sed",
"Seed7",
"Self",
"Shell",
"SIGNAL",
"Simula",
"Simulink",
"Slate",
"Smalltalk",
"Smarty",
"SPARK",
"SPSS",
"SQR",
"Squeak",
"Squirrel",
"Standard ML",
"Suneido",
"SuperCollider",
"TACL",
"Tcl",
"Tex",
"thinBasic",
"TOM",
"Transact-SQL",
"Turing",
"TypeScript",
"Vala/Genie",
"VBScript",
"Verilog",
"VHDL",
"VimL",
"Visual Basic .NET",
"WebDNA",
"Whitespace",
"X10",
"xBase",
"XBase++",
"Xen",
"XPL",
"XSLT",
"XQuery",
"yacc",
"Yorick",
"Z shell",
};
}
void init_branches() noexcept {
this->branches = {
"Human-computer interaction",
"Data science",
"Natural language processing",
"Programming languages",
"Software engineering",
"Architecture and organization",
"Cyber security",
"Information management",
"Networking and communication",
"Computer graphics",
"Platform-based development",
"Graphics and visual computing",
"Algorithms and complexity",
"Parallel and distributed computing",
"Intelligent systems",
"Security and information assurance",
"Computer Science",
"Computer Engineering",
"Information Systems",
"New Media",
"Information Technology (IT)",
"Information Science",
"Mathematical foundations.",
"Algorithms and data structures.",
"Artificial intelligence.",
"Communication and security.",
"Computer architecture.",
"Computer graphics.",
"Concurrent, parallel, and distributed systems.",
"Databases.",
"Programming languages and compilers",
"Scientific computing",
"Software engineering",
"Theory of computing"
};
}
void init_operating_systems() noexcept {
this->operating_systems = {
"Arthur",
"RISC OS",
"Fire OS",
"Amiga OS",
"AMSDOS",
"macOS",
"iOS",
"iPadOS",
"tvOS",
"bridgeOS",
"Atari DOS",
"BeOS",
"Unix",
"BESYS",
"Plan 9",
"Inferno",
"Android",
"Harmony OS",
"LiteOS",
"iRMX",
"PC DOS",
"OS/2",
"Remix OS",
"KaiOS",
"LynxOS",
"Xenix",
"MS-DOS",
"DOS/V",
"Windows",
"Windows 1.0",
"Windows 2.0",
"Windows 3.0",
"Windows 3.1x",
"Windows 3.2",
"Windows 95",
"Windows 98",
"Windows ME",
"Windows NT",
"Windows NT 3.1",
"Windows NT 4.0",
"Windows 2000",
"Windows XP",
"Windows Server 2003",
"Windows Vista",
"Windows Phone 7",
"Windows 8",
"Windows RT",
"Windows Phone 8",
"Windows 8.1",
"Windows Phone 8.1",
"Windows 10",
"Windows 10 Mobile",
"Windows 11",
"ES",
"NeXTSTEP",
"NetWare",
"UnixWare",
"Bada",
"Tizen",
"One UI",
"Sun OS",
"Solaris"
"BSD",
"FreeBSD",
"DragonFlyBSD",
"MidnightBSD",
"GhostBSD",
"TrueOS",
"prismBSD",
"NetBSD",
"OpenBSD",
"Bitrig",
"Darwin",
"GNU Hurd",
"Linux",
"RHEL",
"Rocky Linux"
"RPM",
"Red Hat Linux",
"CentOS",
"Fedora",
"Qubes OS"
"openSUSE",
"SUSE Linux Enterprise Desktop",
"SUSE Linux Enterprise Server",
"SUSE Studio",
"GeckoLinux",
"Mandrake Linux",
"Debian",
"MX Linux",
"Deepin",
"Devuan",
"Kali Linux",
"Pure OS",
"Ubuntu",
"Kubuntu",
"Lubuntu",
"Ubuntu Budgie",
"Ubuntu Kylin",
"Ubuntu Mate",
"Xubuntu",
"Bodhi Linux",
"elementary OS",
"Linux Mint",
"Zorin OS",
"Pop!_OS",
"Arch Linux",
"Manjaro",
"Artix Linux",
"EndeavourOS",
"SteamOS",
"Gentoo",
"Chrome OS",
"Chromium OS",
"NixOS",
"Void Linux",
"GuixSD",
"Solus",
"Redox",
"illumos",
"OpenIndiana",
"FreeDOS",
"Genode",
"FFusionOS",
"Ghost OS",
"Haiku",
"ReactOS",
"TempleOS",
"Serenity",
"Visopsys"
};
}
};
#endif // TYPECODE_TYPECODE_HPP
| 25.086806 | 101 | 0.340069 | [
"object",
"vector"
] |
2eeb3747671f6f17aafa5f353e05cd50ce6b0638 | 6,698 | cpp | C++ | examples/Robotics/HuMAns_Bip/RobotFrot.cpp | bremond/siconos | 8deea56ff6779379f4f69e0376d24a81562a42d4 | [
"Apache-2.0"
] | 6 | 2017-01-12T23:09:28.000Z | 2021-03-20T17:03:58.000Z | examples/Robotics/HuMAns_Bip/RobotFrot.cpp | bremond/siconos | 8deea56ff6779379f4f69e0376d24a81562a42d4 | [
"Apache-2.0"
] | 3 | 2019-01-14T13:44:51.000Z | 2021-05-17T13:57:27.000Z | examples/Robotics/HuMAns_Bip/RobotFrot.cpp | bremond/siconos | 8deea56ff6779379f4f69e0376d24a81562a42d4 | [
"Apache-2.0"
] | 2 | 2019-10-22T13:30:39.000Z | 2020-10-06T10:19:57.000Z |
// =============================== Robot sample (Bip) ===============================
//
// Keywords: LagrangianDS, LagrangianLinear relation, MoreauJeanOSI TimeStepping, LCP.
//
// =============================================================================================
#include "SiconosKernel.hpp"
using namespace std;
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 21; // degrees of freedom for robot
double t0 = 0; // initial computation time
double T = 1.3;//0.005; // final computation time
double h = 0.001; // time step
double criterion = 0.5;
unsigned int maxIter = 5000;
double en = 0.0, et = 0.0, mu = 0.1; // nslaw
// -> mind to set the initial conditions below.
// -------------------------
// --- Dynamical systems ---
// -------------------------
// unsigned int i;
// --- DS: robot bip ---
// The dof are angles between differents parts of the robot.
// Initial position (angles in radian)
SiconosVector q0(nDof), v0(nDof);
q0(1) = -0.1;
q0(2) = 0.2;
q0(3) = -0.1;
q0(5) = -0.1;
q0(6) = 0.2;
q0(7) = -0.1;
SP::LagrangianDS bip(new LagrangianDS(q0, v0));
// external plug-in
bip->setComputeMassFunction("RobotFrotPlugin", "mass");
bip->setComputeFGyrFunction("RobotFrotPlugin", "FGyr");
bip->setComputeJacobianFGyrFunction(0, "RobotFrotPlugin", "jacobianFGyrq");
bip->setComputeJacobianFGyrFunction(1, "RobotFrotPlugin", "jacobianVFGyr");
// -------------------
// --- Interactions---
// -------------------
// Two interactions:
// - one with Lagrangian non linear relation to define contact with ground
// - the other to define angles limitations (articular stops), with lagrangian linear relation
// Both with newton impact nslaw.
// -- relations --
SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(en, et, mu, 3));
string G = "RobotFrotPlugin:G0";
SP::Relation relation(new LagrangianScleronomousR("RobotFrotPlugin:h0", G));
SP::Interaction inter(new Interaction(69, nslaw, relation));
//The linear contraint corresponding to joints limits (hq+b>0)
SP::NonSmoothLaw nslaw2(new NewtonImpactFrictionNSL(en, et, 0, 3));
SimpleMatrix H(90, 21);
SiconosVector b(90);
H.zero();
b.zero();
for (unsigned int i = 0; i < 15; ++i)
{
for (unsigned int j = 0; j < 3; ++j)
{
H(6 * i + j, i) = -1;
H(6 * i + j + 3, i) = 1;
}
}
unsigned int i = 0;
b(3 * i + 0) = 0.21;
b(3 * i + 1) = 0.21;
i++;
b(3 * i + 2) = 0.64;
b(3 * i + 3) = 0.64;
i++;
b(3 * i + 4) = 1.41;
b(3 * i + 5) = -0.11;
i++;
b(3 * i + 6) = 0.20;
b(3 * i + 7) = 1.17;
i++;
b(3 * i + 8) = 0.21;
b(3 * i + 9) = 0.21;
i++;
b(3 * i + 10) = 0.64;
b(3 * i + 11) = 0.64;
i++;
b(3 * i + 12) = 1.41;
b(3 * i + 13) = -0.11;
i++;
b(3 * i + 14) = 0.2;
b(3 * i + 15) = 1.17;
i++;
b(3 * i + 16) = 0.17;
b(3 * i + 17) = 0.17;
i++;
b(3 * i + 18) = 0.14;
b(3 * i + 19) = 0.14;
i++;
b(3 * i + 20) = 0.17;
b(3 * i + 21) = 0.17;
i++;
b(3 * i + 22) = 0.14;
b(3 * i + 23) = 0.14;
i++;
b(3 * i + 24) = 0.17;
b(3 * i + 25) = 0.17;
i++;
b(3 * i + 26) = 0.08;
b(3 * i + 27) = 0.08;
i++;
b(3 * i + 28) = 0.08;
b(3 * i + 29) = 0.21;
SP::Relation relation2(new LagrangianLinearTIR(H, b));
SP::Interaction inter2(new Interaction(90, nslaw2, relation2));
// -------------
// --- Model ---
// -------------
SP::Model Robot(new Model(t0, T));
Robot->nonSmoothDynamicalSystem()->insertDynamicalSystem(bip);
Robot->nonSmoothDynamicalSystem()->link(inter1, bip);
Robot->nonSmoothDynamicalSystem()->link(inter2, bip);
// ----------------
// --- Simulation ---
// ----------------
// -- Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
SP::TimeStepping s(new TimeStepping(t));
// -- OneStepIntegrators --
SP::OneStepIntegrator OSI(new MoreauJeanOSI(bip, 0.500001));
s->insertIntegrator(OSI);
// -- OneStepNsProblem --
string solverName = "NSGS"; // solver algorithm used for non-smooth problem
IntParameters iparam(5);
iparam[0] = 10100; // Max number of iteration
// Solver/formulation
// 0: projection, 1: Newton/AlartCurnier, 2: Newton/Fischer-Burmeister, 3: Path/Glocker
iparam[4] = 4;
DoubleParameters dparam(5);
dparam[0] = 1e-6; // Tolerance
dparam[2] = 1e-8; // Local Tolerance
SP::NonSmoothSolver Mysolver(new NonSmoothSolver(solverName, iparam, dparam));
SP::NonSmoothSolver mySolver(new NonSmoothSolver(solverName, iparam, dparam));
SP::FrictionContact osnspb(new FrictionContact(3, mySolver));
s->insertNonSmoothProblem(osnspb);
cout << "=== End of model loading === " << endl;
Robot->setSimulation(s);
// =========================== End of model definition ===========================
// ================================= Computation =================================
// --- Simulation initialization ---
Robot->initialize();
cout << "End of model initialisation" << endl;
int k = 0; // Current step
unsigned int N = (unsigned int)((T - t0) / h);
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 22;
SimpleMatrix dataPlot(N + 1, outputSize);
// For the initial time step:
// time
dataPlot(k, 0) = Robot->t0();
for (unsigned int i = 1; i < 22; i++)
dataPlot(k, i) = (*bip->q())(i - 1);
// --- Compute elapsed time ---
boost::timer tt;
tt.restart();
// --- Time loop ---
cout << "Start computation ... " << endl;
while (s->hasNextEvent())
{
// get current time step
k++;
cout << k << endl;
s->newtonSolve(criterion, maxIter);
s->nextStep();
dataPlot(k, 0) = s->startingTime();
for (unsigned int i = 1; i < 22; i++)
dataPlot(k, i) = (*bip->q())(i - 1);
}
cout << "time = " << tt.elapsed() << endl;
cout << "End of computation - Number of iterations done: " << k << endl;
// --- Output files ---
ioMatrix::write("result.dat", "ascii", dataPlot, "noDim");
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in \'sample/MultiBeadsColumn\'" << endl;
}
}
| 28.623932 | 99 | 0.508361 | [
"model"
] |
2ef77c3a818302b04357f5a8b60b7517fc65e917 | 4,512 | cpp | C++ | apps/wasp2raw/wasp2raw.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | null | null | null | apps/wasp2raw/wasp2raw.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | null | null | null | apps/wasp2raw/wasp2raw.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | 1 | 2021-12-04T15:35:46.000Z | 2021-12-04T15:35:46.000Z | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <cerrno>
#include <stdio.h>
#include <vapor/CFuncs.h>
#include <vapor/OptionParser.h>
#include <vapor/WASP.h>
#include <vapor/FileUtils.h>
using namespace Wasp;
using namespace VAPoR;
//
// Command line argument stuff
//
struct opt_t {
string varname;
string type;
int lod;
int level;
int nthreads;
vector <int> start;
vector <int> count;
OptionParser::Boolean_T debug;
OptionParser::Boolean_T help;
} opt;
OptionParser::OptDescRec_T set_opts[] = {
{"varname", 1, "var1", "Name of variable"},
{"type", 1, "float32", "Primitive type of output data"},
{"lod", 1, "-1", "Compression levels saved. 0 => coarsest, 1 => "
"next refinement, etc. -1 => all levels defined by the netcdf file"},
{"level",1, "-1","Multiresolution refinement level. Zero implies coarsest "
"resolution"},
{"start",1, "","Colon-delimited NetCDF style start coordinate vector"},
{"count",1, "","Colon-delimited NetCDF style count coordinate vector"},
{"nthreads",1, "0","Number of execution threads. 0 => use number of cores"},
{"debug", 0, "", "Enable diagnostic"},
{"help", 0, "", "Print this message and exit"},
{NULL}
};
OptionParser::Option_T get_options[] = {
{"varname", Wasp::CvtToCPPStr, &opt.varname, sizeof(opt.varname)},
{"type", Wasp::CvtToCPPStr, &opt.type, sizeof(opt.type)},
{"lod", Wasp::CvtToInt, &opt.lod, sizeof(opt.lod)},
{"level", Wasp::CvtToInt, &opt.level, sizeof(opt.level)},
{"start", Wasp::CvtToIntVec, &opt.start, sizeof(opt.start)},
{"count", Wasp::CvtToIntVec, &opt.count, sizeof(opt.count)},
{"nthreads", Wasp::CvtToInt, &opt.nthreads, sizeof(opt.nthreads)},
{"debug", Wasp::CvtToBoolean, &opt.debug, sizeof(opt.debug)},
{"help", Wasp::CvtToBoolean, &opt.help, sizeof(opt.help)},
{NULL}
};
const char *ProgName;
template <class T>
void CopyVar(string ncdffile, string datafile, T dummy) {
WASP wasp(opt.nthreads);
int rc = wasp.Open(ncdffile, NC_WRITE);
vector <size_t> dims;
vector <size_t> bs;
rc = wasp.InqVarDimlens(opt.varname, opt.level, dims, bs);
if (rc<0) exit(1);
rc = wasp.OpenVarRead(opt.varname, opt.level, opt.lod);
if (rc<0) exit(1);
vector <size_t> start(dims.size(), 0);
if (opt.start.size()) {
if (opt.start.size() != dims.size()) {
MyBase::SetErrMsg("Invalid start specification");
exit(1);
}
for (int i=0; i<opt.start.size(); i++) {
start[i] = opt.start[i];
}
}
vector <size_t> count = dims;
if (opt.count.size()) {
if (opt.count.size() != dims.size()) {
MyBase::SetErrMsg("Invalid count specification");
exit(1);
}
for (int i=0; i<opt.count.size(); i++) {
count[i] = opt.count[i];
}
}
size_t nelements = 1;
for (int i=0; i<count.size(); i++) nelements *= count[i];
T *data = new T[nelements];
rc = wasp.GetVara(start, count, data);
if (rc<0) exit(1);
rc = wasp.CloseVar();
if (rc<0) exit(1);
rc = wasp.Close();
if (rc<0) exit(1);
FILE *fp = fopen(datafile.c_str(), "wb");
if (! fp) {
MyBase::SetErrMsg("fopen(%s) : %M", datafile.c_str());
exit(1);
}
rc = fwrite(data, sizeof(*data), nelements, fp);
if (rc != nelements) {
MyBase::SetErrMsg("fread() : %M");
exit(1);
}
}
int main(int argc, char **argv) {
OptionParser op;
MyBase::SetErrMsgFilePtr(stderr);
//
// Parse command line arguments
//
ProgName = FileUtils::LegacyBasename(argv[0]);
if (op.AppendOptions(set_opts) < 0) {
exit(1);
}
if (op.ParseOptions(&argc, argv, get_options) < 0) {
exit(1);
}
if (opt.help) {
cerr << "Usage: " << ProgName << " [options] netcdffile datafile" << endl;
op.PrintOptionHelp(stderr);
exit(0);
}
if (argc != 3) {
cerr << "Usage: " << ProgName << " [options] netcdffile datafile" << endl;
op.PrintOptionHelp(stderr);
exit(1);
}
string ncdffile = argv[1]; // Path to a vdf file
string datafile = argv[2]; // Path to raw data file
if (opt.debug) MyBase::SetDiagMsgFilePtr(stderr);
if (opt.type == "float32") {
float dummy = 0.0;
CopyVar(ncdffile, datafile, dummy);
}
else if (opt.type == "float64" ) {
double dummy = 0.0;
CopyVar(ncdffile, datafile, dummy);
}
else if (opt.type == "int32" ) {
int dummy = 0;
CopyVar(ncdffile, datafile, dummy);
}
else if (opt.type == "int16" ) {
int16_t dummy = 0;
CopyVar(ncdffile, datafile, dummy);
}
else if (opt.type == "uint8" ) {
unsigned char dummy = 0;
CopyVar(ncdffile, datafile, dummy);
}
else {
cerr << "Invalid type " << opt.type << endl;
}
return(0);
}
| 23.5 | 77 | 0.634973 | [
"vector"
] |
2efff115fa2603f1132e26d31271bbf8b9607e82 | 3,839 | cpp | C++ | hackerrank/w34/recurrentontree.cpp | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | hackerrank/w34/recurrentontree.cpp | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | hackerrank/w34/recurrentontree.cpp | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #if defined(LOCAL)
#define PROBLEM_NAME "recurrentontree"
const double _max_double_error = 1e-9;
#include "testutils.h"
#define L(x...) debug(x)
#else
#define L(x, ...) (x)
#include <bits/stdc++.h>
#endif
using namespace std;
using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>;
using lu = unsigned long long;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
using mll = unordered_map<l, l>;
const l INF = numeric_limits<l>::max();
const double EPS = 1e-10; static constexpr auto PI = acos(-1);
const l e0=1, e3=1000, e5=100000, e6=10*e5, e7=10*e6, e8=10*e7, e9=10*e8;
const char lf = '\n';
#define all(x) begin(x), end(x)
#define F(a,b,c) for (l a = l(b); a < l(c); a++)
#define B(a,b,c) for (l a = l(c) - 1; a >= l(b); a--)
#if defined(LOCAL)
#define L(x...) debug(x)
#else
#define L(x, ...) (x)
#endif
const l MOD = e9 + 7;
// 0 1
// 2 3
vl multiply(vl m1, vl m2) {
vl r(4);
r[0] = (m1[0] * m2[0] + m1[1] * m2[2]) % MOD;
r[1] = (m1[0] * m2[1] + m1[1] * m2[3]) % MOD;
r[2] = (m1[2] * m2[0] + m1[3] * m2[2]) % MOD;
r[3] = (m1[2] * m2[1] + m1[3] * m2[3]) % MOD;
return r;
}
vl add(vl m1, vl m2) {
vl r(4);
F(i, 0, 4) r[i] = (m1[i] + m2[i]) % MOD;
return r;
}
vl __fibonacci_m_pow(vl &a, l n) {
if (n <= 1) return a;
vl m1, m2;
if (n % 2 == 0) {
m1 = m2 = __fibonacci_m_pow(a, n / 2);
} else {
m1 = a;
m2 = __fibonacci_m_pow(a, n - 1);
}
return multiply(m1, m2);
}
// n >= 1, {1, 1, 2, 3, 5, ...}
vl fibonacci(l n) {
vl a(4);
if (n == 0) {
a[0] = 1; a[1] = 0; a[2] = 0; a[3] = 1;
return a;
}
a[0] = 1; a[1] = 1; a[2] = 1; a[3] = 0;
return __fibonacci_m_pow(a, n);
}
struct Graph {
vvl adj;
vvl up;
vl depth;
vvl values, paths;
vl fib;
Graph(l n) {
adj.resize(n);
fib.resize(n);
depth.resize(n);
values.resize(n, vl(4));
paths.resize(n, vl(4));
l k = 0;
while ((1 << k) <= n) k++;
up.resize(k, vl(n, -1));
}
void build_up(l a) {
F(i, 1, up.size()) {
l t = up[i - 1][up[i - 1][a]];
if (t == -1) break;
up[i][a] = t;
}
}
l walk(l a, l d) {
l k = 0;
while (d > 0) {
if (d % 2) a = up[k][a];
d /= 2;
k++;
}
return a;
}
l lca(l a, l b) {
a = walk(a, depth[a] - depth[b]);
b = walk(b, depth[b] - depth[a]);
if (a == b) return a;
B(i, 0, up.size()) {
if (up[i][a] != up[i][b]) {
a = up[i][a];
b = up[i][b];
}
}
return up[0][a];
}
void dfs(l root) {
auto fc = (fibonacci(fib[root]));
vl s(4);
for (auto i : adj[root]) {
if (i == up[0][root]) continue;
up[0][i] = root;
dfs(i);
values[root] = add(values[root], multiply(s, paths[i]));
s = add(s, paths[i]);
}
values[root] = add(values[root], s); // ends here
values[root] = add(values[root], values[root]);
values[root] = add(fc, multiply(fc, values[root]));
paths[root] = add(fc, multiply(fc, s));
}
};
void solve(istream& cin, ostream& cout) {
l N; cin >> N;
Graph g(N);
F(i, 0, N - 1) {
l a, b; cin >> a >> b; a--; b--;
g.adj[a].emplace_back(b);
g.adj[b].emplace_back(a);
}
F(i, 0, N) cin >> g.fib[i];
g.dfs(0);
vl s(4);
F(i, 0, N) s = add(s, (g.values[i]));
cout << s[0] << lf;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cout << fixed << setprecision(15);
#if defined(LOCAL)
maybe_run_tests(cin, cout);
// _generate_random_test = generate_random;
// _solve_brute = solve_brute;
// _player_b = player_b;
// _custom_solution_checker = solution_checker;
#else
solve(cin, cout);
#endif
}
| 22.450292 | 73 | 0.515759 | [
"vector"
] |
2c024119f3ce86d9a691eb7efa6950b0a23acba8 | 1,009 | hpp | C++ | gauss.hpp | gonzavesc/convection_final | 39732bd55b2412bddd65844a8fb1b1dd92acfc1f | [
"MIT"
] | null | null | null | gauss.hpp | gonzavesc/convection_final | 39732bd55b2412bddd65844a8fb1b1dd92acfc1f | [
"MIT"
] | null | null | null | gauss.hpp | gonzavesc/convection_final | 39732bd55b2412bddd65844a8fb1b1dd92acfc1f | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath> //std::pow abs
#include <new>
#include <algorithm> //std::max
#include "read.hpp"
#include "initialize.hpp"
#include "export.hpp"
#include "method.hpp"
#include "boundary.hpp"
#ifndef INCLUDE_GSS
#define INCLUDE_GSS
void copyMatrix(std::vector<std::vector<double>>& phi_p, const std::vector<std::vector<double>>& phi);
class gauss{
private:
double err;
public:
gauss(const double& a);
double get_err();
void solver(std::vector<std::vector<double>>& phi, const std::vector<std::vector<double>>& phi_p, const std::vector<std::vector<double>>& ap, const std::vector<std::vector<double>>& ae, const std::vector<std::vector<double>>& aw, const std::vector<std::vector<double>>& an, const std::vector<std::vector<double>>& as,
const std::vector<std::vector<double>>& ap0, const std::vector<std::vector<double>>& b);
};
#endif | 28.828571 | 326 | 0.650149 | [
"vector"
] |
2c0339d29f000754d79f9e8fed1845dae2de1c34 | 3,099 | cpp | C++ | puzzle.cpp | AjayKrP/Project | 3efd2f2fbe4400c5674e18688daefb5a845b5cbe | [
"MIT"
] | null | null | null | puzzle.cpp | AjayKrP/Project | 3efd2f2fbe4400c5674e18688daefb5a845b5cbe | [
"MIT"
] | null | null | null | puzzle.cpp | AjayKrP/Project | 3efd2f2fbe4400c5674e18688daefb5a845b5cbe | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <functional>
using namespace std;
map<vector<vector<int> > , bool> visited;
map<vector<vector<int> > , vector<vector<int> > > parent;
vector<vector<int> > goal(3,vector<int> (3));
bool visit(vector<vector<int> > a)
{
if(visited[a]==true)
return true;
else
return false;
}
int manhattan(vector<vector<int> > a , int moves)
{
int dist=moves;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(a[i][j]!=0)
{
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
if(a[i][j]==goal[k][l])
dist+=abs(i-k)+abs(j-l);
}
}
}
}
}
return dist;
}
bool isGoal(vector<vector<int> > a)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(a[i][j]!=goal[i][j])
return false;
}
}
return true;
}
bool safe(int i,int j)
{
if(i>=0 && i<=2 && j>=0 && j<=2)
return true;
else
return false;
}
int dx[]={-1,+1,0,0};
int dy[]={0,0,-1,+1};
vector<vector<vector<int> > > neighbours(vector<vector<int> > a)
{
pair<int,int> pos;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(a[i][j]==0)
{
pos.first=i;
pos.second=j;
break;
}
}
}
vector<vector<vector<int> > > ans;
for(int k=0;k<4;k++)
{
int cx = pos.first;
int cy = pos.second;
vector<vector<int> > n = a;
if(safe(cx+dx[k],cy+dy[k]))
{
swap(n[cx+dx[k]][cy+dy[k]],n[cx][cy]);
ans.push_back(n);
}
}
return ans;
}
typedef pair<vector<vector<int> > , int> state;
struct cmp
{
bool operator() (state &a, state &b)
{
int am = manhattan(a.first,a.second);
int bm = manhattan(b.first,b.second);
return am<bm;
}
};
void print_path(vector<vector<int> > s)
{
if(parent.count(s))
print_path(parent[s]);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%d ",s[i][j]);
}
cout<<endl;
}
cout<<endl;
return;
}
void print(vector<vector<int> > s)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%d ",s[i][j]);
}
cout<<endl;
}
}
void solve(vector<vector<int> > a, int moves)
{
priority_queue<state,vector<state>,cmp > Q;
Q.push(state(a,moves));
while(!Q.empty())
{
vector<vector<int> > s = Q.top().first;
Q.pop();
visited[s]=true;
//print(s);
if(s==goal)
{
// printf("yeah\n");
print_path(s);
break;
}
vector<vector<vector<int> > > ns = neighbours(s);
vector<vector<vector<int> > >::iterator it;
//printf("1..\n");
for(it=ns.begin();it!=ns.end();it++)
{
//print(*it);
//cout<<endl;
vector<vector<int> > temp = *it;
if(!visit(temp))
{
parent.insert(pair<vector<vector<int> > , vector<vector<int> > >(temp,s));
Q.push(state(temp,moves+1));
}
}
}
return;
}
int main()
{
vector<vector<int> > a(3,vector<int> (3));
//vector<vector<int> > goal(3,vector<int> (3));
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cin>>a[i][j];
}
}
cout<<"Solution...\n\n";
goal[0][0] = 1;
goal[0][1] = 2;
goal[0][2] = 3;
goal[1][0] = 4;
goal[1][1] = 5;
goal[1][2] = 6;
goal[2][0] = 7;
goal[2][1] = 8;
goal[2][2] = 0;
solve(a,0);
}
//input
/*
0 1 3
4 2 5
7 8 6
*/
| 15.191176 | 78 | 0.528235 | [
"vector"
] |
2c0a71b9d41713d2ff01255e37eeea2db6737830 | 5,075 | hpp | C++ | include/zgraph/graph/zadjancency_list_ugraph.hpp | DerThorsten/zgraph | a981f7bc0fef9581626779663a3c54fb8922c72a | [
"MIT"
] | null | null | null | include/zgraph/graph/zadjancency_list_ugraph.hpp | DerThorsten/zgraph | a981f7bc0fef9581626779663a3c54fb8922c72a | [
"MIT"
] | null | null | null | include/zgraph/graph/zadjancency_list_ugraph.hpp | DerThorsten/zgraph | a981f7bc0fef9581626779663a3c54fb8922c72a | [
"MIT"
] | null | null | null | #pragma once
#ifndef ZGRAPH_GRAPH_ZADJACENCY_LIST_UGRAPH_HPP
#define ZGRAPH_GRAPH_ZADJACENCY_LIST_UGRAPH_HPP
#include <cstdint>
#include <iostream>
#include <map>
#include <set>
#include <array>
#include "zgraph/graph/detail/zgraph_items.hpp"
#include "zgraph/graph/detail/zgraph_maps.hpp"
#include "zgraph/detail/zrange.hpp"
#include "zgraph/graph/zgraph_base.hpp"
#include "zgraph/detail/zvalue_map.hpp"
#include <range/v3/view/transform.hpp>
namespace zgraph
{
template<bool is_mutligraph, bool allow_self_loop>
class zadjacency_list_ugraph;
template<bool is_mutligraph, bool allow_self_loop>
class zgraph_type_traits<zadjacency_list_ugraph<is_mutligraph, allow_self_loop>>{
public:
using is_directed_t = std::false_type;
using is_mutligraph_t = std::integral_constant<bool, is_mutligraph>;
using allow_self_loops_t = std::integral_constant<bool, allow_self_loop>;
using graph_t = zadjacency_list_ugraph<is_mutligraph, allow_self_loop>;
using node_index_t = uint64_t;
using edge_index_t = uint64_t;
template<class value_t>
class node_map : public zassociative_graph_item_map<graph_t,znode_tag,std::map<node_index_t, value_t>>{
using base_t = zassociative_graph_item_map<graph_t,znode_tag,std::map<node_index_t, value_t>>;
using base_t::base_t;
};
template<class value_t>
class edge_map : public zassociative_graph_item_map<graph_t,zedge_tag,std::map<edge_index_t, value_t>>{
using base_t = zassociative_graph_item_map<graph_t,zedge_tag,std::map<edge_index_t, value_t>>;
using base_t::base_t;
};
class node_set : public std::set<node_index_t>{
public:
node_set(const graph_t & g){
}
};
};
template<bool is_mutligraph, bool allow_self_loop>
class zadjacency_list_ugraph : public zgraph_base<zadjacency_list_ugraph<is_mutligraph, allow_self_loop>>
{
public:
using base_t = zgraph_base<zadjacency_list_ugraph<is_mutligraph, allow_self_loop>>;
using base_t::endpoints;
using node_index_t = uint64_t;
using edge_index_t = uint64_t;
using adjacency_t = std::map<node_index_t, edge_index_t>;
using endpoint_array_t = std::array<node_index_t, 2>;
zadjacency_list_ugraph()
: m_next_edge_index(0)
{
}
//
bool add_node(const node_index_t node){
return m_adjacencies.try_emplace(node, adjacency_t()).second;
}
edge_index_t add_edge(const node_index_t u, const node_index_t v){
bool new_u = this->add_node(u);
bool new_v = this->add_node(v);
if(new_u || new_v){
// edge cannot exist
const auto edge_index = m_next_edge_index++;
m_edges.emplace(edge_index, endpoint_array_t{u, v});
this->get_adjacency(u).emplace(v, edge_index);
this->get_adjacency(v).emplace(u, edge_index);
return edge_index;
} else{
// edge might exist
auto & adj_u = this->get_adjacency(u);
if(auto find_v = adj_u.find(v); find_v != adj_u.end()){
// edge does exist
return find_v->second;
} else{
// edge does not exist
const auto edge_index = m_next_edge_index++;
m_edges.emplace(edge_index, endpoint_array_t{u, v});
adj_u.emplace(v, edge_index);
this->get_adjacency(v).emplace(u, edge_index);
return edge_index;
}
}
}
// api
const auto & adjacency(const node_index_t node)const{
const auto & adj = get_adjacency(node);
return adj;
//return detail::zconst_range<typename adjacency_t::const_iterator>(adj.begin(), adj.end());
}
// node iter
auto num_nodes()const{
return m_adjacencies.size();
}
auto num_edges() const{
return m_edges.size();
}
decltype(auto) nodes() const{
return m_adjacencies | ranges::views::keys;
}
decltype(auto) edges() const{
return m_edges | ranges::views::keys;
}
const auto & endpoints(const edge_index_t & edge) const{
return m_edges.find(edge)->second;
}
private:
auto & get_adjacency(const node_index_t node){
return m_adjacencies.find(node)->second;
}
const auto & get_adjacency(const node_index_t node) const{
return m_adjacencies.find(node)->second;
}
edge_index_t m_next_edge_index;
std::map<node_index_t, adjacency_t> m_adjacencies;
std::map<edge_index_t, endpoint_array_t> m_edges;
};
} // end namespace zgraph
#endif // ZGRAPH_GRAPH_ZADJACENCY_LIST_UGRAPH_HPP | 28.672316 | 111 | 0.616158 | [
"transform"
] |
2c0ae723bc0d25adf92641733d03517894510dcd | 2,304 | cpp | C++ | Teaching/testParser.cpp | ryhanai/teachingplugin | a495885899eaa36ea00ba8ab89057cd4d3f36350 | [
"MIT"
] | 2 | 2020-07-21T06:08:42.000Z | 2020-07-21T06:08:44.000Z | Teaching/testParser.cpp | ryhanai/teachingplugin | a495885899eaa36ea00ba8ab89057cd4d3f36350 | [
"MIT"
] | null | null | null | Teaching/testParser.cpp | ryhanai/teachingplugin | a495885899eaa36ea00ba8ab89057cd4d3f36350 | [
"MIT"
] | null | null | null | //
// Linux
// g++ -o testParser testParser.cpp -std=c++11
//
#include "Parser.h"
namespace teaching {
class tostr_visitor : public boost::static_visitor<std::string>
{
public:
std::string operator()(ValueNodeSp const& node) const
{
return boost::lexical_cast<std::string>(node->v_);
}
std::string operator()(Vector3dConstNodeSp const& node) const
{
return (boost::format("[%1%,%2%,%3%]")
% boost::apply_visitor(*this, node->x_)
% boost::apply_visitor(*this, node->y_)
% boost::apply_visitor(*this, node->z_)).str();
}
std::string operator()(Vector6dConstNodeSp const& node) const
{
return (boost::format("[%1%,%2%,%3%,%4%,%5%,%6%]")
% boost::apply_visitor(*this, node->x_)
% boost::apply_visitor(*this, node->y_)
% boost::apply_visitor(*this, node->z_)
% boost::apply_visitor(*this, node->Rx_)
% boost::apply_visitor(*this, node->Ry_)
% boost::apply_visitor(*this, node->Rz_)).str();
}
std::string operator()(BinOpNodeSp const& node) const
{
return (boost::format("(%1%%2%%3%)")
% boost::apply_visitor(*this, node->lhs_)
% node->op_
% boost::apply_visitor(*this, node->rhs_)).str();
}
std::string operator()(VariableNodeSp const& node) const
{
return boost::lexical_cast<std::string>(node->nm_);
}
std::string operator()(FunCallNodeSp const& node) const
{
return (boost::format("%1%(%2%)")
% boost::apply_visitor(*this, node->fun_)
% boost::apply_visitor(*this, node->args_)).str();
}
};
}
namespace qi = boost::spirit::qi;
int main()
{
std::string str;
teaching::Node result;
teaching::makeTree<std::string::iterator> parser;
std::vector<teaching::Node> nodeList;
std::string prompt = "> ";
std::cout << prompt;
while (getline(std::cin, str)) {
if (qi::phrase_parse(str.begin(), str.end(), parser, qi::space, result)) {
std::cout << boost::apply_visitor(teaching::tostr_visitor(), result) << std::endl;
} else {
std::cout << parser.getErrorMessage() << std::endl;
parser.clearErrorMessage();
}
std::cout << prompt;
}
return 0;
}
| 29.164557 | 88 | 0.572917 | [
"vector"
] |
2c0b4d6a65c0636d86d0af7931f0bb7db9d098c6 | 7,701 | cpp | C++ | oldsrc/projectBw.cpp | ron2015schmitt/coildes | 2583bc1beb6b5809ed75367970e4f32ba242894a | [
"MIT"
] | null | null | null | oldsrc/projectBw.cpp | ron2015schmitt/coildes | 2583bc1beb6b5809ed75367970e4f32ba242894a | [
"MIT"
] | null | null | null | oldsrc/projectBw.cpp | ron2015schmitt/coildes | 2583bc1beb6b5809ed75367970e4f32ba242894a | [
"MIT"
] | null | null | null |
// Standard C libraries
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
// Standard C++ libraries
#include <iostream>
#include <complex>
using namespace std;
// coil libraries
#include "coils.hpp"
#include "coilio.hpp"
#include "coils_cmdline.hpp"
#include "surface.hpp"
#include "inductancematrix.hpp"
#include "rhomatrix.hpp"
#include "gammamatrix.hpp"
#include "omegamatrix.hpp"
#include "gradfvector.hpp"
#include "coilfft.hpp"
// This is the file that defines the B field configuration
// Main Function for code
int main (int argc, char *argv[])
{
disable_all_options();
enable_option(opt_ff);
enable_option(opt_Nphi);
enable_option(opt_Ntheta);
enable_option(opt_Nnn);
enable_option(opt_Nmm);
enable_option(opt_Bpf);
enable_option(opt_Nharm);
enable_option(opt_Mharm);
enable_option(opt_omegaf);
// parse command line input
if (!parse_cmd(argc, argv))
return 1;
//
// ios_base::fmtflags flags = ios_base::right | ios_base::scientific;
string fext = "txt";
string ftemp;
p3vectorformat::textformat(text_nobraces);
Vector <double> datavec("datavec");
datavec.perline(1);
datavec.textformat(text_nobraces);
Matrix <double> data("data");
data.perline(1);
data.textformat(text_nobraces);
string fname;
// variables for measuring times
struct tms tbuff;
clock_t ckstart;
// display Matricks mode
cout << endl;
display_execution_mode();
cout << endl;
// Create angle grid
const unsigned int Npts = Ntheta*Nphi;
Vector<double> thetas(Npts,"thetas");
Vector<double> phis(Npts,"phis");
anglevectors(thetas, phis, Ntheta, Nphi);
ostringstream strmtmp1;
strmtmp1 <<Nnn;
string Nnn_str(strmtmp1.str());
ostringstream strmtmp2;
strmtmp2 <<Nmm;
string Nmm_str(strmtmp2.str());
// Create Fourier Mode vectors
Vector<double> nn("nn");
Vector<double> mm("mm");
unsigned int NF;
bool mode00 = true;
if ( (Nharm >1) ||(Mharm>1) )
modevectors(NF,nn,mm,Nnn,Nmm,Nharm,Mharm,mode00);
else
modevectors(NF,nn,mm,Nnn,Nmm,mode00);
// these exclude the n=0,m=0 case
Vector<double> nnR("nnR");
Vector<double> mmR("mmR");
unsigned int NFR;
mode00 = false;
if ( (Nharm >1) ||(Mharm>1) )
modevectors(NFR,nnR,mmR,Nnn,Nmm,Nharm,Mharm,mode00);
else
modevectors(NFR,nnR,mmR,Nnn,Nmm,mode00);
// coefficient C is the integration coef for the fourier transform
// C = dtheta*dphi
// = (2*pi/Ntheta)*(2*pi/Nphi)
// = (2*pi*2*pi/Npts)
const double C = (2*PI*2*PI/double(Npts));
const double Csqr = C*C;
// Create ortho normal series
cout << endl;
cout<<"$ Generate orthonormal series matrix ("<<Npts<<" x "<<NF<<")"<<endl;
STARTTIME(tbuff,ckstart);
Matrix<complex<double> > fs(Npts,NF,"fs");
fseries(nn,mm,thetas,phis,fs);
STOPTIME(tbuff,ckstart);
cout << endl;
cout<<"$ Generate reduced orthonormal series matrix ("<<Npts<<" x "<<NFR<<")"<<endl;
STARTTIME(tbuff,ckstart);
Matrix<complex<double> > fsR(Npts,NFR,"fsR");
fseries(nnR,mmR,thetas,phis,fsR);
STOPTIME(tbuff,ckstart);
Vector<complex<double> > BrF(NFR,"BrF");
cout <<endl<< "$ Loading Plasma Br sin/cos fourier coefficients from " << flux_filename << endl;
if (load_coefs(flux_filename,CoefFileFormat_sincos,nnR,mmR,BrF))
return 3;
Vector<double> Br(Npts, "Br");
expandfunction(Br,BrF,fsR);
// load or calculate B field
cout << endl;
cout<<"$ Load tangent B field "<<endl;
STARTTIME(tbuff,ckstart);
cout <<endl<< "$ Loading BTOTAL_phi fourier coefficients from " << Bp_filename << endl;
Vector<complex<double> > BpF(NF,"BpF");
if (load_coefs( Bp_filename,CoefFileFormat_sincos,nn,mm,BpF))
return 6;
Vector<double> Bp(Npts, "Bp");
expandfunction(Bp,BpF,fs);
STOPTIME(tbuff,ckstart);
Vector<double> Bw(Npts, "Bw");
Bw = Br / Bp;
Vector<complex<double> > BwF(NFR,"BwF");
transformfunction(Bw,BwF,fsR);
datavec = real(BwF);
fname = "BwF.Nn="+Nnn_str+".Nm="+Nmm_str+".R.out";
dispcr(fname);
save(datavec,fname);
datavec = imag(BwF);
fname = "BwF.Nn="+Nnn_str+".Nm="+Nmm_str+".I.out";
dispcr(fname);
save(datavec,fname);
Matrix<complex<double> > P(NFR,NFR,"P");
cout<<"$ Load Omega matrix ("<<NFR<<"x"<<NFR<<")"<<endl;
STARTTIME(tbuff,ckstart);
data.perline(1);
data.textformat(text_nobraces);
data.resize(NFR,NFR);
fname = omega_filename + ".PR.out";
load(data,fname);
Matrix <double> data2("data2");
data2.perline(1);
data2.textformat(text_nobraces);
data2.resize(NFR,NFR);
fname = omega_filename + ".PI.out";
load(data2,fname);
P = mcomplex(data,data2);
data.clear();
data2.clear();
STOPTIME(tbuff,ckstart);
Matrix<complex<double> > Pinv(NFR,NFR,"Pinv");
matricks_lapack::inv(P,Pinv);
Vector<complex<double> > Bw_projF(NFR,"Bw_projF");
Bw_projF = (Pinv|BwF);
datavec = real(Bw_projF);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".R.out";
dispcr(fname);
save(datavec,fname);
datavec = imag(Bw_projF);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".I.out";
dispcr(fname);
save(datavec,fname);
Vector<unsigned int> ii;
Vector<double> magn = abs(Bw_projF);
ii = sortrevwind(magn);
fname = "projectBw.isort.out";
dispcr(fname);
ii.perline(1);
ii.textformat(text_nobraces);
save(ii,fname);
Vector<double> mmRsorted(NFR,"mmRsorted");
Vector<double> nnRsorted(NFR,"nnRsorted");
Bw_projF = Bw_projF[ii];
fname = omega_filename + ".mmRsort.out";
mmRsorted.textformat(text_nobraces);
mmRsorted.perline(1);
load(mmRsorted,fname);
mmRsorted = mmRsorted[ii];
fname = omega_filename + ".nnRsort.out";
nnRsorted.textformat(text_nobraces);
nnRsorted.perline(1);
load(nnRsorted,fname);
nnRsorted = nnRsorted[ii];
datavec = real(Bw_projF);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".Rsorted.out";
dispcr(fname);
save(datavec,fname);
datavec = imag(Bw_projF);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".Isorted.out";
dispcr(fname);
save(datavec,fname);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".mmRsort.out";
dispcr(fname);
mmRsorted.perline(1);
mmRsorted.textformat(text_nobraces);
save(mmRsorted,fname);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".nnRsort.out";
dispcr(fname);
nnRsorted.perline(1);
nnRsorted.textformat(text_nobraces);
save(nnRsorted,fname);
Vector<double> EV(NFR,"EV");
fname = "omegaNormd.Nn="+Nnn_str+".Nm="+Nmm_str+".EV.out";
dispcr(fname);
EV.perline(1);
EV.textformat(text_nobraces);
load(EV,fname);
EV=1/EV[ii];
datavec = EV;
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".EVinv.sorted.out";
dispcr(fname);
save(datavec,fname);
Bw_projF = Bw_projF * EV;
magn = abs(Bw_projF);
ii = sortrevwind(magn);
Bw_projF = Bw_projF[ii];
mmRsorted = mmRsorted[ii];
nnRsorted = nnRsorted[ii];
datavec = real(Bw_projF);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".BwEV.Rsorted.out";
dispcr(fname);
save(datavec,fname);
datavec = imag(Bw_projF);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".BwEV.Isorted.out";
dispcr(fname);
save(datavec,fname);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".BwEV.mmRsort.out";
dispcr(fname);
mmRsorted.perline(1);
mmRsorted.textformat(text_nobraces);
save(mmRsorted,fname);
fname = "projectBw.Nn="+Nnn_str+".Nm="+Nmm_str+".BwEV.nnRsort.out";
dispcr(fname);
nnRsorted.perline(1);
nnRsorted.textformat(text_nobraces);
save(nnRsorted,fname);
return 0;
} // main()
| 22.386628 | 99 | 0.656668 | [
"vector",
"transform"
] |
2c0ee4550f86c3827947b6068f7d2425cace8421 | 5,169 | cc | C++ | examples/samples/elle/serialization.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | examples/samples/elle/serialization.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | examples/samples/elle/serialization.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | #include <string>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <elle/UUID.hh>
#include <elle/Version.hh>
#include <elle/assert.hh>
#include <elle/serialization.hh>
#include <elle/serialization/json.hh>
#include <elle/serialization/binary.hh>
static const auto unknown_date = boost::posix_time::time_from_string(
"1970-01-01 00:00:00.000");
namespace elle
{
// The current serialization version.
elle::Version serialization_tag::version(1, 0, 0);
}
// A Record class, that has evolved, from version 0.1.0 to version 0.3.0.
// 0.1.0
// + title (std::string)
// + artist (std::string)
// + id (elle::UUID)
// + unwanted (int)
// 0.2.0:
// + release_date (boost::posix_time::ptime)
// - unwanted (int)
// 0.3.0:
// + tags (std::vector<std::string>)
struct Record
: public elle::Printable
{
Record(std::string title,
std::string artist,
boost::posix_time::ptime const& release_date)
: _title(std::move(title))
, _artist(std::move(artist))
, _id(elle::UUID::random())
, _release_date(release_date)
{}
/// Add a deserialization constructor.
Record(elle::serialization::SerializerIn& in,
elle::Version const& version)
{
this->serialize(in, version);
}
/// The serialization interface.
void
serialize(elle::serialization::Serializer& s,
elle::Version const& version)
{
// Serialize fields that didn't change.
s.serialize("title", this->_title);
s.serialize("artist", this->_artist);
s.serialize("id", this->_id);
// Simulate a field that use to be here at version 0.1.0 but is not wanted
// anymore.
if (version < elle::Version(0, 2, 0))
{
int unwanted = 3;
s.serialize("unwanted", unwanted);
}
// Serialize new field 'release_date' introduced at version 0.2.0.
if (version >= elle::Version(0, 2, 0))
s.serialize("release_date", this->_release_date);
else if (s.in())
// Field was missing from 0.1.0 serialized objects, so give it the default
// value we want.
// boost::optional would also work.
this->_release_date = unknown_date;
// Serialize new field 'tags' introduced at version 0.3.0 and use the
// default std::vector<std::string> if it didn't exist.
if (version >= elle::Version(0, 3, 0))
s.serialize("tags", this->_tags);
}
/// The implementation of the pure virtual elle::Printable::print method.
void
print(std::ostream& out) const override
{
out << "[" << this->_artist << "] " << this->_title;
if (this->_release_date != unknown_date)
out << " (" << this->_release_date << ")";
if (!this->_tags.empty())
out << " categories: " << this->_tags;
}
private:
ELLE_ATTRIBUTE_R(std::string, title);
ELLE_ATTRIBUTE_R(std::string, artist);
ELLE_ATTRIBUTE_R(elle::UUID, id);
ELLE_ATTRIBUTE_R(boost::posix_time::ptime, release_date);
ELLE_ATTRIBUTE_RX(std::vector<std::string>, tags);
public:
using serialization_tag = elle::serialization_tag;
};
int
main()
{
auto record
= Record("Sandstorm", "Darube",
boost::posix_time::time_from_string("1999-11-26 00:00:00.000"));
record.tags().emplace_back("Dance");
record.tags().emplace_back("Electronic");
// Serialize Record as in version 0.1.0, where release_date & tags didn't
// exist yet.
{
std::stringstream ss;
elle::serialization::binary::serialize(record, ss, elle::Version(0, 1, 0));
auto r = elle::serialization::binary::deserialize<Record>(ss, true);
ELLE_ASSERT_EQ(r.title(), record.title());
ELLE_ASSERT_EQ(r.artist(), record.artist());
ELLE_ASSERT_EQ(r.id(), record.id());
ELLE_ASSERT_NEQ(r.release_date(), record.release_date());
ELLE_ASSERT_NEQ(r.tags(), record.tags());
std::cout << "Record serialized at version 0.1.0 looks like: "
<< std::endl << "> " << r << std::endl << std::endl;
}
// Serialize Record as in version 0.2.0, where tags didn't exist.
{
std::stringstream ss;
elle::serialization::binary::serialize(record, ss, elle::Version(0, 2, 0));
auto r = elle::serialization::binary::deserialize<Record>(ss, true);
ELLE_ASSERT_EQ(r.title(), record.title());
ELLE_ASSERT_EQ(r.artist(), record.artist());
ELLE_ASSERT_EQ(r.id(), record.id());
ELLE_ASSERT_EQ(r.release_date(), record.release_date());
ELLE_ASSERT_NEQ(r.tags(), record.tags());
std::cout << "Record serialized at version 0.2.0 looks like: "
<< std::endl << "> " << r << std::endl << std::endl;
}
// Serialize Record as in version 0.3.0, the final version of the object.
{
std::stringstream ss;
elle::serialization::binary::serialize(record, ss, elle::Version(0, 3, 0));
auto r = elle::serialization::binary::deserialize<Record>(ss);
ELLE_ASSERT_EQ(r.title(), record.title());
ELLE_ASSERT_EQ(r.artist(), record.artist());
ELLE_ASSERT_EQ(r.id(), record.id());
ELLE_ASSERT_EQ(r.release_date(), record.release_date());
ELLE_ASSERT_EQ(r.tags(), record.tags());
std::cout << "Record serialized at version 0.3.0 looks like: "
<< std::endl << "> " << r << std::endl;
}
}
| 33.564935 | 80 | 0.643645 | [
"object",
"vector"
] |
2c0f08f456456a45785358268b1265ea28e0c5a0 | 1,331 | cc | C++ | out/longest_increasing_subsequence.cc | FardaleM/metalang | 171557c540f3e2c051ec39ea150afb740c1f615f | [
"BSD-2-Clause"
] | 22 | 2017-04-24T10:00:45.000Z | 2021-04-01T10:11:05.000Z | out/longest_increasing_subsequence.cc | FardaleM/metalang | 171557c540f3e2c051ec39ea150afb740c1f615f | [
"BSD-2-Clause"
] | 12 | 2017-03-26T18:34:21.000Z | 2019-03-21T19:13:03.000Z | out/longest_increasing_subsequence.cc | FardaleM/metalang | 171557c540f3e2c051ec39ea150afb740c1f615f | [
"BSD-2-Clause"
] | 7 | 2017-10-14T13:33:33.000Z | 2021-03-18T15:18:50.000Z | #include <iostream>
#include <vector>
int dichofind(int len, std::vector<int> * tab, int tofind, int a, int b) {
if (a >= b - 1)
return a;
else
{
int c = (a + b) / 2;
if (tab->at(c) < tofind)
return dichofind(len, tab, tofind, c, b);
else
return dichofind(len, tab, tofind, a, c);
}
}
int process(int len, std::vector<int> * tab) {
std::vector<int> *size = new std::vector<int>( len );
for (int j = 0; j < len; j++)
if (j == 0)
size->at(j) = 0;
else
size->at(j) = len * 2;
for (int i = 0; i < len; i++)
{
int k = dichofind(len, size, tab->at(i), 0, len - 1);
if (size->at(k + 1) > tab->at(i))
size->at(k + 1) = tab->at(i);
}
for (int l = 0; l < len; l++)
std::cout << size->at(l) << " ";
for (int m = 0; m < len; m++)
{
int k = len - 1 - m;
if (size->at(k) != len * 2)
return k;
}
return 0;
}
int main() {
int len, n;
std::cin >> n;
for (int i = 1; i <= n; i++)
{
std::cin >> len;
std::vector<int> *d = new std::vector<int>( len );
for (int e = 0; e < len; e++)
{
std::cin >> d->at(e);
}
std::cout << process(len, d) << "\n";
}
}
| 23.350877 | 74 | 0.410218 | [
"vector"
] |
2c0f10bcfc5ecad6d967673cfea6e335f43d195c | 1,593 | cpp | C++ | ecs/src/v2/model/AddServerGroupMemberRequestBody.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ecs/src/v2/model/AddServerGroupMemberRequestBody.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | ecs/src/v2/model/AddServerGroupMemberRequestBody.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ecs/v2/model/AddServerGroupMemberRequestBody.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ecs {
namespace V2 {
namespace Model {
AddServerGroupMemberRequestBody::AddServerGroupMemberRequestBody()
{
addMemberIsSet_ = false;
}
AddServerGroupMemberRequestBody::~AddServerGroupMemberRequestBody() = default;
void AddServerGroupMemberRequestBody::validate()
{
}
web::json::value AddServerGroupMemberRequestBody::toJson() const
{
web::json::value val = web::json::value::object();
if(addMemberIsSet_) {
val[utility::conversions::to_string_t("add_member")] = ModelBase::toJson(addMember_);
}
return val;
}
bool AddServerGroupMemberRequestBody::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("add_member"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("add_member"));
if(!fieldValue.is_null())
{
ServerGroupMember refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setAddMember(refVal);
}
}
return ok;
}
ServerGroupMember AddServerGroupMemberRequestBody::getAddMember() const
{
return addMember_;
}
void AddServerGroupMemberRequestBody::setAddMember(const ServerGroupMember& value)
{
addMember_ = value;
addMemberIsSet_ = true;
}
bool AddServerGroupMemberRequestBody::addMemberIsSet() const
{
return addMemberIsSet_;
}
void AddServerGroupMemberRequestBody::unsetaddMember()
{
addMemberIsSet_ = false;
}
}
}
}
}
}
| 19.666667 | 101 | 0.71312 | [
"object",
"model"
] |
2c10acf40ca89f9fa691b4477bd11170e3b40eb6 | 4,002 | hpp | C++ | core/src/builders/terrain/RegionTypes.hpp | hexrain/utymap | 39cb7684bf014ecc770ed1c46d953f13e103f3f5 | [
"Apache-2.0"
] | 946 | 2016-03-13T23:00:37.000Z | 2022-03-29T08:35:30.000Z | core/src/builders/terrain/RegionTypes.hpp | hexrain/utymap | 39cb7684bf014ecc770ed1c46d953f13e103f3f5 | [
"Apache-2.0"
] | 136 | 2016-03-30T11:54:45.000Z | 2020-10-31T13:05:27.000Z | core/src/builders/terrain/RegionTypes.hpp | hexrain/utymap | 39cb7684bf014ecc770ed1c46d953f13e103f3f5 | [
"Apache-2.0"
] | 168 | 2016-05-02T15:04:53.000Z | 2022-03-28T17:23:26.000Z | #ifndef BUILDERS_TERRAIN_REGIONTYPES_HPP_DEFINED
#define BUILDERS_TERRAIN_REGIONTYPES_HPP_DEFINED
#include "builders/MeshBuilder.hpp"
#include "mapcss/Style.hpp"
#include "mapcss/StyleConsts.hpp"
#include "math/PolyClip.hpp"
#include <memory>
namespace utymap {
namespace builders {
/// Region context encapsulates information about given region.
struct RegionContext final {
const utymap::mapcss::Style style;
/// Prefix in mapcss.
const std::string prefix;
const utymap::builders::MeshBuilder::GeometryOptions geometryOptions;
const utymap::builders::MeshBuilder::AppearanceOptions appearanceOptions;
RegionContext(const utymap::mapcss::Style &style,
const std::string &prefix,
const utymap::builders::MeshBuilder::GeometryOptions &geometryOptions,
const utymap::builders::MeshBuilder::AppearanceOptions &appearanceOptions) :
style(style),
prefix(prefix),
geometryOptions(std::move(geometryOptions)),
appearanceOptions(std::move(appearanceOptions)) {
}
/// Creates region context using given arguments.
static RegionContext create(const utymap::builders::BuilderContext &context,
const utymap::mapcss::Style &style,
const std::string &prefix) {
using StyleConsts = utymap::mapcss::StyleConsts;
auto relativeSize = context.boundingBox.height();
MeshBuilder::GeometryOptions geometryOptions(
style.getValue(prefix + StyleConsts::MaxAreaKey(), relativeSize*relativeSize),
style.getValue(prefix + StyleConsts::EleNoiseFreqKey(), relativeSize),
std::numeric_limits<double>::lowest(), // no fixed elevation
style.getValue(prefix + StyleConsts::HeightOffsetKey(), relativeSize),
1 // no new vertices on boundaries
);
auto textureIndex = static_cast<std::uint16_t>(style.getValue(prefix + StyleConsts::TextureIndexKey()));
const auto &textureRegion = context.styleProvider
.getTexture(textureIndex, style.getString(prefix + StyleConsts::TextureTypeKey()))
.random(0); // TODO use seed for randomization
double scale = style.getValue(prefix + StyleConsts::TextureScaleKey());
MeshBuilder::AppearanceOptions appearanceOptions(
context.styleProvider.getGradient(style.getString(prefix + StyleConsts::GradientKey())),
style.getValue(prefix + StyleConsts::ColorNoiseFreqKey(), context.boundingBox),
textureIndex,
textureRegion,
scale > 0 ? scale : 1
);
return RegionContext(style, prefix, geometryOptions, appearanceOptions);
}
};
/// Represents terrain region.
struct Region final {
Region() : level(0), area(0), context(nullptr), geometry() {
}
Region(Region &&other) :
level(other.level),
area(other.area),
context(std::move(other.context)),
geometry(std::move(other.geometry)) {
};
Region(const Region &) = delete;
Region &operator=(const Region &) = delete;
Region &operator=(Region &&) = delete;
/// Layer flag. If it's set all with such flag should be merged together.
bool isLayer() const {
return context==nullptr;
}
/// Level value: zero for objects on terrain surface.
int level;
/// Area of polygon.
double area;
/// Context is optional: might be empty if polygon is layer
std::shared_ptr<const RegionContext> context;
/// Geometry of region.
utymap::math::IntPaths geometry;
};
/// Represents terrain regions grouped by sort order.
struct Layer {
int sortOrder = 0;
std::vector<std::shared_ptr<const Region>> regions;
Layer() = default;
Layer(const Layer &) = delete;
Layer &operator=(const Layer &) = delete;
Layer &operator=(Layer &&other) {
sortOrder = other.sortOrder;
regions = std::move(other.regions);
return *this;
}
Layer(Layer &&other) :
sortOrder(other.sortOrder),
regions(std::move(other.regions)) {
}
};
}
}
#endif // BUILDERS_TERRAIN_REGIONTYPES_HPP_DEFINED
| 31.511811 | 108 | 0.691654 | [
"geometry",
"vector"
] |
2c12ecdbcc5d99f3e46f207680f6c961c0edb68e | 9,084 | cpp | C++ | ThirdParty/poco/Foundation/testsuite/src/CoreTest.cpp | gregmedlock/roadrunnerwork | 11f18f78ef3e381bc59c546a8d5e3ed46d8ab596 | [
"Apache-2.0"
] | null | null | null | ThirdParty/poco/Foundation/testsuite/src/CoreTest.cpp | gregmedlock/roadrunnerwork | 11f18f78ef3e381bc59c546a8d5e3ed46d8ab596 | [
"Apache-2.0"
] | null | null | null | ThirdParty/poco/Foundation/testsuite/src/CoreTest.cpp | gregmedlock/roadrunnerwork | 11f18f78ef3e381bc59c546a8d5e3ed46d8ab596 | [
"Apache-2.0"
] | null | null | null | //
// CoreTest.cpp
//
// $Id: //poco/1.4/Foundation/testsuite/src/CoreTest.cpp#2 $
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "CoreTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Bugcheck.h"
#include "Poco/Exception.h"
#include "Poco/Environment.h"
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/Buffer.h"
#include "Poco/AtomicCounter.h"
#include "Poco/Nullable.h"
#include "Poco/Ascii.h"
#include <iostream>
#include <vector>
#include <cstring>
using Poco::Bugcheck;
using Poco::Exception;
using Poco::Environment;
using Poco::Thread;
using Poco::Runnable;
using Poco::Buffer;
using Poco::AtomicCounter;
using Poco::Nullable;
using Poco::Ascii;
namespace
{
class ACTRunnable: public Poco::Runnable
{
public:
ACTRunnable(AtomicCounter& counter):
_counter(counter)
{
}
void run()
{
for (int i = 0; i < 100000; ++i)
{
_counter++;
_counter--;
++_counter;
--_counter;
}
}
private:
AtomicCounter& _counter;
};
}
//
// The bugcheck test is normally disabled, as it
// causes a break into the debugger.
//
#define ENABLE_BUGCHECK_TEST 0
CoreTest::CoreTest(const std::string& name): CppUnit::TestCase(name)
{
}
CoreTest::~CoreTest()
{
}
void CoreTest::testPlatform()
{
std::cout << "POCO_OS: " << POCO_OS << std::endl;
std::cout << "POCO_ARCH: " << POCO_ARCH << std::endl;
}
void CoreTest::testFixedLength()
{
assert (sizeof(Poco::Int8) == 1);
assert (sizeof(Poco::UInt8) == 1);
assert (sizeof(Poco::Int16) == 2);
assert (sizeof(Poco::UInt16) == 2);
assert (sizeof(Poco::Int32) == 4);
assert (sizeof(Poco::UInt32) == 4);
#if defined(POCO_HAVE_INT64)
assert (sizeof(Poco::Int64) == 8);
assert (sizeof(Poco::UInt64) == 8);
#endif
assert (sizeof(Poco::IntPtr) == sizeof(void*));
assert (sizeof(Poco::UIntPtr) == sizeof(void*));
}
void CoreTest::testBugcheck()
{
#if ENABLE_BUGCHECK_TEST
try
{
Bugcheck::assertion("test", __FILE__, __LINE__);
failmsg("must throw exception");
}
catch (Exception&)
{
}
try
{
Bugcheck::nullPointer("test", __FILE__, __LINE__);
failmsg("must throw exception");
}
catch (Exception&)
{
}
try
{
Bugcheck::bugcheck("test", __FILE__, __LINE__);
failmsg("must throw exception");
}
catch (Exception&)
{
}
#endif
}
void CoreTest::testEnvironment()
{
#if !defined(_WIN32_WCE)
Environment::set("FOO", "BAR");
assert (Environment::has("FOO"));
assert (Environment::get("FOO") == "BAR");
#endif
try
{
std::string v = Environment::get("THISONEDOESNOTEXIST123");
failmsg("Environment variable does not exist - must throw exception");
}
catch (Exception&)
{
}
std::cout << "OS Name: " << Environment::osName() << std::endl;
std::cout << "OS Display Name: " << Environment::osDisplayName() << std::endl;
std::cout << "OS Version: " << Environment::osVersion() << std::endl;
std::cout << "OS Architecture: " << Environment::osArchitecture() << std::endl;
std::cout << "Node Name: " << Environment::nodeName() << std::endl;
std::cout << "Node ID: " << Environment::nodeId() << std::endl;
std::cout << "Number of CPUs: " << Environment::processorCount() << std::endl;
}
void CoreTest::testBuffer()
{
std::size_t s = 10;
Buffer<int> b(s);
std::vector<int> v;
for (int i = 0; i < s; ++i)
v.push_back(i);
std::memcpy(b.begin(), &v[0], sizeof(int) * v.size());
assert (s == b.size());
for (int i = 0; i < s; ++i)
assert (b[i] == i);
#if ENABLE_BUGCHECK_TEST
try { int i = b[s]; fail ("must fail"); }
catch (Exception&) { }
#endif
}
void CoreTest::testAtomicCounter()
{
AtomicCounter ac;
assert (ac.value() == 0);
assert (ac++ == 0);
assert (ac-- == 1);
assert (++ac == 1);
assert (--ac == 0);
ac = 2;
assert (ac.value() == 2);
ac = 0;
assert (ac.value() == 0);
AtomicCounter ac2(2);
assert (ac2.value() == 2);
ACTRunnable act(ac);
Thread t1;
Thread t2;
Thread t3;
Thread t4;
Thread t5;
t1.start(act);
t2.start(act);
t3.start(act);
t4.start(act);
t5.start(act);
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
assert (ac.value() == 0);
}
void CoreTest::testNullable()
{
Nullable<int> n1;
assert (n1.isNull());
assert (n1.value(42) == 42);
try
{
int tmp = n1.value();
fail("null value, must throw");
}
catch (Poco::NullValueException&)
{
}
n1 = 1;
assert (!n1.isNull());
assert (n1.value() == 1);
Nullable<int> n2(42);
assert (!n2.isNull());
assert (n2.value() == 42);
assert (n2.value(99) == 42);
n1 = n2;
assert (!n1.isNull());
assert (n1.value() == 42);
n1.clear();
assert (n1.isNull());
}
void CoreTest::testAscii()
{
assert (Ascii::isAscii('A'));
assert (!Ascii::isAscii(-1));
assert (!Ascii::isAscii(128));
assert (!Ascii::isAscii(222));
assert (Ascii::isSpace(' '));
assert (Ascii::isSpace('\t'));
assert (Ascii::isSpace('\r'));
assert (Ascii::isSpace('\n'));
assert (!Ascii::isSpace('A'));
assert (!Ascii::isSpace(-1));
assert (!Ascii::isSpace(222));
assert (Ascii::isDigit('0'));
assert (Ascii::isDigit('1'));
assert (Ascii::isDigit('2'));
assert (Ascii::isDigit('3'));
assert (Ascii::isDigit('4'));
assert (Ascii::isDigit('5'));
assert (Ascii::isDigit('6'));
assert (Ascii::isDigit('7'));
assert (Ascii::isDigit('8'));
assert (Ascii::isDigit('9'));
assert (!Ascii::isDigit('a'));
assert (Ascii::isHexDigit('0'));
assert (Ascii::isHexDigit('1'));
assert (Ascii::isHexDigit('2'));
assert (Ascii::isHexDigit('3'));
assert (Ascii::isHexDigit('4'));
assert (Ascii::isHexDigit('5'));
assert (Ascii::isHexDigit('6'));
assert (Ascii::isHexDigit('7'));
assert (Ascii::isHexDigit('8'));
assert (Ascii::isHexDigit('9'));
assert (Ascii::isHexDigit('a'));
assert (Ascii::isHexDigit('b'));
assert (Ascii::isHexDigit('c'));
assert (Ascii::isHexDigit('d'));
assert (Ascii::isHexDigit('e'));
assert (Ascii::isHexDigit('f'));
assert (Ascii::isHexDigit('A'));
assert (Ascii::isHexDigit('B'));
assert (Ascii::isHexDigit('C'));
assert (Ascii::isHexDigit('D'));
assert (Ascii::isHexDigit('E'));
assert (Ascii::isHexDigit('F'));
assert (!Ascii::isHexDigit('G'));
assert (Ascii::isPunct('.'));
assert (Ascii::isPunct(','));
assert (!Ascii::isPunct('A'));
assert (Ascii::isAlpha('a'));
assert (Ascii::isAlpha('Z'));
assert (!Ascii::isAlpha('0'));
assert (Ascii::isLower('a'));
assert (!Ascii::isLower('A'));
assert (Ascii::isUpper('A'));
assert (!Ascii::isUpper('a'));
assert (Ascii::toLower('A') == 'a');
assert (Ascii::toLower('z') == 'z');
assert (Ascii::toLower('0') == '0');
assert (Ascii::toUpper('a') == 'A');
assert (Ascii::toUpper('0') == '0');
assert (Ascii::toUpper('Z') == 'Z');
}
void CoreTest::setUp()
{
}
void CoreTest::tearDown()
{
}
CppUnit::Test* CoreTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CoreTest");
CppUnit_addTest(pSuite, CoreTest, testPlatform);
CppUnit_addTest(pSuite, CoreTest, testFixedLength);
CppUnit_addTest(pSuite, CoreTest, testBugcheck);
CppUnit_addTest(pSuite, CoreTest, testEnvironment);
CppUnit_addTest(pSuite, CoreTest, testBuffer);
CppUnit_addTest(pSuite, CoreTest, testAtomicCounter);
CppUnit_addTest(pSuite, CoreTest, testNullable);
CppUnit_addTest(pSuite, CoreTest, testAscii);
return pSuite;
}
| 23.594805 | 81 | 0.625165 | [
"object",
"vector"
] |
2c2493b117e54b4f916af13b36c3440cada16123 | 1,375 | cpp | C++ | bistro/nodes/test/test_nodes.cpp | pradeepvaka/bistro | e34bc17c06967a94e7897cd29019e1da2b421704 | [
"MIT"
] | null | null | null | bistro/nodes/test/test_nodes.cpp | pradeepvaka/bistro | e34bc17c06967a94e7897cd29019e1da2b421704 | [
"MIT"
] | null | null | null | bistro/nodes/test/test_nodes.cpp | pradeepvaka/bistro | e34bc17c06967a94e7897cd29019e1da2b421704 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include "bistro/bistro/nodes/Nodes.h"
#include "bistro/bistro/utils/hostname.h"
#include "bistro/bistro/nodes/test/utils.h"
using namespace facebook::bistro;
using namespace std;
TEST(TestNodes, CheckIterateOverLevel) {
Nodes nodes;
// Test both forms of add()
vector<std::shared_ptr<const Node>> nodes_vector =
{make_shared<Node>("foo", 1, true)};
nodes.add(nodes_vector.begin(), nodes_vector.end());
EXPECT_EQ("bar", nodes.add("bar", 2, true)->name());
// Test iterating over levels
for (const auto& node : nodes.iterateOverLevel(0)) {
EXPECT_EQ(getLocalHostName(), node->name()); // Always made by Nodes
}
for (const auto& node : nodes.iterateOverLevel(1)) {
EXPECT_EQ("foo", node->name());
}
for (const auto& node : nodes.iterateOverLevel(2)) {
EXPECT_EQ("bar", node->name());
}
for (const auto& node : nodes.iterateOverLevel(3)) { // Nonexistent level
FAIL() << "Not reached";
}
// Test noninstance node iteration for other tests :)
int count = 0;
for (const auto& node : iterate_non_instance_nodes(nodes)) {
EXPECT_NE("instance", node->name());
count++;
}
EXPECT_EQ(2, count);
}
| 29.255319 | 76 | 0.676364 | [
"vector"
] |
2c2495d4f1748b901795084419e16d33a960e65e | 2,339 | cpp | C++ | 11418.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 11418.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 11418.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
int T,N,K,x,y,z,i,f;
int s,t;
vector<int> adjlist[55];
vector<string> name[30];
int adjmat[55][55],path[55];
bool visited[55];
char msk[50];
void augment(int now)
{
if(now==s) f=1; else if(path[now]!=-1)
{
augment(path[now]);
adjmat[path[now]][now]-=f;
adjmat[now][path[now]]+=f;
}
}
int main()
{
scanf("%d",&T);
for(i=1;i<=T;i++)
{
scanf("%d",&N);
s=0,t=2*N+1;
for(x=s;x<=t;x++)
{
adjlist[x].clear();
for(y=s;y<=t;y++) adjmat[x][y]=0;
}
for(x=1;x<=N;x++)
{
adjlist[s].pb(x);
adjlist[x].pb(s);
adjmat[s][x]=1;
adjlist[x+N].pb(t);
adjlist[t].pb(x+N);
adjmat[x+N][t]=1;
}
for(z=1;z<=N;z++)
{
name[z].clear();
scanf("%d",&K);
while(K--)
{
scanf("%s",msk);
int len=strlen(msk);
for(x=0;x<len;x++) if((msk[x]>='A')&&(msk[x]<='Z')) msk[x]^=32;
msk[0]^=32;
name[z].pb(msk);
y= msk[0]-'A'+1;
if(y>N) continue;
adjlist[y].pb(z+N);
adjlist[z+N].pb(y);
adjmat[y][z+N]=1;
}
}
while(1)
{
for(x=s;x<=t;x++)
{
visited[x]=false;
path[x]=-1;
}
visited[s]=true;
queue<int> q;
q.push(s);
while(!q.empty())
{
int now = q.front();q.pop();
for(x=0;x<adjlist[now].size();x++)
{
int next = adjlist[now][x];
if((!visited[next])&&(adjmat[now][next]!=0))
{
visited[next]=true;
path[next]=now;
q.push(next);
}
}
}
f=0;
augment(t);
if(!f) break;
}
printf("Case #%d:\n",i);
for(x=1;x<=N;x++)
{
for(y=1+N;y<=2*N;y++) if((!adjmat[x][y])&&(adjmat[y][x])) break;
y-=N;
for(z=0;z<name[y].size();z++) if((char)(name[y][z][0])==(char)('A'+x-1))
{
printf("%s\n",name[y][z].c_str());
break;
}
}
}
return 0;
}
| 17.198529 | 76 | 0.48525 | [
"vector"
] |
2c259592ae7414817a0af4f39ef1702f3a2c2355 | 968 | cpp | C++ | src/main.cpp | kodo-pp/ccom | 77e6668b0243e4b37d8eca8f63d50b7e8034d4d2 | [
"Unlicense"
] | null | null | null | src/main.cpp | kodo-pp/ccom | 77e6668b0243e4b37d8eca8f63d50b7e8034d4d2 | [
"Unlicense"
] | null | null | null | src/main.cpp | kodo-pp/ccom | 77e6668b0243e4b37d8eca8f63d50b7e8034d4d2 | [
"Unlicense"
] | null | null | null | #include <ccom/util.hpp>
#include <ccom/rasterizer.hpp>
#include <ccom/compositor.hpp>
#include <ccom/geometry.hpp>
#include <ccom/objects/triangle.hpp>
#include <ccom/objects/rectangle.hpp>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <unistd.h>
int main() {
std::cout.sync_with_stdio(false);
std::cin.tie(nullptr);
const int width = 60, height = 40;
auto& rast = ccom::get_rasterizer();
auto& comp = ccom::get_compositor();
auto rect = new ccom::objects::Rectangle(
{10, 10},
{15, 20},
'o'
);
comp.add(rect);
rast.set_buffer_size(width, height, '.');
while (true) {
rast.clear_buffer('.');
rect->rotate(-2, ccom::geometry::AngleMeasurementUnit::degrees);
auto angle = rect->get_rotation();
rect->move(sin(-angle) * 0.3, cos(-angle) * 0.3);
comp.draw(rast);
rast.flush_buffer(std::cout);
usleep(1000000 / 60);
};
}
| 23.609756 | 72 | 0.605372 | [
"geometry"
] |
2c25dca180060028cf279c291b97e68937be4407 | 7,368 | cpp | C++ | src/main.cpp | yangchunluo/udacity-self-driving-p10-mpc | d6dbd2e4d033c999e73dd48492d08b63f70f2c1d | [
"MIT"
] | null | null | null | src/main.cpp | yangchunluo/udacity-self-driving-p10-mpc | d6dbd2e4d033c999e73dd48492d08b63f70f2c1d | [
"MIT"
] | null | null | null | src/main.cpp | yangchunluo/udacity-self-driving-p10-mpc | d6dbd2e4d033c999e73dd48492d08b63f70f2c1d | [
"MIT"
] | null | null | null | #include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "MPC.h"
#include "json.hpp"
#include "polyutils.h"
#include <cassert>
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// This value assumes the model presented in the classroom is used.
//
// It was obtained by measuring the radius formed by running the vehicle in the
// simulator around in a circle with a constant steering angle and velocity on a
// flat terrain.
//
// Lf was tuned until the the radius formed by the simulating the model
// presented in the classroom matched the previous radius.
//
// This is the length from front to CoG that has a similar radius.
const double Lf = 2.67;
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.rfind("}]");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
// Convert from map to vehcile coordinate for X
inline double map_to_vehicle_coordinate_x(double mx, double my,
double vx, double vy, double vpsi) {
return (my - vy) * sin(vpsi) + (mx - vx) * cos(vpsi);
}
// Convert from map to vehcile coordinate for Y
inline double map_to_vehicle_coordinate_y(double mx, double my,
double vx, double vy, double vpsi) {
return (my - vy) * cos(vpsi) - (mx - vx) * sin(vpsi);
}
int main() {
uWS::Hub h;
size_t counter = 0;
double total_cost = 0;
// MPC is initialized here!
MPC mpc;
h.onMessage([&mpc, &counter, &total_cost](
uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
string sdata = string(data).substr(0, length);
// cout << sdata << endl;
if (! (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2')) {
return;
}
string s = hasData(sdata);
if (s == "") {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
return;
}
auto j = json::parse(s);
string event = j[0].get<string>();
if (event != "telemetry") {
return;
}
// j[1] is the data JSON object
vector<double> ptsx = j[1]["ptsx"];
vector<double> ptsy = j[1]["ptsy"];
double px = j[1]["x"];
double py = j[1]["y"];
double psi = j[1]["psi"];
double v = j[1]["speed"];
double delta = j[1]["steering_angle"];
double a = j[1]["throttle"];
// Steering angle sent back from Unity is of the opposite direction:
// i.e. positive steering angle signifies right turn where as in our vehicle
// model it means left turn.
delta *= -1;
// Translate waypoints from map to vehicle coordinate system.
for (int i = 0; i < ptsx.size(); i++) {
double mx = ptsx[i],
my = ptsy[i];
ptsx[i] = map_to_vehicle_coordinate_x(mx, my, px, py, psi);
ptsy[i] = map_to_vehicle_coordinate_y(mx, my, px, py, psi);
}
// Now the coordinate origin is the car itself.
px = py = psi = 0;
// Fit a third-degree polynomial to the translated waypoints.
auto coeffs = poly_fit(ptsx, ptsy, 3);
// Deal with actuator latency by predicting the vehicle states in the future
// using the kinematic model and initialize MPC with the future states.
const long latencyMs = 100;
const double latency = latencyMs / 1000.0;
// Here we assume latency is very small.
px += v * latency;
py += v * latency * delta * latency;
psi += v * delta / Lf * latency;
// For error terms, use (actual - reference)
double cte = py - poly_eval(coeffs, px);
double epsi = psi - atan(poly_deriv_1(coeffs, px));
// Update velocity last.
v += a * latency;
// Assumble the initiate states.
Eigen::VectorXd state(6);
state << px, // Vehicle's x coorindate
py, // Vehicle's y coorindate
psi, // Vehicle's heading direction
v, // Vehicle velocity
cte, // Crosstrek error
epsi; // Heading error
// Solve MPC problem.
auto res = mpc.Solve(state, coeffs, deg2rad(25), Lf);
counter += 1;
total_cost += res.cost;
printf("Running average of cost: %f\n", total_cost / counter);
json msgJson;
// Scale the steering angle to [-1, 1]. Negate the sign with conform with Unity.
msgJson["steering_angle"] = -res.steering / (deg2rad(25) * Lf);
msgJson["throttle"] = res.throttle;
/*
* Display MPC predicted trajectory, whose length is proportional to the velocity.
* In the simulation, these points will be connected by a green line.
*/
msgJson["mpc_x"] = res.xpos;
msgJson["mpc_y"] = res.ypos;
/*
* Display the waypoints/reference line. Use the fitted polynomial.
* In the simulation, these points will be connected by a yellow line.
*/
vector<double> next_x_vals;
vector<double> next_y_vals;
const double x_inc = 2.5; /* meters. */
const int num_points = 40;
for (int i = 0; i < num_points; i++) {
next_x_vals.push_back(x_inc * i);
next_y_vals.push_back(poly_eval(coeffs, x_inc * i));
}
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
// std::cout << msg << std::endl;
// Latency
// The purpose is to mimic real driving conditions where
// the car does actuate the commands instantly.
//
// Feel free to play around with this value but should be to drive
// around the track with 100ms latency.
//
// NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE
// SUBMITTING.
this_thread::sleep_for(chrono::milliseconds(latencyMs));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
});
// We don't need this since we're not using HTTP but if it's removed the
// program doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| 32.746667 | 86 | 0.610885 | [
"object",
"vector",
"model"
] |
2c283749d7526d410d51440bc5859e76532304b4 | 1,751 | cpp | C++ | 1322_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 1322_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 1322_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | // Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<int>v(n);
for(int i=0;i<n;i++)
cin>>v[i];
int colors[n+1]={0};
map<int,int>col;
set<int>primes{2,3,5,7,11,13,17,19,23,29,31};
set<int>used_col;
int max_col=-1;
int curr_col=1;
for(int i=0;i<n;i++)
{
for(auto it:primes)
{
if(v[i]%it==0)
{
//cout<<curr_col<<endl;
if(col.count(it)==0)
{
col[it]=curr_col ;
colors[i]=curr_col;
curr_col++;
max_col=max(max_col,colors[i]);
used_col.insert(colors[i]);
break;
}
else
{
colors[i]=col[it];
break;
}
}
}
}
// for(int i=0;i<n;i++)
// {
// if(colors[i]==0)
// {
// for(int j=1;j<=11;j++)
// {
// if(used_col.find(j)==used_col.end())
// {
// colors[i]=j;
// used_col.insert(j);
// max_col=max(max_col,colors[i]);
// }
// }
// }
// }
cout<<max_col<<endl;
for(int i=0;i<n;i++)
cout<<colors[i]<<" ";
cout<<endl;
}
} | 19.897727 | 106 | 0.533409 | [
"vector"
] |
2c3020f3922f90a227adc9d31c6bb41ae24234c1 | 6,975 | cc | C++ | tensorflow/compiler/plugin/poplar/tests/debug_info_test.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 74 | 2020-07-06T17:11:39.000Z | 2022-01-28T06:31:28.000Z | tensorflow/compiler/plugin/poplar/tests/debug_info_test.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 9 | 2020-10-13T23:25:29.000Z | 2022-02-10T06:54:48.000Z | tensorflow/compiler/plugin/poplar/tests/debug_info_test.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 12 | 2020-07-08T07:27:17.000Z | 2021-12-27T08:54:27.000Z | /* Copyright 2021 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 <fstream>
#include "include/json/json.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/debug_info.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/env.h"
struct TemporaryFileManager {
public:
explicit TemporaryFileManager(const std::string& file_name)
: file_name_(file_name) {
if (!tensorflow::Env::Default()->LocalTempFilename(&file_name_)) {
LOG(FATAL) << "Could not create a file.";
}
}
~TemporaryFileManager() {
auto status = tensorflow::Env::Default()->DeleteFile(file_name_);
if (!status.ok()) {
LOG(FATAL) << status.ToString();
}
}
const std::string& GetFileName() { return file_name_; }
private:
std::string file_name_;
};
namespace xla {
namespace poplarplugin {
namespace {
StatusOr<Json::Value> ReadJsonFile(const std::string& file_name) {
std::ifstream file(file_name);
Json::Value output;
Json::Reader reader;
if (!reader.parse(file, output)) {
return InternalError("Could not parse json file.");
}
return output;
}
using DebugInfoTest = HloTestBase;
TEST_F(DebugInfoTest, TestXlaOpDebugInfo) {
TemporaryFileManager tfm("file.json");
poplar::DebugInfo::initializeStreamer(tfm.GetFileName(),
poplar::DebugSerializationFormat::JSON);
{
poplar::DebugContext debug_context(
"test", poplar::SourceLocation("function_name", "file_name", 42));
xla::OpMetadata metadata;
metadata.set_op_type("fred");
metadata.set_op_name("test");
XlaOpDebugInfo debug_info(debug_context, metadata);
}
poplar::DebugInfo::closeStreamer();
TF_ASSERT_OK_AND_ASSIGN(auto root, ReadJsonFile(tfm.GetFileName()));
EXPECT_EQ(1, root["contexts"].size());
auto c = root["contexts"][0];
EXPECT_EQ("xla_op", c["layer"].asString());
EXPECT_EQ("op", c["category"].asString());
EXPECT_EQ("test", c["op_name"].asString());
EXPECT_EQ("fred", c["op_type"].asString());
EXPECT_FALSE(c.isMember("sourcefile"));
EXPECT_FALSE(c.isMember("sourceline"));
}
TEST_F(DebugInfoTest, TestHloInstructionDebugInfo_Constant) {
TemporaryFileManager tfm("file.json");
poplar::DebugInfo::initializeStreamer(tfm.GetFileName(),
poplar::DebugSerializationFormat::JSON);
{
poplar::DebugContext debug_context(
poplar::SourceLocation("function_name", "file_name", 42));
auto instruction = HloInstruction::CreateConstant(xla::Literal());
HloInstructionDebugInfo debug_info(debug_context, instruction.get());
}
poplar::DebugInfo::closeStreamer();
TF_ASSERT_OK_AND_ASSIGN(auto root, ReadJsonFile(tfm.GetFileName()));
EXPECT_EQ(1, root["contexts"].size());
auto c = root["contexts"][0];
EXPECT_EQ("hloinstruction", c["layer"].asString());
EXPECT_EQ("constant", c["hlo_name"].asString());
EXPECT_EQ(-1, c["hlo_id"].asInt64());
EXPECT_EQ("constant", c["opcode"].asString());
EXPECT_EQ("() -> ()", c["signature"].asString());
EXPECT_EQ("%constant = () constant({...})", c["debug_string"].asString());
EXPECT_EQ(0, c["operand_count"].asInt());
EXPECT_EQ(0, c["operands"].size());
EXPECT_EQ(0, c["users"].size());
}
TEST_F(DebugInfoTest, TestHloInstructionDebugInfo_Dot) {
TemporaryFileManager tfm("file.json");
poplar::DebugInfo::initializeStreamer(tfm.GetFileName(),
poplar::DebugSerializationFormat::JSON);
{
poplar::DebugContext debug_context(
poplar::SourceLocation("function_name", "file_name", 42));
Shape r1f32 = ShapeUtil::MakeShape(F32, {1});
DotDimensionNumbers dot_dnums;
dot_dnums.add_lhs_batch_dimensions(0);
dot_dnums.add_rhs_batch_dimensions(0);
auto x = HloInstruction::CreateParameter(0, r1f32, "x");
auto y = HloInstruction::CreateParameter(1, r1f32, "y");
// Need to create a root node for a computation so we can get computation
// added to the instruction below. This is just so we can test for the
// presence of the fields.
auto root = HloInstruction::CreateDot(r1f32, x.get(), y.get(), dot_dnums,
DefaultPrecisionConfig(2));
auto builder = HloComputation::Builder("ComputationA");
builder.AddInstruction(std::move(root));
auto instruction = HloInstruction::CreateDot(
r1f32, x.get(), y.get(), dot_dnums, DefaultPrecisionConfig(2));
auto computation = builder.Build(root.get());
auto a = computation->AddInstruction(std::move(instruction));
HloInstructionDebugInfo debug_info(debug_context, a);
}
poplar::DebugInfo::closeStreamer();
TF_ASSERT_OK_AND_ASSIGN(auto root, ReadJsonFile(tfm.GetFileName()));
EXPECT_EQ(1, root["contexts"].size());
auto c = root["contexts"][0];
EXPECT_EQ("hloinstruction", c["layer"].asString());
EXPECT_EQ("dot", c["hlo_name"].asString());
EXPECT_EQ(-1, c["hlo_id"].asInt64());
EXPECT_EQ("dot", c["opcode"].asString());
EXPECT_EQ("(f32[1], f32[1]) -> f32[1]", c["signature"].asString());
EXPECT_EQ(
"%dot = f32[1]{0} dot(f32[1]{0} %x, f32[1]{0} %y), lhs_batch_dims={0}, "
"lhs_contracting_dims={}, rhs_batch_dims={0}, rhs_contracting_dims={}",
c["debug_string"].asString());
EXPECT_EQ(2, c["operand_count"].asInt());
EXPECT_EQ(2, c["operands"].size());
EXPECT_EQ(0, c["users"].size());
EXPECT_EQ("ComputationA", c["computation"].asString());
EXPECT_EQ(-1, c["computation_id"].asInt64());
}
TEST_F(DebugInfoTest, TestPoplarOpDefDebugInfo) {
TemporaryFileManager tfm("file.json");
poplar::DebugInfo::initializeStreamer(tfm.GetFileName(),
poplar::DebugSerializationFormat::JSON);
{
poplar::DebugContext debug_context(
poplar::SourceLocation("function_name", "file_name", 42));
PoplarOpDefDebugInfo debug_info(debug_context, "SomeClass");
}
poplar::DebugInfo::closeStreamer();
TF_ASSERT_OK_AND_ASSIGN(auto root, ReadJsonFile(tfm.GetFileName()));
EXPECT_EQ(1, root["contexts"].size());
auto c = root["contexts"][0];
EXPECT_EQ("poplar_driver", c["layer"].asString());
EXPECT_EQ("SomeClass", c["class"].asString());
}
} // namespace
} // namespace poplarplugin
} // namespace xla
| 34.875 | 80 | 0.678996 | [
"shape"
] |
2c36a514877579df52c066a3e728bab07b65f0a7 | 4,096 | cpp | C++ | OPHD/UI/FactoryListBox.cpp | belgianguy/OPHD | d59009d63b6f10fc9a95c36c392d72509e52a21c | [
"BSD-3-Clause"
] | null | null | null | OPHD/UI/FactoryListBox.cpp | belgianguy/OPHD | d59009d63b6f10fc9a95c36c392d72509e52a21c | [
"BSD-3-Clause"
] | null | null | null | OPHD/UI/FactoryListBox.cpp | belgianguy/OPHD | d59009d63b6f10fc9a95c36c392d72509e52a21c | [
"BSD-3-Clause"
] | null | null | null | #include "FactoryListBox.h"
#include "../Things/Structures/Factory.h"
#include "../Cache.h"
#include "../Constants.h"
#include <NAS2D/Utility.h>
#include <NAS2D/Renderer/Renderer.h>
using namespace NAS2D;
const int LIST_ITEM_HEIGHT = 58;
const Image* STRUCTURE_ICONS = nullptr;
static const Font* MAIN_FONT = nullptr;
static const Font* MAIN_FONT_BOLD = nullptr;
static void drawItem(Renderer& renderer, FactoryListBox::FactoryListBoxItem& item, int x, int y, int w, int offset, bool highlight)
{
Factory* f = item.factory;
const auto& structureColor = structureColorFromIndex(f->state());
const auto& structureTextColor = structureTextColorFromIndex(f->state());
const auto highlightColor = NAS2D::Color{structureColor.red, structureColor.green, structureColor.blue, 75};
const auto subImageColor = NAS2D::Color{255, 255, 255, structureColor.alpha};
// draw highlight rect so as not to tint/hue colors of everything else
if (highlight) { renderer.drawBoxFilled(NAS2D::Rectangle{x, y - offset, w, LIST_ITEM_HEIGHT}, highlightColor); }
renderer.drawBox(NAS2D::Rectangle{x + 2, y + 2 - offset, w - 4, LIST_ITEM_HEIGHT - 4}, structureColor);
renderer.drawSubImage(*STRUCTURE_ICONS, NAS2D::Point{x + 8, y + 8 - offset}, NAS2D::Rectangle{item.icon_slice.x, item.icon_slice.y, 46, 46}, subImageColor);
renderer.drawText(*MAIN_FONT_BOLD, f->name(), NAS2D::Point{x + 64, ((y + 29) - MAIN_FONT_BOLD->height() / 2) - offset}, structureTextColor);
renderer.drawText(*MAIN_FONT, productDescription(f->productType()), NAS2D::Point{x + w - 112, ((y + 19) - MAIN_FONT_BOLD->height() / 2) - offset}, structureTextColor);
// PROGRESS BAR
float percentage = (f->productType() == ProductType::PRODUCT_NONE) ? 0.0f : (f->productionTurnsCompleted() / f->productionTurnsToComplete());
drawBasicProgressBar(x + w - 112, y + 30 - offset, 105, 11, percentage, 2);
}
FactoryListBox::FactoryListBox()
{
item_height(LIST_ITEM_HEIGHT);
STRUCTURE_ICONS = &imageCache.load("ui/structures.png");
MAIN_FONT = &fontCache.load(constants::FONT_PRIMARY, 12);
MAIN_FONT_BOLD = &fontCache.load(constants::FONT_PRIMARY_BOLD, 12);
}
/**
* Adds a Factory to the FactoryListBox.
*
* Specialized version of the default addItem(ListBoxItem*) function.
*/
void FactoryListBox::addItem(Factory* factory)
{
/// \fixme Could be much more elegant via a lambda expression
for (auto item : mItems)
{
if (static_cast<FactoryListBoxItem*>(item)->factory == factory)
{
std::cout << "FactoryListBox::addItem(): annoying bug, fix it." << std::endl;
return;
}
}
/// \fixme super sloppy
const auto& text = factory->name();
const auto iconPosition = (factory->state() == StructureState::Destroyed) ? NAS2D::Point<int>{414, 368} :
(text == constants::UNDERGROUND_FACTORY) ? NAS2D::Point<int>{138, 276} :
(text == constants::SEED_FACTORY) ? NAS2D::Point<int>{460, 368} :
NAS2D::Point<int>{0, 46}; // Surface factory
add<FactoryListBoxItem>(text, factory, iconPosition);
}
/**
* Sets the current selection.
*
* \param f Pointer to a Factory object. Safe to pass \c nullptr.
*/
void FactoryListBox::setSelected(Factory* f)
{
if (mItems.empty() || f == nullptr) { return; }
for (std::size_t i = 0; i < mItems.size(); ++i)
{
FactoryListBoxItem* item = static_cast<FactoryListBoxItem*>(mItems[i]);
if (item->factory == f)
{
setSelection(i);
return;
}
}
}
Factory* FactoryListBox::selectedFactory()
{
return (selectedIndex() == constants::NO_SELECTION) ? nullptr : static_cast<FactoryListBoxItem*>(mItems[selectedIndex()])->factory;
}
/**
* Draws the FactoryListBox
*/
void FactoryListBox::update()
{
if (!visible()) { return; }
ListBoxBase::update();
auto& renderer = Utility<Renderer>::get();
renderer.clipRect(mRect);
// ITEMS
for (std::size_t i = 0; i < mItems.size(); ++i)
{
drawItem(renderer, *static_cast<FactoryListBoxItem*>(mItems[i]),
positionX(),
positionY() + (static_cast<int>(i) * LIST_ITEM_HEIGHT),
static_cast<int>(item_width()),
static_cast<int>(draw_offset()),
i == selectedIndex());
}
renderer.clipRectClear();
}
| 30.567164 | 168 | 0.703125 | [
"object"
] |
2c3f701dc0dcd0f5ba7b9e92edd1fb6b13c4f7f1 | 6,156 | cc | C++ | bam/src/hst_svc_mapping.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | bam/src/hst_svc_mapping.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | bam/src/hst_svc_mapping.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2014 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include "com/centreon/broker/bam/hst_svc_mapping.hh"
using namespace com::centreon::broker::bam;
/**
* Default constructor.
*/
hst_svc_mapping::hst_svc_mapping() {}
/**
* Copy constructor.
*
* @param[in] other Object to copy.
*/
hst_svc_mapping::hst_svc_mapping(hst_svc_mapping const& other) {
_internal_copy(other);
}
/**
* Destructor.
*/
hst_svc_mapping::~hst_svc_mapping() {}
/**
* Assignment operator.
*
* @param[in] other Object to copy.
*
* @return This object.
*/
hst_svc_mapping& hst_svc_mapping::operator=(
hst_svc_mapping const& other) {
if (this != &other)
_internal_copy(other);
return (*this);
}
/**
* Get host ID by its name.
*
* @param[in] hst Host name.
*
* @return Host ID, 0 if it was not found.
*/
unsigned int hst_svc_mapping::get_host_id(
std::string const& hst) const {
return (get_service_id(hst, "").first);
}
/**
* Get service ID by its name.
*
* @param[in] hst Host name.
* @param[in] svc Service description.
*
* @return Pair of integers with host ID and service ID, (0, 0) if it
* was not found.
*/
std::pair<unsigned int, unsigned int> hst_svc_mapping::get_service_id(
std::string const& hst,
std::string const& svc) const {
std::map<std::pair<std::string, std::string>,
std::pair<unsigned int, unsigned int> >::const_iterator
it(_mapping.find(std::make_pair(hst, svc)));
return ((it != _mapping.end()) ? it->second : std::make_pair(0u, 0u));
}
/**
* Set the ID of a host.
*
* @param[in] hst Host name.
* @param[in] host_id Host ID.
*/
void hst_svc_mapping::set_host(
std::string const& hst,
unsigned int host_id) {
set_service(hst, "", host_id, 0u, true);
return ;
}
/**
* Set the ID of a service.
*
* @param[in] hst Host name.
* @param[in] svc Service description.
* @param[in] host_id Host ID.
* @param[in] service_id Service ID.
*/
void hst_svc_mapping::set_service(
std::string const& hst,
std::string const& svc,
unsigned int host_id,
unsigned int service_id,
bool activated) {
_mapping[std::make_pair(hst, svc)] = std::make_pair(host_id, service_id);
_activated_mapping[std::make_pair(host_id, service_id)] = activated;
return ;
}
/**
* Get if the service is activated.
*
* @param[in] hst_id The host id.
* @param[in] service_id The service id.
*
* @return True if activated.
*/
bool hst_svc_mapping::get_activated (
unsigned int hst_id,
unsigned int service_id) const {
std::map<std::pair<unsigned int, unsigned int>, bool>::const_iterator
it (_activated_mapping.find(std::make_pair(hst_id, service_id)));
return (it == _activated_mapping.end() ? true : it->second);
}
/**
* Register a metric.
*
* @param[in] metric_id The id of the metric.
* @param[in] metric_name The name of the metric.
* @param[in] host_id The id of the host.
* @param[in] service_id The id of the service.
*/
void hst_svc_mapping::register_metric(
unsigned int metric_id,
std::string const& metric_name,
unsigned int host_id,
unsigned int service_id) {
_metrics[std::make_pair(host_id, service_id)][metric_name] = metric_id;
_metric_by_name.insert(std::make_pair(metric_name, metric_id));
}
/**
* Get metric ids from name/host and service ids.
*
* If both host id and service id are equal to zero,
* will match all metric ids with the same name.
*
* @param[in] metric_name The metric name.
* @param[in] host_id The host id. Can be zero.
* @param[in] service_id The service id. Can be zero.
*
* @return A list of found metric ids.
*/
std::set<unsigned int>
hst_svc_mapping::get_metric_ids(
std::string const& metric_name,
unsigned int host_id,
unsigned int service_id) const {
std::set<unsigned int> retval;
if (host_id != 0 || service_id != 0) {
std::map<std::pair<unsigned int, unsigned int>,
std::map<std::string, unsigned int> >::const_iterator
metrics_found = _metrics.find(std::make_pair(host_id, service_id));
if (metrics_found == _metrics.end())
return (retval);
std::map<std::string, unsigned int>::const_iterator
metric_found = metrics_found->second.find(metric_name);
if (metric_found != metrics_found->second.end())
retval.insert(metric_found->second);
}
else {
std::pair<std::multimap<std::string, unsigned int>::const_iterator,
std::multimap<std::string, unsigned int>::const_iterator>
found = _metric_by_name.equal_range(metric_name);
for (; found.first != found.second; ++found.first)
retval.insert(found.first->second);
}
return (retval);
}
/**
* Copy internal data members.
*
* @param[in] other Object to copy.
*/
void hst_svc_mapping::_internal_copy(hst_svc_mapping const& other) {
_mapping = other._mapping;
_activated_mapping = other._activated_mapping;
_metrics = other._metrics;
_metric_by_name = other._metric_by_name;
return ;
}
| 29.883495 | 88 | 0.61436 | [
"object"
] |
2c47b0de398e9de34dbbfbb2ac71c65227d51efe | 1,961 | cpp | C++ | test/TestOpAlgoLoopsPassingData.cpp | cnheider/vulkan-kompute | 267f92763ee7743549a4d5299fee61054bbb4689 | [
"Apache-2.0"
] | 5 | 2020-11-09T06:49:55.000Z | 2022-01-22T15:43:32.000Z | test/TestOpAlgoLoopsPassingData.cpp | cnheider/vulkan-kompute | 267f92763ee7743549a4d5299fee61054bbb4689 | [
"Apache-2.0"
] | null | null | null | test/TestOpAlgoLoopsPassingData.cpp | cnheider/vulkan-kompute | 267f92763ee7743549a4d5299fee61054bbb4689 | [
"Apache-2.0"
] | 1 | 2021-02-13T08:12:29.000Z | 2021-02-13T08:12:29.000Z |
#include "gtest/gtest.h"
#include "kompute/Kompute.hpp"
TEST(TestProcessingIterations, IterateThroughMultipleSumAndCopies)
{
kp::Manager mgr;
float TOTAL_ITER = 10;
std::vector<float> testExpectedOutVec = { TOTAL_ITER,
TOTAL_ITER,
TOTAL_ITER };
std::shared_ptr<kp::Tensor> tensorA{ new kp::Tensor({ 0, 0, 0 }) };
std::shared_ptr<kp::Tensor> tensorB{ new kp::Tensor({ 0, 0, 0 }) };
std::string shader(R"(
#version 450
layout (local_size_x = 1) in;
layout(set = 0, binding = 0) buffer a { float pa[]; };
layout(set = 0, binding = 1) buffer b { float pb[]; };
void main() {
uint index = gl_GlobalInvocationID.x;
pb[index] = pa[index] + 1;
}
)");
std::weak_ptr<kp::Sequence> sqWeakPtr =
mgr.getOrCreateManagedSequence("default");
if (std::shared_ptr<kp::Sequence> sq = sqWeakPtr.lock()) {
sq->begin();
sq->record<kp::OpTensorCreate>({ tensorA, tensorB });
sq->end();
sq->eval();
}
std::weak_ptr<kp::Sequence> sqWeakPtr2 =
mgr.getOrCreateManagedSequence("run");
if (std::shared_ptr<kp::Sequence> sq = sqWeakPtr2.lock()) {
sq->begin();
sq->record<kp::OpAlgoBase<>>(
{ tensorA, tensorB },
std::vector<char>(shader.begin(), shader.end()));
sq->record<kp::OpTensorCopy>({ tensorB, tensorA });
sq->end();
for (size_t i = 0; i < TOTAL_ITER; i++) {
sq->eval();
}
}
std::weak_ptr<kp::Sequence> sqWeakPtr3 =
mgr.getOrCreateManagedSequence("export");
if (std::shared_ptr<kp::Sequence> sq = sqWeakPtr3.lock()) {
sq->begin();
sq->record<kp::OpTensorSyncLocal>({ tensorA, tensorB });
sq->end();
sq->eval();
}
EXPECT_EQ(tensorA->data(), testExpectedOutVec);
}
| 24.822785 | 71 | 0.539521 | [
"vector"
] |
2c4824bc51727043951e4a927d8c6c845d947489 | 6,439 | cpp | C++ | src/qpid/broker/amqp/ManagedConnection.cpp | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | 1 | 2017-11-29T09:19:02.000Z | 2017-11-29T09:19:02.000Z | src/qpid/broker/amqp/ManagedConnection.cpp | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | null | null | null | src/qpid/broker/amqp/ManagedConnection.cpp | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | null | null | null | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "qpid/broker/amqp/ManagedConnection.h"
#include "qpid/broker/amqp/Exception.h"
#include "qpid/amqp/descriptors.h"
#include "qpid/broker/Broker.h"
#include "qpid/management/ManagementAgent.h"
#include "qpid/log/Statement.h"
#include "qpid/types/Variant.h"
#include "qmf/org/apache/qpid/broker/EventClientConnect.h"
#include "qmf/org/apache/qpid/broker/EventClientDisconnect.h"
namespace _qmf = qmf::org::apache::qpid::broker;
namespace qpid {
namespace broker {
namespace amqp {
namespace {
const std::string CLIENT_PROCESS_NAME("qpid.client_process");
const std::string CLIENT_PID("qpid.client_pid");
const std::string CLIENT_PPID("qpid.client_ppid");
template <typename T> T getProperty(const std::string& key, const qpid::types::Variant::Map& props, T defaultValue)
{
qpid::types::Variant::Map::const_iterator i = props.find(key);
if (i != props.end()) {
return i->second;
} else {
return defaultValue;
}
}
}
ManagedConnection::ManagedConnection(Broker& broker, const std::string i, bool brokerInitiated) : id(i), agent(0)
{
//management integration:
agent = broker.getManagementAgent();
if (agent != 0) {
qpid::management::Manageable* parent = broker.GetVhostObject();
connection = _qmf::Connection::shared_ptr(new _qmf::Connection(agent, this, parent, id, !brokerInitiated, false, "AMQP 1.0"));
agent->addObject(connection);
}
}
ManagedConnection::~ManagedConnection()
{
if (agent && connection) {
agent->raiseEvent(_qmf::EventClientDisconnect(id, userid, connection->get_remoteProperties()));
connection->resourceDestroy();
}
QPID_LOG_CAT(debug, model, "Delete connection. user:" << userid << " rhost:" << id);
}
void ManagedConnection::setUserId(const std::string& uid)
{
userid = uid;
if (connection) {
connection->set_authIdentity(userid);
}
}
void ManagedConnection::opened()
{
if (agent) {
agent->raiseEvent(_qmf::EventClientConnect(id, userid, connection->get_remoteProperties()));
}
QPID_LOG_CAT(debug, model, "Create connection. user:" << userid << " rhost:" << id );
}
void ManagedConnection::setSaslMechanism(const std::string& mechanism)
{
if (connection) {
connection->set_saslMechanism(mechanism);
}
}
void ManagedConnection::setSaslSsf(int ssf)
{
if (connection) {
connection->set_saslSsf(ssf);
}
}
void ManagedConnection::setPeerProperties(std::map<std::string, types::Variant>& p)
{
peerProperties = p;
if (connection) {
connection->set_remoteProperties(peerProperties);
std::string procName = getProperty(CLIENT_PROCESS_NAME, peerProperties, std::string());
uint32_t pid = getProperty(CLIENT_PID, peerProperties, 0);
uint32_t ppid = getProperty(CLIENT_PPID, peerProperties, 0);
if (!procName.empty())
connection->set_remoteProcessName(procName);
if (pid != 0)
connection->set_remotePid(pid);
if (ppid != 0)
connection->set_remoteParentPid(ppid);
}
}
void ManagedConnection::setContainerId(const std::string& container)
{
containerid = container;
peerProperties["container-id"] = containerid;
if (connection) {
connection->set_remoteProperties(peerProperties);
}
}
const std::string& ManagedConnection::getContainerId() const
{
return containerid;
}
void ManagedConnection::setInterconnectDomain(const std::string& d)
{
domain = d;
}
const std::string& ManagedConnection::getInterconnectDomain() const
{
return domain;
}
qpid::management::ManagementObject::shared_ptr ManagedConnection::GetManagementObject() const
{
return connection;
}
std::string ManagedConnection::getId() const { return id; }
const management::ObjectId ManagedConnection::getObjectId() const
{
return GetManagementObject()->getObjectId();
}
const std::string& ManagedConnection::getUserId() const
{
return userid;
}
const std::string& ManagedConnection::getMgmtId() const
{
return id;
}
const std::map<std::string, types::Variant>& ManagedConnection::getClientProperties() const
{
return connection->get_remoteProperties();
}
bool ManagedConnection::isLink() const
{
return false;
}
bool ManagedConnection::isLocal(const OwnershipToken* t) const
{
return this == t;
}
void ManagedConnection::outgoingMessageSent()
{
if (connection) connection->inc_msgsToClient();
}
void ManagedConnection::incomingMessageReceived()
{
if (connection) connection->inc_msgsFromClient();
}
void ManagedConnection::closedByManagement()
{
throw Exception(qpid::amqp::error_conditions::NOT_IMPLEMENTED, QPID_MSG(id << "Connection close requested, but not implemented"));
}
qpid::management::Manageable::status_t ManagedConnection::ManagementMethod(uint32_t methodId, qpid::management::Args&, std::string& error)
{
qpid::management::Manageable::status_t status = qpid::management::Manageable::STATUS_UNKNOWN_METHOD;
try {
switch (methodId)
{
case _qmf::Connection::METHOD_CLOSE :
closedByManagement();
if (connection) connection->set_closing(true);
status = qpid::management::Manageable::STATUS_OK;
break;
}
} catch (const Exception& e) {
if (e.symbol() == qpid::amqp::error_conditions::NOT_IMPLEMENTED) {
status = qpid::management::Manageable::STATUS_NOT_IMPLEMENTED;
} else {
error = e.what();
status = qpid::management::Manageable::STATUS_EXCEPTION;
}
}
return status;
}
}}} // namespace qpid::broker::amqp
| 29.948837 | 138 | 0.69809 | [
"model"
] |
2c4987716a367eca93f4fe53919322b2d35b5dde | 62,536 | hpp | C++ | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/openssl/ssl/sslctx.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 10 | 2021-03-29T13:52:06.000Z | 2022-03-10T02:24:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/openssl/ssl/sslctx.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | null | null | null | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/openssl/ssl/sslctx.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 6 | 2021-07-03T07:56:56.000Z | 2022-02-14T15:28:23.000Z | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// Wrap the OpenSSL SSL API as defined in <openssl/ssl.h>
// so that it can be used as the SSL layer by the OpenVPN core.
#ifndef OPENVPN_OPENSSL_SSL_SSLCTX_H
#define OPENVPN_OPENSSL_SSL_SSLCTX_H
#include <string>
#include <cstring>
#include <sstream>
#include <utility>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/mode.hpp>
#include <openvpn/common/options.hpp>
#include <openvpn/common/base64.hpp>
#include <openvpn/common/string.hpp>
#include <openvpn/common/uniqueptr.hpp>
#include <openvpn/common/hexstr.hpp>
#include <openvpn/common/to_string.hpp>
#include <openvpn/common/unicode.hpp>
#include <openvpn/frame/frame.hpp>
#include <openvpn/buffer/buffer.hpp>
#include <openvpn/pki/cclist.hpp>
#include <openvpn/pki/epkibase.hpp>
#include <openvpn/ssl/kuparse.hpp>
#include <openvpn/ssl/nscert.hpp>
#include <openvpn/ssl/tlsver.hpp>
#include <openvpn/ssl/tls_remote.hpp>
#include <openvpn/ssl/sslconsts.hpp>
#include <openvpn/ssl/sslapi.hpp>
#include <openvpn/ssl/ssllog.hpp>
#include <openvpn/ssl/sni_handler.hpp>
#include <openvpn/openssl/util/error.hpp>
#include <openvpn/openssl/pki/x509.hpp>
#include <openvpn/openssl/pki/crl.hpp>
#include <openvpn/openssl/pki/pkey.hpp>
#include <openvpn/openssl/pki/dh.hpp>
#include <openvpn/openssl/pki/x509store.hpp>
#include <openvpn/openssl/bio/bio_memq_stream.hpp>
#include <openvpn/openssl/ssl/sess_cache.hpp>
#ifdef HAVE_JSON
#include <openvpn/common/jsonhelper.hpp>
#endif
// An SSL Context is essentially a configuration that can be used
// to generate an arbitrary number of actual SSL connections objects.
// OpenSSLContext is an SSL Context implementation that uses the
// OpenSSL library as a backend.
namespace openvpn {
// Represents an SSL configuration that can be used
// to instantiate actual SSL sessions.
class OpenSSLContext : public SSLFactoryAPI
{
public:
typedef RCPtr<OpenSSLContext> Ptr;
typedef CertCRLListTemplate<OpenSSLPKI::X509List, OpenSSLPKI::CRLList> CertCRLList;
enum {
MAX_CIPHERTEXT_IN = 64 // maximum number of queued input ciphertext packets
};
// The data needed to construct an OpenSSLContext.
class Config : public SSLConfigAPI
{
friend class OpenSSLContext;
public:
typedef RCPtr<Config> Ptr;
virtual SSLFactoryAPI::Ptr new_factory()
{
return SSLFactoryAPI::Ptr(new OpenSSLContext(this));
}
virtual void set_mode(const Mode& mode_arg)
{
mode = mode_arg;
}
virtual const Mode& get_mode() const
{
return mode;
}
// if this callback is defined, no private key needs to be loaded
virtual void set_external_pki_callback(ExternalPKIBase* external_pki_arg)
{
external_pki = external_pki_arg;
}
// server side
virtual void set_session_ticket_handler(TLSSessionTicketBase* session_ticket_handler_arg)
{
session_ticket_handler = session_ticket_handler_arg;
}
// client side
virtual void set_client_session_tickets(const bool v)
{
client_session_tickets = v;
}
// server side
virtual void set_sni_handler(SNI::HandlerBase* sni_handler_arg)
{
sni_handler = sni_handler_arg;
}
// client side
virtual void set_sni_name(const std::string& sni_name_arg)
{
sni_name = sni_name_arg;
}
virtual void set_private_key_password(const std::string& pwd)
{
pkey.set_private_key_password(pwd);
}
virtual void load_ca(const std::string& ca_txt, bool strict)
{
ca.parse_pem(ca_txt, "ca");
}
virtual void load_crl(const std::string& crl_txt)
{
ca.parse_pem(crl_txt, "crl");
}
virtual void load_cert(const std::string& cert_txt)
{
cert.parse_pem(cert_txt, "cert");
}
virtual void load_cert(const std::string& cert_txt, const std::string& extra_certs_txt)
{
load_cert(cert_txt);
if (!extra_certs_txt.empty())
CertCRLList::from_string(extra_certs_txt, "extra-certs", &extra_certs, nullptr);
}
virtual void load_private_key(const std::string& key_txt)
{
pkey.parse_pem(key_txt, "private key");
}
virtual void load_dh(const std::string& dh_txt)
{
dh.parse_pem(dh_txt);
}
virtual std::string extract_ca() const
{
return ca.certs.render_pem();
}
virtual std::string extract_crl() const
{
return ca.crls.render_pem();
}
virtual std::string extract_cert() const
{
return cert.render_pem();
}
virtual std::vector<std::string> extract_extra_certs() const
{
std::vector<std::string> ret;
for (auto const& cert : extra_certs)
ret.push_back(cert.render_pem());
return ret;
}
virtual std::string extract_private_key() const
{
return pkey.render_pem();
}
virtual std::string extract_dh() const
{
return dh.render_pem();
}
virtual PKType::Type private_key_type() const
{
if (!pkey.defined())
return PKType::PK_NONE;
return pkey.key_type();
}
virtual size_t private_key_length() const
{
return pkey.key_length();
}
virtual void set_frame(const Frame::Ptr& frame_arg)
{
frame = frame_arg;
}
virtual void set_debug_level(const int debug_level)
{
ssl_debug_level = debug_level;
}
virtual void set_flags(const unsigned int flags_arg)
{
flags = flags_arg;
}
virtual void set_ns_cert_type(const NSCert::Type ns_cert_type_arg)
{
ns_cert_type = ns_cert_type_arg;
}
virtual void set_remote_cert_tls(const KUParse::TLSWebType wt)
{
KUParse::remote_cert_tls(wt, ku, eku);
}
virtual void set_tls_remote(const std::string& tls_remote_arg)
{
tls_remote = tls_remote_arg;
}
virtual void set_tls_version_min(const TLSVersion::Type tvm)
{
tls_version_min = tvm;
}
virtual void set_tls_version_min_override(const std::string& override)
{
TLSVersion::apply_override(tls_version_min, override);
}
virtual void set_tls_cert_profile(const TLSCertProfile::Type type)
{
tls_cert_profile = type;
}
virtual void set_tls_cert_profile_override(const std::string& override)
{
TLSCertProfile::apply_override(tls_cert_profile, override);
}
virtual void set_local_cert_enabled(const bool v)
{
local_cert_enabled = v;
}
virtual void set_force_aes_cbc_ciphersuites(const bool v)
{
force_aes_cbc_ciphersuites = v;
}
virtual void set_x509_track(X509Track::ConfigSet x509_track_config_arg)
{
x509_track_config = std::move(x509_track_config_arg);
}
virtual void set_rng(const RandomAPI::Ptr& rng_arg)
{
// Not implemented (other than assert_crypto check)
// because OpenSSL is hardcoded to use its own RNG.
rng_arg->assert_crypto();
}
virtual std::string validate_cert(const std::string& cert_txt) const
{
OpenSSLPKI::X509 cert(cert_txt, "cert");
return cert.render_pem();
}
virtual std::string validate_cert_list(const std::string& certs_txt) const
{
CertCRLList certs(certs_txt, "cert list");
return certs.render_pem();
}
virtual std::string validate_private_key(const std::string& key_txt) const
{
OpenSSLPKI::PKey pkey(key_txt, "private key");
return pkey.render_pem();
}
virtual std::string validate_dh(const std::string& dh_txt) const
{
OpenSSLPKI::DH dh(dh_txt);
return dh.render_pem();
}
virtual std::string validate_crl(const std::string& crl_txt) const
{
OpenSSLPKI::CRL crl(crl_txt);
return crl.render_pem();
}
virtual void load(const OptionList& opt, const unsigned int lflags)
{
// client/server
if (lflags & LF_PARSE_MODE)
mode = opt.exists("client") ? Mode(Mode::CLIENT) : Mode(Mode::SERVER);
// possibly disable peer cert verification
if ((lflags & LF_ALLOW_CLIENT_CERT_NOT_REQUIRED)
&& opt.exists("client-cert-not-required"))
flags |= SSLConst::NO_VERIFY_PEER;
// sni
{
const std::string name = opt.get_optional("sni", 1, 256);
if (!name.empty())
set_sni_name(name);
}
// ca
{
std::string ca_txt = opt.cat("ca");
if (lflags & LF_RELAY_MODE)
ca_txt += opt.cat("relay-extra-ca");
load_ca(ca_txt, true);
}
// CRL
{
const std::string crl_txt = opt.cat("crl-verify");
if (!crl_txt.empty())
load_crl(crl_txt);
}
// local cert/key
if (local_cert_enabled)
{
// cert
{
const std::string& cert_txt = opt.get("cert", 1, Option::MULTILINE);
const std::string ec_txt = opt.cat("extra-certs");
load_cert(cert_txt, ec_txt);
}
// private key
if (!external_pki)
{
const std::string& key_txt = opt.get("key", 1, Option::MULTILINE);
load_private_key(key_txt);
}
}
// DH
if (mode.is_server())
{
const std::string& dh_txt = opt.get("dh", 1, Option::MULTILINE);
load_dh(dh_txt);
}
// relay mode
std::string relay_prefix;
if (lflags & LF_RELAY_MODE)
relay_prefix = "relay-";
// ns-cert-type
ns_cert_type = NSCert::ns_cert_type(opt, relay_prefix);
// parse remote-cert-x options
KUParse::remote_cert_tls(opt, relay_prefix, ku, eku);
KUParse::remote_cert_ku(opt, relay_prefix, ku);
KUParse::remote_cert_eku(opt, relay_prefix, eku);
// parse tls-remote
tls_remote = opt.get_optional(relay_prefix + "tls-remote", 1, 256);
// Parse tls-version-min option.
tls_version_min = TLSVersion::parse_tls_version_min(opt, relay_prefix, maxver());
// parse tls-cert-profile
tls_cert_profile = TLSCertProfile::parse_tls_cert_profile(opt, relay_prefix);
// unsupported cert checkers
{
}
}
#ifdef OPENVPN_JSON_INTERNAL
// The get_string_ref methods require internal JSON and do not work with jsoncpp
virtual SSLConfigAPI::Ptr json_override(const Json::Value& root, const bool load_cert_key) const override
{
static const char title[] = "json_override";
Config::Ptr ret(new Config);
// inherit from self
ret->mode = mode;
ret->dh = dh;
ret->frame = frame;
ret->ssl_debug_level = ssl_debug_level;
ret->flags = flags;
ret->local_cert_enabled = local_cert_enabled;
// ca
{
const std::string& ca_txt = json::get_string_ref(root, "ca", title);
ret->load_ca(ca_txt, true);
}
// CRL
{
const std::string crl_txt = json::get_string_optional(root, "crl_verify", std::string(), title);
if (!crl_txt.empty())
ret->load_crl(crl_txt);
}
// cert/key
if (load_cert_key && local_cert_enabled)
{
bool loaded_cert = false;
// cert/extra_certs
{
const std::string cert_txt = json::get_string_optional(root, "cert", std::string(), title);
if (!cert_txt.empty())
{
const std::string ec_txt = json::get_string_optional(root, "extra_certs", std::string(), title);
ret->load_cert(cert_txt, ec_txt);
loaded_cert = true;
}
else
{
ret->cert = cert;
ret->extra_certs = extra_certs;
}
}
// private key
if (loaded_cert && !external_pki)
{
const std::string& key_txt = json::get_string_ref(root, "key", title);
if (!key_txt.empty())
ret->load_private_key(key_txt);
else
ret->pkey = pkey;
}
}
else
{
// inherit from self
ret->cert = cert;
ret->extra_certs = extra_certs;
ret->pkey = pkey;
}
// ns_cert_type
{
const std::string ct = json::get_string_optional(root, "ns_cert_type", std::string(), title);
if (!ct.empty())
ret->ns_cert_type = NSCert::ns_cert_type(ct);
}
// ku, eku
{
const std::string ct = json::get_string_optional(root, "remote_cert_tls", std::string(), title);
if (!ct.empty())
KUParse::remote_cert_tls(ct, ret->ku, ret->eku);
}
// tls_version_min
{
const std::string tvm = json::get_string_optional(root, "tls_version_min", std::string(), title);
if (!tvm.empty())
ret->tls_version_min = TLSVersion::parse_tls_version_min(tvm, false, maxver());
}
// tls_cert_profile
{
const std::string prof = json::get_string_optional(root, "tls_cert_profile", std::string(), title);
if (!prof.empty())
ret->tls_cert_profile = TLSCertProfile::parse_tls_cert_profile(prof);
}
return ret;
}
#endif
private:
static TLSVersion::Type maxver()
{
// Return maximum TLS version supported by OpenSSL.
// Assume that presence of SSL_OP_NO_TLSvX macro indicates
// that local OpenSSL library implements TLSvX.
#if defined(SSL_OP_NO_TLSv1_3)
return TLSVersion::V1_3;
#elif defined(SSL_OP_NO_TLSv1_2)
return TLSVersion::V1_2;
#elif defined(SSL_OP_NO_TLSv1_1)
return TLSVersion::V1_1;
#else
return TLSVersion::V1_0;
#endif
}
Mode mode;
CertCRLList ca; // from OpenVPN "ca" and "crl-verify" option
OpenSSLPKI::X509 cert; // from OpenVPN "cert" option
OpenSSLPKI::X509List extra_certs; // from OpenVPN "extra-certs" option
OpenSSLPKI::PKey pkey; // private key
OpenSSLPKI::DH dh; // diffie-hellman parameters (only needed in server mode)
ExternalPKIBase* external_pki = nullptr;
TLSSessionTicketBase* session_ticket_handler = nullptr; // server side only
SNI::HandlerBase* sni_handler = nullptr; // server side only
Frame::Ptr frame;
int ssl_debug_level = 0;
unsigned int flags = 0; // defined in sslconsts.hpp
std::string sni_name; // client side only
NSCert::Type ns_cert_type{NSCert::NONE};
std::vector<unsigned int> ku; // if defined, peer cert X509 key usage must match one of these values
std::string eku; // if defined, peer cert X509 extended key usage must match this OID/string
std::string tls_remote;
TLSVersion::Type tls_version_min{TLSVersion::UNDEF}; // minimum TLS version that we will negotiate
TLSCertProfile::Type tls_cert_profile{TLSCertProfile::UNDEF};
X509Track::ConfigSet x509_track_config;
bool local_cert_enabled = true;
bool force_aes_cbc_ciphersuites = false;
bool client_session_tickets = false;
};
// Represents an actual SSL session.
// Normally instantiated by OpenSSLContext::ssl().
class SSL : public SSLAPI
{
friend class OpenSSLContext;
public:
typedef RCPtr<SSL> Ptr;
void start_handshake() override
{
SSL_do_handshake(ssl);
}
ssize_t write_cleartext_unbuffered(const void *data, const size_t size) override
{
const int status = BIO_write(ssl_bio, data, size);
if (status < 0)
{
if (status == -1 && BIO_should_retry(ssl_bio))
return SSLConst::SHOULD_RETRY;
else
{
mark_no_cache();
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::SSL::write_cleartext: BIO_write failed, size=" << size << " status=" << status);
}
}
else
return status;
}
ssize_t read_cleartext(void *data, const size_t capacity) override
{
if (!overflow)
{
const int status = BIO_read(ssl_bio, data, capacity);
if (status < 0)
{
if (status == -1 && BIO_should_retry(ssl_bio))
return SSLConst::SHOULD_RETRY;
else
{
mark_no_cache();
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::SSL::read_cleartext: BIO_read failed, cap=" << capacity << " status=" << status);
}
}
else
return status;
}
else
throw ssl_ciphertext_in_overflow();
}
bool read_cleartext_ready() const override
{
return !bmq_stream::memq_from_bio(ct_in)->empty() || SSL_pending(ssl) > 0;
}
void write_ciphertext(const BufferPtr& buf) override
{
bmq_stream::MemQ* in = bmq_stream::memq_from_bio(ct_in);
if (in->size() < MAX_CIPHERTEXT_IN)
in->write_buf(buf);
else
overflow = true;
}
void write_ciphertext_unbuffered(const unsigned char *data, const size_t size) override
{
bmq_stream::MemQ* in = bmq_stream::memq_from_bio(ct_in);
if (in->size() < MAX_CIPHERTEXT_IN)
in->write(data, size);
else
overflow = true;
}
bool read_ciphertext_ready() const override
{
return !bmq_stream::memq_from_bio(ct_out)->empty();
}
BufferPtr read_ciphertext() override
{
return bmq_stream::memq_from_bio(ct_out)->read_buf();
}
std::string ssl_handshake_details() const override
{
return ssl_handshake_details(ssl);
}
// Return true if we did a full SSL handshake/negotiation.
// Return false for cached, reused, or persisted sessions.
// Also returns false if previously called on this session.
virtual bool did_full_handshake() override
{
if (called_did_full_handshake)
return false;
called_did_full_handshake = true;
return !SSL_session_reused(ssl);
}
const AuthCert::Ptr& auth_cert() const override
{
// Reused sessions don't call the cert verify callbacks,
// so we must use an alternative method to build authcert.
if (authcert && authcert->is_uninitialized())
rebuild_authcert();
return authcert;
}
void mark_no_cache() override
{
sess_cache_key.reset();
}
~SSL()
{
ssl_erase();
}
static void init_static()
{
bmq_stream::init_static();
ssl_data_index = SSL_get_ex_new_index(0, (char *)"OpenSSLContext::SSL", nullptr, nullptr, nullptr);
context_data_index = SSL_get_ex_new_index(0, (char *)"OpenSSLContext", nullptr, nullptr, nullptr);
/*
* We actually override some of the OpenSSL SSLv23 methods here,
* in particular the ssl_pending method. We want ssl_pending
* to return 0 until the SSL negotiation establishes the
* actual method. The default OpenSSL SSLv23 ssl_pending method
* (ssl_undefined_const_function) triggers an OpenSSL error condition
* when calling SSL_pending early which is not what we want.
*
* This depends on SSL23 being a generic method and OpenSSL later
* switching to a spefic TLS method (TLS10method etc..) with
* ssl23_get_client_method that has the proper ssl3_pending pending method.
*
* OpenSSL 1.1.x does not allow hacks like this anymore. So overriding is not
* possible. Fortunately OpenSSL 1.1 also always defines ssl_pending method to
* be ssl3_pending, so this hack is no longer needed.
*/
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ssl23_method_client_ = *SSLv23_client_method();
ssl23_method_client_.ssl_pending = ssl_pending_override;
ssl23_method_server_ = *SSLv23_server_method();
ssl23_method_server_.ssl_pending = ssl_pending_override;
#endif
}
private:
SSL(const OpenSSLContext& ctx, const std::string* hostname, const std::string* cache_key)
{
ssl_clear();
try {
// init SSL objects
ssl = SSL_new(ctx.ctx);
if (!ssl)
throw OpenSSLException("OpenSSLContext::SSL: SSL_new failed");
// release unneeded buffers
SSL_set_mode(ssl, SSL_MODE_RELEASE_BUFFERS);
// verify hostname
if (hostname && !(ctx.config->flags & SSLConst::NO_VERIFY_HOSTNAME))
{
X509_VERIFY_PARAM *param = SSL_get0_param(ssl);
X509_VERIFY_PARAM_set_hostflags(param, 0);
X509_VERIFY_PARAM_set1_host(param, hostname->c_str(), 0);
}
// init BIOs
ssl_bio = BIO_new(BIO_f_ssl());
if (!ssl_bio)
throw OpenSSLException("OpenSSLContext::SSL: BIO_new BIO_f_ssl failed");
ct_in = mem_bio(ctx.config->frame);
ct_out = mem_bio(ctx.config->frame);
// set client/server mode
if (ctx.config->mode.is_server())
{
SSL_set_accept_state(ssl);
authcert.reset(new AuthCert());
if (!ctx.config->x509_track_config.empty())
authcert->x509_track.reset(new X509Track::Set);
}
else if (ctx.config->mode.is_client())
{
if (cache_key && ctx.sess_cache)
{
// see if a cached session already exists for our cache_key
ctx.sess_cache->extract(*cache_key, [this](SSL_SESSION* sess) {
if (!SSL_set_session(ssl, sess))
throw OpenSSLException("SSL_set_session failed");
});
// cache the session before its end-of-life if no errors occur
sess_cache_key.reset(new OpenSSLSessionCache::Key(*cache_key, ctx.sess_cache));
}
SSL_set_connect_state(ssl);
// client-side SNI
if (!ctx.config->sni_name.empty())
{
if (SSL_set_tlsext_host_name(ssl, ctx.config->sni_name.c_str()) != 1)
throw OpenSSLException("OpenSSLContext::SSL: SSL_set_tlsext_host_name failed (sni_name)");
}
else if ((ctx.config->flags & SSLConst::ENABLE_CLIENT_SNI) && hostname)
{
if (SSL_set_tlsext_host_name(ssl, hostname->c_str()) != 1)
throw OpenSSLException("OpenSSLContext::SSL: SSL_set_tlsext_host_name failed (hostname)");
}
}
else
OPENVPN_THROW(ssl_context_error, "OpenSSLContext::SSL: unknown client/server mode");
// effect SSL/BIO linkage
ssl_bio_linkage = true; // after this point, no need to explicitly BIO_free ct_in/ct_out
SSL_set_bio (ssl, ct_in, ct_out);
BIO_set_ssl (ssl_bio, ssl, BIO_NOCLOSE);
if (ssl_data_index < 0)
throw ssl_context_error("OpenSSLContext::SSL: ssl_data_index is uninitialized");
SSL_set_ex_data (ssl, ssl_data_index, this);
set_parent(&ctx);
}
catch (...)
{
ssl_erase();
throw;
}
}
void set_parent(const OpenSSLContext* ctx)
{
if (context_data_index < 0)
throw ssl_context_error("OpenSSLContext::SSL: context_data_index is uninitialized");
SSL_set_ex_data(ssl, context_data_index, (void *)ctx);
}
void rebuild_authcert() const
{
::X509 *cert = SSL_get_peer_certificate(ssl);
if (cert)
{
// save the issuer cert fingerprint
static_assert(sizeof(AuthCert::issuer_fp) == SHA_DIGEST_LENGTH, "size inconsistency");
unsigned int md_len = sizeof(AuthCert::issuer_fp);
X509_digest (cert, EVP_sha1 (), authcert->issuer_fp, &md_len);
// save the Common Name
authcert->cn = x509_get_field(cert, NID_commonName);
// save the leaf cert serial number
const ASN1_INTEGER *ai = X509_get_serialNumber(cert);
authcert->sn = ai ? ASN1_INTEGER_get(ai) : -1;
X509_free (cert);
}
}
// Indicate no data available for our custom SSLv23 method
static int ssl_pending_override(const ::SSL *)
{
return 0;
}
// Print a one line summary of SSL/TLS session handshake.
static std::string ssl_handshake_details (const ::SSL *c_ssl)
{
std::ostringstream os;
::X509 *cert = SSL_get_peer_certificate (c_ssl);
if (cert)
os << "CN=" << x509_get_field(cert, NID_commonName) << ", ";
os << SSL_get_version (c_ssl);
const SSL_CIPHER *ciph = SSL_get_current_cipher (c_ssl);
if (ciph)
os << ", cipher " << SSL_CIPHER_get_version (ciph) << ' ' << SSL_CIPHER_get_name (ciph);
if (cert != nullptr)
{
EVP_PKEY *pkey = X509_get_pubkey (cert);
if (pkey != nullptr)
{
if (EVP_PKEY_id (pkey) == EVP_PKEY_RSA && EVP_PKEY_get0_RSA (pkey) != nullptr && RSA_get0_n(EVP_PKEY_get0_RSA (pkey)) != nullptr)
os << ", " << BN_num_bits (RSA_get0_n(EVP_PKEY_get0_RSA (pkey))) << " bit RSA";
#ifndef OPENSSL_NO_DSA
else if (EVP_PKEY_id (pkey) == EVP_PKEY_DSA && EVP_PKEY_get0_DSA (pkey) != nullptr && DSA_get0_p(EVP_PKEY_get0_DSA (pkey))!= nullptr)
os << ", " << BN_num_bits (DSA_get0_p(EVP_PKEY_get0_DSA (pkey))) << " bit DSA";
#endif
EVP_PKEY_free (pkey);
}
X509_free (cert);
}
// This has been changed in upstream SSL to have a const
// parameter, so we cast away const for older versions compatibility
// (Upstream commit: c04b66b18d1a90f0c6326858e4b8367be5444582)
if (SSL_session_reused(const_cast<::SSL *>(c_ssl)))
os << " [REUSED]";
return os.str();
}
void ssl_clear()
{
ssl_bio_linkage = false;
ssl = nullptr;
ssl_bio = nullptr;
ct_in = nullptr;
ct_out = nullptr;
overflow = false;
called_did_full_handshake = false;
sess_cache_key.reset();
}
void ssl_erase()
{
if (!ssl_bio_linkage)
{
if (ct_in)
BIO_free(ct_in);
if (ct_out)
BIO_free(ct_out);
}
if (ssl_bio)
BIO_free_all(ssl_bio);
if (ssl)
{
if (sess_cache_key)
{
SSL_set_shutdown(ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
sess_cache_key->commit(SSL_get1_session(ssl));
}
SSL_free(ssl);
}
openssl_clear_error_stack();
ssl_clear();
}
static BIO* mem_bio(const Frame::Ptr& frame)
{
BIO *bio = BIO_new(bmq_stream::BIO_s_memq());
if (!bio)
throw OpenSSLException("OpenSSLContext::SSL: BIO_new failed on bmq_stream");
bmq_stream::memq_from_bio(bio)->set_frame(frame);
return bio;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
/*
* Return modified OpenSSL SSLv23 methods,
* as configured in init_static().
*/
static const SSL_METHOD* tls_method_client()
{
return &ssl23_method_client_;
}
static const SSL_METHOD* tls_method_server()
{
return &ssl23_method_server_;
}
#else
static const SSL_METHOD* tls_method_client ()
{
return TLS_client_method ();
}
static const SSL_METHOD* tls_method_server ()
{
return TLS_server_method ();
}
#endif
::SSL *ssl; // OpenSSL SSL object
BIO *ssl_bio; // read/write cleartext from here
BIO *ct_in; // write ciphertext to here
BIO *ct_out; // read ciphertext from here
AuthCert::Ptr authcert;
OpenSSLSessionCache::Key::UPtr sess_cache_key; // client-side only
OpenSSLContext::Ptr sni_ctx;
bool ssl_bio_linkage;
bool overflow;
bool called_did_full_handshake;
// Helps us to store pointer to self in ::SSL object
static int ssl_data_index;
static int context_data_index;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
// Modified SSLv23 methods
static SSL_METHOD ssl23_method_client_;
static SSL_METHOD ssl23_method_server_;
#endif
};
private:
class ExternalPKIImpl {
public:
ExternalPKIImpl(SSL_CTX* ssl_ctx, ::X509* cert, ExternalPKIBase* external_pki_arg)
: external_pki(external_pki_arg), n_errors(0)
{
RSA *rsa = nullptr;
RSA *pub_rsa = nullptr;
RSA_METHOD *rsa_meth = nullptr;
const char *errtext = "";
/* allocate custom RSA method object */
rsa_meth = RSA_meth_new ("OpenSSLContext::ExternalPKIImpl private key RSA Method", RSA_METHOD_FLAG_NO_CHECK);
RSA_meth_set_pub_enc (rsa_meth, rsa_pub_enc);
RSA_meth_set_pub_dec (rsa_meth, rsa_pub_dec);
RSA_meth_set_priv_enc (rsa_meth, rsa_priv_enc);
RSA_meth_set_priv_dec (rsa_meth, rsa_priv_dec);
RSA_meth_set_init (rsa_meth, nullptr);
RSA_meth_set_finish (rsa_meth, rsa_finish);
RSA_meth_set0_app_data (rsa_meth, this);
/* allocate RSA object */
rsa = RSA_new();
if (rsa == nullptr)
{
SSLerr(SSL_F_SSL_USE_PRIVATEKEY, ERR_R_MALLOC_FAILURE);
errtext = "RSA_new";
goto err;
}
/* get the public key */
if (X509_get0_pubkey(cert) == nullptr) /* nullptr before SSL_CTX_use_certificate() is called */
{
errtext = "pkey is NULL";
goto err;
}
if (EVP_PKEY_id (X509_get0_pubkey(cert)) != EVP_PKEY_RSA )
{
errtext = "pkey is not RSA";
goto err;
}
pub_rsa = EVP_PKEY_get0_RSA (X509_get0_pubkey(cert));
/* initialize RSA object */
rsa = RSA_new ();
/* only set e and n as d (private key) is outside our control */
RSA_set0_key(rsa, BN_dup(RSA_get0_n(pub_rsa)), BN_dup(RSA_get0_e(pub_rsa)), nullptr);
RSA_set_flags (rsa, RSA_FLAG_EXT_PKEY);
if (!RSA_set_method(rsa, rsa_meth))
{
errtext = "RSA_set_method";
goto err;
}
/* bind our custom RSA object to ssl_ctx */
if (!SSL_CTX_use_RSAPrivateKey(ssl_ctx, rsa))
{
errtext = "SSL_CTX_use_RSAPrivateKey";
goto err;
}
RSA_free(rsa); /* doesn't necessarily free, just decrements refcount */
return;
err:
if (rsa)
RSA_free(rsa);
else
{
if (rsa_meth)
RSA_meth_free (rsa_meth);
}
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::ExternalPKIImpl: " << errtext);
}
unsigned int get_n_errors() const { return n_errors; }
private:
OPENVPN_EXCEPTION(openssl_external_pki);
/* called at RSA_free */
static int rsa_finish(RSA *rsa)
{
RSA_meth_free (const_cast<RSA_METHOD*>(RSA_get_method (rsa)));
return 1;
}
/* sign arbitrary data */
static int rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
ExternalPKIImpl* self = (ExternalPKIImpl*)(RSA_meth_get0_app_data (RSA_get_method(rsa)));
try {
if (padding != RSA_PKCS1_PADDING && padding != RSA_NO_PADDING)
{
RSAerr (RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
throw ssl_external_pki("OpenSSL: bad padding type");
}
std::string padding_algo;
if (padding == RSA_PKCS1_PADDING)
{
padding_algo = "RSA_PKCS1_PADDING";
}
else if (padding == RSA_NO_PADDING)
{
padding_algo = "RSA_NO_PADDING";
}
/* convert 'from' to base64 */
ConstBuffer from_buf(from, flen, true);
const std::string from_b64 = base64->encode(from_buf);
/* get signature */
std::string sig_b64;
const bool status = self->external_pki->sign(from_b64, sig_b64, padding_algo);
if (!status)
throw ssl_external_pki("OpenSSL: could not obtain signature");
/* decode base64 signature to binary */
const int len = RSA_size(rsa);
Buffer sig(to, len, false);
base64->decode(sig, sig_b64);
/* verify length */
if (sig.size() != len)
throw ssl_external_pki("OpenSSL: incorrect signature length");
/* return length of signature */
return len;
}
catch (const std::exception& e)
{
OPENVPN_LOG("OpenSSLContext::ExternalPKIImpl::rsa_priv_enc exception: " << e.what());
++self->n_errors;
return -1;
}
}
static void not_implemented(RSA *rsa)
{
ExternalPKIImpl* self = (ExternalPKIImpl*)(RSA_meth_get0_app_data (RSA_get_method (rsa)));
++self->n_errors;
}
/* encrypt */
static int rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
not_implemented(rsa);
return -1;
}
/* verify arbitrary data */
static int
rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
not_implemented(rsa);
return -1;
}
/* decrypt */
static int
rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
not_implemented(rsa);
return -1;
}
ExternalPKIBase* external_pki;
unsigned int n_errors;
};
/////// start of main class implementation
OpenSSLContext(Config* config_arg)
: config(config_arg)
{
try
{
// Create new SSL_CTX for server or client mode
if (config->mode.is_server())
{
ctx = SSL_CTX_new(SSL::tls_method_server());
if (ctx == nullptr)
throw OpenSSLException("OpenSSLContext: SSL_CTX_new failed for server method");
// Set DH object
if (!config->dh.defined())
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: DH not defined");
if (!SSL_CTX_set_tmp_dh(ctx, config->dh.obj()))
throw OpenSSLException("OpenSSLContext: SSL_CTX_set_tmp_dh failed");
if (config->flags & SSLConst::SERVER_TO_SERVER)
SSL_CTX_set_purpose(ctx, X509_PURPOSE_SSL_SERVER);
// server-side SNI
if (config->sni_handler)
{
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
#define OPENSSL_SERVER_SNI
SSL_CTX_set_client_hello_cb(ctx, client_hello_callback, nullptr);
#else
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: server-side SNI requires OpenSSL 1.1 or higher");
#endif
}
}
else if (config->mode.is_client())
{
ctx = SSL_CTX_new(SSL::tls_method_client());
if (ctx == nullptr)
throw OpenSSLException("OpenSSLContext: SSL_CTX_new failed for client method");
}
else
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: unknown config->mode");
// Set SSL options
if (!(config->flags & SSLConst::NO_VERIFY_PEER))
{
int vf = SSL_VERIFY_PEER;
if (!(config->flags & SSLConst::PEER_CERT_OPTIONAL))
vf |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
SSL_CTX_set_verify(ctx, vf,
config->mode.is_client() ? verify_callback_client : verify_callback_server);
SSL_CTX_set_verify_depth(ctx, 16);
}
/* Disable SSLv2 and SSLv3, might be a noop but does not hurt */
long sslopt = SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE | SSL_OP_NO_COMPRESSION | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
if (config->mode.is_server())
{
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
if (config->session_ticket_handler)
{
const std::string sess_id_context = config->session_ticket_handler->session_id_context();
if (!SSL_CTX_set_session_id_context(ctx, (unsigned char *)sess_id_context.c_str(), sess_id_context.length()))
throw OpenSSLException("OpenSSLContext: SSL_CTX_set_session_id_context failed");
if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, tls_ticket_key_callback))
throw OpenSSLException("OpenSSLContext: SSL_CTX_set_tlsext_ticket_key_cb failed");
}
else
sslopt |= SSL_OP_NO_TICKET;
// send a client CA list to the client
if (config->flags & SSLConst::SEND_CLIENT_CA_LIST)
{
for (const auto& e : config->ca.certs)
{
if (SSL_CTX_add_client_CA(ctx, e.obj()) != 1)
throw OpenSSLException("OpenSSLContext: SSL_CTX_add_client_CA failed");
}
}
}
else
{
if (config->client_session_tickets)
{
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT);
sess_cache.reset(new OpenSSLSessionCache);
}
else
{
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
sslopt |= SSL_OP_NO_TICKET;
}
}
/* mbed TLS also ignores tls version when force aes cbc cipher suites is on */
if (!config->force_aes_cbc_ciphersuites)
{
if (config->tls_version_min > TLSVersion::V1_0)
sslopt |= SSL_OP_NO_TLSv1;
# ifdef SSL_OP_NO_TLSv1_1
if (config->tls_version_min > TLSVersion::V1_1)
sslopt |= SSL_OP_NO_TLSv1_1;
# endif
# ifdef SSL_OP_NO_TLSv1_2
if (config->tls_version_min > TLSVersion::V1_2)
sslopt |= SSL_OP_NO_TLSv1_2;
# endif
# ifdef SSL_OP_NO_TLSv1_3
if (config->tls_version_min > TLSVersion::V1_3)
sslopt |= SSL_OP_NO_TLSv1_3;
# endif
}
SSL_CTX_set_options(ctx, sslopt);
if (config->force_aes_cbc_ciphersuites)
{
if (!SSL_CTX_set_cipher_list(ctx, "DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA"))
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: SSL_CTX_set_cipher_list failed for force_aes_cbc_ciphersuites");
}
else
{
if (!SSL_CTX_set_cipher_list(ctx,
/* default list as a basis */
"DEFAULT"
/* Disable export ciphers, low and medium */
":!EXP:!LOW:!MEDIUM"
/* Disable static (EC)DH keys (no forward secrecy) */
":!kDH:!kECDH"
/* Disable DSA private keys */
":!DSS"
/* Disable RC4 cipher */
":!RC4"
/* Disable MD5 */
":!MD5"
/* Disable unsupported TLS modes */
":!PSK:!SRP:!kRSA"
/* Disable SSLv2 cipher suites*/
":!SSLv2"
))
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: SSL_CTX_set_cipher_list failed");
#if OPENSSL_VERSION_NUMBER >= 0x10002000L && OPENSSL_VERSION_NUMBER < 0x10100000L
SSL_CTX_set_ecdh_auto(ctx, 1); // this method becomes a no-op in OpenSSL 1.1
#endif
}
/* HAVE_SSL_CTX_SET_SECURITY_LEVEL exists from OpenSSL-1.1.0 up */
#ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
switch(TLSCertProfile::default_if_undef(config->tls_cert_profile))
{
case TLSCertProfile::UNDEF:
OPENVPN_THROW(ssl_context_error,
"OpenSSLContext: undefined tls-cert-profile");
break;
#ifdef OPENVPN_USE_TLS_MD5
case TLSCertProfile::INSECURE:
SSL_CTX_set_security_level(ctx, 0);
break;
#endif
case TLSCertProfile::LEGACY:
SSL_CTX_set_security_level(ctx, 1);
break;
case TLSCertProfile::PREFERRED:
SSL_CTX_set_security_level(ctx, 2);
break;
case TLSCertProfile::SUITEB:
SSL_CTX_set_security_level(ctx, 3);
break;
default:
OPENVPN_THROW(ssl_context_error,
"OpenSSLContext: unexpected tls-cert-profile value");
break;
}
#else
// when OpenSSL does not CertProfile support we force the user to set 'legacy'
if (TLSCertProfile::default_if_undef(config->tls_cert_profile) != TLSCertProfile::LEGACY)
{
OPENVPN_THROW(ssl_context_error,
"OpenSSLContext: tls-cert-profile not supported by this OpenSSL build. Use 'legacy' instead");
}
#endif
if (config->local_cert_enabled)
{
// Set certificate
if (!config->cert.defined())
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: cert not defined");
if (SSL_CTX_use_certificate(ctx, config->cert.obj()) != 1)
throw OpenSSLException("OpenSSLContext: SSL_CTX_use_certificate failed");
// Set private key
if (config->external_pki)
{
epki = new ExternalPKIImpl(ctx, config->cert.obj(), config->external_pki);
}
else
{
if (!config->pkey.defined())
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: private key not defined");
if (SSL_CTX_use_PrivateKey(ctx, config->pkey.obj()) != 1)
throw OpenSSLException("OpenSSLContext: SSL_CTX_use_PrivateKey failed");
// Check cert/private key compatibility
if (!SSL_CTX_check_private_key(ctx))
throw OpenSSLException("OpenSSLContext: private key does not match the certificate");
}
// Set extra certificates that are part of our own certificate
// chain but shouldn't be included in the verify chain.
if (config->extra_certs.defined())
{
for (const auto& e : config->extra_certs)
{
if (SSL_CTX_add_extra_chain_cert(ctx, e.obj_dup()) != 1)
throw OpenSSLException("OpenSSLContext: SSL_CTX_add_extra_chain_cert failed");
}
}
}
// Set CAs/CRLs
if (config->ca.certs.defined())
update_trust(config->ca);
else if (!(config->flags & SSLConst::NO_VERIFY_PEER))
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: CA not defined");
// Show handshake debugging info
if (config->ssl_debug_level)
SSL_CTX_set_info_callback (ctx, info_callback);
}
catch (...)
{
erase();
throw;
}
}
public:
// create a new SSL instance
virtual SSLAPI::Ptr ssl()
{
return SSL::Ptr(new SSL(*this, nullptr, nullptr));
}
// like ssl() above but verify hostname against cert CommonName and/or SubjectAltName
virtual SSLAPI::Ptr ssl(const std::string* hostname, const std::string* cache_key)
{
return SSL::Ptr(new SSL(*this, hostname, cache_key));
}
void update_trust(const CertCRLList& cc)
{
OpenSSLPKI::X509Store store(cc);
SSL_CTX_set_cert_store(ctx, store.release());
}
~OpenSSLContext()
{
erase();
}
virtual const Mode& mode() const
{
return config->mode;
}
private:
// ns-cert-type verification
bool ns_cert_type_defined() const
{
return config->ns_cert_type != NSCert::NONE;
}
bool verify_ns_cert_type(::X509* cert) const
{
if (config->ns_cert_type == NSCert::SERVER)
return X509_check_purpose (cert, X509_PURPOSE_SSL_SERVER, 0);
else if (config->ns_cert_type == NSCert::CLIENT)
return X509_check_purpose (cert, X509_PURPOSE_SSL_CLIENT, 0);
else
return true;
}
// remote-cert-ku verification
bool x509_cert_ku_defined() const
{
return config->ku.size() > 0;
}
bool verify_x509_cert_ku(::X509 *cert) const
{
bool found = false;
ASN1_BIT_STRING *ku = (ASN1_BIT_STRING *)X509_get_ext_d2i(cert, NID_key_usage, nullptr, nullptr);
if (ku)
{
// Extract key usage bits
unsigned int nku = 0;
{
for (int i = 0; i < 8; i++)
{
if (ASN1_BIT_STRING_get_bit(ku, i))
nku |= 1 << (7 - i);
}
}
// Fixup if no LSB bits
if ((nku & 0xff) == 0)
nku >>= 8;
// Validating certificate key usage
{
for (std::vector<unsigned int>::const_iterator i = config->ku.begin(); i != config->ku.end(); ++i)
{
if (nku == *i)
{
found = true;
break;
}
}
}
ASN1_BIT_STRING_free(ku);
}
return found;
}
// remote-cert-eku verification
bool x509_cert_eku_defined() const
{
return !config->eku.empty();
}
bool verify_x509_cert_eku(::X509 *cert) const
{
bool found = false;
EXTENDED_KEY_USAGE *eku = (EXTENDED_KEY_USAGE *)X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr);
if (eku)
{
// Validating certificate extended key usage
for (int i = 0; !found && i < sk_ASN1_OBJECT_num(eku); i++)
{
ASN1_OBJECT *oid = sk_ASN1_OBJECT_value(eku, i);
char oid_str[256];
if (!found && OBJ_obj2txt(oid_str, sizeof(oid_str), oid, 0) != -1)
{
// Compare EKU against string
if (config->eku == oid_str)
found = true;
}
if (!found && OBJ_obj2txt(oid_str, sizeof(oid_str), oid, 1) != -1)
{
// Compare EKU against OID
if (config->eku == oid_str)
found = true;
}
}
sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
}
return found;
}
static std::string x509_get_subject(::X509 *cert)
{
unique_ptr_del<char> subject(X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0),
[](char* p) { OPENSSL_free(p); });
if (subject)
return std::string(subject.get());
else
return std::string("");
}
static std::string x509_get_field(::X509 *cert, const int nid)
{
static const char nullc = '\0';
std::string ret;
X509_NAME *x509_name = X509_get_subject_name(cert);
int i = X509_NAME_get_index_by_NID(x509_name, nid, -1);
if (i >= 0)
{
X509_NAME_ENTRY *ent = X509_NAME_get_entry(x509_name, i);
if (ent)
{
ASN1_STRING *val = X509_NAME_ENTRY_get_data(ent);
unsigned char *buf;
buf = (unsigned char *)1; // bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround
const int len = ASN1_STRING_to_UTF8(&buf, val);
if (len > 0)
{
if (std::strlen((char *)buf) == len)
ret = (char *)buf;
OPENSSL_free(buf);
}
}
}
else
{
i = X509_get_ext_by_NID(cert, nid, -1);
if (i >= 0)
{
X509_EXTENSION *ext = X509_get_ext(cert, i);
if (ext)
{
BIO *bio = BIO_new(BIO_s_mem());
if (bio)
{
if (X509V3_EXT_print(bio, ext, 0, 0))
{
if (BIO_write(bio, &nullc, 1) == 1)
{
char *str;
const long len = BIO_get_mem_data(bio, &str);
if (std::strlen(str) == len)
ret = str;
}
}
BIO_free(bio);
}
}
}
}
return ret;
}
static std::string x509_get_serial(::X509 *cert)
{
ASN1_INTEGER *asn1_i;
BIGNUM *bignum;
char *openssl_serial;
asn1_i = X509_get_serialNumber(cert);
bignum = ASN1_INTEGER_to_BN(asn1_i, NULL);
openssl_serial = BN_bn2dec(bignum);
const std::string ret = openssl_serial;
BN_free(bignum);
OPENSSL_free(openssl_serial);
return ret;
}
static std::string x509_get_serial_hex(::X509 *cert)
{
const ASN1_INTEGER *asn1_i = X509_get_serialNumber(cert);
return render_hex_sep(asn1_i->data, asn1_i->length, ':', false);
}
static void x509_track_extract_nid(const X509Track::Type xt_type,
const int nid,
::X509 *cert,
const int depth,
X509Track::Set& xts)
{
const std::string value = x509_get_field(cert, nid);
if (!value.empty())
xts.emplace_back(xt_type, depth, x509_get_field(cert, nid));
}
static void x509_track_extract_from_cert(::X509 *cert,
const int depth,
const X509Track::ConfigSet& cs,
X509Track::Set& xts)
{
for (auto &c : cs)
{
if (c.depth_match(depth))
{
switch (c.type)
{
case X509Track::SERIAL:
xts.emplace_back(X509Track::SERIAL,
depth,
x509_get_serial(cert));
break;
case X509Track::SERIAL_HEX:
xts.emplace_back(X509Track::SERIAL_HEX,
depth,
x509_get_serial_hex(cert));
break;
case X509Track::SHA1:
{
unsigned char buf[EVP_MAX_MD_SIZE];
unsigned int len = EVP_MAX_MD_SIZE;
X509_digest (cert, EVP_sha1 (), buf, &len);
xts.emplace_back (X509Track::SHA1,
depth,
render_hex_sep (buf, len, ':', true));
}
break;
case X509Track::CN:
x509_track_extract_nid(X509Track::CN, NID_commonName, cert, depth, xts);
break;
case X509Track::C:
x509_track_extract_nid(X509Track::C, NID_countryName, cert, depth, xts);
break;
case X509Track::L:
x509_track_extract_nid(X509Track::L, NID_localityName, cert, depth, xts);
break;
case X509Track::ST:
x509_track_extract_nid(X509Track::ST, NID_stateOrProvinceName, cert, depth, xts);
break;
case X509Track::O:
x509_track_extract_nid(X509Track::O, NID_organizationName, cert, depth, xts);
break;
case X509Track::OU:
x509_track_extract_nid(X509Track::OU, NID_organizationalUnitName, cert, depth, xts);
break;
case X509Track::EMAIL:
x509_track_extract_nid(X509Track::EMAIL, NID_pkcs9_emailAddress, cert, depth, xts);
break;
default:
break;
}
}
}
}
static std::string cert_status_line(int preverify_ok,
int depth,
int err,
const std::string& subject)
{
std::string ret;
ret.reserve(128);
ret = "VERIFY";
if (preverify_ok)
ret += " OK";
else
ret += " FAIL";
ret += ": depth=";
ret += openvpn::to_string(depth);
ret += ", ";
if (!subject.empty())
ret += subject;
else
ret += "NO_SUBJECT";
if (!preverify_ok)
{
ret += " [";
ret += X509_verify_cert_error_string(err);
ret += ']';
}
return ret;
}
static AuthCert::Fail::Type cert_fail_code(const int openssl_err)
{
// NOTE: this method should never return OK
switch (openssl_err)
{
case X509_V_ERR_CERT_HAS_EXPIRED:
return AuthCert::Fail::EXPIRED;
default:
return AuthCert::Fail::CERT_FAIL;
}
}
static int verify_callback_client(int preverify_ok, X509_STORE_CTX *ctx)
{
// get the OpenSSL SSL object
::SSL* ssl = (::SSL*) X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
// get OpenSSLContext
const OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data (ssl, SSL::context_data_index);
// get depth
const int depth = X509_STORE_CTX_get_error_depth(ctx);
// get current certificate
X509* current_cert = X509_STORE_CTX_get_current_cert (ctx);
// log subject
const std::string subject = x509_get_subject(current_cert);
if (self->config->flags & SSLConst::LOG_VERIFY_STATUS)
OPENVPN_LOG_SSL(cert_status_line(preverify_ok, depth, X509_STORE_CTX_get_error(ctx), subject));
// leaf-cert verification
if (depth == 0)
{
// verify ns-cert-type
if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad ns-cert-type in leaf certificate");
preverify_ok = false;
}
// verify X509 key usage
if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 key usage in leaf certificate");
preverify_ok = false;
}
// verify X509 extended key usage
if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 extended key usage in leaf certificate");
preverify_ok = false;
}
// verify tls-remote
if (!self->config->tls_remote.empty())
{
const std::string subj = TLSRemote::sanitize_x509_name(subject);
const std::string common_name = TLSRemote::sanitize_common_name(x509_get_field(current_cert, NID_commonName));
TLSRemote::log(self->config->tls_remote, subj, common_name);
if (!TLSRemote::test(self->config->tls_remote, subj, common_name))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- tls-remote match failed");
preverify_ok = false;
}
}
}
return preverify_ok;
}
static int verify_callback_server(int preverify_ok, X509_STORE_CTX *ctx)
{
// get the OpenSSL SSL object
::SSL* ssl = (::SSL*) X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
// get OpenSSLContext
const OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data (ssl, SSL::context_data_index);
// get OpenSSLContext::SSL
SSL* self_ssl = (SSL *) SSL_get_ex_data (ssl, SSL::ssl_data_index);
// get error code
const int err = X509_STORE_CTX_get_error(ctx);
// get depth
const int depth = X509_STORE_CTX_get_error_depth(ctx);
// get current certificate
X509* current_cert = X509_STORE_CTX_get_current_cert (ctx);
// log subject
if (self->config->flags & SSLConst::LOG_VERIFY_STATUS)
OPENVPN_LOG_SSL(cert_status_line(preverify_ok, depth, err, x509_get_subject(current_cert)));
// record cert error in authcert
if (!preverify_ok && self_ssl->authcert)
self_ssl->authcert->add_fail(depth, cert_fail_code(err), X509_verify_cert_error_string(err));
if (depth == 1) // issuer cert
{
// save the issuer cert fingerprint
if (self_ssl->authcert)
{
static_assert(sizeof(AuthCert::issuer_fp) == SHA_DIGEST_LENGTH, "size inconsistency");
unsigned int digest_len = sizeof(AuthCert::issuer_fp);
if (!X509_digest (current_cert, EVP_sha1 (), self_ssl->authcert->issuer_fp, &digest_len))
preverify_ok = false;
}
}
else if (depth == 0) // leaf cert
{
// verify ns-cert-type
if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad ns-cert-type in leaf certificate");
if (self_ssl->authcert)
self_ssl->authcert->add_fail(depth, AuthCert::Fail::BAD_CERT_TYPE, "bad ns-cert-type in leaf certificate");
preverify_ok = false;
}
// verify X509 key usage
if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 key usage in leaf certificate");
if (self_ssl->authcert)
self_ssl->authcert->add_fail(depth, AuthCert::Fail::BAD_CERT_TYPE, "bad X509 key usage in leaf certificate");
preverify_ok = false;
}
// verify X509 extended key usage
if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 extended key usage in leaf certificate");
if (self_ssl->authcert)
self_ssl->authcert->add_fail(depth, AuthCert::Fail::BAD_CERT_TYPE, "bad X509 extended key usage in leaf certificate");
preverify_ok = false;
}
if (self_ssl->authcert)
{
// save the Common Name
self_ssl->authcert->cn = x509_get_field(current_cert, NID_commonName);
// save the leaf cert serial number
const ASN1_INTEGER *ai = X509_get_serialNumber(current_cert);
self_ssl->authcert->sn = ai ? ASN1_INTEGER_get(ai) : -1;
}
}
// x509-track enabled?
if (self_ssl->authcert && self_ssl->authcert->x509_track)
x509_track_extract_from_cert(current_cert,
depth,
self->config->x509_track_config,
*self_ssl->authcert->x509_track);
return preverify_ok || self->deferred_cert_verify_failsafe(*self_ssl);
}
// Print debugging information on SSL/TLS session negotiation.
static void info_callback (const ::SSL *s, int where, int ret)
{
if (where & SSL_CB_LOOP)
{
OPENVPN_LOG_SSL("SSL state (" << (where & SSL_ST_CONNECT ? "connect" : where & SSL_ST_ACCEPT ? "accept" : "undefined") << "): " << SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT)
{
OPENVPN_LOG_SSL("SSL alert (" << (where & SSL_CB_READ ? "read" : "write") << "): " << SSL_alert_type_string_long(ret) << ": " << SSL_alert_desc_string_long(ret));
}
}
static int tls_ticket_key_callback(::SSL *ssl,
unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH],
::EVP_CIPHER_CTX *ctx,
::HMAC_CTX *hctx,
int enc)
{
// get OpenSSLContext
const OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data (ssl, SSL::context_data_index);
if (!self)
return -1;
// get user-defined session ticket handler
TLSSessionTicketBase* t = self->config->session_ticket_handler;
if (!t)
return -1;
if (enc)
{
// create new ticket
TLSSessionTicketBase::Name name;
TLSSessionTicketBase::Key key;
switch (t->create_session_ticket_key(name, key))
{
case TLSSessionTicketBase::NO_TICKET:
case TLSSessionTicketBase::TICKET_EXPIRING: // doesn't really make sense for enc==1?
// NOTE: OpenSSL may segfault on a zero return.
// This appears to be fixed by:
// commit dbdb96617cce2bd4356d57f53ecc327d0e31f2ad
// Author: Todd Short <tshort@akamai.com>
// Date: Thu May 12 18:16:52 2016 -0400
// Fix session ticket and SNI
//OPENVPN_LOG("tls_ticket_key_callback: create: no ticket or expiring ticket");
#if OPENSSL_VERSION_NUMBER < 0x1000212fL // 1.0.2r
if (!randomize_name_key(name, key))
return -1;
// fallthrough
#else
return 0;
#endif
case TLSSessionTicketBase::TICKET_AVAILABLE:
if (!RAND_bytes(iv, EVP_MAX_IV_LENGTH))
return -1;
if (!tls_ticket_init_cipher_hmac(key, iv, ctx, hctx, enc))
return -1;
static_assert(TLSSessionTicketBase::Name::SIZE == 16, "unexpected name size");
std::memcpy(key_name, name.value_, TLSSessionTicketBase::Name::SIZE);
//OPENVPN_LOG("tls_ticket_key_callback: created ticket");
return 1;
default:
//OPENVPN_LOG("tls_ticket_key_callback: create: bad ticket");
return -1;
}
}
else
{
// lookup existing ticket
static_assert(TLSSessionTicketBase::Name::SIZE == 16, "unexpected name size");
const TLSSessionTicketBase::Name name(key_name);
TLSSessionTicketBase::Key key;
switch (t->lookup_session_ticket_key(name, key))
{
case TLSSessionTicketBase::TICKET_AVAILABLE:
if (!tls_ticket_init_cipher_hmac(key, iv, ctx, hctx, enc))
return -1;
//OPENVPN_LOG("tls_ticket_key_callback: found ticket");
return 1;
case TLSSessionTicketBase::TICKET_EXPIRING:
if (!tls_ticket_init_cipher_hmac(key, iv, ctx, hctx, enc))
return -1;
//OPENVPN_LOG("tls_ticket_key_callback: expiring ticket");
return 2;
case TLSSessionTicketBase::NO_TICKET:
//OPENVPN_LOG("tls_ticket_key_callback: lookup: no ticket");
return 0;
default:
//OPENVPN_LOG("tls_ticket_key_callback: lookup: bad ticket");
return -1;
}
}
}
static bool tls_ticket_init_cipher_hmac(const TLSSessionTicketBase::Key& key,
unsigned char iv[EVP_MAX_IV_LENGTH],
::EVP_CIPHER_CTX *ctx,
::HMAC_CTX *hctx,
const int enc)
{
static_assert(TLSSessionTicketBase::Key::CIPHER_KEY_SIZE == 32, "unexpected cipher key size");
if (!EVP_CipherInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key.cipher_value_, iv, enc))
return false;
if (!HMAC_Init_ex(hctx, key.hmac_value_, TLSSessionTicketBase::Key::HMAC_KEY_SIZE, EVP_sha256(), nullptr))
return false;
return true;
}
static bool randomize_name_key(TLSSessionTicketBase::Name& name,
TLSSessionTicketBase::Key& key)
{
if (!RAND_bytes(name.value_, TLSSessionTicketBase::Name::SIZE))
return false;
if (!RAND_bytes(key.cipher_value_, TLSSessionTicketBase::Key::CIPHER_KEY_SIZE))
return false;
if (!RAND_bytes(key.hmac_value_, TLSSessionTicketBase::Key::HMAC_KEY_SIZE))
return false;
return true;
}
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
static int client_hello_callback(::SSL *s, int *al, void *)
{
std::string sni_name;
// get OpenSSLContext
OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data(s, SSL::context_data_index);
// get OpenSSLContext::SSL
SSL* self_ssl = (SSL *) SSL_get_ex_data(s, SSL::ssl_data_index);
try {
// get the SNI from the client hello
sni_name = client_hello_get_sni(s);
// process the SNI name, if provided
if (!sni_name.empty())
{
// save the SNI name in authcert
if (self_ssl->authcert)
self_ssl->authcert->sni = sni_name;
// ignore the SNI if no handler was provided
if (self->config->sni_handler)
{
// get an alternative SSLFactoryAPI from the sni_handler
SSLFactoryAPI::Ptr fapi;
try {
SNI::Metadata::UPtr sm;
fapi = self->config->sni_handler->sni_hello(sni_name, sm, self->config);
if (self_ssl->authcert)
self_ssl->authcert->sni_metadata = std::move(sm);
}
catch (const std::exception& e)
{
OPENVPN_LOG("SNI HANDLER ERROR: " << e.what());
return sni_error(e.what(), SSL_AD_INTERNAL_ERROR, self, self_ssl, al);
}
if (!fapi)
return sni_error("SNI name not found", SSL_AD_UNRECOGNIZED_NAME, self, self_ssl, al);
// make sure that returned SSLFactoryAPI is an OpenSSLContext
self_ssl->sni_ctx = fapi.dynamic_pointer_cast<OpenSSLContext>();
if (!self_ssl->sni_ctx)
throw Exception("sni_handler returned wrong kind of SSLFactoryAPI");
// don't modify SSL CTX if the returned SSLFactoryAPI is ourself
if (fapi.get() != self)
{
SSL_set_SSL_CTX(s, self_ssl->sni_ctx->ctx);
self_ssl->set_parent(self_ssl->sni_ctx.get());
}
}
}
return SSL_CLIENT_HELLO_SUCCESS;
}
catch (const std::exception& e)
{
OPENVPN_LOG("SNI exception in OpenSSLContext, SNI=" << sni_name << " : " << e.what());
*al = SSL_AD_INTERNAL_ERROR;
return SSL_CLIENT_HELLO_ERROR;
}
}
static int sni_error(std::string err,
const int ssl_ad_error,
OpenSSLContext* self,
SSL* self_ssl,
int* al)
{
if (self_ssl->authcert)
self_ssl->authcert->add_fail(0, AuthCert::Fail::SNI_ERROR, std::move(err));
if (self->deferred_cert_verify_failsafe(*self_ssl))
return SSL_CLIENT_HELLO_SUCCESS;
*al = ssl_ad_error;
return SSL_CLIENT_HELLO_ERROR;
}
static size_t sni_get_len(ConstBuffer& buf)
{
size_t ret = buf.pop_front() << 8;
ret += buf.pop_front();
return ret;
}
static std::string client_hello_get_sni(::SSL* s)
{
const unsigned char *p;
size_t remaining;
if (!SSL_client_hello_get0_ext(s, TLSEXT_TYPE_server_name, &p, &remaining))
return std::string();
// For safety, map a ConstBuffer onto returned OpenSSL TLSEXT_TYPE_server_name data.
ConstBuffer buf(p, remaining, true);
// Extract the length of the supplied list of names,
// and check that it matches size of remaining data
// in buf.
{
const size_t len = sni_get_len(buf);
if (len != buf.size())
throw Exception("bad name list size");
}
// Next byte must be TLSEXT_NAMETYPE_host_name.
if (buf.pop_front() != TLSEXT_NAMETYPE_host_name)
throw Exception("expecting TLSEXT_NAMETYPE_host_name");
// Now try to extract the SNI name.
{
const size_t len = sni_get_len(buf);
if (len > buf.size())
throw Exception("bad name size");
if (!Unicode::is_valid_utf8_uchar_buf(buf.c_data(), len, 1024 | Unicode::UTF8_NO_CTRL))
throw Exception("invalid UTF-8");
return std::string((const char *)buf.c_data(), len);
}
}
#endif
// Return true if we should continue with authentication
// even though there was an error, because the user has
// enabled SSLConst::DEFERRED_CERT_VERIFY and wants the
// error to be logged in authcert so that it can be handled
// by a higher layer.
bool deferred_cert_verify_failsafe(const SSL& ssl) const
{
return (config->flags & SSLConst::DEFERRED_CERT_VERIFY)
&& ssl.authcert // failsafe: don't defer error unless
&& ssl.authcert->is_fail(); // authcert has recorded it
}
void erase()
{
if (epki)
{
delete epki;
epki = nullptr;
}
if (ctx)
{
SSL_CTX_free(ctx);
ctx = nullptr;
}
}
Config::Ptr config;
SSL_CTX* ctx = nullptr;
ExternalPKIImpl* epki = nullptr;
OpenSSLSessionCache::Ptr sess_cache; // client-side only
};
#ifdef OPENVPN_NO_EXTERN
int OpenSSLContext::SSL::ssl_data_index = -1;
int OpenSSLContext::SSL::context_data_index = -1;
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L && defined(OPENVPN_NO_EXTERN)
SSL_METHOD OpenSSLContext::SSL::ssl23_method_client_;
SSL_METHOD OpenSSLContext::SSL::ssl23_method_server_;
#endif
inline const std::string get_ssl_library_version()
{
return OPENSSL_VERSION_TEXT;
}
}
#endif
| 29.140727 | 165 | 0.661859 | [
"object",
"vector"
] |
2c4baca7dbb25c696e1d4b5019d11b976ebb564f | 852 | cpp | C++ | 6.Searching/2.indexofLastoccur.cpp | abhishekmishra25/leetcode | 855d64fa5da737ba099c4c2f9c84b6af4bb2239d | [
"MIT"
] | null | null | null | 6.Searching/2.indexofLastoccur.cpp | abhishekmishra25/leetcode | 855d64fa5da737ba099c4c2f9c84b6af4bb2239d | [
"MIT"
] | null | null | null | 6.Searching/2.indexofLastoccur.cpp | abhishekmishra25/leetcode | 855d64fa5da737ba099c4c2f9c84b6af4bb2239d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// creating a calss soluction
class soluction
{
public:
int Lastindex(vector<int> &arr, int target)
{
int low = 0, high = arr.size() - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (arr[mid] > target)
high = mid - 1;
else if (arr[mid] < target)
low = mid + 1;
else
{
if (mid == arr.size() - 1 || arr[mid] != arr[mid + 1])
return mid;
else
low = mid + 1;
}
}
return -1;
}
};
// main function
int main()
{
vector<int> arr = {10, 10, 20, 20, 30, 30, 40};
int target = 30;
soluction ob1;
cout << ob1.Lastindex(arr, target) << endl;
return 0;
} | 22.421053 | 70 | 0.428404 | [
"vector"
] |
2c5256e8e63eead9e6a2b8209c1a3ef430653b28 | 1,772 | cpp | C++ | examples/dbv2.cpp | struct/mathilda | 2edbdcc6fedc9165b916050dc3f97ffe8322c225 | [
"BSD-3-Clause"
] | 33 | 2015-07-31T16:32:47.000Z | 2020-02-12T18:17:49.000Z | examples/dbv2.cpp | struct/mathilda | 2edbdcc6fedc9165b916050dc3f97ffe8322c225 | [
"BSD-3-Clause"
] | 2 | 2015-07-31T18:37:49.000Z | 2016-08-12T13:56:28.000Z | examples/dbv2.cpp | struct/mathilda | 2edbdcc6fedc9165b916050dc3f97ffe8322c225 | [
"BSD-3-Clause"
] | 10 | 2015-07-31T16:34:05.000Z | 2019-12-10T12:44:16.000Z | // Copyright 2015/2016 Yahoo Inc.
// Licensed under the BSD license, see LICENSE file for terms.
// Written by Chris Rohlf
// An example Dirbuster tool that uses Mathilda
// g++ -o dbv2 dbv2.cpp mathilda.cpp mathilda_utils.cpp mathilda_fork.cpp dirbuster.cpp -std=c++11 -ggdb -lcurl -luv
#include "mathilda.h"
#include "mathilda_utils.h"
#include "dirbuster.h"
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
const char *h = argv[1];
const char *p = argv[2];
const char *d = argv[3];
if(!h || !p || !d) {
cout << "dbv2 <hosts> <pages> <directories>" << endl;
return ERR;
}
std::vector <std::string> ips;
std::vector <std::string> hosts;
std::vector <std::string> tls_hosts;
std::vector <std::string> pages;
std::vector <std::string> dirs;
MathildaUtils::read_file((char *) h, ips);
MathildaUtils::read_file((char *) p, pages);
MathildaUtils::read_file((char *) d, dirs);
for(auto y : ips) {
std::vector<std::string> out;
// Expects format of "port:IP"
MathildaUtils::split(y, ':', out);
std::string host = out[1];
MathildaUtils::addr_to_name(out[1], host);
if(out[0] == "443") {
tls_hosts.push_back(host);
} else {
hosts.push_back(host);
}
}
auto cookie_file = "";
Dirbuster *dirb = new Dirbuster(hosts, pages, dirs, cookie_file, 80);
dirb->run();
for(auto pt : dirb->paths) {
cout << pt << endl;
}
delete dirb;
dirb = new Dirbuster(tls_hosts, pages, dirs, cookie_file, 443);
dirb->run();
for(auto pt : dirb->paths) {
cout << pt << endl;
}
delete dirb;
return OK;
} | 25.314286 | 116 | 0.589165 | [
"vector"
] |
2c58dfcb0df88f281cf1d94fc892c39f92be1075 | 89,239 | cpp | C++ | src/HumidAirProp.cpp | CaioMSPinheiro/git-clone-https-github.com-CoolProp-CoolProp---recursive | 936939b8ab8a2040eb81ee5f2b23890c630731bd | [
"MIT"
] | 1 | 2021-07-07T16:37:52.000Z | 2021-07-07T16:37:52.000Z | src/HumidAirProp.cpp | CaioMSPinheiro/git-clone-https-github.com-CoolProp-CoolProp---recursive | 936939b8ab8a2040eb81ee5f2b23890c630731bd | [
"MIT"
] | 1 | 2021-07-12T19:35:24.000Z | 2021-07-13T04:18:23.000Z | src/HumidAirProp.cpp | CaioMSPinheiro/git-clone-https-github.com-CoolProp-CoolProp---recursive | 936939b8ab8a2040eb81ee5f2b23890c630731bd | [
"MIT"
] | 1 | 2021-07-07T16:38:23.000Z | 2021-07-07T16:38:23.000Z | #if defined(_MSC_VER)
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#endif
#include <memory>
#include "HumidAirProp.h"
#include "Backends/Helmholtz/HelmholtzEOSBackend.h"
#include "Solvers.h"
#include "CoolPropTools.h"
#include "Ice.h"
#include "CoolProp.h"
#include "crossplatform_shared_ptr.h"
#include "Exceptions.h"
#include <algorithm> // std::next_permutation
#include <stdlib.h>
#include "math.h"
#include "time.h"
#include "stdio.h"
#include <string.h>
#include <iostream>
#include <list>
#include "externals/IF97/IF97.h"
/// This is a stub overload to help with all the strcmp calls below and avoid needing to rewrite all of them
std::size_t strcmp(const std::string &s, const std::string &e){
return s.compare(e);
}
std::size_t strcmp(const std::string &s, const char *e){ // To avoid unnecessary constructors
return s.compare(e);
}
std::size_t strcmp(const char *e, const std::string &s){
return -s.compare(e);
}
// This is a lazy stub function to avoid recoding all the strcpy calls below
void strcpy(std::string &s, const std::string &e){
s = e;
}
shared_ptr<CoolProp::HelmholtzEOSBackend> Water, Air;
shared_ptr<CoolProp::AbstractState> WaterIF97;
namespace HumidAir
{
enum givens{GIVEN_INVALID=0, GIVEN_TDP,GIVEN_PSIW, GIVEN_HUMRAT,GIVEN_VDA, GIVEN_VHA,GIVEN_TWB,GIVEN_RH,GIVEN_ENTHALPY,GIVEN_ENTHALPY_HA,GIVEN_ENTROPY,GIVEN_ENTROPY_HA, GIVEN_T,GIVEN_P,GIVEN_VISC,GIVEN_COND,GIVEN_CP,GIVEN_CPHA, GIVEN_COMPRESSIBILITY_FACTOR, GIVEN_PARTIAL_PRESSURE_WATER, GIVEN_CV, GIVEN_CVHA, GIVEN_INTERNAL_ENERGY, GIVEN_INTERNAL_ENERGY_HA, GIVEN_SPEED_OF_SOUND, GIVEN_ISENTROPIC_EXPONENT};
void _HAPropsSI_inputs(double p, const std::vector<givens> &input_keys, const std::vector<double> &input_vals, double &T, double &psi_w);
double _HAPropsSI_outputs(givens OuputType, double p, double T, double psi_w);
void check_fluid_instantiation()
{
if (!Water.get()){
Water.reset(new CoolProp::HelmholtzEOSBackend("Water"));
}
if (!WaterIF97.get()){
WaterIF97.reset(CoolProp::AbstractState::factory("IF97","Water"));
}
if (!Air.get()){
Air.reset(new CoolProp::HelmholtzEOSBackend("Air"));
}
};
static double epsilon=0.621945,R_bar=8.314472;
static int FlagUseVirialCorrelations=0,FlagUseIsothermCompressCorrelation=0,FlagUseIdealGasEnthalpyCorrelations=0;
double f_factor(double T, double p);
// A couple of convenience functions that are needed quite a lot
static double MM_Air(void)
{
check_fluid_instantiation();
return Air->keyed_output(CoolProp::imolar_mass);
}
static double MM_Water(void)
{
check_fluid_instantiation();
return Water->keyed_output(CoolProp::imolar_mass);
}
static double B_Air(double T)
{
check_fluid_instantiation();
Air->specify_phase(CoolProp::iphase_gas);
Air->update_DmolarT_direct(1e-12,T);
Air->unspecify_phase();
return Air->keyed_output(CoolProp::iBvirial);
}
static double dBdT_Air(double T)
{
check_fluid_instantiation();
Air->specify_phase(CoolProp::iphase_gas);
Air->update_DmolarT_direct(1e-12,T);
Air->unspecify_phase();
return Air->keyed_output(CoolProp::idBvirial_dT);
}
static double B_Water(double T)
{
check_fluid_instantiation();
Water->specify_phase(CoolProp::iphase_gas);
Water->update_DmolarT_direct(1e-12,T);
Water->unspecify_phase();
return Water->keyed_output(CoolProp::iBvirial);
}
static double dBdT_Water(double T)
{
check_fluid_instantiation();
Water->specify_phase(CoolProp::iphase_gas);
Water->update_DmolarT_direct(1e-12,T);
Water->unspecify_phase();
return Water->keyed_output(CoolProp::idBvirial_dT);
}
static double C_Air(double T)
{
check_fluid_instantiation();
Air->specify_phase(CoolProp::iphase_gas);
Air->update_DmolarT_direct(1e-12,T);
Air->unspecify_phase();
return Air->keyed_output(CoolProp::iCvirial);
}
static double dCdT_Air(double T)
{
check_fluid_instantiation();
Air->specify_phase(CoolProp::iphase_gas);
Air->update_DmolarT_direct(1e-12,T);
Air->unspecify_phase();
return Air->keyed_output(CoolProp::idCvirial_dT);
}
static double C_Water(double T)
{
check_fluid_instantiation();
Water->specify_phase(CoolProp::iphase_gas);
Water->update_DmolarT_direct(1e-12,T);
Water->unspecify_phase();
return Water->keyed_output(CoolProp::iCvirial);
}
static double dCdT_Water(double T)
{
check_fluid_instantiation();
Water->specify_phase(CoolProp::iphase_gas);
Water->update_DmolarT_direct(1e-12,T);
Water->unspecify_phase();
return Water->keyed_output(CoolProp::idCvirial_dT);
}
void UseVirialCorrelations(int flag)
{
if (flag==0 || flag==1)
{
FlagUseVirialCorrelations=flag;
}
else
{
printf("UseVirialCorrelations takes an integer, either 0 (no) or 1 (yes)\n");
}
}
void UseIsothermCompressCorrelation(int flag)
{
if (flag==0 || flag==1)
{
FlagUseIsothermCompressCorrelation=flag;
}
else
{
printf("UseIsothermCompressCorrelation takes an integer, either 0 (no) or 1 (yes)\n");
}
}
void UseIdealGasEnthalpyCorrelations(int flag)
{
if (flag==0 || flag==1)
{
FlagUseIdealGasEnthalpyCorrelations=flag;
}
else
{
printf("UseIdealGasEnthalpyCorrelations takes an integer, either 0 (no) or 1 (yes)\n");
}
}
static double Brent_HAProps_W(givens OutputKey, double p, givens In1Name, double Input1, double TargetVal, double W_min, double W_max)
{
// Iterating for W,
double W;
class BrentSolverResids : public CoolProp::FuncWrapper1D
{
private:
givens OutputKey;
double p;
givens In1Key;
double Input1, TargetVal;
std::vector<givens> input_keys;
std::vector<double> input_vals;
public:
BrentSolverResids(givens OutputKey, double p, givens In1Key, double Input1, double TargetVal) : OutputKey(OutputKey), p(p), In1Key(In1Key), Input1(Input1), TargetVal(TargetVal)
{
input_keys.resize(2); input_keys[0] = In1Key; input_keys[1] = GIVEN_HUMRAT;
input_vals.resize(2); input_vals[0] = Input1;
};
double call(double W){
input_vals[1] = W;
double T = _HUGE, psi_w = _HUGE;
_HAPropsSI_inputs(p, input_keys, input_vals, T, psi_w);
if (CoolProp::get_debug_level() > 0){ std::cout << format("T: %g K, psi_w %g\n", T, psi_w); }
return _HAPropsSI_outputs(OutputKey, p, T, psi_w) - TargetVal;
}
};
BrentSolverResids BSR = BrentSolverResids(OutputKey, p, In1Name, Input1, TargetVal);
// Now we need to check the bounds and make sure that they are ok (don't yield invalid output)
// and actually bound the solution
double r_min = BSR.call(W_min);
bool W_min_valid = ValidNumber(r_min);
double r_max = BSR.call(W_max);
bool W_max_valid = ValidNumber(r_max);
if (!W_min_valid && !W_max_valid){
throw CoolProp::ValueError(format("Both W_min [%g] and W_max [%g] yield invalid output values in Brent_HAProps_W",W_min,W_max).c_str());
}
else if (W_min_valid && !W_max_valid){
while (!W_max_valid){
// Reduce W_max until it works
W_max = 0.95*W_max + 0.05*W_min;
r_max = BSR.call(W_max);
W_max_valid = ValidNumber(r_max);
}
}
else if (!W_min_valid && W_max_valid){
while (!W_min_valid){
// Increase W_min until it works
W_min = 0.95*W_min + 0.05*W_max;
r_min = BSR.call(W_min);
W_min_valid = ValidNumber(r_min);
}
}
// We will do a secant call if the values at W_min and W_max have the same sign
if (r_min*r_max > 0){
if (std::abs(r_min) < std::abs(r_max)){
W = CoolProp::Secant(BSR, W_min, 0.01*W_min, 1e-7, 50);
}
else{
W = CoolProp::Secant(BSR, W_max, -0.01*W_max, 1e-7, 50);
}
}
else{
W = CoolProp::Brent(BSR, W_min, W_max, 1e-7, 1e-4, 50);
}
return W;
}
static double Brent_HAProps_T(givens OutputKey, double p, givens In1Name, double Input1, double TargetVal, double T_min, double T_max)
{
double T;
class BrentSolverResids : public CoolProp::FuncWrapper1D
{
private:
givens OutputKey;
double p;
givens In1Key;
double Input1, TargetVal;
std::vector<givens> input_keys;
std::vector<double> input_vals;
public:
BrentSolverResids(givens OutputKey, double p, givens In1Key, double Input1, double TargetVal) : OutputKey(OutputKey), p(p), In1Key(In1Key), Input1(Input1), TargetVal(TargetVal)
{
input_keys.resize(2); input_keys[0] = In1Key; input_keys[1] = GIVEN_T;
input_vals.resize(2); input_vals[0] = Input1;
};
double call(double T){
input_vals[1] = T;
double psi_w;
_HAPropsSI_inputs(p, input_keys, input_vals, T, psi_w);
return _HAPropsSI_outputs(OutputKey, p, T, psi_w) - TargetVal;
}
};
BrentSolverResids BSR = BrentSolverResids(OutputKey, p, In1Name, Input1, TargetVal);
// Now we need to check the bounds and make sure that they are ok (don't yield invalid output)
// and actually bound the solution
double r_min = BSR.call(T_min);
bool T_min_valid = ValidNumber(r_min);
double r_max = BSR.call(T_max);
bool T_max_valid = ValidNumber(r_max);
if (!T_min_valid && !T_max_valid){
throw CoolProp::ValueError(format("Both T_min [%g] and T_max [%g] yield invalid output values in Brent_HAProps_T",T_min,T_max).c_str());
}
else if (T_min_valid && !T_max_valid){
while (!T_max_valid){
// Reduce T_max until it works
T_max = 0.95*T_max + 0.05*T_min;
r_max = BSR.call(T_max);
T_max_valid = ValidNumber(r_max);
}
}
else if (!T_min_valid && T_max_valid){
while (!T_min_valid){
// Increase T_min until it works
T_min = 0.95*T_min + 0.05*T_max;
r_min = BSR.call(T_min);
T_min_valid = ValidNumber(r_min);
}
}
// We will do a secant call if the values at T_min and T_max have the same sign
if (r_min*r_max > 0){
if (std::abs(r_min) < std::abs(r_max)){
T = CoolProp::Secant(BSR, T_min, 0.01*T_min, 1e-7, 50);
}
else{
T = CoolProp::Secant(BSR, T_max, -0.01*T_max, 1e-7, 50);
}
}
else{
T = CoolProp::Brent(BSR, T_min, T_max, 1e-7, 1e-4, 50);
}
return T;
}
static double Secant_Tdb_at_saturated_W(double psi_w, double p, double T_guess)
{
double T;
class BrentSolverResids : public CoolProp::FuncWrapper1D
{
private:
double pp_water, psi_w, p;
public:
BrentSolverResids(double psi_w, double p) : psi_w(psi_w), p(p) { pp_water = psi_w*p; };
~BrentSolverResids(){};
double call(double T){
double p_ws;
if (T>=273.16){
// Saturation pressure [Pa] using IF97 formulation
p_ws= IF97::psat97(T);
}
else{
// Sublimation pressure [Pa]
p_ws=psub_Ice(T);
}
double f = f_factor(T, p);
double pp_water_calc = f*p_ws;
double psi_w_calc = pp_water_calc/p;
return (psi_w_calc - psi_w)/psi_w;
}
};
BrentSolverResids Resids(psi_w, p);
try{
T = CoolProp::Secant(Resids, T_guess, 0.1, 1e-7, 100);
if (!ValidNumber(T)){
throw CoolProp::ValueError("Intermediate value for Tdb is invalid");
}
}
catch(std::exception &e){
T = CoolProp::Brent(Resids, 100, 640, 1e-15, 1e-10, 100);
}
return T;
}
//static double Brent_Tdb_at_saturated_W(double psi_w, double p, double T_min, double T_max)
//{
// double T;
// class BrentSolverResids : public CoolProp::FuncWrapper1D
// {
// private:
// double pp_water, psi_w, p;
// public:
// BrentSolverResids(double psi_w, double p) : psi_w(psi_w), p(p) { pp_water = psi_w*p; };
// ~BrentSolverResids(){};
//
// double call(double T){
// double p_ws;
// if (T>=273.16){
// // Saturation pressure [Pa] using IF97 formulation
// p_ws= IF97::psat97(T);
// }
// else{
// // Sublimation pressure [Pa]
// p_ws=psub_Ice(T);
// }
// double f = f_factor(T, p);
// double pp_water_calc = f*p_ws;
// double psi_w_calc = pp_water_calc/p;
// return (psi_w_calc - psi_w)/psi_w;
// }
// };
//
// BrentSolverResids Resids(psi_w, p);
//
// T = CoolProp::Brent(Resids, 150, 350, 1e-16, 1e-7, 100);
//
// return T;
//}
/*
static double Secant_HAProps_T(const std::string &OutputName, const std::string &Input1Name, double Input1, const std::string &Input2Name, double Input2, double TargetVal, double T_guess)
{
// Use a secant solve in order to yield a target output value for HAProps by altering T
double x1=0,x2=0,x3=0,y1=0,y2=0,eps=5e-7,f=999,T=300,change;
int iter=1;
std::string sT = "T";
while ((iter<=3 || (std::abs(f)>eps && std::abs(change)>1e-10)) && iter<100)
{
if (iter==1){x1=T_guess; T=x1;}
if (iter==2){x2=T_guess+0.001; T=x2;}
if (iter>2) {T=x2;}
f=HAPropsSI(OutputName,sT,T,Input1Name,Input1,Input2Name,Input2)-TargetVal;
if (iter==1){y1=f;}
if (iter>1)
{
y2=f;
x3=x2-y2/(y2-y1)*(x2-x1);
change = y2/(y2-y1)*(x2-x1);
y1=y2; x1=x2; x2=x3;
}
iter=iter+1;
}
return T;
}
*/
static double Secant_HAProps_W( double p, double T, givens OutputType, double TargetVal, double W_guess)
{
// Use a secant solve in order to yield a target output value for HAProps by altering humidity ratio
double x1=0,x2=0,x3=0,y1=0,y2=0,eps=1e-12,f=999,W=0.0001;
int iter=1;
std::vector<givens> input_keys(2,GIVEN_T); input_keys[1] = GIVEN_HUMRAT;
std::vector<double> input_vals(2,T);
if (OutputType == GIVEN_TWB){eps = 1e-7;}
double _T, psi_w;
while ((iter<=3 || std::abs(f)>eps) && iter<100)
{
if (iter == 1){x1 = W_guess; W = x1;}
if (iter == 2){x2 = W_guess*1.1; W = x2;}
if (iter > 2) {W = x2;}
input_vals[1] = W; _HAPropsSI_inputs(p, input_keys, input_vals, _T, psi_w);
f = _HAPropsSI_outputs(OutputType, p, T, psi_w) - TargetVal;
if (iter == 1){y1 = f;}
if (iter > 1)
{
y2=f;
x3=x2-0.5*y2/(y2-y1)*(x2-x1);
y1=y2; x1=x2; x2=x3;
}
iter=iter+1;
}
return W;
}
// Mixed virial components
static double _B_aw(double T)
{
check_fluid_instantiation();
// Returns value in m^3/mol
double a[]={0,0.665687e2,-0.238834e3,-0.176755e3};
double b[]={0,-0.237,-1.048,-3.183};
double rhobarstar=1000,Tstar=100;
return 1/rhobarstar*(a[1]*pow(T/Tstar,b[1])+a[2]*pow(T/Tstar,b[2])+a[3]*pow(T/Tstar,b[3]))/1000; // Correlation has units of dm^3/mol, to convert to m^3/mol, divide by 1000
}
static double _dB_aw_dT(double T)
{
check_fluid_instantiation();
// Returns value in m^3/mol
double a[]={0,0.665687e2,-0.238834e3,-0.176755e3};
double b[]={0,-0.237,-1.048,-3.183};
double rhobarstar=1000,Tstar=100;
return 1/rhobarstar/Tstar*(a[1]*b[1]*pow(T/Tstar,b[1]-1)+a[2]*b[2]*pow(T/Tstar,b[2]-1)+a[3]*b[3]*pow(T/Tstar,b[3]-1))/1000; // Correlation has units of dm^3/mol/K, to convert to m^3/mol/K, divide by 1000
}
static double _C_aaw(double T)
{
check_fluid_instantiation();
// Function return has units of m^6/mol^2
double c[]={0,0.482737e3,0.105678e6,-0.656394e8,0.294442e11,-0.319317e13};
double rhobarstar=1000,Tstar=1,summer=0; int i;
for (i=1;i<=5;i++)
{
summer+=c[i]*pow(T/Tstar,1-i);
}
return 1.0/rhobarstar/rhobarstar*summer/1e6; // Correlation has units of dm^6/mol^2, to convert to m^6/mol^2 divide by 1e6
}
static double _dC_aaw_dT(double T)
{
check_fluid_instantiation();
// Function return in units of m^6/mol^2/K
double c[]={0,0.482737e3,0.105678e6,-0.656394e8,0.294442e11,-0.319317e13};
double rhobarstar=1000,Tstar=1,summer=0; int i;
for (i=2;i<=5;i++)
{
summer+=c[i]*(1-i)*pow(T/Tstar,-i);
}
return 1.0/rhobarstar/rhobarstar/Tstar*summer/1e6; // Correlation has units of dm^6/mol^2/K, to convert to m^6/mol^2/K divide by 1e6
}
static double _C_aww(double T)
{
check_fluid_instantiation();
// Function return has units of m^6/mol^2
double d[]={0,-0.1072887e2,0.347804e4,-0.383383e6,0.334060e8};
double rhobarstar=1,Tstar=1,summer=0; int i;
for (i=1;i<=4;i++)
{
summer+=d[i]*pow(T/Tstar,1-i);
}
return -1.0/rhobarstar/rhobarstar*exp(summer)/1e6; // Correlation has units of dm^6/mol^2, to convert to m^6/mol^2 divide by 1e6
}
static double _dC_aww_dT(double T)
{
check_fluid_instantiation();
// Function return in units of m^6/mol^2/K
double d[]={0,-0.1072887e2,0.347804e4,-0.383383e6,0.334060e8};
double rhobarstar=1,Tstar=1,summer1=0,summer2=0; int i;
for (i=1;i<=4;i++)
{
summer1+=d[i]*pow(T/Tstar,1-i);
}
for (i=2;i<=4;i++)
{
summer2+=d[i]*(1-i)*pow(T/Tstar,-i);
}
return -1.0/rhobarstar/rhobarstar/Tstar*exp(summer1)*summer2/1e6; // Correlation has units of dm^6/mol^2/K, to convert to m^6/mol^2/K divide by 1e6
}
static double B_m(double T, double psi_w)
{
// Bm has units of m^3/mol
double B_aa,B_ww,B_aw;
if (FlagUseVirialCorrelations==1)
{
B_aa=-0.000721183853646 +1.142682674467e-05*T -8.838228412173e-08*pow(T,2)
+4.104150642775e-10*pow(T,3) -1.192780880645e-12*pow(T,4) +2.134201312070e-15*pow(T,5)
-2.157430412913e-18*pow(T,6) +9.453830907795e-22*pow(T,7);
B_ww=-10.8963128394 +2.439761625859e-01*T -2.353884845100e-03*pow(T,2)
+1.265864734412e-05*pow(T,3) -4.092175700300e-08*pow(T,4) +7.943925411344e-11*pow(T,5)
-8.567808759123e-14*pow(T,6) +3.958203548563e-17*pow(T,7);
}
else
{
B_aa = B_Air(T); // [m^3/mol]
B_ww = B_Water(T); // [m^3/mol]
}
B_aw=_B_aw(T); // [m^3/mol]
return pow(1-psi_w,2)*B_aa+2*(1-psi_w)*psi_w*B_aw+psi_w*psi_w*B_ww;
}
static double dB_m_dT(double T, double psi_w)
{
//dBm_dT has units of m^3/mol/K
double dB_dT_aa,dB_dT_ww,dB_dT_aw;
if (FlagUseVirialCorrelations)
{
dB_dT_aa=1.65159324353e-05 -3.026130954749e-07*T +2.558323847166e-09*pow(T,2) -1.250695660784e-11*pow(T,3) +3.759401946106e-14*pow(T,4) -6.889086380822e-17*pow(T,5) +7.089457032972e-20*pow(T,6) -3.149942145971e-23*pow(T,7);
dB_dT_ww=0.65615868848 -1.487953162679e-02*T +1.450134660689e-04*pow(T,2) -7.863187630094e-07*pow(T,3) +2.559556607010e-09*pow(T,4) -4.997942221914e-12*pow(T,5) +5.417678681513e-15*pow(T,6) -2.513856275241e-18*pow(T,7);
}
else
{
dB_dT_aa=dBdT_Air(T); // [m^3/mol]
dB_dT_ww=dBdT_Water(T); // [m^3/mol]
}
dB_dT_aw=_dB_aw_dT(T); // [m^3/mol]
return pow(1-psi_w,2)*dB_dT_aa+2*(1-psi_w)*psi_w*dB_dT_aw+psi_w*psi_w*dB_dT_ww;
}
static double C_m(double T, double psi_w)
{
// Cm has units of m^6/mol^2
double C_aaa,C_www,C_aww,C_aaw;
if (FlagUseVirialCorrelations)
{
C_aaa=1.29192158975e-08 -1.776054020409e-10*T +1.359641176409e-12*pow(T,2)
-6.234878717893e-15*pow(T,3) +1.791668730770e-17*pow(T,4) -3.175283581294e-20*pow(T,5)
+3.184306136120e-23*pow(T,6) -1.386043640106e-26*pow(T,7);
C_www=-0.580595811134 +1.365952762696e-02*T -1.375986293288e-04*pow(T,2)
+7.687692259692e-07*pow(T,3) -2.571440816920e-09*pow(T,4) +5.147432221082e-12*pow(T,5)
-5.708156494894e-15*pow(T,6) +2.704605721778e-18*pow(T,7);
}
else
{
C_aaa=C_Air(T); //[m^6/mol^2]
C_www=C_Water(T); //[m^6/mol^2]
}
C_aaw=_C_aaw(T); //[m^6/mol^2]
C_aww=_C_aww(T); //[m^6/mol^2]
return pow(1-psi_w,3)*C_aaa+3*pow(1-psi_w,2)*psi_w*C_aaw+3*(1-psi_w)*psi_w*psi_w*C_aww+pow(psi_w,3)*C_www;
}
static double dC_m_dT(double T, double psi_w)
{
// dCm_dT has units of m^6/mol^2/K
double dC_dT_aaa,dC_dT_www,dC_dT_aww,dC_dT_aaw;
// NDG for fluid EOS for virial terms
if (FlagUseVirialCorrelations)
{
dC_dT_aaa=-2.46582342273e-10 +4.425401935447e-12*T -3.669987371644e-14*pow(T,2) +1.765891183964e-16*pow(T,3) -5.240097805744e-19*pow(T,4) +9.502177003614e-22*pow(T,5) -9.694252610339e-25*pow(T,6) +4.276261986741e-28*pow(T,7);
dC_dT_www=0.0984601196142 -2.356713397262e-03*T +2.409113323685e-05*pow(T,2) -1.363083778715e-07*pow(T,3) +4.609623799524e-10*pow(T,4) -9.316416405390e-13*pow(T,5) +1.041909136255e-15*pow(T,6) -4.973918480607e-19*pow(T,7);
}
else
{
dC_dT_aaa=dCdT_Air(T); // [m^6/mol^2]
dC_dT_www=dCdT_Water(T); // [m^6/mol^2]
}
dC_dT_aaw=_dC_aaw_dT(T); // [m^6/mol^2]
dC_dT_aww=_dC_aww_dT(T); // [m^6/mol^2]
return pow(1-psi_w,3)*dC_dT_aaa+3*pow(1-psi_w,2)*psi_w*dC_dT_aaw+3*(1-psi_w)*psi_w*psi_w*dC_dT_aww+pow(psi_w,3)*dC_dT_www;
}
double HumidityRatio(double psi_w)
{
return psi_w*epsilon/(1-psi_w);
}
static double HenryConstant(double T)
{
// Result has units of 1/Pa
double p_ws,beta_N2,beta_O2,beta_Ar,beta_a,tau,Tr,Tc=647.096;
Tr=T/Tc;
tau=1-Tr;
p_ws = IF97::psat97(T); //[Pa]
beta_N2=p_ws*exp(-9.67578/Tr+4.72162*pow(tau,0.355)/Tr+11.70585*pow(Tr,-0.41)*exp(tau));
beta_O2=p_ws*exp(-9.44833/Tr+4.43822*pow(tau,0.355)/Tr+11.42005*pow(Tr,-0.41)*exp(tau));
beta_Ar=p_ws*exp(-8.40954/Tr+4.29587*pow(tau,0.355)/Tr+10.52779*pow(Tr,-0.41)*exp(tau));
beta_a=1/(0.7812/beta_N2+0.2095/beta_O2+0.0093/beta_Ar);
return 1/(1.01325*beta_a);
}
double isothermal_compressibility(double T, double p)
{
double k_T;
if (T> 273.16)
{
if (FlagUseIsothermCompressCorrelation)
{
k_T = 1.6261876614E-22*pow(T,6) - 3.3016385196E-19*pow(T,5) + 2.7978984577E-16*pow(T,4)
- 1.2672392901E-13*pow(T,3) + 3.2382864853E-11*pow(T,2) - 4.4318979503E-09*T + 2.5455947289E-07;
}
else
{
// Use IF97 to do the P,T call
WaterIF97->update(CoolProp::PT_INPUTS, p, T);
Water->update(CoolProp::DmassT_INPUTS, WaterIF97->rhomass(), T);
k_T = Water->keyed_output(CoolProp::iisothermal_compressibility);
}
}
else
{
k_T = IsothermCompress_Ice(T,p); //[1/Pa]
}
return k_T;
}
double f_factor(double T, double p)
{
double f=0,Rbar=8.314371,eps=1e-8;
double x1=0,x2=0,x3,y1=0,y2,change=_HUGE;
int iter=1;
double p_ws,B_aa,B_aw,B_ww,C_aaa,C_aaw,C_aww,C_www,
line1,line2,line3,line4,line5,line6,line7,line8,k_T,beta_H,LHS,RHS,psi_ws,
vbar_ws;
// Saturation pressure [Pa]
if (T>273.16)
{
// It is liquid water
Water->update(CoolProp::QT_INPUTS, 0, T);
p_ws = Water->p();
vbar_ws = 1.0/Water->keyed_output(CoolProp::iDmolar); //[m^3/mol]
beta_H = HenryConstant(T); //[1/Pa]
}
else
{
// It is ice
p_ws = psub_Ice(T); // [Pa]
beta_H = 0;
vbar_ws = dg_dp_Ice(T,p)*MM_Water(); //[m^3/mol]
}
k_T = isothermal_compressibility(T,p); //[1/Pa]
// Hermann: In the iteration process of the enhancement factor in Eq. (3.25), k_T is set to zero for pw,s (T) > p.
if (p_ws>p)
{
k_T=0;
beta_H=0;
}
// NDG for fluid EOS for virial terms
if (FlagUseVirialCorrelations)
{
B_aa=-0.000721183853646 +1.142682674467e-05*T -8.838228412173e-08*pow(T,2)
+4.104150642775e-10*pow(T,3) -1.192780880645e-12*pow(T,4) +2.134201312070e-15*pow(T,5)
-2.157430412913e-18*pow(T,6) +9.453830907795e-22*pow(T,7);
B_ww=-10.8963128394 +2.439761625859e-01*T -2.353884845100e-03*pow(T,2)
+1.265864734412e-05*pow(T,3) -4.092175700300e-08*pow(T,4) +7.943925411344e-11*pow(T,5)
-8.567808759123e-14*pow(T,6) +3.958203548563e-17*pow(T,7);
C_aaa=1.29192158975e-08 -1.776054020409e-10*T +1.359641176409e-12*pow(T,2)
-6.234878717893e-15*pow(T,3) +1.791668730770e-17*pow(T,4) -3.175283581294e-20*pow(T,5)
+3.184306136120e-23*pow(T,6) -1.386043640106e-26*pow(T,7);
C_www=-0.580595811134 +1.365952762696e-02*T -1.375986293288e-04*pow(T,2)
+7.687692259692e-07*pow(T,3) -2.571440816920e-09*pow(T,4) +5.147432221082e-12*pow(T,5)
-5.708156494894e-15*pow(T,6) +2.704605721778e-18*pow(T,7);
}
else
{
B_aa = B_Air(T); // [m^3/mol]
C_aaa = C_Air(T); // [m^6/mol^2]
B_ww = B_Water(T); // [m^3/mol]
C_www = C_Water(T); // [m^6/mol^2]
}
B_aw = _B_aw(T); //[m^3/mol]
C_aaw = _C_aaw(T); //[m^6/mol^2]
C_aww = _C_aww(T); //[m^6/mol^2]
// Use a little secant loop to find f iteratively
// Start out with a guess value of 1 for f
while ((iter<=3 || change>eps) && iter<100)
{
if (iter==1){x1=1.00; f=x1;}
if (iter==2){x2=1.00+0.000001; f=x2;}
if (iter>2) {f=x2;}
// Left-hand-side of Equation 3.25
LHS=log(f);
// Eqn 3.24
psi_ws=f*p_ws/p;
// All the terms forming the RHS of Eqn 3.25
line1=((1+k_T*p_ws)*(p-p_ws)-k_T*(p*p-p_ws*p_ws)/2.0)/(Rbar*T)*vbar_ws+log(1-beta_H*(1-psi_ws)*p);
line2=pow(1-psi_ws,2)*p/(Rbar*T)*B_aa-2*pow(1-psi_ws,2)*p/(Rbar*T)*B_aw-(p-p_ws-pow(1-psi_ws,2)*p)/(Rbar*T)*B_ww;
line3=pow(1-psi_ws,3)*p*p/pow(Rbar*T,2)*C_aaa+(3*pow(1-psi_ws,2)*(1-2*(1-psi_ws))*p*p)/(2*pow(Rbar*T,2))*C_aaw;
line4=-3*pow(1-psi_ws,2)*psi_ws*p*p/pow(Rbar*T,2)*C_aww-((3-2*psi_ws)*psi_ws*psi_ws*p*p-p_ws*p_ws)/(2*pow(Rbar*T,2))*C_www;
line5=-(pow(1-psi_ws,2)*(-2+3*psi_ws)*psi_ws*p*p)/pow(Rbar*T,2)*B_aa*B_ww;
line6=-(2*pow(1-psi_ws,3)*(-1+3*psi_ws)*p*p)/pow(Rbar*T,2)*B_aa*B_aw;
line7=(6*pow(1-psi_ws,2)*psi_ws*psi_ws*p*p)/pow(Rbar*T,2)*B_ww*B_aw-(3*pow(1-psi_ws,4)*p*p)/(2*pow(Rbar*T,2))*B_aa*B_aa;
line8=-(2*pow(1-psi_ws,2)*psi_ws*(-2+3*psi_ws)*p*p)/pow(Rbar*T,2)*B_aw*B_aw-(p_ws*p_ws-(4-3*psi_ws)*pow(psi_ws,3)*p*p)/(2*pow(Rbar*T,2))*B_ww*B_ww;
RHS=line1+line2+line3+line4+line5+line6+line7+line8;
if (iter==1){y1=LHS-RHS;}
if (iter>1)
{
y2=LHS-RHS;
x3=x2-y2/(y2-y1)*(x2-x1);
change=std::abs(y2/(y2-y1)*(x2-x1));
y1=y2; x1=x2; x2=x3;
}
iter=iter+1;
}
if (f>=1.0)
return f;
else
return 1.0;
}
void HAHelp(void)
{
printf("Sorry, Need to update!");
}
int returnHumAirCode(const char * Code)
{
if (!strcmp(Code,"GIVEN_TDP"))
return GIVEN_TDP;
else if (!strcmp(Code,"GIVEN_HUMRAT"))
return GIVEN_HUMRAT;
else if (!strcmp(Code,"GIVEN_TWB"))
return GIVEN_TWB;
else if (!strcmp(Code,"GIVEN_RH"))
return GIVEN_RH;
else if (!strcmp(Code,"GIVEN_ENTHALPY"))
return GIVEN_ENTHALPY;
else
{
fprintf(stderr,"Code to returnHumAirCode in HumAir.c [%s] not understood",Code);
return -1;
}
}
double Viscosity(double T, double p, double psi_w)
{
/*
Using the method of:
P.T. Tsilingiris, 2009, Thermophysical and transport properties of humid air at temperature range between 0 and 100 oC, Energy Conversion and Management, 49, 1098-1010
but using the detailed measurements for pure fluid from IAPWS formulations
*/
double mu_a,mu_w,Phi_av,Phi_va,Ma,Mw;
Mw=MM_Water();
Ma=MM_Air();
// Viscosity of dry air at dry-bulb temp and total pressure
Air->update(CoolProp::PT_INPUTS,p,T);
mu_a=Air->keyed_output(CoolProp::iviscosity);
// Saturated water vapor of pure water at total pressure
Water->update(CoolProp::PQ_INPUTS, p, 1);
mu_w=Water->keyed_output(CoolProp::iviscosity);
Phi_av=sqrt(2.0)/4.0*pow(1+Ma/Mw,-0.5)*pow(1+sqrt(mu_a/mu_w)*pow(Mw/Ma,0.25),2); //[-]
Phi_va=sqrt(2.0)/4.0*pow(1+Mw/Ma,-0.5)*pow(1+sqrt(mu_w/mu_a)*pow(Ma/Mw,0.25),2); //[-]
return (1-psi_w)*mu_a/((1-psi_w)+psi_w*Phi_av)+psi_w*mu_w/(psi_w+(1-psi_w)*Phi_va);
}
double Conductivity(double T, double p, double psi_w)
{
/*
Using the method of:
P.T. Tsilingiris, 2009, Thermophysical and transport properties of humid air at temperature range between 0 and 100 oC, Energy Conversion and Management, 49, 1098-1010
but using the detailed measurements for pure fluid from IAPWS formulations
*/
double mu_a,mu_w,k_a,k_w,Phi_av,Phi_va,Ma,Mw;
Mw=MM_Water();
Ma=MM_Air();
// Viscosity of dry air at dry-bulb temp and total pressure
Air->update(CoolProp::PT_INPUTS,p,T);
mu_a=Air->keyed_output(CoolProp::iviscosity);
k_a=Air->keyed_output(CoolProp::iconductivity);
// Conductivity of saturated pure water at total pressure
Water->update(CoolProp::PQ_INPUTS, p, 1);
mu_w=Water->keyed_output(CoolProp::iviscosity);
k_w=Water->keyed_output(CoolProp::iconductivity);
Phi_av=sqrt(2.0)/4.0*pow(1+Ma/Mw,-0.5)*pow(1+sqrt(mu_a/mu_w)*pow(Mw/Ma,0.25),2); //[-]
Phi_va=sqrt(2.0)/4.0*pow(1+Mw/Ma,-0.5)*pow(1+sqrt(mu_w/mu_a)*pow(Ma/Mw,0.25),2); //[-]
return (1-psi_w)*k_a/((1-psi_w)+psi_w*Phi_av)+psi_w*k_w/(psi_w+(1-psi_w)*Phi_va);
}
/**
@param T Temperature in K
@param p Pressure in Pa
@param psi_w Water mole fraction in mol_w/mol_ha
@returns v Molar volume on a humid-air basis in m^3/mol_ha
*/
double MolarVolume(double T, double p, double psi_w)
{
// Output in m^3/mol_ha
int iter;
double v_bar0, v_bar=0, R_bar=8.314472,x1=0,x2=0,x3,y1=0,y2,resid,eps,Bm,Cm;
// -----------------------------
// Iteratively find molar volume
// -----------------------------
// Start by assuming it is an ideal gas to get initial guess
v_bar0 = R_bar*T/p; // [m^3/mol_ha]
// Bring outside the loop since not a function of v_bar
Bm = B_m(T,psi_w);
Cm = C_m(T,psi_w);
iter=1; eps=1e-11; resid=999;
while ((iter<=3 || std::abs(resid)>eps) && iter<100)
{
if (iter==1){x1=v_bar0; v_bar=x1;}
if (iter==2){x2=v_bar0+0.000001; v_bar=x2;}
if (iter>2) {v_bar=x2;}
// want v_bar in m^3/mol_ha and R_bar in J/mol_ha-K
resid = (p-(R_bar)*T/v_bar*(1+Bm/v_bar+Cm/(v_bar*v_bar)))/p;
if (iter==1){y1=resid;}
if (iter>1)
{
y2=resid;
x3=x2-y2/(y2-y1)*(x2-x1);
y1=y2; x1=x2; x2=x3;
}
iter=iter+1;
}
return v_bar; // [J/mol_ha]
}
double Pressure(double T, double v_bar, double psi_w){
double R_bar = 8.314472;
double Bm = B_m(T, psi_w);
double Cm = C_m(T, psi_w);
return (R_bar)*T/v_bar*(1+Bm/v_bar+Cm/(v_bar*v_bar));
}
double IdealGasMolarEnthalpy_Water(double T, double p)
{
double hbar_w_0, tau, hbar_w;
// Ideal-Gas contribution to enthalpy of water
hbar_w_0 = -0.01102303806; //[J/mol]
// Calculate the offset in the water enthalpy from a given state with a known (desired) enthalpy
double Tref = 473.15, vmolarref = 0.038837428192186184, href = 51885.582451893446;
Water->update(CoolProp::DmolarT_INPUTS,1/vmolarref,Tref);
double tauref = Water->keyed_output(CoolProp::iT_reducing)/Tref; //[no units]
double href_EOS = R_bar*Tref*(1+tauref*Water->keyed_output(CoolProp::idalpha0_dtau_constdelta));
double hoffset = href - href_EOS;
tau = Water->keyed_output(CoolProp::iT_reducing)/T;
Water->specify_phase(CoolProp::iphase_gas);
Water->update_DmolarT_direct(p/(R_bar*T), T);
Water->unspecify_phase();
hbar_w = hbar_w_0 + hoffset + R_bar*T*(1+tau*Water->keyed_output(CoolProp::idalpha0_dtau_constdelta));
return hbar_w;
}
double IdealGasMolarEntropy_Water(double T, double p)
{
// Serious typo in RP-1485 - should use total pressure rather than
// reference pressure in density calculation for water vapor molar entropy
double sbar_w, tau, R_bar;
R_bar = 8.314371; //[J/mol/K]
// Calculate the offset in the water entropy from a given state with a known (desired) entropy
double Tref = 473.15, pref = 101325, sref = 141.18297895840303;
Water->update(CoolProp::DmolarT_INPUTS,pref/(R_bar*Tref),Tref);
double tauref = Water->keyed_output(CoolProp::iT_reducing)/Tref; //[no units]
double sref_EOS = R_bar*(tauref*Water->keyed_output(CoolProp::idalpha0_dtau_constdelta)-Water->keyed_output(CoolProp::ialpha0));
double soffset = sref - sref_EOS;
// Now calculate it based on the given inputs
tau = Water->keyed_output(CoolProp::iT_reducing)/T;
Water->specify_phase(CoolProp::iphase_gas);
Water->update(CoolProp::DmolarT_INPUTS,p/(R_bar*T),T);
Water->unspecify_phase();
sbar_w = soffset + R_bar*(tau*Water->keyed_output(CoolProp::idalpha0_dtau_constdelta)-Water->keyed_output(CoolProp::ialpha0)); //[kJ/kmol/K]
return sbar_w;
}
double IdealGasMolarEnthalpy_Air(double T, double p)
{
double hbar_a_0, tau, hbar_a, R_bar_Lemmon;
// Ideal-Gas contribution to enthalpy of air
hbar_a_0 = -7914.149298; //[J/mol]
R_bar_Lemmon = 8.314510; //[J/mol/K]
// Calculate the offset in the air enthalpy from a given state with a known (desired) enthalpy
double Tref = 473.15, vmolarref = 0.038837428192186184, href = 13782.240592933371;
Air->update(CoolProp::DmolarT_INPUTS, 1/vmolarref, Tref);
double tauref = 132.6312/Tref; //[no units]
double href_EOS = R_bar_Lemmon*Tref*(1+tauref*Air->keyed_output(CoolProp::idalpha0_dtau_constdelta));
double hoffset = href - href_EOS;
// Tj is given by 132.6312 K
tau = 132.6312/T;
// Now calculate it based on the given inputs
Air->specify_phase(CoolProp::iphase_gas);
Air->update_DmolarT_direct(p/(R_bar*T), T);
Air->unspecify_phase();
hbar_a = hbar_a_0 + hoffset + R_bar_Lemmon*T*(1+tau*Air->keyed_output(CoolProp::idalpha0_dtau_constdelta)); //[J/mol]
return hbar_a;
}
double IdealGasMolarEntropy_Air(double T, double vmolar_a)
{
double sbar_0_Lem, tau, sbar_a, R_bar_Lemmon = 8.314510, T0=273.15, p0=101325, vmolar_a_0;
// Ideal-Gas contribution to entropy of air
sbar_0_Lem = -196.1375815; //[J/mol/K]
vmolar_a_0 = R_bar_Lemmon*T0/p0; //[m^3/mol]
// Calculate the offset in the air entropy from a given state with a known (desired) entropy
double Tref = 473.15, vmolarref = 0.038837605637863169, sref = 212.22365283759311;
Air->update(CoolProp::DmolarT_INPUTS, 1/vmolar_a_0, Tref);
double tauref = 132.6312/Tref; //[no units]
double sref_EOS = R_bar_Lemmon*(tauref*Air->keyed_output(CoolProp::idalpha0_dtau_constdelta)-Air->keyed_output(CoolProp::ialpha0))+R_bar_Lemmon*log(vmolarref/vmolar_a_0);
double soffset = sref - sref_EOS;
// Tj and rhoj are given by 132.6312 and 302.5507652 respectively
tau = 132.6312/T; //[no units]
Air->specify_phase(CoolProp::iphase_gas);
Air->update_DmolarT_direct(1/vmolar_a_0,T);
Air->unspecify_phase();
sbar_a=sbar_0_Lem + soffset + R_bar_Lemmon*(tau*Air->keyed_output(CoolProp::idalpha0_dtau_constdelta)-Air->keyed_output(CoolProp::ialpha0))+R_bar_Lemmon*log(vmolar_a/vmolar_a_0); //[J/mol/K]
return sbar_a; //[J/mol[air]/K]
}
/**
@param T Temperature, in K
@param p Pressure (not used)
@param psi_w Water mole fraction (mol_w/mol_ha)
@param vmolar Mixture molar volume in m^3/mol_ha
@returns h_ha Mixture molar enthalpy on a humid air basis in J/mol_ha
*/
double MolarEnthalpy(double T, double p, double psi_w, double vmolar)
{
// In units of kJ/kmol
// vbar (molar volume) in m^3/kg
double hbar_0, hbar_a, hbar_w, hbar, R_bar=8.314472;
// ----------------------------------------
// Enthalpy
// ----------------------------------------
// Constant for enthalpy
// Not clear why getting rid of this term yields the correct values in the table, but enthalpies are equal to an additive constant, so not a big deal
hbar_0=0.0;//2.924425468; //[kJ/kmol]
if (FlagUseIdealGasEnthalpyCorrelations){
hbar_w = 2.7030251618E-03*T*T + 3.1994361015E+01*T + 3.6123174929E+04;
hbar_a = 9.2486716590E-04*T*T + 2.8557221776E+01*T - 7.8616129429E+03;
}
else{
hbar_w = IdealGasMolarEnthalpy_Water(T, p); // [J/mol[water]]
hbar_a = IdealGasMolarEnthalpy_Air(T, p); // [J/mol[dry air]]
}
// If the user changes the reference state for water or Air, we need to ensure that the values returned from this
// function are always the same as the formulation expects. Therefore we can use a state point for which we know what the
// enthalpy should be and then correct the calculated values for the enthalpy.
hbar = hbar_0+(1-psi_w)*hbar_a+psi_w*hbar_w+R_bar*T*((B_m(T,psi_w)-T*dB_m_dT(T,psi_w))/vmolar+(C_m(T,psi_w)-T/2.0*dC_m_dT(T,psi_w))/(vmolar*vmolar));
return hbar; //[J/mol_ha]
}
double MolarInternalEnergy(double T, double p, double psi_w, double vmolar)
{
return MolarEnthalpy(T, p, psi_w, vmolar) - p*vmolar;
}
double MassEnthalpy_per_kgha(double T, double p, double psi_w)
{
double vmolar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
double h_bar = MolarEnthalpy(T, p, psi_w, vmolar); //[J/mol_ha]
double M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966; // [kg_ha/mol_ha]
return h_bar/M_ha; //[J/kg_ha]
}
double MassEnthalpy_per_kgda(double T, double p, double psi_w)
{
double vmolar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
double h_bar = MolarEnthalpy(T, p, psi_w, vmolar); //[J/mol_ha]
double W = HumidityRatio(psi_w); //[kg_w/kg_da] // (1+W) is kg_ha/kg_da
double M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966; // [kg_ha/mol_ha]
return h_bar*(1+W)/M_ha; //[J/kg_da]
}
double MassInternalEnergy_per_kgha(double T, double p, double psi_w)
{
double vmolar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
double h_bar = MolarInternalEnergy(T, p, psi_w, vmolar); //[J/mol_ha]
double M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966; // [kg_ha/mol_ha]
return h_bar/M_ha; //[J/kg_ha]
}
double MassInternalEnergy_per_kgda(double T, double p, double psi_w)
{
double vmolar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
double h_bar = MolarInternalEnergy(T, p, psi_w, vmolar); //[J/mol_da]
double W = HumidityRatio(psi_w); //[kg_w/kg_da] // (1+W) is kg_ha/kg_da
double M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966; // [kg_ha/mol_ha]
return h_bar*(1+W)/M_ha; //[J/kg_da]
}
/**
@param T Temperature, in K
@param p Pressure (not used)
@param psi_w Water mole fraction (mol_w/mol_ha)
@param v_bar Mixture molar volume in m^3/mol_ha
@returns s_ha Mixture molar entropy on a humid air basis in J/mol_ha/K
*/
double MolarEntropy(double T, double p, double psi_w, double v_bar)
{
// vbar (molar volume) in m^3/mol
double x1=0,x2=0,x3=0,y1=0,y2=0,eps=1e-8,f=999,R_bar_Lem=8.314510;
int iter=1;
double sbar_0,sbar_a=0,sbar_w=0,sbar,R_bar=8.314472,vbar_a_guess, Baa, Caaa,vbar_a=0;
double B,dBdT,C,dCdT;
// Constant for entropy
sbar_0=0.02366427495; //[J/mol/K]
// Calculate vbar_a, the molar volume of dry air
// B_m, C_m, etc. functions take care of the units
Baa = B_m(T,0);
B = B_m(T,psi_w);
dBdT = dB_m_dT(T,psi_w);
Caaa = C_m(T,0);
C = C_m(T,psi_w);
dCdT = dC_m_dT(T,psi_w);
vbar_a_guess = R_bar_Lem*T/p; //[m^3/mol] since p in [Pa]
while ((iter<=3 || std::abs(f)>eps) && iter<100)
{
if (iter==1){x1=vbar_a_guess; vbar_a=x1;}
if (iter==2){x2=vbar_a_guess+0.001; vbar_a=x2;}
if (iter>2) {vbar_a=x2;}
f=R_bar_Lem*T/vbar_a*(1+Baa/vbar_a+Caaa/pow(vbar_a,2))-p;
if (iter==1){y1=f;}
if (iter>1)
{
y2=f;
x3=x2-y2/(y2-y1)*(x2-x1);
y1=y2; x1=x2; x2=x3;
}
iter=iter+1;
}
if (FlagUseIdealGasEnthalpyCorrelations){
std::cout << "Not implemented" << std::endl;
}
else{
sbar_w=IdealGasMolarEntropy_Water(T,p);
sbar_a=IdealGasMolarEntropy_Air(T,vbar_a);
}
if (psi_w!=0){
sbar = sbar_0+(1-psi_w)*sbar_a+psi_w*sbar_w-R_bar*( (B+T*dBdT)/v_bar+(C+T*dCdT)/(2*pow(v_bar,2))+(1-psi_w)*log(1-psi_w)+psi_w*log(psi_w));
}
else{
sbar = sbar_0+sbar_a;
}
return sbar; //[J/mol_ha/K]
}
double MassEntropy_per_kgha(double T, double p, double psi_w)
{
double vmolar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
double s_bar = MolarEntropy(T, p, psi_w, vmolar); //[J/mol_ha/K]
double M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966; // [kg_ha/mol_ha]
return s_bar/M_ha; //[J/kg_ha/K]
}
double MassEntropy_per_kgda(double T, double p, double psi_w)
{
double vmolar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
double s_bar = MolarEntropy(T, p, psi_w, vmolar); //[J/mol_ha/K]
double M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966; // [kg_ha/mol_ha]
double W = HumidityRatio(psi_w); //[kg_w/kg_da] // (1+W) is kg_ha/kg_da
return s_bar*(1+W)/M_ha; //[J/kg_da/K]
}
double DewpointTemperature(double T, double p, double psi_w)
{
int iter;
double p_w,eps,resid,Tdp=0,x1=0,x2=0,x3,y1=0,y2,T0;
double p_ws_dp,f_dp;
// Make sure it isn't dry air, return an impossible temperature otherwise
if ((1-psi_w)<1e-16)
{
return -1;
}
// ------------------------------------------
// Iteratively find the dewpoint temperature
// ------------------------------------------
// The highest dewpoint temperature possible is the dry-bulb temperature.
// When they are equal, the air is saturated (R=1)
p_w = psi_w*p;
// 611.65... is the triple point pressure of water in Pa
if (p_w > 611.6547241637944){
T0 = IF97::Tsat97(p) - 1;
}
else{
T0 = 268;
}
// A good guess for Tdp is that enhancement factor is unity, which yields
// p_w_s = p_w, and get guess for T from saturation temperature
iter=1; eps=1e-5; resid=999;
while ((iter<=3 || std::abs(resid)>eps) && iter<100)
{
if (iter==1){x1 = T0; Tdp=x1;}
if (iter==2){x2 = x1 + 0.1; Tdp=x2;}
if (iter>2) {Tdp=x2;}
if (Tdp >= 273.16)
{
// Saturation pressure at dewpoint [Pa]
p_ws_dp = IF97::psat97(Tdp);
}
else
{
// Sublimation pressure at icepoint [Pa]
p_ws_dp=psub_Ice(Tdp);
}
// Enhancement Factor at dewpoint temperature [-]
f_dp=f_factor(Tdp,p);
// Error between target and actual pressure [Pa]
resid=p_w-p_ws_dp*f_dp;
if (iter==1){y1=resid;}
if (iter>1)
{
y2=resid;
x3=x2-y2/(y2-y1)*(x2-x1);
y1=y2; x1=x2; x2=x3;
}
iter=iter+1;
}
return Tdp;
}
class WetBulbSolver : public CoolProp::FuncWrapper1D
{
private:
double _p,_W,LHS;
public:
WetBulbSolver(double T, double p, double psi_w)
: _p(p),_W(epsilon*psi_w/(1-psi_w))
{
//These things are all not a function of Twb
double v_bar_w = MolarVolume(T,p,psi_w),
M_ha = MM_Water()*psi_w+(1-psi_w)*0.028966;
LHS = MolarEnthalpy(T,p,psi_w,v_bar_w)*(1+_W)/M_ha;
}
double call(double Twb)
{
double epsilon=0.621945;
double f_wb,p_ws_wb,p_s_wb,W_s_wb,h_w,M_ha_wb,psi_wb,v_bar_wb;
// Enhancement Factor at wetbulb temperature [-]
f_wb=f_factor(Twb,_p);
if (Twb > 273.16)
{
// Saturation pressure at wetbulb temperature [Pa]
p_ws_wb= IF97::psat97(Twb);
}
else
{
// Sublimation pressure at wetbulb temperature [kPa]
p_ws_wb=psub_Ice(Twb);
}
// Vapor pressure
p_s_wb = f_wb*p_ws_wb;
// wetbulb humidity ratio
W_s_wb = epsilon*p_s_wb/(_p-p_s_wb);
// wetbulb water mole fraction
psi_wb = W_s_wb/(epsilon+W_s_wb);
if (Twb > 273.16)
{
// Use IF97 to do the flash
WaterIF97->update(CoolProp::PT_INPUTS, _p, Twb);
// Enthalpy of water [J/kg_water]
Water->update(CoolProp::DmassT_INPUTS, WaterIF97->rhomass(), Twb);
h_w = Water->keyed_output(CoolProp::iHmass); //[J/kg_water]
}
else
{
// Enthalpy of ice [J/kg_water]
h_w=h_Ice(Twb,_p);
}
// Mole masses of wetbulb and humid air
M_ha_wb = MM_Water()*psi_wb+(1-psi_wb)*0.028966;
v_bar_wb=MolarVolume(Twb,_p,psi_wb);
double RHS = (MolarEnthalpy(Twb,_p,psi_wb,v_bar_wb)*(1+W_s_wb)/M_ha_wb+(_W-W_s_wb)*h_w);
if (!ValidNumber(LHS-RHS)){throw CoolProp::ValueError();}
return LHS - RHS;
}
};
class WetBulbTminSolver : public CoolProp::FuncWrapper1D
{
public:
double p,hair_dry;
WetBulbTminSolver(double p, double hair_dry):p(p),hair_dry(hair_dry){}
double call(double Ts)
{
double RHS = HAPropsSI("H","T",Ts,"P",p,"R",1);
if (!ValidNumber(RHS)){throw CoolProp::ValueError();}
return RHS - this->hair_dry;
}
};
double WetbulbTemperature(double T, double p, double psi_w)
{
// ------------------------------------------
// Iteratively find the wetbulb temperature
// ------------------------------------------
//
// If the temperature is less than the saturation temperature of water
// for the given atmospheric pressure, the highest wetbulb temperature that is possible is the dry bulb
// temperature
//
// If the temperature is above the saturation temperature corresponding to the atmospheric pressure,
// then the maximum value for the wetbulb temperature is the saturation temperature
double Tmax = T;
double Tsat = IF97::Tsat97(p);
if (T >= Tsat)
{
Tmax = Tsat;
}
// Instantiate the solver container class
WetBulbSolver WBS(T, p, psi_w);
double return_val;
try{
return_val = Brent(WBS,Tmax+1,100, DBL_EPSILON, 1e-12, 50);
// Solution obtained is out of range (T>Tmax)
if (return_val > Tmax + 1) {throw CoolProp::ValueError();}
}
catch(...)
{
// The lowest wetbulb temperature that is possible for a given dry bulb temperature
// is the saturated air temperature which yields the enthalpy of dry air at dry bulb temperature
try{
double hair_dry = MassEnthalpy_per_kgda(T,p,0); // both /kg_ha and /kg_da are the same here since dry air
// Directly solve for the saturated temperature that yields the enthalpy desired
WetBulbTminSolver WBTS(p,hair_dry);
double Tmin = Brent(WBTS,210,Tsat-1,1e-12,1e-12,50);
return_val = Brent(WBS,Tmin-30,Tmax-1,1e-12,1e-12,50);
}
catch(...)
{
return_val = _HUGE;
}
}
return return_val;
}
static givens Name2Type(const std::string &Name)
{
if (!strcmp(Name,"Omega") || !strcmp(Name,"HumRat") || !strcmp(Name,"W"))
return GIVEN_HUMRAT;
else if (!strcmp(Name,"psi_w") || !strcmp(Name, "Y"))
return GIVEN_PSIW;
else if (!strcmp(Name,"Tdp") || !strcmp(Name,"T_dp") || !strcmp(Name,"DewPoint") || !strcmp(Name,"D"))
return GIVEN_TDP;
else if (!strcmp(Name,"Twb") || !strcmp(Name,"T_wb") || !strcmp(Name,"WetBulb") || !strcmp(Name,"B"))
return GIVEN_TWB;
else if (!strcmp(Name,"Enthalpy") || !strcmp(Name,"H") || !strcmp(Name,"Hda"))
return GIVEN_ENTHALPY;
else if (!strcmp(Name,"Hha"))
return GIVEN_ENTHALPY_HA;
else if (!strcmp(Name,"InternalEnergy") || !strcmp(Name,"U") || !strcmp(Name,"Uda"))
return GIVEN_INTERNAL_ENERGY;
else if (!strcmp(Name,"Uha"))
return GIVEN_INTERNAL_ENERGY_HA;
else if (!strcmp(Name,"Entropy") || !strcmp(Name,"S") || !strcmp(Name,"Sda"))
return GIVEN_ENTROPY;
else if (!strcmp(Name,"Sha"))
return GIVEN_ENTROPY_HA;
else if (!strcmp(Name,"RH") || !strcmp(Name,"RelHum") || !strcmp(Name,"R"))
return GIVEN_RH;
else if (!strcmp(Name,"Tdb") || !strcmp(Name,"T_db") || !strcmp(Name,"T"))
return GIVEN_T;
else if (!strcmp(Name,"P"))
return GIVEN_P;
else if (!strcmp(Name,"V") || !strcmp(Name,"Vda"))
return GIVEN_VDA;
else if (!strcmp(Name,"Vha"))
return GIVEN_VHA;
else if (!strcmp(Name,"mu") || !strcmp(Name,"Visc") || !strcmp(Name,"M"))
return GIVEN_VISC;
else if (!strcmp(Name,"k") || !strcmp(Name,"Conductivity") || !strcmp(Name,"K"))
return GIVEN_COND;
else if (!strcmp(Name,"C") || !strcmp(Name,"cp"))
return GIVEN_CP;
else if (!strcmp(Name,"Cha") || !strcmp(Name,"cp_ha"))
return GIVEN_CPHA;
else if (!strcmp(Name,"CV"))
return GIVEN_CV;
else if (!strcmp(Name,"CVha") || !strcmp(Name,"cv_ha"))
return GIVEN_CVHA;
else if (!strcmp(Name,"P_w"))
return GIVEN_PARTIAL_PRESSURE_WATER;
else if (!strcmp(Name,"isentropic_exponent"))
return GIVEN_ISENTROPIC_EXPONENT;
else if (!strcmp(Name,"speed_of_sound"))
return GIVEN_SPEED_OF_SOUND;
else if (!strcmp(Name,"Z"))
return GIVEN_COMPRESSIBILITY_FACTOR;
else
throw CoolProp::ValueError(format("Sorry, your input [%s] was not understood to Name2Type. Acceptable values are T,P,R,W,D,B,H,S,M,K and aliases thereof\n",Name.c_str()));
}
int TypeMatch(int TypeCode, const std::string &Input1Name, const std::string &Input2Name, const std::string &Input3Name)
{
// Return the index of the input variable that matches the input, otherwise return -1 for failure
if (TypeCode==Name2Type(Input1Name))
return 1;
if (TypeCode==Name2Type(Input2Name))
return 2;
if (TypeCode==Name2Type(Input3Name))
return 3;
else
return -1;
}
double MoleFractionWater(double T, double p, int HumInput, double InVal)
{
double p_ws,f,W,epsilon=0.621945,Tdp,p_ws_dp,f_dp,p_w_dp,p_s,RH;
if (HumInput==GIVEN_HUMRAT) //(2)
{
W=InVal;
return W/(epsilon+W);
}
else if (HumInput==GIVEN_RH)
{
if (T>=273.16)
{
// Saturation pressure [Pa]
p_ws= IF97::psat97(T);
}
else
{
// Sublimation pressure [Pa]
p_ws=psub_Ice(T);
}
// Enhancement Factor [-]
f=f_factor(T,p);
// Saturation pressure [Pa]
p_s=f*p_ws;
RH=InVal;
W=epsilon*RH*p_s/(p-RH*p_s);
return W/(epsilon+W);
}
else if (HumInput==GIVEN_TDP)
{
Tdp=InVal;
// Saturation pressure at dewpoint [Pa]
if (Tdp>=273.16){
p_ws_dp = IF97::psat97(Tdp);
}
else{
// Sublimation pressure [Pa]
p_ws_dp=psub_Ice(Tdp);
}
// Enhancement Factor at dewpoint temperature [-]
f_dp=f_factor(Tdp,p);
// Water vapor pressure at dewpoint [Pa]
p_w_dp=f_dp*p_ws_dp;
// Water mole fraction [-]
return p_w_dp/p;
}
else
{
return -1000000;
}
}
double RelativeHumidity(double T, double p, double psi_w)
{
double p_ws, f, p_s;
if (T >= 273.16){
// Saturation pressure [Pa]
p_ws = IF97::psat97(T);
}
else{
// sublimation pressure [Pa]
p_ws = psub_Ice(T);
}
// Enhancement Factor [-]
f = f_factor(T,p);
// Saturation pressure [Pa]
p_s = f*p_ws;
// Calculate the relative humidity
return psi_w*p/p_s;
}
void convert_to_SI(const std::string &Name, double &val)
{
switch(Name2Type(Name))
{
case GIVEN_COND:
case GIVEN_ENTHALPY:
case GIVEN_ENTHALPY_HA:
case GIVEN_ENTROPY:
case GIVEN_ENTROPY_HA:
case GIVEN_INTERNAL_ENERGY:
case GIVEN_INTERNAL_ENERGY_HA:
case GIVEN_CP:
case GIVEN_CPHA:
case GIVEN_CV:
case GIVEN_CVHA:
case GIVEN_P:
case GIVEN_PARTIAL_PRESSURE_WATER:
case GIVEN_SPEED_OF_SOUND:
case GIVEN_ISENTROPIC_EXPONENT:
val *= 1000; return;
case GIVEN_T:
case GIVEN_TDP:
case GIVEN_TWB:
case GIVEN_RH:
case GIVEN_VDA:
case GIVEN_VHA:
case GIVEN_HUMRAT:
case GIVEN_VISC:
case GIVEN_PSIW:
case GIVEN_COMPRESSIBILITY_FACTOR:
return;
case GIVEN_INVALID:
throw CoolProp::ValueError(format("invalid input to convert_to_SI"));
}
}
void convert_from_SI(const std::string &Name, double &val)
{
switch(Name2Type(Name))
{
case GIVEN_COND:
case GIVEN_ENTHALPY:
case GIVEN_ENTHALPY_HA:
case GIVEN_ENTROPY:
case GIVEN_ENTROPY_HA:
case GIVEN_INTERNAL_ENERGY:
case GIVEN_INTERNAL_ENERGY_HA:
case GIVEN_CP:
case GIVEN_CPHA:
case GIVEN_CV:
case GIVEN_CVHA:
case GIVEN_P:
case GIVEN_PARTIAL_PRESSURE_WATER:
case GIVEN_SPEED_OF_SOUND:
case GIVEN_ISENTROPIC_EXPONENT:
val /= 1000; return;
case GIVEN_T:
case GIVEN_TDP:
case GIVEN_TWB:
case GIVEN_RH:
case GIVEN_VDA:
case GIVEN_VHA:
case GIVEN_HUMRAT:
case GIVEN_VISC:
case GIVEN_PSIW:
case GIVEN_COMPRESSIBILITY_FACTOR:
return;
case GIVEN_INVALID:
throw CoolProp::ValueError(format("invalid input to convert_from_SI"));
}
}
double HAProps(const std::string &OutputName, const std::string &Input1Name, double Input1, const std::string &Input2Name, double Input2, const std::string &Input3Name, double Input3)
{
convert_to_SI(Input1Name, Input1);
convert_to_SI(Input2Name, Input2);
convert_to_SI(Input3Name, Input3);
double out = HAPropsSI(OutputName, Input1Name, Input1, Input2Name, Input2, Input3Name, Input3);
convert_from_SI(OutputName, out);
return out;
}
long get_input_key(const std::vector<givens> &input_keys, givens key)
{
if (input_keys.size() != 2){throw CoolProp::ValueError("input_keys is not 2-element vector");}
if (input_keys[0] == key){ return 0; }
else if (input_keys[1] == key){ return 1; }
else{ return -1; }
}
bool match_input_key(const std::vector<givens> &input_keys, givens key)
{
return get_input_key(input_keys, key) >= 0;
}
/// Calculate T (dry bulb temp) and psi_w (water mole fraction) given the pair of inputs
void _HAPropsSI_inputs(double p, const std::vector<givens> &input_keys, const std::vector<double> &input_vals, double &T, double &psi_w)
{
if (CoolProp::get_debug_level() > 0){ std::cout << format("length of input_keys is %d\n", input_keys.size()); }
if (input_keys.size() != input_vals.size()){ throw CoolProp::ValueError(format("Length of input_keys (%d) does not equal that of input_vals (%d)", input_keys.size(), input_vals.size())); }
long key = get_input_key(input_keys, GIVEN_T);
if (key >= 0) // Found T (or alias) as an input
{
long other = 1 - key; // 2 element vector
T = input_vals[key];
if (CoolProp::get_debug_level() > 0){ std::cout << format("One of the inputs is T: %g K\n", T); }
givens othergiven = input_keys[other];
switch(othergiven){
case GIVEN_RH:
case GIVEN_HUMRAT:
case GIVEN_TDP:
if (CoolProp::get_debug_level() > 0){
std::cout << format("other input value is %g\n", input_vals[other]);
std::cout << format("other input index is %d\n", othergiven);
}
psi_w = MoleFractionWater(T, p, othergiven, input_vals[other]); break;
default:
{
double W;
try{
// Find the value for W
double W_guess = 0.0001;
W = Secant_HAProps_W(p, T, othergiven, input_vals[other], W_guess);
if (!ValidNumber(W)){
throw CoolProp::ValueError("Iterative value for W is invalid");
}
}
catch(...){
// Use the Brent's method solver to find W. Slow but reliable
double W_min = 0.001, W_max = 1;
givens MainInputKey = GIVEN_T;
double MainInputValue = T;
// Secondary input is the one that you are trying to match
double SecondaryInputValue = input_vals[other];
givens SecondaryInputKey = input_keys[other];
W = Brent_HAProps_W(SecondaryInputKey, p, MainInputKey, MainInputValue, SecondaryInputValue, W_min, W_max);
}
// Mole fraction of water
psi_w = MoleFractionWater(T, p, GIVEN_HUMRAT, W);
}
}
}
else
{
if (CoolProp::get_debug_level() > 0){ std::cout << format("The main input is not T\n", T); }
// Need to iterate to find dry bulb temperature since temperature is not provided
if ((key = get_input_key(input_keys, GIVEN_HUMRAT)) >= 0){} // Humidity ratio is given
else if ((key = get_input_key(input_keys, GIVEN_RH)) >= 0){} // Relative humidity is given
else if ((key = get_input_key(input_keys, GIVEN_TDP)) >= 0){} // Dewpoint temperature is given
else{
throw CoolProp::ValueError("Sorry, but currently at least one of the variables as an input to HAPropsSI() must be temperature, relative humidity, humidity ratio, or dewpoint\n Eventually will add a 2-D NR solver to find T and psi_w simultaneously, but not included now");
}
// Don't allow inputs that have two water inputs
int number_of_water_content_inputs = (get_input_key(input_keys, GIVEN_HUMRAT) >= 0) + (get_input_key(input_keys, GIVEN_RH) >= 0) + (get_input_key(input_keys, GIVEN_TDP) >= 0);
if (number_of_water_content_inputs > 1){
throw CoolProp::ValueError("Sorry, but cannot provide two inputs that are both water-content (humidity ratio, relative humidity, absolute humidity");
}
// 2-element vector
long other = 1 - key;
// Main input is the one that you are using in the call to HAPropsSI
double MainInputValue = input_vals[key];
givens MainInputKey = input_keys[key];
// Secondary input is the one that you are trying to match
double SecondaryInputValue = input_vals[other];
givens SecondaryInputKey = input_keys[other];
if (CoolProp::get_debug_level() > 0){
std::cout << format("Main input is %g\n", MainInputValue);
std::cout << format("Secondary input is %g\n", SecondaryInputValue);
}
double T_min = 200;
double T_max = 450;
if (MainInputKey == GIVEN_RH){
if (MainInputValue < 1e-10){
T_max = 640;
// For wetbulb, has to be below critical temp
if (SecondaryInputKey == GIVEN_TWB || SecondaryInputKey == GIVEN_ENTHALPY){
T_max = 640;
}
if (SecondaryInputKey == GIVEN_TDP){
throw CoolProp::ValueError("For dry air, dewpoint is an invalid input variable\n");
}
}
else{
T_max = CoolProp::PropsSI("T","P",p,"Q",0,"Water") - 1;
}
}
// Minimum drybulb temperature is the drybulb temperature corresponding to saturated air for the humidity ratio
// if the humidity ratio is provided
else if (MainInputKey == GIVEN_HUMRAT){
if (MainInputValue < 1e-10){
T_min = 135; // Around the critical point of dry air
T_max = 1000;
}
else{
// Convert given humidity ratio to water mole fraction in vapor phase
double T_dummy = -1, // Not actually needed
psi_w_sat = MoleFractionWater(T_dummy, p, GIVEN_HUMRAT, MainInputValue);
// Partial pressure of water, which is equal to f*p_{w_s}
double pp_water_sat = psi_w_sat*p;
// Assume unity enhancement factor, calculate guess for drybulb temperature
// for given water phase composition
if (pp_water_sat > Water->p_triple()){
T_min = IF97::Tsat97(pp_water_sat);
}
else{
T_min = 230;
}
// Iteratively solve for temperature that will give desired pp_water_sat
T_min = Secant_Tdb_at_saturated_W(psi_w_sat, p, T_min);
}
}
try{
// Use the Brent's method solver to find T. Slow but reliable
T = Brent_HAProps_T(SecondaryInputKey, p, MainInputKey, MainInputValue, SecondaryInputValue, T_min,T_max);
}
catch(std::exception &e){
if (CoolProp::get_debug_level() > 0){ std::cout << "ERROR: " << e.what() << std::endl; }
CoolProp::set_error_string(e.what());
T = _HUGE;
psi_w = _HUGE;
return;
}
// Otherwise, find psi_w for further calculations in the following section
std::vector<givens> input_keys(2, GIVEN_T); input_keys[1] = MainInputKey;
std::vector<double> input_vals(2, T); input_vals[1] = MainInputValue;
_HAPropsSI_inputs(p, input_keys, input_vals, T, psi_w);
}
}
double _HAPropsSI_outputs(givens OutputType, double p, double T, double psi_w)
{
if (CoolProp::get_debug_level() > 0){ std::cout << format("_HAPropsSI_outputs :: T: %g K, psi_w: %g\n", T, psi_w); }
double M_ha=(1-psi_w)*0.028966+MM_Water()*psi_w; //[kg_ha/mol_ha]
// -----------------------------------------------------------------
// Calculate and return the desired value for known set of p,T,psi_w
// -----------------------------------------------------------------
switch (OutputType){
case GIVEN_T:
return T;
case GIVEN_P:
return p;
case GIVEN_VDA:{
double v_bar = MolarVolume(T,p,psi_w); //[m^3/mol_ha]
double W = HumidityRatio(psi_w); //[kg_w/kg_a]
return v_bar*(1+W)/M_ha; //[m^3/kg_da]
}
case GIVEN_VHA:{
double v_bar = MolarVolume(T,p,psi_w); //[m^3/mol_ha]
return v_bar/M_ha; //[m^3/kg_ha]
}
case GIVEN_PSIW:{
return psi_w; //[mol_w/mol]
}
case GIVEN_PARTIAL_PRESSURE_WATER:{
return psi_w*p; //[Pa]
}
case GIVEN_ENTHALPY:{
return MassEnthalpy_per_kgda(T,p,psi_w); //[J/kg_da]
}
case GIVEN_ENTHALPY_HA:{
return MassEnthalpy_per_kgha(T,p,psi_w); //[J/kg_ha]
}
case GIVEN_INTERNAL_ENERGY:{
return MassInternalEnergy_per_kgda(T,p,psi_w); //[J/kg_da]
}
case GIVEN_INTERNAL_ENERGY_HA:{
return MassInternalEnergy_per_kgha(T,p,psi_w); //[J/kg_ha]
}
case GIVEN_ENTROPY:{
return MassEntropy_per_kgda(T,p,psi_w); //[J/kg_da/K]
}
case GIVEN_ENTROPY_HA:{
return MassEntropy_per_kgha(T,p,psi_w); //[J/kg_ha/K]
}
case GIVEN_TDP:{
return DewpointTemperature(T,p,psi_w); //[K]
}
case GIVEN_TWB:{
return WetbulbTemperature(T,p,psi_w); //[K]
}
case GIVEN_HUMRAT:{
return HumidityRatio(psi_w);
}
case GIVEN_RH:{
return RelativeHumidity(T,p,psi_w);
}
case GIVEN_VISC:{
return Viscosity(T,p,psi_w);
}
case GIVEN_COND:{
return Conductivity(T,p,psi_w);
}
case GIVEN_CP:{
// [J/kg_ha/K]*[kg_ha/kg_da] because 1+W = kg_ha/kg_da
return _HAPropsSI_outputs(GIVEN_CPHA, p, T, psi_w)*(1+HumidityRatio(psi_w));
}
case GIVEN_CPHA:{
double v_bar1,v_bar2,h_bar1,h_bar2, cp_ha, dT = 1e-3;
v_bar1=MolarVolume(T-dT,p,psi_w); //[m^3/mol_ha]
h_bar1=MolarEnthalpy(T-dT,p,psi_w,v_bar1); //[J/mol_ha]
v_bar2=MolarVolume(T+dT,p,psi_w); //[m^3/mol_ha]
h_bar2=MolarEnthalpy(T+dT,p,psi_w,v_bar2); //[J/mol_ha]
cp_ha = (h_bar2-h_bar1)/(2*dT); //[J/mol_ha/K]
return cp_ha/M_ha; //[J/kg_ha/K]
}
case GIVEN_CV:{
// [J/kg_ha/K]*[kg_ha/kg_da] because 1+W = kg_ha/kg_da
return _HAPropsSI_outputs(GIVEN_CVHA, p, T, psi_w)*(1+HumidityRatio(psi_w));
}
case GIVEN_CVHA:{
double v_bar,p_1,p_2,u_bar1,u_bar2, cv_bar, dT = 1e-3;
v_bar = MolarVolume(T,p,psi_w); //[m^3/mol_ha]
p_1 = Pressure(T-dT, v_bar, psi_w);
u_bar1=MolarInternalEnergy(T-dT,p_1,psi_w,v_bar); //[J/mol_ha]
p_2 = Pressure(T+dT, v_bar, psi_w);
u_bar2=MolarInternalEnergy(T+dT,p_2,psi_w,v_bar); //[J/mol_ha]
cv_bar = (u_bar2-u_bar1)/(2*dT); //[J/mol_ha/K]
return cv_bar/M_ha; //[J/kg_ha/K]
}
case GIVEN_ISENTROPIC_EXPONENT:{
CoolPropDbl v_bar, dv = 1e-8, p_1, p_2;
CoolPropDbl cp = _HAPropsSI_outputs(GIVEN_CPHA, p, T, psi_w); //[J/kg_da/K]
CoolPropDbl cv = _HAPropsSI_outputs(GIVEN_CVHA, p, T, psi_w); //[J/kg_da/K]
v_bar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
p_1 = Pressure(T, v_bar-dv, psi_w);
p_2 = Pressure(T, v_bar+dv, psi_w);
CoolPropDbl dpdv__constT = (p_2 - p_1)/(2*dv);
return -cp/cv*dpdv__constT*v_bar/p;
}
case GIVEN_SPEED_OF_SOUND:{
CoolPropDbl v_bar, dv = 1e-8, p_1, p_2;
CoolPropDbl cp = _HAPropsSI_outputs(GIVEN_CPHA, p, T, psi_w); //[J/kg_da/K]
CoolPropDbl cv = _HAPropsSI_outputs(GIVEN_CVHA, p, T, psi_w); //[J/kg_da/K]
v_bar = MolarVolume(T, p, psi_w); //[m^3/mol_ha]
p_1 = Pressure(T, v_bar-dv, psi_w);
p_2 = Pressure(T, v_bar+dv, psi_w);
CoolPropDbl dvdrho = -v_bar*v_bar;
CoolPropDbl dpdrho__constT = (p_2 - p_1)/(2*dv)*dvdrho;
return sqrt(1/M_ha*cp/cv*dpdrho__constT);
}
case GIVEN_COMPRESSIBILITY_FACTOR:{
double v_bar = MolarVolume(T,p,psi_w); //[m^3/mol_ha]
double R_u_molar = 8.314472; // J/mol/K
return p*v_bar/(R_u_molar*T);
}
default:
return _HUGE;
}
}
double HAPropsSI(const std::string &OutputName, const std::string &Input1Name, double Input1, const std::string &Input2Name, double Input2, const std::string &Input3Name, double Input3)
{
try
{
// Add a check to make sure that Air and Water fluid states have been properly instantiated
check_fluid_instantiation();
Water->clear();
Air->clear();
if (CoolProp::get_debug_level() > 0){ std::cout << format("HAPropsSI(%s,%s,%g,%s,%g,%s,%g)\n", OutputName.c_str(), Input1Name.c_str(), Input1, Input2Name.c_str(), Input2, Input3Name.c_str(), Input3); }
std::vector<givens> input_keys(2);
std::vector<double> input_vals(2);
givens In1Type, In2Type, In3Type, OutputType;
double p, T = _HUGE, psi_w = _HUGE;
// First figure out what kind of inputs you have, convert names to enum values
In1Type = Name2Type(Input1Name.c_str());
In2Type = Name2Type(Input2Name.c_str());
In3Type = Name2Type(Input3Name.c_str());
// Output type
OutputType = Name2Type(OutputName.c_str());
// Check for trivial inputs
if (OutputType == In1Type){return Input1;}
if (OutputType == In2Type){return Input2;}
if (OutputType == In3Type){return Input3;}
// Check that pressure is provided; load input vectors
if (In1Type == GIVEN_P){
p = Input1;
input_keys[0] = In2Type; input_keys[1] = In3Type;
input_vals[0] = Input2; input_vals[1] = Input3;
}
else if (In2Type == GIVEN_P){
p = Input2;
input_keys[0] = In1Type; input_keys[1] = In3Type;
input_vals[0] = Input1; input_vals[1] = Input3;
}
else if (In3Type == GIVEN_P){
p = Input3;
input_keys[0] = In1Type; input_keys[1] = In2Type;
input_vals[0] = Input1; input_vals[1] = Input2;
}
else{
throw CoolProp::ValueError("Pressure must be one of the inputs to HAPropsSI");
}
if (input_keys[0] == input_keys[1]){
throw CoolProp::ValueError("Other two inputs to HAPropsSI aside from pressure cannot be the same");
}
// Parse the inputs to get to set of p, T, psi_w
_HAPropsSI_inputs(p, input_keys, input_vals, T, psi_w);
if (CoolProp::get_debug_level() > 0){ std::cout << format("HAPropsSI input conversion yields T: %g, psi_w: %g\n", T, psi_w); }
// Calculate the output value desired
double val = _HAPropsSI_outputs(OutputType, p, T, psi_w);
if (CoolProp::get_debug_level() > 0){ std::cout << format("HAPropsSI is about to return %g\n", val); }
return val;
}
catch (std::exception &e)
{
CoolProp::set_error_string(e.what());
return _HUGE;
}
catch (...)
{
return _HUGE;
}
}
double HAProps_Aux(const char* Name,double T, double p, double W, char *units)
{
// This function provides some things that are not usually needed, but could be interesting for debug purposes.
// Add a check to make sure that Air and Water fluid states have been properly instantiated
check_fluid_instantiation();
// Requires W since it is nice and fast and always defined. Put a dummy value if you want something that doesn't use humidity
// Takes temperature, pressure, and humidity ratio W as inputs;
double psi_w,B_aa,C_aaa,B_ww,C_www,B_aw,C_aaw,C_aww,v_bar;
try{
if (!strcmp(Name,"Baa"))
{
B_aa=B_Air(T); // [m^3/mol]
strcpy(units,"m^3/mol");
return B_aa;
}
else if (!strcmp(Name,"Caaa"))
{
C_aaa=C_Air(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return C_aaa;
}
else if (!strcmp(Name,"Bww"))
{
B_ww=B_Water(T); // [m^3/mol]
strcpy(units,"m^3/mol");
return B_ww;
}
else if (!strcmp(Name,"Cwww"))
{
C_www=C_Water(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return C_www;
}
else if (!strcmp(Name,"dBaa"))
{
B_aa=dBdT_Air(T); // [m^3/mol]
strcpy(units,"m^3/mol");
return B_aa;
}
else if (!strcmp(Name,"dCaaa"))
{
C_aaa=dCdT_Air(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return C_aaa;
}
else if (!strcmp(Name,"dBww"))
{
B_ww=dBdT_Water(T); // [m^3/mol]
strcpy(units,"m^3/mol");
return B_ww;
}
else if (!strcmp(Name,"dCwww"))
{
C_www=dCdT_Water(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return C_www;
}
else if (!strcmp(Name,"Baw"))
{
B_aw=_B_aw(T); // [m^3/mol]
strcpy(units,"m^3/mol");
return B_aw;
}
else if (!strcmp(Name,"Caww"))
{
C_aww=_C_aww(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return C_aww;
}
else if (!strcmp(Name,"Caaw"))
{
C_aaw=_C_aaw(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return C_aaw;
}
else if (!strcmp(Name,"dBaw"))
{
double dB_aw=_dB_aw_dT(T); // [m^3/mol]
strcpy(units,"m^3/mol");
return dB_aw;
}
else if (!strcmp(Name,"dCaww"))
{
double dC_aww=_dC_aww_dT(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return dC_aww;
}
else if (!strcmp(Name,"dCaaw"))
{
double dC_aaw=_dC_aaw_dT(T); // [m^6/mol^2]
strcpy(units,"m^6/mol^2");
return dC_aaw;
}
else if (!strcmp(Name,"beta_H"))
{
strcpy(units,"1/Pa");
return HenryConstant(T);
}
else if (!strcmp(Name,"kT"))
{
strcpy(units,"1/Pa");
if (T>273.16)
{
// Use IF97 to do the flash
WaterIF97->update(CoolProp::PT_INPUTS, p, T);
Water->update(CoolProp::PT_INPUTS, WaterIF97->rhomass(), T);
return Water->keyed_output(CoolProp::iisothermal_compressibility);
}
else
return IsothermCompress_Ice(T,p); //[1/Pa]
}
else if (!strcmp(Name,"p_ws"))
{
strcpy(units,"Pa");
if (T>273.16){
return IF97::psat97(T);
}
else
return psub_Ice(T);
}
else if (!strcmp(Name,"vbar_ws"))
{
strcpy(units,"m^3/mol");
if (T>273.16)
{
Water->update(CoolProp::QT_INPUTS, 0, T);
return 1.0/Water->keyed_output(CoolProp::iDmolar);
}
else
{
// It is ice
return dg_dp_Ice(T,p)*MM_Water()/1000/1000; //[m^3/mol]
}
}
else if (!strcmp(Name,"f"))
{
strcpy(units,"-");
return f_factor(T,p);
}
// Get psi_w since everything else wants it
psi_w=MoleFractionWater(T,p,GIVEN_HUMRAT,W);
if (!strcmp(Name,"Bm"))
{
strcpy(units,"m^3/mol");
return B_m(T,psi_w);
}
else if (!strcmp(Name,"Cm"))
{
strcpy(units,"m^6/mol^2");
return C_m(T,psi_w);
}
else if (!strcmp(Name,"hvirial"))
{
v_bar=MolarVolume(T,p,psi_w);
return 8.3145*T*((B_m(T,psi_w)-T*dB_m_dT(T,psi_w))/v_bar+(C_m(T,psi_w)-T/2.0*dC_m_dT(T,psi_w))/(v_bar*v_bar));
}
//else if (!strcmp(Name,"ha"))
//{
// delta=1.1/322; tau=132/T;
// return 1+tau*DerivTerms("dphi0_dTau",tau,delta,"Water");
//}
//else if (!strcmp(Name,"hw"))
//{
// //~ return Props('D','T',T,'P',p,"Water")/322; tau=647/T;
// delta=1000/322; tau=647/T;
// //~ delta=rho_Water(T,p,TYPE_TP);tau=647/T;
// return 1+tau*DerivTerms("dphi0_dTau",tau,delta,"Water");
//}
else if (!strcmp(Name,"hbaro_w"))
{
return IdealGasMolarEnthalpy_Water(T,p);
}
else if (!strcmp(Name,"hbaro_a"))
{
return IdealGasMolarEnthalpy_Air(T,p);
}
else if (!strcmp(Name,"h_Ice"))
{
strcpy(units, "J/kg");
return h_Ice(T, p);
}
else if (!strcmp(Name,"s_Ice"))
{
strcpy(units, "J/kg/K");
return s_Ice(T, p);
}
else if (!strcmp(Name,"psub_Ice"))
{
strcpy(units, "Pa");
return psub_Ice(T);
}
else if (!strcmp(Name,"g_Ice"))
{
strcpy(units, "J/kg");
return g_Ice(T, p);
}
else if (!strcmp(Name,"rho_Ice"))
{
strcpy(units, "kg/m^3");
return rho_Ice(T, p);
}
else
{
printf("Sorry I didn't understand your input [%s] to HAProps_Aux\n",Name);
return -1;
}
}
catch(...){}
return _HUGE;
}
double cair_sat(double T)
{
// Humid air saturation specific heat at 1 atmosphere.
// Based on a correlation from EES, good from 250K to 300K.
// No error bound checking is carried out
// T: [K]
// cair_s: [kJ/kg-K]
return 2.14627073E+03-3.28917768E+01*T+1.89471075E-01*T*T-4.86290986E-04*T*T*T+4.69540143E-07*T*T*T*T;
}
double IceProps(const char* Name, double T, double p)
{
if (!strcmp(Name,"s"))
{
return s_Ice(T,p*1000.0);
}
else if (!strcmp(Name,"rho"))
{
return rho_Ice(T,p*1000.0);
}
else if (!strcmp(Name,"h"))
{
return h_Ice(T,p*1000.0);
}
else
{
return 1e99;
}
}
} /* namespace HumidAir */
#ifdef ENABLE_CATCH
#include <math.h>
#include "catch.hpp"
TEST_CASE("Check HA Virials from Table A.2.1","[RP1485]")
{
SECTION("B_aa")
{
CHECK(std::abs(HumidAir::B_Air(-60+273.15)/(-33.065/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::B_Air(0+273.15)/(-13.562/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::B_Air(200+273.15)/(11.905/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::B_Air(350+273.15)/(18.949/1e6)-1) < 1e-3);
}
SECTION("B_ww")
{
CHECK(std::abs(HumidAir::B_Water(-60+273.15)/(-11174/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::B_Water(0+273.15)/(-2025.6/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::B_Water(200+273.15)/(-200.52/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::B_Water(350+273.15)/(-89.888/1e6)-1) < 1e-3);
}
SECTION("B_aw")
{
CHECK(std::abs(HumidAir::_B_aw(-60+273.15)/(-68.306/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::_B_aw(0+273.15)/(-38.074/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::_B_aw(200+273.15)/(-2.0472/1e6)-1) < 1e-3);
CHECK(std::abs(HumidAir::_B_aw(350+273.15)/(7.5200/1e6)-1) < 1e-3);
}
SECTION("C_aaa")
{
CHECK(std::abs(HumidAir::C_Air(-60+273.15)/(2177.9/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::C_Air(0+273.15)/(1893.1/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::C_Air(200+273.15)/(1551.2/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::C_Air(350+273.15)/(1464.7/1e12)-1) < 1e-3);
}
SECTION("C_www")
{
CHECK(std::abs(HumidAir::C_Water(-60+273.15)/(-1.5162999202e-04)-1) < 1e-3); // Relaxed criterion for this parameter
CHECK(std::abs(HumidAir::C_Water(0+273.15)/(-10981960/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::C_Water(200+273.15)/(-0.00000003713759442)-1) < 1e-3);
CHECK(std::abs(HumidAir::C_Water(350+273.15)/(-0.000000001198914198)-1) < 1e-3);
}
SECTION("C_aaw")
{
CHECK(std::abs(HumidAir::_C_aaw(-60+273.15)/(1027.3/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::_C_aaw(0+273.15)/(861.02/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::_C_aaw(200+273.15)/(627.15/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::_C_aaw(350+273.15)/(583.79/1e12)-1) < 1e-3);
}
SECTION("C_aww")
{
CHECK(std::abs(HumidAir::_C_aww(-60+273.15)/(-1821432/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::_C_aww(0+273.15)/(-224234/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::_C_aww(200+273.15)/(-8436.5/1e12)-1) < 1e-3);
CHECK(std::abs(HumidAir::_C_aww(350+273.15)/(-2486.9/1e12)-1) < 1e-3);
}
}
TEST_CASE("Enhancement factor from Table A.3","[RP1485]")
{
CHECK(std::abs(HumidAir::f_factor(-60+273.15,101325)/(1.00708)-1) < 1e-3);
CHECK(std::abs(HumidAir::f_factor( 80+273.15,101325)/(1.00573)-1) < 1e-3);
CHECK(std::abs(HumidAir::f_factor(-60+273.15,10000e3)/(2.23918)-1) < 1e-3);
CHECK(std::abs(HumidAir::f_factor(300+273.15,10000e3)/(1.04804)-1) < 1e-3);
}
TEST_CASE("Isothermal compressibility from Table A.5","[RP1485]")
{
CHECK(std::abs(HumidAir::isothermal_compressibility(-60+273.15,101325)/(0.10771e-9)-1) < 1e-3);
CAPTURE(HumidAir::isothermal_compressibility( 80+273.15,101325));
CHECK(std::abs(HumidAir::isothermal_compressibility( 80+273.15,101325)/(0.46009e-9)-1) < 1e-2); // Relaxed criterion for this parameter
CHECK(std::abs(HumidAir::isothermal_compressibility(-60+273.15,10000e3)/(0.10701e-9)-1) < 1e-3);
CHECK(std::abs(HumidAir::isothermal_compressibility(300+273.15,10000e3)/(3.05896e-9)-1) < 1e-3);
}
TEST_CASE("Henry constant from Table A.6","[RP1485]")
{
CHECK(std::abs(HumidAir::HenryConstant(0.010001+273.15)/(0.22600e-9)-1) < 1e-3);
CHECK(std::abs(HumidAir::HenryConstant(300+273.15)/(0.58389e-9)-1) < 1e-3);
}
// A structure to hold the values for one call to HAProps
struct hel
{
public:
std::string in1,in2,in3,out;
double v1, v2, v3, expected;
hel(std::string in1, double v1, std::string in2, double v2, std::string in3, double v3, std::string out, double expected)
{
this->in1 = in1; this->in2 = in2; this->in3 = in3;
this->v1 = v1; this->v2 = v2; this->v3 = v3;
this->expected = expected; this->out = out;
};
};
hel table_A11[] ={hel("T",473.15,"W",0.00,"P",101325,"B",45.07+273.15),
hel("T",473.15,"W",0.00,"P",101325,"V",1.341),
hel("T",473.15,"W",0.00,"P",101325,"H",202520),
hel("T",473.15,"W",0.00,"P",101325,"S",555.8),
hel("T",473.15,"W",0.50,"P",101325,"B",81.12+273.15),
hel("T",473.15,"W",0.50,"P",101325,"V",2.416),
hel("T",473.15,"W",0.50,"P",101325,"H",1641400),
hel("T",473.15,"W",0.50,"P",101325,"S",4829.5),
hel("T",473.15,"W",1.00,"P",101325,"B",88.15+273.15),
hel("T",473.15,"W",1.00,"P",101325,"V",3.489),
hel("T",473.15,"W",1.00,"P",101325,"H",3079550),
hel("T",473.15,"W",1.00,"P",101325,"S",8889.0)};
hel table_A12[] ={hel("T",473.15,"W",0.00,"P",1e6,"B",90.47+273.15),
hel("T",473.15,"W",0.00,"P",1e6,"V",0.136),
hel("T",473.15,"W",0.00,"P",1e6,"H",201940),
hel("T",473.15,"W",0.00,"P",1e6,"S",-101.1), // Using CoolProp 4.2, this value seems incorrect from report
hel("T",473.15,"W",0.50,"P",1e6,"B",148.49+273.15),
hel("T",473.15,"W",0.50,"P",1e6,"V",0.243),
hel("T",473.15,"W",0.50,"P",1e6,"H",1630140),
hel("T",473.15,"W",0.50,"P",1e6,"S",3630.2),
hel("T",473.15,"W",1.00,"P",1e6,"B",159.92+273.15),
hel("T",473.15,"W",1.00,"P",1e6,"V",0.347),
hel("T",473.15,"W",1.00,"P",1e6,"H",3050210),
hel("T",473.15,"W",1.00,"P",1e6,"S",7141.3)};
hel table_A15[] ={hel("T",473.15,"W",0.10,"P",1e7,"B",188.92+273.15),
hel("T",473.15,"W",0.10,"P",1e7,"V",0.016),
hel("T",473.15,"W",0.10,"P",1e7,"H",473920),
hel("T",473.15,"W",0.10,"P",1e7,"S",-90.1),
hel("T",473.15,"W",0.10,"P",1e7,"R",0.734594),
};
class HAPropsConsistencyFixture
{
public:
std::vector<hel> inputs;
std::string in1,in2,in3,out;
double v1, v2, v3, expected, actual;
void set_table(hel h[], int nrow){
inputs = std::vector<hel>(h, h + nrow);
};
void set_values(hel &h){
this->in1 = h.in1; this->in2 = h.in2; this->in3 = h.in3;
this->v1 = h.v1; this->v2 = h.v2; this->v3 = h.v3;
this->expected = h.expected; this->out = h.out;
};
void call(){
actual = HumidAir::HAPropsSI(out.c_str(), in1.c_str(), v1, in2.c_str(), v2, in3.c_str(), v3);
}
};
TEST_CASE_METHOD(HAPropsConsistencyFixture, "ASHRAE RP1485 Tables", "[RP1485]")
{
SECTION("Table A.15")
{
set_table(table_A15, 5);
for (std::size_t i = 0; i < inputs.size(); ++i){
set_values(inputs[i]);
call();
CAPTURE(inputs[i].in1);
CAPTURE(inputs[i].v1);
CAPTURE(inputs[i].in2);
CAPTURE(inputs[i].v2);
CAPTURE(inputs[i].in3);
CAPTURE(inputs[i].v3);
CAPTURE(out);
CAPTURE(actual);
CAPTURE(expected);
std::string errmsg = CoolProp::get_global_param_string("errstring");
CAPTURE(errmsg);
CHECK(std::abs(actual/expected-1) < 0.01);
}
}
SECTION("Table A.11")
{
set_table(table_A11, 12);
for (std::size_t i = 0; i < inputs.size(); ++i){
set_values(inputs[i]);
call();
CAPTURE(inputs[i].in1);
CAPTURE(inputs[i].v1);
CAPTURE(inputs[i].in2);
CAPTURE(inputs[i].v2);
CAPTURE(inputs[i].in3);
CAPTURE(inputs[i].v3);
CAPTURE(out);
CAPTURE(actual);
CAPTURE(expected);
std::string errmsg = CoolProp::get_global_param_string("errstring");
CAPTURE(errmsg);
CHECK(std::abs(actual/expected-1) < 0.01);
}
}
SECTION("Table A.12")
{
set_table(table_A12, 12);
for (std::size_t i = 0; i < inputs.size(); ++i){
set_values(inputs[i]);
call();
CAPTURE(inputs[i].in1);
CAPTURE(inputs[i].v1);
CAPTURE(inputs[i].in2);
CAPTURE(inputs[i].v2);
CAPTURE(inputs[i].in3);
CAPTURE(inputs[i].v3);
CAPTURE(out);
CAPTURE(actual);
CAPTURE(expected);
std::string errmsg = CoolProp::get_global_param_string("errstring");
CAPTURE(errmsg);
CHECK(std::abs(actual/expected-1) < 0.01);
}
}
}
TEST_CASE("Assorted tests","[HAPropsSI]")
{
CHECK(ValidNumber(HumidAir::HAPropsSI("T", "H", 267769, "P", 104300, "W", 0.0)));
CHECK(ValidNumber(HumidAir::HAPropsSI("T", "B", 252.84, "W", 5.097e-4, "P", 101325)));
CHECK(ValidNumber(HumidAir::HAPropsSI("T", "B",290, "R", 1, "P", 101325)));
}
// a predicate implemented as a function:
bool is_not_a_pair (const std::set<std::size_t> &item) { return item.size() != 2; }
const int number_of_inputs = 6;
std::string inputs[number_of_inputs] = {"W","D","B","R","T","V"};//,"H","S"};
class ConsistencyTestData
{
public:
bool is_built;
std::vector<Dictionary> data;
std::list<std::set<std::size_t> > inputs_list;
ConsistencyTestData(){
is_built = false;
};
void build(){
if (is_built){return;}
std::vector<std::size_t> indices(number_of_inputs);
for (std::size_t i = 0; i < number_of_inputs; ++i){ indices[i] = i;}
// Generate a powerset of all the permutations of all lengths of inputs
std::set<std::size_t> indices_set(indices.begin(), indices.end());
std::set<std::set<std::size_t> > inputs_powerset = powerset(indices_set);
inputs_list = std::list<std::set<std::size_t> >(inputs_powerset.begin(), inputs_powerset.end());
inputs_list.remove_if(is_not_a_pair);
const int NT = 10, NW = 5;
double p = 101325;
for (double T = 210; T < 350; T += (350-210)/(NT-1))
{
double Wsat = HumidAir::HAPropsSI("W", "T", T, "P", p, "R", 1.0);
for (double W = 1e-5; W < Wsat; W += (Wsat-1e-5)/(NW-1)){
Dictionary vals;
// Calculate all the values using T, W
for (int i = 0; i < number_of_inputs; ++i){
double v = HumidAir::HAPropsSI(inputs[i], "T", T, "P", p, "W", W);
vals.add_number(inputs[i], v);
}
data.push_back(vals);
std::cout << format("T %g W %g\n",T,W);
}
}
is_built = true;
};
} consistency_data;
/*
* This test is incredibly slow, which is why it is currently commented out. Many of the tests also fail
*
TEST_CASE("HAPropsSI", "[HAPropsSI]")
{
consistency_data.build();
double p = 101325;
for (std::size_t i = 0; i < consistency_data.data.size(); ++i)
{
for (std::list<std::set<std::size_t> >::iterator iter = consistency_data.inputs_list.begin(); iter != consistency_data.inputs_list.end(); ++iter)
{
std::vector<std::size_t> pair(iter->begin(), iter->end());
std::string i0 = inputs[pair[0]], i1 = inputs[pair[1]];
double v0 = consistency_data.data[i].get_double(i0), v1 = consistency_data.data[i].get_double(i1);
if ((i0 == "B" && i1 == "V") || (i1 == "B" && i0 == "V")){continue;}
std::ostringstream ss2;
ss2 << "Inputs: \"" << i0 << "\"," << v0 << ",\"" << i1 << "\"," << v1;
SECTION(ss2.str(), ""){
double T = consistency_data.data[i].get_double("T");
double W = consistency_data.data[i].get_double("W");
double Wcalc = HumidAir::HAPropsSI("W", i0, v0, i1, v1, "P", p);
double Tcalc = HumidAir::HAPropsSI("T", i0, v0, i1, v1, "P", p);
std::string err = CoolProp::get_global_param_string("errstring");
CAPTURE(T);
CAPTURE(W);
CAPTURE(Tcalc);
CAPTURE(Wcalc);
CAPTURE(err);
CHECK(std::abs(Tcalc - T) < 1e-1);
CHECK(std::abs((Wcalc - W)/W) < 1e-3);
}
}
}
}
*/
#endif /* CATCH_ENABLED */
| 36.829963 | 412 | 0.588554 | [
"vector"
] |
2c595201860a8e0e77f08d60e821dc83913b92c7 | 12,431 | cpp | C++ | blast/src/connect/services/remote_app.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/connect/services/remote_app.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/connect/services/remote_app.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id: remote_app.cpp 584886 2019-04-18 16:59:46Z sadyrovr $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Maxim Didenko, Dmitry Kazimirov
*
* File Description:
*
*/
#include <ncbi_pch.hpp>
#include <connect/services/grid_rw_impl.hpp>
#include <connect/services/remote_app.hpp>
#include <connect/services/error_codes.hpp>
#include <corelib/ncbifile.hpp>
#define NCBI_USE_ERRCODE_X ConnServ_Remote
BEGIN_NCBI_SCOPE
//////////////////////////////////////////////////////////////////////////////
//
inline CNcbiOstream& WriteStrWithLen(CNcbiOstream& os, const string& str)
{
os << str.size() << ' ' << str;
return os;
}
inline CNcbiIstream& ReadStrWithLen(CNcbiIstream& is, string& str)
{
string::size_type len;
if (!is.good()) return is;
is >> len;
if (!is.good()) return is;
vector<char> buf(len+1);
is.read(&buf[0], len+1);
str.assign(buf.begin()+1, buf.end());
return is;
}
//////////////////////////////////////////////////////////////////////////////
//
CBlobStreamHelper::~CBlobStreamHelper()
{
try {
Reset();
} NCBI_CATCH_ALL_X(14, "CBlobStreamHelper::~CBlobStreamHelper()");
}
CNcbiOstream& CBlobStreamHelper::GetOStream(const string& fname /*= ""*/,
EStdOutErrStorageType type /*= eBlobStorage*/,
size_t max_inline_size /*= kMaxBlobInlineSize*/)
{
if (!m_GridWrite.stream) {
_ASSERT(!m_GridRead.stream);
m_GridWrite(m_Storage, max_inline_size, *m_Data);
*m_GridWrite.stream << (int) type << " ";
WriteStrWithLen(*m_GridWrite.stream, fname);
if (!fname.empty() && type == eLocalFile) {
m_GridWrite.stream.reset(new CNcbiOfstream(fname.c_str()));
m_GridWrite.writer.reset();
if (!m_GridWrite.stream->good()) {
NCBI_THROW(CFileException, eRelativePath,
"Cannot open " + fname + " for output");
}
m_GridWrite.stream->exceptions(IOS_BASE::badbit | IOS_BASE::failbit);
}
}
return *m_GridWrite.stream;
}
int CBlobStreamHelper::x_GetTypeAndName(CNcbiIstream& istream,
string& name)
{
int res = eBlobStorage;
if (istream.good()) istream >> res;
if (istream.good()) ReadStrWithLen(istream, name);
return res;
}
CNcbiIstream& CBlobStreamHelper::GetIStream(string* fname /*= NULL*/,
EStdOutErrStorageType* type /*= NULL*/)
{
if (!m_GridRead.stream) {
_ASSERT(!m_GridWrite.stream);
m_GridRead(m_Storage, *m_Data, m_DataSize);
string name;
int tmp = (int)eBlobStorage;
try {
tmp = x_GetTypeAndName(*m_GridRead.stream, name);
} catch (...) {
if (!m_GridRead.stream->eof()) {
string msg =
"Job output does not match remote_app output format";
ERR_POST_X(1, msg);
m_GridRead.stream.reset(new CNcbiIstrstream(msg.c_str()));
}
return *m_GridRead.stream.get();
}
if (fname) *fname = name;
if (type) *type = (EStdOutErrStorageType)tmp;
if (!name.empty() && (EStdOutErrStorageType)tmp == eLocalFile) {
m_GridRead.stream.reset(new CNcbiIfstream(name.c_str()));
if (m_GridRead.stream->good()) {
m_GridRead.stream->exceptions(IOS_BASE::badbit | IOS_BASE::failbit);
} else {
string msg = "Can not open " + name;
msg += " for reading";
ERR_POST_X(2, msg);
m_GridRead.stream.reset(new CNcbiIstrstream(msg.c_str()));
}
}
}
return *m_GridRead.stream;
}
void CBlobStreamHelper::Reset()
{
m_GridRead.Reset();
m_GridWrite.Reset(true);
}
//////////////////////////////////////////////////////////////////////////////
//
CAtomicCounter CRemoteAppRequest::sm_DirCounter;
const string kLocalFSSign = "LFS";
CRemoteAppRequest::~CRemoteAppRequest()
{
try {
Reset();
} NCBI_CATCH_ALL_X(15, "CRemoteAppRequest::~CRemoteAppRequest()");
}
void CRemoteAppRequest::Send(CNcbiOstream& os)
{
m_StdIn.Reset();
typedef map<string,string> TFmap;
TFmap file_map;
ITERATE(TFiles, it, GetFileNames()) {
const string& fname = it->first;
if (it->second == eLocalFile) {
file_map[fname] = kLocalFSSign;
continue;
}
CFile file(fname);
string blobid;
if (!file.Exists()) {
LOG_POST_X(3, Warning << "File :\"" << fname << "\" does not exist.");
continue;
}
if (NStr::Find(GetCmdLine(), fname) == NPOS) {
LOG_POST_X(4, Warning << "File :\"" << fname << "\" is not found in cmdline. Skipping.");
continue;
}
CNcbiIfstream inf(fname.c_str());
if (inf.good()) {
unique_ptr<CNcbiOstream> of(GetNetCacheAPI().CreateOStream(blobid));
*of << inf.rdbuf();
file_map[fname] = blobid;
}
}
WriteStrWithLen(os, GetCmdLine());
WriteStrWithLen(os, m_InBlobIdOrData);
os << file_map.size() << ' ';
ITERATE(TFmap, itf, file_map) {
WriteStrWithLen(os, itf->first);
WriteStrWithLen(os, itf->second);
}
WriteStrWithLen(os, m_StdOutFileName);
WriteStrWithLen(os, m_StdErrFileName);
os << (int)m_StorageType << " ";
os << GetAppRunTimeout() << " ";
os << (int)m_ExlusiveMode;
Reset();
}
static void s_ReplaceArg( vector<string>& args, const string& old_fname,
const string& new_fname)
{
for(vector<string>::iterator it = args.begin();
it != args.end(); ++it) {
string& arg = *it;
SIZE_TYPE pos = NStr::Find(arg, old_fname);
if (pos == NPOS)
return;
if ( (pos == 0 || !isalnum((unsigned char)arg[pos-1]) )
&& pos + old_fname.size() == arg.size())
arg = NStr::Replace(arg, old_fname, new_fname);
}
}
bool CRemoteAppRequest::x_Deserialize(CNcbiIstream& is, TStoredFiles* files)
{
// Partial deserialization doesn't create working dir and deserialize files,
// but fills the "files" map with deserialized filenames and blob IDs.
const bool partial_deserialization = files;
if (partial_deserialization)
files->clear();
Reset();
string cmdline;
ReadStrWithLen(is, cmdline);
SetCmdLine(cmdline);
ReadStrWithLen(is, m_InBlobIdOrData);
int fcount = 0;
vector<string> args;
if (!is.good()) return false;
is >> fcount;
if ( fcount > 0 && !partial_deserialization) {
TokenizeCmdLine(GetCmdLine(), args);
x_CreateWDir();
}
for( int i = 0; i < fcount; ++i) {
string blobid, fname;
ReadStrWithLen(is, fname);
ReadStrWithLen(is, blobid);
if (!is.good()) return false;
const bool is_blob = blobid != kLocalFSSign;
if (partial_deserialization) {
files->insert(make_pair(fname, is_blob ? blobid : kEmptyStr));
} else if (is_blob) {
string nfname = GetWorkingDir() + CDirEntry::GetPathSeparator()
+ blobid;
CNcbiOfstream of(nfname.c_str());
if (of.good()) {
unique_ptr<CNcbiIstream> blob_is(GetNetCacheAPI().GetIStream(blobid));
of << blob_is->rdbuf();
blob_is.reset();
s_ReplaceArg(args, fname, nfname);
}
}
}
if ( fcount > 0 && !partial_deserialization) {
SetCmdLine(JoinCmdLine(args));
}
ReadStrWithLen(is, m_StdOutFileName);
ReadStrWithLen(is, m_StdErrFileName);
if (!is.good()) return false;
int tmp;
is >> tmp;
m_StorageType = (EStdOutErrStorageType)tmp;
if (!is.good()) return false;
is >> tmp; SetAppRunTimeout(tmp);
if (!is.good()) return false;
is >> tmp;
m_ExlusiveMode = tmp != 0;
return !is.fail();
}
void CRemoteAppRequest::Reset()
{
m_CmdLine = "";
m_Files.clear();
m_AppRunTimeout = 0;
x_RemoveWDir();
m_StdIn.Reset();
m_InBlobIdOrData = "";
m_StdInDataSize = 0;
m_ExlusiveMode = false;
}
void CRemoteAppRequest::x_CreateWDir()
{
if (!m_TmpDirName.empty())
return;
m_TmpDirName = m_TmpDirPath + NStr::NumericToString(sm_DirCounter.Add(1));
CDir wdir(m_TmpDirName);
if (wdir.Exists())
wdir.Remove();
CDir(m_TmpDirName).CreatePath();
}
void CRemoteAppRequest::x_RemoveWDir()
{
if (m_TmpDirName.empty())
return;
CDir dir(m_TmpDirName);
if (dir.Exists())
dir.Remove();
m_TmpDirName = "";
}
//////////////////////////////////////////////////////////////////////////////
//
CRemoteAppRequest::CRemoteAppRequest(
CNetCacheAPI::TInstance storage, size_t max_inline_size) :
m_NetCacheAPI(storage),
m_AppRunTimeout(0),
m_TmpDirPath(CDir::GetCwd() + CDirEntry::GetPathSeparator()),
m_StdIn(storage, m_InBlobIdOrData, m_StdInDataSize),
m_StdInDataSize(0),
m_StorageType(eBlobStorage),
m_ExlusiveMode(false),
m_MaxInlineSize(max_inline_size)
{
}
CRemoteAppResult::~CRemoteAppResult()
{
try {
Reset();
} NCBI_CATCH_ALL_X(16, "CRemoteAppResult::~CRemoteAppResult()");
}
void CRemoteAppResult::Serialize(CNcbiOstream& os)
{
m_StdOut.Reset();
m_StdErr.Reset();
WriteStrWithLen(os, m_OutBlobIdOrData);
WriteStrWithLen(os, m_ErrBlobIdOrData);
os << GetRetCode();
}
void CRemoteAppResult::Receive(CNcbiIstream& is)
{
Reset();
ReadStrWithLen(is, m_OutBlobIdOrData);
ReadStrWithLen(is, m_ErrBlobIdOrData);
int ret = -1; is >> ret; SetRetCode(ret);
}
void CRemoteAppResult::Reset()
{
m_RetCode = -1;
m_OutBlobIdOrData = "";
m_OutBlobSize = 0;
m_StdOut.Reset();
m_ErrBlobIdOrData = "";
m_ErrBlobSize = 0;
m_StdErr.Reset();
m_StdOutFileName = "";
m_StdErrFileName = "";
m_StorageType = eBlobStorage;
}
void TokenizeCmdLine(const string& cmdline, vector<string>& args)
{
if (!cmdline.empty()) {
string arg;
for (size_t i = 0; i < cmdline.size();) {
if (cmdline[i] == ' ') {
if (!arg.empty()) {
args.push_back(arg);
arg.erase();
}
i++;
continue;
}
if (cmdline[i] == '\'' || cmdline[i] == '"') {
char quote = cmdline[i];
while( ++i < cmdline.size() && cmdline[i] != quote )
arg += cmdline[i];
args.push_back(arg);
arg.erase();
++i;
continue;
}
arg += cmdline[i++];
}
if (!arg.empty())
args.push_back(arg);
}
}
string JoinCmdLine(const vector<string>& args)
{
string cmd_line;
for (vector<string>::const_iterator it = args.begin();
it != args.end(); ++it) {
if (it != args.begin())
cmd_line += ' ';
if (it->find(" ") != string::npos)
cmd_line += '\"' + *it + '\"';
else
cmd_line += *it;
}
return cmd_line;
}
END_NCBI_SCOPE
| 28.842227 | 101 | 0.570187 | [
"vector"
] |
2c5af74ab93f1a2e4d9bf6998b5c1376d98e4dda | 30,226 | cpp | C++ | pytorch/torch/csrc/jit/script/init.cpp | raghavnauhria/whatmt | c20483a437c82936cb0fb8080925e37b9c4bba87 | [
"MIT"
] | null | null | null | pytorch/torch/csrc/jit/script/init.cpp | raghavnauhria/whatmt | c20483a437c82936cb0fb8080925e37b9c4bba87 | [
"MIT"
] | 1 | 2019-07-22T09:48:46.000Z | 2019-07-22T09:48:46.000Z | pytorch/torch/csrc/jit/script/init.cpp | raghavnauhria/whatmt | c20483a437c82936cb0fb8080925e37b9c4bba87 | [
"MIT"
] | null | null | null | #include <torch/csrc/jit/script/init.h>
#include <torch/csrc/Device.h>
#include <torch/csrc/jit/import.h>
#include <torch/csrc/jit/script/compiler.h>
#include <torch/csrc/jit/script/module.h>
#include <torch/csrc/jit/script/module_python.h>
#include <torch/csrc/jit/script/python_sugared_value.h>
#include <torch/csrc/jit/script/sugared_value.h>
#include <torch/csrc/jit/testing/file_check.h>
#include <torch/csrc/jit/constants.h>
#include <torch/csrc/jit/graph_executor.h>
#include <torch/csrc/jit/hooks_for_testing.h>
#include <torch/csrc/jit/import_source.h>
#include <torch/csrc/jit/irparser.h>
#include <torch/csrc/jit/passes/python_print.h>
#include <torch/csrc/jit/pybind_utils.h>
#include <torch/csrc/jit/python_tracer.h>
#include <torch/csrc/jit/script/logging.h>
#include <torch/csrc/jit/script/parser.h>
#include <torch/csrc/jit/tracer.h>
#include <torch/csrc/api/include/torch/ordered_dict.h>
#include <ATen/ATen.h>
#include <ATen/core/function_schema.h>
#include <ATen/core/qualified_name.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <chrono>
#include <cstddef>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
PYBIND11_MAKE_OPAQUE(torch::jit::script::ExtraFilesMap);
namespace torch {
namespace jit {
namespace script {
using ::c10::Argument;
using ::c10::FunctionSchema;
using ResolutionCallback = std::function<py::function(std::string)>;
using FunctionDefaults = std::unordered_map<std::string, py::object>;
namespace {
// A resolver that will inspect the outer Python scope to find `name`.
struct PythonResolver : public Resolver {
explicit PythonResolver(ResolutionCallback rcb) : rcb_(std::move(rcb)) {}
/**
* While compiling classes, the class type we're compiling will not be
* available in Python, since we haven't finished defining the class yet. So
* in order to make the class type available to its own methods, we need to
* explicitly resolve it.
*
* @param rcb Python function to resolve a name to its Python object in the
* enclosing scope
* @param classname The unqualified classname of the class currently being
* compiled.
* @param classType The class's type.
*/
explicit PythonResolver(
ResolutionCallback rcb,
std::string classname,
ClassTypePtr classType)
: rcb_(std::move(rcb)),
classname_(std::move(classname)),
classType_(std::move(classType)) {}
std::shared_ptr<SugaredValue> resolveValue(
const std::string& name,
Function& m,
const SourceRange& loc) const override {
AutoGIL ag;
py::object obj = rcb_(name);
if (obj.is(py::none())) {
return nullptr;
}
return toSugaredValue(obj, m, loc);
}
static bool isNamedTupleClass(py::object obj) {
auto tuple_type = reinterpret_cast<PyObject*>(&PyTuple_Type);
return PyObject_IsSubclass(obj.ptr(), tuple_type) &&
py::hasattr(obj, "_fields");
}
TypePtr resolveType(const std::string& name, const SourceRange& loc) const override {
if (classType_ && name == classname_) {
return classType_;
}
AutoGIL ag;
py::object obj = rcb_(name);
if (obj.is(py::none())) {
return nullptr;
}
py::bool_ isClass = py::module::import("inspect").attr("isclass")(obj);
if (!py::cast<bool>(isClass)) {
return nullptr;
}
auto qualifiedName = c10::QualifiedName(py::cast<std::string>(
py::module::import("torch.jit").attr("_qualified_name")(obj)));
if (isNamedTupleClass(obj)) {
// Currently don't support default values
if (py::hasattr(obj, "_field_defaults")) {
auto default_dict = py::cast<std::map<std::string, py::object>>(
py::getattr(obj, "_field_defaults"));
if (default_dict.size()) {
std::string error_msg =
"Default values are currently not supported"
" on NamedTuple fields in TorchScript. Fields "
"with default values: [";
bool first = true;
for (const auto& kv : default_dict) {
if (!first) {
error_msg += ", ";
}
error_msg += kv.first;
}
error_msg += "]";
throw ErrorReport(loc) << error_msg;
}
}
py::object props = py::module::import("torch.jit")
.attr("_get_named_tuple_properties")(obj);
std::string unqualName;
std::vector<std::string> fields;
std::vector<TypePtr> annotations;
std::tie(unqualName, fields, annotations) = py::cast<
std::tuple<std::string, decltype(fields), decltype(annotations)>>(
props);
auto tt = TupleType::create(
annotations,
qualifiedName,
TupleType::namedTupleSchemaFromNamesAndTypes(qualifiedName, fields, annotations));
CompilationUnit::_get_python_cu().register_class(tt);
return tt;
}
return CompilationUnit::_get_python_cu().get_class(qualifiedName);
}
private:
ResolutionCallback rcb_;
std::string classname_;
ClassTypePtr classType_;
};
std::shared_ptr<PythonResolver> pythonResolver(ResolutionCallback rcb) {
return std::make_shared<PythonResolver>(rcb);
}
std::shared_ptr<PythonResolver> pythonResolver(
ResolutionCallback rcb,
std::string classname,
ClassTypePtr classType) {
return std::make_shared<PythonResolver>(
rcb, std::move(classname), std::move(classType));
}
} // namespace
FunctionSchema getSchemaWithNameAndDefaults(
const SourceRange& range,
const FunctionSchema& schema,
const at::optional<std::string>& new_name,
const FunctionDefaults& default_args) {
std::vector<Argument> new_args;
for (auto& arg : schema.arguments()) {
auto it = default_args.find(arg.name());
if (it != default_args.end()) {
try {
IValue value;
auto n = arg.N();
auto list_type = arg.type()->cast<ListType>();
if (n && *n > 0 && list_type) {
// BroadcastingList, allow default values T for arg types List[T]
value = toIValue(it->second, list_type->getElementType());
} else {
value = toIValue(it->second, arg.type());
}
new_args.emplace_back(
arg.name(), arg.type(), arg.N(), value, arg.kwarg_only());
} catch (py::cast_error& e) {
throw ErrorReport(range)
<< "Expected a default value of type " << arg.type()->python_str()
<< " on parameter \"" << arg.name() << "\"";
}
} else {
new_args.push_back(arg);
}
}
return FunctionSchema(
new_name.value_or(schema.name()),
schema.overload_name(),
new_args,
schema.returns(),
schema.is_vararg(),
schema.is_varret());
}
static Self moduleSelf(const Module& m, const py::object& py_m) {
return [m, py_m](Value* v) {
v->setType(m.module_object()->type());
return std::make_shared<ModuleValue>(v, m, py_m);
};
}
static TypePtr getTensorType(
const at::Tensor& t,
const TypeKind type_kind) {
switch (type_kind) {
case TypeKind::DimensionedTensorType:
return DimensionedTensorType::create(t);
case TypeKind::CompleteTensorType: {
auto scalar_type = t.scalar_type();
auto sizes = t.sizes();
return CompleteTensorType::create(scalar_type, at::kCPU, sizes);
}
default:
throw std::runtime_error(
"Attempted to call getTensorType for type kind other than DimensionedTensorType or CompleteTensorType.");
}
}
static TupleTypePtr getTupleTensorType(
const Stack::const_iterator& s_iter,
const Stack::const_iterator& s_iter_end,
const TypePtr& tupleType,
const TypeKind type_kind) {
AT_ASSERT(tupleType->kind() == TupleType::Kind);
AT_ASSERT(s_iter != s_iter_end);
std::vector<TypePtr> types;
for (const auto& subType : tupleType->containedTypes()) {
if (subType->kind() == TupleType::Kind) {
types.push_back(getTupleTensorType(s_iter+1, s_iter_end, subType, type_kind));
} else {
types.push_back(getTensorType(s_iter->toTensor(), type_kind));
}
}
return TupleType::create(types);
}
static void setInputTensorTypes(
Graph& g,
const Stack& stack,
const TypeKind type_kind = TypeKind::DimensionedTensorType) {
at::ArrayRef<Value*> input_values = g.inputs();
auto s_iter = stack.begin();
for (auto v : input_values) {
AT_ASSERT(s_iter != stack.end());
if (v->type()->kind() == TupleType::Kind) {
AT_ASSERT(v->node()->kind() == prim::Param);
v->setType(
getTupleTensorType(s_iter, stack.end(), v->type(), type_kind));
} else {
v->setType(getTensorType(s_iter->toTensor(), type_kind));
s_iter++;
}
}
}
static std::shared_ptr<Graph> _propagate_shapes(
Graph& graph,
std::vector<at::Tensor> inputs,
bool with_grad = false) {
Stack stack(inputs.begin(), inputs.end());
auto retval = graph.copy();
setInputTensorTypes(*retval, stack);
PropagateInputShapes(retval);
return retval;
}
static std::shared_ptr<Graph> _propagate_and_assign_input_shapes(
Graph& graph,
const std::vector<at::Tensor>& inputs,
bool with_grad = false,
bool propagate = true) {
auto retval = graph.copy();
if (propagate) {
setInputTensorTypes(*retval, fmap<IValue>(inputs), TypeKind::DimensionedTensorType);
PropagateInputShapes(retval);
}
setInputTensorTypes(*retval, fmap<IValue>(inputs), TypeKind::CompleteTensorType);
return retval;
}
static std::shared_ptr<Graph> _assign_output_shapes(
Graph& graph,
std::vector<at::Tensor> outputs) {
auto retval = graph.copy();
AT_ASSERT(retval->outputs().size() == outputs.size());
for (size_t i = 0; i < outputs.size(); ++i) {
auto scalar_type = outputs[i].scalar_type();
auto sizes = outputs[i].sizes();
auto type =
torch::jit::CompleteTensorType::create(scalar_type, at::kCPU, sizes);
retval->outputs()[i]->setType(type);
}
return retval;
}
void addFunctionToModule(
Module& module,
const std::shared_ptr<Function>& func) {
// Make a graph with a fake self argument
auto graph = func->graph()->copy();
auto v = graph->insertInput(0, "self");
v->setType(module.module_object()->type());
module.module_object()->type()->compilation_unit()->create_function(
"forward", graph);
}
void initJitScriptBindings(PyObject* module) {
auto m = py::handle(module).cast<py::module>();
// STL containers are not mutable by default and hence we need to bind as
// follows.
py::bind_map<ExtraFilesMap>(m, "ExtraFilesMap");
// torch.jit.ScriptModule is a subclass of this C++ object.
// Methods here are prefixed with _ since they should not be
// public.
py::class_<Module>(m, "ScriptModule")
.def(py::init<std::string>())
.def(
"save",
[](Module& m,
const std::string& filename,
const ExtraFilesMap& _extra_files = ExtraFilesMap()) {
m.save(filename, _extra_files);
},
py::arg("filename"),
py::arg("_extra_files") = ExtraFilesMap())
.def(
"save_to_buffer",
[](Module& m, const ExtraFilesMap& _extra_files = ExtraFilesMap()) {
std::ostringstream buf;
m.save(buf, _extra_files);
return py::bytes(buf.str());
},
py::arg("_extra_files") = ExtraFilesMap())
.def("_set_optimized", &Module::set_optimized)
.def(
"_define",
[](Module& m,
py::object py_m,
const std::string& script,
ResolutionCallback rcb) {
c10::optional<Self> self;
m.class_compilation_unit()->define(
script, pythonResolver(rcb), moduleSelf(m, py_m));
didFinishEmitModule(m);
})
.def(
"_create_methods",
[](Module& m,
py::object py_m,
const std::vector<Def>& defs,
const std::vector<ResolutionCallback>& rcbs,
const std::vector<FunctionDefaults>& defaults) {
std::vector<ResolverPtr> resolvers;
resolvers.reserve(rcbs.size());
for (auto& callback : rcbs) {
resolvers.push_back(pythonResolver(callback));
}
m.class_compilation_unit()->define(
defs, resolvers, moduleSelf(m, py_m));
// Stitch in default arguments for each Def if provided
auto defaults_it = defaults.begin();
auto defs_it = defs.begin();
while (defs_it != defs.end()) {
auto& method = m.class_compilation_unit()->get_function(
(*defs_it).name().name());
method.setSchema(getSchemaWithNameAndDefaults(
defs_it->range(),
method.getSchema(),
at::nullopt,
*defaults_it));
++defs_it;
++defaults_it;
}
didFinishEmitModule(m);
})
.def(
"_get_method",
[](Module& self, const std::string& name) -> Method {
return self.get_method(name);
},
py::keep_alive<0, 1>())
.def("_register_parameter", &Module::register_parameter)
.def(
"_get_functions",
[](Module& self) {
return self.class_compilation_unit()->get_functions();
})
.def(
"_register_attribute",
[](Module& self, std::string name, TypePtr type, py::object value) {
self.register_attribute(name, type, toIValue(value, type));
})
.def("_register_module", &Module::register_module)
.def("_register_buffer", &Module::register_buffer)
.def(
"_set_attribute",
[](Module& self, const std::string& name, py::object value) {
auto attr = self.find_attribute(name);
TORCH_CHECK(attr, "Could not find attribute '", name, "'");
auto ivalue = toIValue(value, attr->type());
attr->setValue(ivalue);
})
.def("_set_parameter", &Module::set_parameter)
.def("_get_parameter", &Module::get_parameter)
.def("_get_buffer", &Module::get_buffer)
.def("_get_attribute", &Module::get_attribute)
.def("_get_module", &Module::get_module)
.def(
"_get_modules",
[](Module& self) {
std::vector<std::pair<std::string, Module>> modules;
for (Slot s : self.get_module_slots()) {
modules.emplace_back(s.name(), s.to_module());
}
return modules;
})
.def(
"_get_parameters",
[](Module& self) -> py::tuple {
auto parameters = self.get_parameters();
py::tuple result(parameters.size());
auto i = 0;
for (Slot p : parameters) {
py::tuple r(2);
result[i++] = std::make_tuple(
p.name(), autograd::as_variable_ref(p.value().toTensor()));
}
return result;
})
.def(
"_get_attributes",
[](Module& self) -> py::tuple {
auto attributes = self.get_attributes();
py::tuple result(attributes.size());
size_t i = 0;
for (Slot buffer : attributes) {
py::tuple r(3);
IValue v = buffer.value();
result[i++] = std::make_tuple(
buffer.name(), buffer.type(), toPyObject(std::move(v)));
}
return result;
})
.def(
"_has_attribute",
[](Module& self, const std::string& name) -> bool {
return self.find_attribute(name).has_value();
})
.def(
"_has_parameter",
[](Module& self, const std::string& name) -> bool {
return self.find_parameter(name).has_value();
})
.def(
"_has_buffer",
[](Module& self, const std::string& name) -> bool {
return self.find_buffer(name).has_value();
})
.def(
"_has_module",
[](Module& self, const std::string& name) {
return bool(self.find_module(name));
})
.def(
"_has_method",
[](Module& self, const std::string& name) {
return bool(self.find_method(name));
})
.def(
"_method_names",
[](Module& self) {
return fmap(self.get_methods(), [](const Method& method) {
return method.name();
});
})
.def(
"_create_method_from_trace",
[](Module& self,
const std::string& name,
py::function func,
py::tuple input_tuple,
py::function var_lookup_fn,
bool force_outplace) {
// prereq: Module's buffers and parameters are unique
// this was ensured in python before calling this function
auto typed_inputs = toTypedStack(input_tuple);
auto graph = tracer::createGraphByTracing(
func, typed_inputs, var_lookup_fn, force_outplace, &self);
self.module_object()->type()->compilation_unit()->create_function(
name, graph);
didFinishEmitModule(self);
})
.def(
"get_debug_state",
[](Module& self) {
if (auto m = self.find_method("forward")) {
return m->get_executor().getDebugState();
}
throw std::runtime_error(
"Attempted to call get_debug_state on a Module without a compiled forward()");
})
.def_property_readonly(
"code",
[](Module& self) {
std::ostringstream ss;
std::vector<at::Tensor> tensors;
std::vector<c10::NamedTypePtr> classes;
SourceRangeRecords source_ranges;
PythonPrint(
ss,
source_ranges,
*self.class_compilation_unit(),
true,
tensors,
classes,
false);
return ss.str();
})
.def("apply", &Module::apply)
.def("_copy_into", &Module::copy_into)
.def(
"clone_method", [](Module& m, Module& orig, const std::string& name) {
m.clone_method(orig, name);
});
py::class_<CompilationUnit, std::shared_ptr<CompilationUnit>>(
m, "CompilationUnit")
.def(py::init<>())
.def("find_function", &CompilationUnit::find_function)
.def("set_optimized", &CompilationUnit::set_optimized)
.def(
"define",
[](CompilationUnit& cu,
const std::string& src,
ResolutionCallback rcb) {
cu.define(src, pythonResolver(rcb), nullptr);
});
py::class_<Function, std::shared_ptr<Function>>(
m, "Function", py::dynamic_attr())
.def(
"__call__",
[](py::args args, py::kwargs kwargs) {
// see: [pybind11 varargs]
Function& callee = py::cast<Function&>(args[0]);
bool tracing = tracer::isTracing();
if (tracing) {
tracer::getTracingState()->graph->push_scope(callee.name());
}
py::object result = invokeScriptFunctionFromPython(
callee, tuple_slice(std::move(args), 1), std::move(kwargs));
if (tracing) {
tracer::getTracingState()->graph->pop_scope();
}
return result;
})
.def(
"save",
[](std::shared_ptr<Function> self,
const std::string& filename,
const ExtraFilesMap& _extra_files = ExtraFilesMap()) {
Module module("__main__");
addFunctionToModule(module, self);
module.save(filename, _extra_files);
},
py::arg("filename"),
py::arg("_extra_files") = ExtraFilesMap())
.def(
"save_to_buffer",
[](std::shared_ptr<Function> self,
const ExtraFilesMap& _extra_files = ExtraFilesMap()) {
std::ostringstream buf;
Module module("__main__");
addFunctionToModule(module, self);
return py::bytes(buf.str());
},
py::arg("_extra_files") = ExtraFilesMap())
.def_property_readonly("graph", &Function::graph)
.def_property_readonly("schema", &Function::getSchema)
.def_property_readonly(
"code",
[](Function& self) {
std::ostringstream ss;
std::vector<at::Tensor> tensors;
std::vector<c10::NamedTypePtr> classes;
SourceRangeRecords source_ranges;
PythonPrint(
ss, source_ranges, self, false, tensors, classes, false);
return ss.str();
})
.def(
"get_debug_state",
[](Function& self) { return self.get_executor().getDebugState(); })
.def_property_readonly("name", &Function::name);
py::class_<Method>(m, "ScriptMethod", py::dynamic_attr())
.def(
"__call__",
[](py::args args, py::kwargs kwargs) {
// see: [pybind11 varargs]
Method& method = py::cast<Method&>(args[0]);
return invokeScriptMethodFromPython(
method, tuple_slice(std::move(args), 1), std::move(kwargs));
})
.def_property_readonly("graph", &Method::graph)
.def("_lowered_graph", &Method::_lowered_graph)
.def_property_readonly(
"schema", [](Method& m) { return m.function().getSchema(); })
.def_property_readonly("name", &Method::name)
.def_property_readonly("code", [](Method& self) {
std::ostringstream ss;
std::vector<at::Tensor> tensors;
std::vector<c10::NamedTypePtr> classes;
SourceRangeRecords source_ranges;
PythonPrint(
ss, source_ranges, self.function(), true, tensors, classes, false);
return ss.str();
});
m.def(
"_jit_recursive_script",
[]() { return getRecursiveScriptMode(); });
m.def(
"_jit_recursive_script",
[](bool recurse) { getRecursiveScriptMode() = recurse; });
m.def(
"_jit_script_compile",
[](const Def& def, ResolutionCallback rcb, FunctionDefaults defaults) {
C10_LOG_API_USAGE_ONCE("torch.script.compile");
CompilationUnit cu;
cu.define({def}, {pythonResolver(rcb)}, nullptr);
std::shared_ptr<Function> defined = cu.get_functions().at(0);
defined->setSchema(getSchemaWithNameAndDefaults(
def.range(), defined->getSchema(), def.name().name(), defaults));
didFinishEmitFunction(defined);
return defined;
});
m.def(
"_create_function_from_trace",
[](std::string name,
py::function func,
py::tuple input_tuple,
py::function var_lookup_fn,
bool force_outplace) {
auto typed_inputs = toTypedStack(input_tuple);
auto graph = tracer::createGraphByTracing(
func, typed_inputs, var_lookup_fn, force_outplace);
CompilationUnit cu;
auto result = cu.create_function(std::move(name), std::move(graph));
didFinishEmitFunction(result);
return result;
});
m.def(
"_jit_script_class_compile",
[](const std::string& qualifiedName,
const ClassDef& classDef,
ResolutionCallback rcb) {
C10_LOG_API_USAGE_ONCE("torch.script.class");
auto cu = std::make_shared<CompilationUnit>();
auto classType =
ClassType::create(c10::QualifiedName(qualifiedName), cu);
CompilationUnit::_get_python_cu().register_class(classType);
std::vector<ResolverPtr> rcbs;
std::vector<Def> methodDefs;
for (const auto& def : classDef.defs()) {
methodDefs.push_back(def);
rcbs.push_back(
pythonResolver(rcb, classDef.name().name(), classType));
}
cu->define(methodDefs, rcbs, simpleSelf(classType));
});
m.def("parse_type_comment", [](const std::string& comment) {
Parser p(std::make_shared<Source>(comment));
return Decl(p.parseTypeComment());
});
m.def("merge_type_from_type_comment", &mergeTypesFromTypeComment);
m.def(
"import_ir_module",
[](ModuleLookup module_lookup,
const std::string& filename,
py::object map_location,
ExtraFilesMap& extra_files) {
c10::optional<at::Device> optional_device;
if (!map_location.is(py::none())) {
AT_ASSERT(THPDevice_Check(map_location.ptr()));
optional_device =
reinterpret_cast<THPDevice*>(map_location.ptr())->device;
}
import_ir_module(module_lookup, filename, optional_device, extra_files);
});
m.def(
"import_ir_module_from_buffer",
[](ModuleLookup module_lookup,
const std::string& buffer,
py::object map_location,
ExtraFilesMap& extra_files) {
std::istringstream in(buffer);
c10::optional<at::Device> optional_device;
if (!map_location.is(py::none())) {
AT_ASSERT(THPDevice_Check(map_location.ptr()));
optional_device =
reinterpret_cast<THPDevice*>(map_location.ptr())->device;
}
import_ir_module(module_lookup, in, optional_device, extra_files);
});
m.def(
"_jit_import_functions",
[](CompilationUnit& cu,
const std::string& src,
const std::vector<at::Tensor>& constant_table,
const Self& self) {
import_functions(
CompilationUnit::_get_python_cu_const(),
cu,
std::make_shared<Source>(src),
constant_table,
self,
nullptr);
});
m.def("_jit_set_emit_hooks", setEmitHooks);
m.def("_jit_get_emit_hooks", getEmitHooks);
m.def("_jit_clear_class_registry", CompilationUnit::_clear_python_cu);
m.def(
"_debug_set_autodiff_subgraph_inlining",
debugSetAutodiffSubgraphInlining);
m.def("_propagate_shapes", _propagate_shapes);
m.def(
"_propagate_and_assign_input_shapes",
_propagate_and_assign_input_shapes);
m.def(
"_assign_output_shapes",
_assign_output_shapes);
m.def("_jit_python_print", [](py::object obj) {
std::ostringstream ss;
std::vector<at::Tensor> constants;
std::vector<c10::NamedTypePtr> classes;
SourceRangeRecords source_ranges;
if (auto self = as_module(obj)) {
PythonPrint(
ss,
source_ranges,
*self->class_compilation_unit(),
true,
constants,
classes,
true);
} else if (auto self = as_function(obj)) {
PythonPrint(ss, source_ranges, *self, false, constants, classes, true);
} else {
auto& m = py::cast<Method&>(obj);
PythonPrint(
ss, source_ranges, m.function(), true, constants, classes, true);
}
return std::make_pair(ss.str(), std::move(constants));
});
m.def(
"_last_executed_optimized_graph",
[]() { return lastExecutedOptimizedGraph(); },
"Retrieve the optimized graph that was run the last time the graph executor ran on this thread");
m.def(
"_create_function_from_graph",
[](const std::string& name, std::shared_ptr<Graph> graph) {
return CompilationUnit().create_function(name, graph);
});
py::class_<testing::FileCheck>(m, "FileCheck")
.def(py::init<>())
.def("check", &testing::FileCheck::check)
.def("check_not", &testing::FileCheck::check_not)
.def("check_same", &testing::FileCheck::check_same)
.def("check_next", &testing::FileCheck::check_next)
.def("check_count", &testing::FileCheck::check_count)
.def("check_dag", &testing::FileCheck::check_dag)
.def("check_count", &testing::FileCheck::check_count)
.def(
"check_count",
[](testing::FileCheck& f,
const std::string& str,
size_t count,
bool exactly) { return f.check_count(str, count, exactly); },
"Check Count",
py::arg("str"),
py::arg("count"),
py::arg("exactly") = false)
.def(
"run",
[](testing::FileCheck& f, const std::string& str) {
return f.run(str);
})
.def(
"run", [](testing::FileCheck& f, const Graph& g) { return f.run(g); })
.def(
"run",
[](testing::FileCheck& f,
const std::string& input,
const std::string& output) { return f.run(input, output); },
"Run",
py::arg("checks_file"),
py::arg("test_file"))
.def(
"run",
[](testing::FileCheck& f, const std::string& input, const Graph& g) {
return f.run(input, g);
},
"Run",
py::arg("checks_file"),
py::arg("graph"));
m.def(
"_logging_set_logger",
[](logging::LoggerBase* logger) { return logging::setLogger(logger); },
py::return_value_policy::reference);
py::class_<logging::LoggerBase, std::shared_ptr<logging::LoggerBase>>(
m, "LoggerBase");
py::enum_<logging::LockingLogger::AggregationType>(m, "AggregationType")
.value("SUM", logging::LockingLogger::AggregationType::SUM)
.value("AVG", logging::LockingLogger::AggregationType::AVG)
.export_values();
py::class_<
logging::LockingLogger,
logging::LoggerBase,
std::shared_ptr<logging::LockingLogger>>(m, "LockingLogger")
.def(py::init<>())
.def("set_aggregation_type", &logging::LockingLogger::setAggregationType)
.def("get_counter_val", &logging::LockingLogger::getCounterValue);
py::class_<
logging::NoopLogger,
logging::LoggerBase,
std::shared_ptr<logging::NoopLogger>>(m, "NoopLogger")
.def(py::init<>());
}
} // namespace script
} // namespace jit
} // namespace torch
| 34.903002 | 115 | 0.592106 | [
"object",
"vector"
] |
2c5bed22ac89aa529a388baa456c1f3988833e3f | 43,640 | cc | C++ | interface/java.cc | stganser/isl | c3d4d80529bd2ed087c13688234f362a0150eae1 | [
"MIT"
] | null | null | null | interface/java.cc | stganser/isl | c3d4d80529bd2ed087c13688234f362a0150eae1 | [
"MIT"
] | null | null | null | interface/java.cc | stganser/isl | c3d4d80529bd2ed087c13688234f362a0150eae1 | [
"MIT"
] | null | null | null | #include "isl_config.h"
#include <cctype>
#include <cstdio>
#include <sstream>
#include "generator.h"
#include "java.h"
static const string packagePath = "isl/";
static const string jniSrc = "isl_jni.c";
static const string commonHeader =
"package isl;\n"
"import isl.*;\n"
"import java.lang.ref.ReferenceQueue;\n";
static string name2camelcase(const string &name, bool startUpper)
{
bool mkUpper = startUpper;
string javaname;
for (string::const_iterator it = name.begin(); it != name.end(); ++it) {
char c = *it;
if (c == '_')
mkUpper = true;
else if (mkUpper) {
javaname += toupper(c);
mkUpper = false;
} else
javaname += c;
}
return javaname;
}
static string enumval2java(const isl_enum &enu, const string &valname)
{
return name2camelcase(enu.name_without_enum(valname), true);
}
/* Drop the "isl_" initial part of the type name "name".
*/
static const string type2java(const string &name)
{
assert(name.length() >= 4);
return name2camelcase(name.substr(4), true);
}
static const string jniCallbackApplyMID(int nr_parms)
{
return "JNICallback" + to_string(nr_parms) + "_apply_mid";
}
static const string jniIntCallbackApplyMID(int nr_parms)
{
return "JNIIntCallback" + to_string(nr_parms) + "_apply_mid";
}
static const string jnifn(const string &name, const string &retty)
{
string jniname;
for (unsigned i=0; i<name.length(); ++i) {
char ch = name[i];
jniname += ch;
if (ch == '_')
jniname += '1';
}
return "JNIEXPORT " + retty + " JNICALL Java_isl_Impl_" + jniname
+ "(JNIEnv *env, jclass theclass";
}
static const string jlong2islptr(const string &longExpr, const string &type) {
return "((" + type + " *) (uintptr_t) " + longExpr + ")";
}
static const string islptr2jlong(const string &islptr) {
return "((jlong) (uintptr_t) " + islptr + ")";
}
/* Get the representation of type "ty" on the C side of the
* JNI interface.
*/
string java_generator::paramtype2jni_c(QualType ty) {
if (is_isl_class(ty))
return "jlong";
else if (is_isl_ctx(ty))
return "jlong";
else if (is_string(ty))
return "jstring";
else if (is_isl_enum(ty))
return "jint";
else if (ty->isIntegerType())
if (ty.getAsString().compare("int") == 0)
return "jint";
else
return "jlong";
else if (is_callback(ty))
return "jobject";
else if (is_string(ty))
return "jstring";
else if (ty->isVoidType())
return "void";
else if (ty->isFunctionPointerType())
return "jobject";
else if (ty->isPointerType()) {
QualType targetty = ty->getPointeeType();
if (targetty->isVoidType())
return "jobject";
else if (targetty->isIntegerType())
return "jintArray";
else if (is_isl_class(targetty))
return "jlongArray";
} else if (ty.getAsString().compare("double") == 0)
return "jdouble";
cerr << "Unhandled type in paramtype2jni: " << ty.getAsString() << endl;
exit(1);
}
/* Get the parameter type of an argument of type "ty" of a Java function
* representing a given isl function in the JNI interface.
* When isBool is true, then a pointer to int argument is assumed to
* denote a boolean output parameter.
* When wrapperTypes is true, a wrapper class (e.g. "Integer") is returned
* instead of the underlying primitive type (e.g. "int").
*/
string java_generator::paramtype2jni(QualType ty, bool wrapperTypes,
bool isBool)
{
string type;
if (is_isl_ctx(ty)) {
type = "long";
} else if (is_isl_result_argument(ty)) {
type = "long[]";
} else if (is_isl_class(ty)) {
type = "long";
} else if (is_isl_enum(ty)) {
type = "int";
} else if (is_string(ty)) {
type = "String";
} else if (ty->isFunctionPointerType()) {
const FunctionProtoType *ft =
ty->getPointeeType()->getAs<FunctionProtoType>();
unsigned nArgs =
ft->getNumArgs() - 1; // drop "void *user" argument
ostringstream os;
bool intCB = ft->getReturnType()->isIntegerType();
os << (intCB ? "JNIIntCallback" : "JNICallback") << dec << nArgs;
type = os.str();
} else if (ty->isPointerType()) {
if (ty->getPointeeType().getAsString().compare("int") == 0)
type = isBool ? "boolean[]" : "int[]";
else
type = "long";
} else if (ty->isVoidType())
type = "void";
else if (ty->isIntegerType()) {
if (ty.getAsString().compare("long") == 0)
type = wrapperTypes ? "Long" : "long";
else
type = wrapperTypes ? "Integer" : "int";
} else if (ty.getAsString().compare("double") == 0)
type = wrapperTypes ? "Double" : "double";
else {
cerr << "Unsupported argument type: " << ty.getAsString()
<< endl;
exit(1);
}
return type;
}
string java_generator::rettype2jni_c(QualType ty)
{
return paramtype2jni_c(ty);
}
string java_generator::paramtype2jni(const ParmVarDecl *decl)
{
return paramtype2jni(decl->getOriginalType(), false);
}
string java_generator::paramtype2java(const ParmVarDecl *decl)
{
return paramtype2java(decl->getOriginalType(), false);
}
/* Get the return type of the Java function representing a given isl
* function in the Java interface.
*/
string java_generator::rettype2jni(const FunctionDecl *method)
{
return paramtype2jni(method->getReturnType());
}
/* Get the Java type corresponding to a given parameter type
* of an isl function.
* When wrapperTypes is true, a wrapper class (e.g. "Integer") is
* returned instead of the underlying primitive type (e.g. "int").
*/
string java_generator::paramtype2java(QualType type, bool wrapperTypes,
bool isBool)
{
if (is_isl_ctx(type)) {
return "Ctx";
} else if (is_isl_type(type)) {
return javaTypeName(type);
} else if (is_isl_result_argument(type)) {
return javaTypeName(type->getPointeeType()) + "[]";
} else if (type->isPointerType()) {
QualType ptype = type->getPointeeType();
if (ptype->isFunctionType()) {
const FunctionProtoType *ft =
ptype->getAs<FunctionProtoType>();
unsigned nArgs =
ft->getNumArgs() - 1; // drop "void *user" argument
ostringstream os;
bool nonVoidCB = !ft->getReturnType()->isIntegerType();
os << (nonVoidCB ? "Callback" : "VoidCallback") << dec
<< nArgs << "<";
for (unsigned i = 0; i < nArgs; ++i)
os << (i > 0 ? "," : "")
<< paramtype2java(ft->getArgType(i), true);
if (nonVoidCB)
os << ","
<< paramtype2java(ft->getReturnType(), true);
os << ">";
return os.str();
}
}
return paramtype2jni(type, wrapperTypes, isBool);
}
/* Get the return type of the Java method corresponding
* to the given isl function.
*/
string java_generator::rettype2java(const FunctionDecl *method)
{
QualType retty = method->getReturnType();
if (is_isl_bool(retty)) {
return "boolean";
}
return paramtype2java(retty);
}
static const char *keywords[] = {"void", 0};
string java_generator::methodname2java(const isl_class &clazz,
const string &methodname)
{
const string cname = clazz.name_without_class(methodname);
string jname = name2camelcase(cname, false);
for (const char **p = keywords; *p; ++p) {
if (jname == *p) {
jname += "_";
break;
}
}
return jname;
}
string java_generator::isl_ptr(const string &classname,
const string &expression, bool is_takes)
{
ostringstream os;
if (is_takes) {
if (classname.compare("isl_printer") == 0)
os << "(" << expression << ").makePtr0()";
else {
os << "Impl." << classname << "_copy(("
<< expression << ").ptr)";
}
} else {
os << "(" << expression << ").ptr";
}
return os.str();
}
string java_generator::javaTypeName(QualType ty)
{
return type2java(extract_type(ty));
}
void java_generator::print_additional_val_methods(ostream &os)
{
os << " // Additional convenience methods" << endl
<< " public static Val fromBigInteger(Ctx ctx, "
"java.math.BigInteger i) { return readFromStr(ctx, "
"i.toString()); }" << endl
<< " public static Val fromLong(Ctx ctx, long l) { return "
"readFromStr(ctx, Long.toString(l)); }" << endl
<< " public static Val fromInt(Ctx ctx, int i) { return "
"readFromStr(ctx, Integer.toString(i)); }" << endl
<< " public java.math.BigInteger getNum() {" << endl
<< " return new "
"java.math.BigInteger(toString().split(\"/\")[0]);" << endl
<< " }" << endl << " public java.math.BigInteger getDen() {"
<< endl << " String[] s = toString().split(\"/\");" << endl
<< " return new java.math.BigInteger(s.length == 2 ? s[1] : "
"\"1\");" << endl << " }" << endl;
}
void java_generator::print_additional_ctx_methods(ostream &os)
{
os << " final void freeIslC() {" << endl
<< " Reference<? extends Object> ref = null;" << endl
<< " while ((ref = this.refQ.poll()) != null) {" << endl
<< " DLnkdPhntmRef phRef = (DLnkdPhntmRef) ref;" << endl
<< " phRef.freeCPtr();" << endl
<< " phRef.remove();" << endl
<< " }" << endl
<< " }" << endl
<< " void checkError() {" << endl
<< " int error = Impl.isl_ctx_last_error(ptr);" << endl
<< " if (error != 0) { // "
"0 == isl_error_none" << endl
<< " Impl.isl_ctx_reset_error(ptr);" << endl
<< " throw new IslException(\"isl error (\" + error + \")\");"
<< endl
<< " }" << endl
<< " }" << endl;
}
/* Construct a wrapper for a callback argument (at position "arg").
* Assign the wrapper to "cb". We assume here that a function call
* has at most one callback argument.
* fdecl and f_arg are the function declaration containing the callback
* and the position of the callback argument, respectively.
*/
void java_generator::print_callback(FunctionDecl *fdecl, unsigned f_arg,
ostream &os, QualType type,
const string &arg)
{
const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
unsigned n_arg = fn->getNumArgs();
bool has_result;
string res_ty, err_res, ok_res;
QualType t = fn->getReturnType();
if (is_isl_class(t)) {
has_result = true;
res_ty = "long";
ok_res = "SHOULD_NEVER_BE_USED";
} else if (t->isIntegerType()) {
has_result = false;
res_ty = "int";
ok_res = "0";
} else {
cerr << "Error: unhandled result type for callback: "
<< t.getAsString() << endl;
exit(1);
}
const string cbClass((has_result ? "JNICallback" : "JNIIntCallback") + to_string(n_arg-1));
os << " " << cbClass << " cb = new " << cbClass << "() {" << endl
<< " public " << res_ty << " apply(";
for (unsigned i = 0; i < n_arg - 1; ++i) {
assert(is_isl_type(fn->getArgType(i)));
if (i > 0)
os << ", ";
os << "long cb_arg" << dec << i;
}
os << ") {" << endl;
os << " ";
if (has_result)
os << res_ty << " res = ";
os << arg << ".apply(";
for (unsigned i = 0; i < n_arg - 1; ++i) {
bool is_keep = is_callback_argument_keep(fdecl, f_arg, i);
// __isl_keep arguments must be copied (because the wrapper object
// frees the pointer when it is deleted)
const string &name = extract_type(fn->getArgType(i));
bool has_copy = name.compare("isl_printer") != 0;
if (is_keep && !has_copy) {
cerr << "Error: Callback in " << fdecl->getName().str()
<< "has __isl_keep argument which has no copy function" << endl;
exit(1);
}
if (i > 0)
os << ", ";
os << "new " << type2java(name)
<< "(ctx, " << (is_keep ? "Impl." + name + "_copy" : "")
<< "(cb_arg" << dec << i << "))";
}
os << ")" << (is_isl_class(t) ? ".ptr" : "") << ";" << endl;
if (!has_result) {
os << " return " << ok_res << ';' << endl;
} else {
// when the callback returns an isl object,
// copy the pointer because the wrapper object
// return by the callback will also free the isl object
// when it is deleted
const string &name = extract_type(fn->getReturnType());
bool has_copy = name.compare("isl_printer") != 0;
if (has_copy) {
os << " res = Impl."
<< name << "_copy(res);" << endl;
}
os << " return res;" << endl;
}
os << " }" << endl
<< " };" << endl;
}
void java_generator::prepare_argument(FunctionDecl *fdecl, unsigned f_arg, ostream &os, const ParmVarDecl *param)
{
QualType type = param->getOriginalType();
const string &name = param->getNameAsString();
if (is_callback(type)) {
print_callback(fdecl, f_arg, os, type->getPointeeType(), name);
} else if (is_isl_result_argument(type)) {
type = type->getPointeeType();
string javaTyName = javaTypeName(type);
os << " assert " << name << " == null || " << name
<< ".length == 1;" << endl
<< " long[] _" << name << " = " << name
<< " == null ? null : new long[1];" << endl;
} else if (is_unsigned(type)) {
os << " assert " << name << " >= 0;" << endl;
} else if (is_isl_class(type)) {
// Make sure the isl object is of the right type,
// i.e., it matches the compile time type of the
// parameter (an actual argument for, e.g., isl_union_set
// could be an isl_set at runtime).
os << " " << name << " = " << name << ".as"
<< javaTypeName(type) << "();" << endl;
}
}
void java_generator::print_argument(ostream &os, ParmVarDecl *param)
{
const string &name = param->getNameAsString();
QualType type = param->getOriginalType();
if (is_callback(type)) {
os << "cb";
} else if (is_isl_result_argument(type)) {
os << "_" << name;
} else if (is_isl_enum(type))
os << name << ".value";
else if (is_isl_class(type)) {
os << isl_ptr(extract_type(type), name, takes(param));
} else if (is_string(type)) {
os << name;
} else {
os << name;
}
}
void java_generator::handle_result_argument(ostream &os,
const ParmVarDecl *param)
{
const string &name = param->getNameAsString();
QualType type = param->getOriginalType();
if (is_isl_result_argument(type)) {
const string javaTyName = javaTypeName(type->getPointeeType());
os << " if (" << name << " != null)" << endl
<< " " << name << "[0] = new " << javaTyName
<< "(ctx, _" << name << "[0]);" << endl;
}
}
void java_generator::handle_enum_return(ostream &os, const string &res,
const isl_enum &enu)
{
os << " switch(" << res << ") {" << endl;
map<string, int>::const_iterator it;
// TODO: it->second is not unique! (isl_dim_set == isl_dim_out)
for (it = enu.values.begin(); it != enu.values.end(); ++it) {
os << " case " << it->second << ": return "
<< type2java(enu.name) << "." << enumval2java(enu, it->first)
<< ";" << endl;
}
os << " default: throw new IllegalStateException"
<< "(\"No enum constant in " << type2java(enu.name)
<< " for value \" + (" << res << ") + \"?\");" << endl
<< " }" << endl;
}
void java_generator::handle_return(ostream &os, const FunctionDecl *method,
const string &resVar)
{
QualType rettype = method->getReturnType();
string fullname = method->getName();
if (rettype->isVoidType()) {
os << " ctx.checkError();" << endl;
} else if (is_isl_class(rettype)) {
string type;
type = type2java(extract_type(method->getReturnType()));
os << " if (" << resVar << " == 0L) {" << endl
<< " Impl.isl_ctx_reset_error("
"ctx.ptr);" << endl
<< " throw new IslException(\"" << fullname
<< " returned a NULL pointer.\");" << endl
<< " }" << endl
<< " ctx.checkError();" << endl
<< " return new " << type << "(ctx, "
<< resVar << ");" << endl;
} else if (is_isl_enum(rettype)) {
os << " ctx.checkError();" << endl;
handle_enum_return(os, resVar, find_enum(rettype));
} else if (is_isl_bool(rettype)) {
os << " if (" << resVar << " == -1) {" << endl
<< " Impl.isl_ctx_reset_error("
"ctx.ptr);" << endl
<< " throw new IslException(\"" << fullname
<< " returned isl_error.\");" << endl
<< " }" << endl
<< " ctx.checkError();" << endl
<< " return " << resVar << " != 0;" << endl;
} else {
os << " ctx.checkError();" << endl
<< " return " << resVar << ";" << endl;
}
}
/* Print a java method corresponding to the C function "method".
* "subclass" is set if the method belongs to a class that is a subclass
* of some other class ("super").
*
* If the function has a callback argument, then it also has a "user"
* argument. Since Java has closures, there is no need for such
* a user argument in the Java interface, so we simply drop it.
* We also create a wrapper ("cb") for the callback.
*
* For methods with callbacks (which we assume to return 0 or -1) we
* set the return type of the Java method and the return type of the
* callback to "void" since errors should be signaled through exceptions.
*
* If the function consumes a reference, then we pass it a copy of
* the actual argument.
*/
void java_generator::print_method(ostream &os, isl_class &clazz,
FunctionDecl *method, bool subclass,
string super)
{
string p_name = type2java(clazz.name);
string fullname = method->getName();
string cname = methodname2java(clazz, fullname);
int num_params = method->getNumParams();
int drop_user = has_user_pointer(method) ? 1 : 0;
bool is_void = method->getReturnType()->isVoidType();
os << " public " << rettype2java(method) << " " << cname << "(";
for (int i = 1; i < num_params - drop_user; ++i) {
if (i > 1)
os << ", ";
ParmVarDecl *param = method->getParamDecl(i);
os << (is_callback(param->getOriginalType()) ? "final " : "")
<< paramtype2java(param) << " " << param->getNameAsString();
}
os << ") {" << endl;
const string ctx = clazz.is_ctx() ? "this" : "this.ctx";
// final ctx allows usage in inner class
os << " final Ctx ctx = " << ctx << ";" << endl
<< " synchronized(ctx) {" << endl;
// Look for already collected java wrapper objects and free connected
// isl structure.
os << " ctx.freeIslC();" << endl;
// Declare variable 'self' which represents 'this' but
// with the required isl type (i.e., possibly a super type
// of the actual class).
os << " " << p_name << " self = this.as" << p_name << "();"
<< endl;
for (int i = 1; i < num_params - drop_user; ++i) {
ParmVarDecl *param = method->getParamDecl(i);
prepare_argument(method, i, os, param);
}
os << " ";
if (!is_void)
os << rettype2jni(method) << " res = ";
os << "Impl." << fullname << "("
<< isl_ptr(clazz.name, "self", takes(method->getParamDecl(0)));
for (int i = 1; i < num_params - drop_user; ++i) {
ParmVarDecl *param = method->getParamDecl(i);
os << ", ";
print_argument(os, param);
}
os << ");" << endl;
for (int i = 1; i < num_params - drop_user; ++i) {
const ParmVarDecl *param = method->getParamDecl(i);
handle_result_argument(os, param);
}
handle_return(os, method, "res");
os << " }" << endl
<< " }" << endl;
print_method_jni(method);
}
void java_generator::print_method_jni(FunctionDecl *method) {
string fullname = method->getName();
int num_params = method->getNumParams();
int drop_user = has_user_pointer(method) ? 1 : 0;
bool is_void = method->getReturnType()->isVoidType();
QualType retty = method->getReturnType();
ostream &impl_os = outputfile(packagePath + "Impl.java");
impl_os << " static native " << rettype2jni(method) << " " << fullname << "(";
for (int i = 0; i < num_params-drop_user; ++i) {
const ParmVarDecl *param = method->getParamDecl(i);
if (i > 0)
impl_os << ", ";
impl_os << paramtype2jni(param) << " "
<< param->getNameAsString();
}
impl_os << ");" << endl;
ostream &c_os = outputfile(jniSrc);
int callback = -1;
for (int i = 0; i < num_params-drop_user; ++i) {
const ParmVarDecl *param = method->getParamDecl(i);
QualType ty = param->getOriginalType();
if (is_callback(ty)) {
const FunctionProtoType *fn = ty->getPointeeType()->getAs<FunctionProtoType>();
int num_cbparms = fn->getNumParams();
QualType retty = fn->getReturnType();
c_os << retty.getAsString() << ' ' << fullname << "_callback"
<< dec << i << '(';
for (int j=0; j<num_cbparms; ++j) {
if (j > 0)
c_os << ", ";
c_os << fn->getArgType(j).getAsString() << " arg" << dec << j;
}
c_os << ") {" << endl
<< " struct callbackinfo *cbinfo = (struct callbackinfo *)arg" << dec << (num_cbparms-1) << ';' << endl
<< " JNIEnv *env = cbinfo->env;" << endl
<< " jobject cb = cbinfo->cb;" << endl;
string sig = "(";
for (int j=0; j<num_cbparms-1; ++j) {
string argty = extract_type(fn->getArgType(j));
c_os << " jlong ptr" << dec << j << " = " << islptr2jlong(string("arg") + to_string(j)) << ';' << endl;
sig += "J";
}
string cb_mid;
if (retty->isIntegerType())
cb_mid = jniIntCallbackApplyMID(num_cbparms-1);
else if (is_isl_class(retty))
cb_mid = jniCallbackApplyMID(num_cbparms-1);
sig += retty->isIntegerType() ? ")I" : ")J";
c_os << " if (" << cb_mid << " == NULL) {" << endl
<< " jclass clz = (*env)->GetObjectClass(env, cb);" << endl
<< " " << cb_mid << " = (*env)->GetMethodID(env, clz, \"apply\", \"" << sig << "\");" << endl
<< " }" << endl;
c_os << " ";
if (retty->isIntegerType())
c_os << "jint res = (*env)->CallIntMethod(env, cb, " << cb_mid;
else if (is_isl_class(retty))
c_os << "jlong res = (*env)->CallLongMethod(env, cb, " << cb_mid;
for (int j=0; j<num_cbparms-1; ++j)
c_os << ", ptr" << dec << j;
c_os << ");" << endl;
if (retty->isIntegerType()) {
c_os << " if ((*env)->ExceptionCheck(env) == JNI_TRUE)" << endl
<< " return -1;" << endl
<< " return res;" << endl;
} else if (is_isl_class(retty)) {
c_os << " if ((*env)->ExceptionCheck(env) == JNI_TRUE)" << endl
<< " return NULL;" << endl
<< " return "
<< jlong2islptr("res", extract_type(retty))
<< ';' << endl;
}
c_os << "}" << endl;
callback = i;
}
}
c_os << jnifn(fullname, rettype2jni_c(retty));
for (int i = 0; i < num_params-drop_user; ++i) {
const ParmVarDecl *param = method->getParamDecl(i);
c_os << ", " << paramtype2jni_c(param->getOriginalType()) << " "
<< param->getNameAsString();
}
c_os << ") {" << endl;
for (int i = 0; i < num_params-drop_user; ++i) {
const ParmVarDecl *param = method->getParamDecl(i);
QualType ty = param->getOriginalType();
const string &pname = param->getNameAsString();
const string argName = string("arg") + to_string(i);
if (is_isl_class(ty) || is_isl_ctx(ty)) {
string c_type = is_isl_ctx(ty) ? "isl_ctx" : extract_type(ty);
c_os << " " << c_type << " *" << argName << " = "
<< jlong2islptr(pname, c_type) << ';' << endl;
} else if (is_string(ty)) {
c_os << " const char *" << argName << " = (*env)->GetStringUTFChars(env, "
<< pname << ", NULL);" << endl;
} else if (is_callback(ty)) {
c_os << " // There are two memory leaks here: we never free 'cbinfo' and" << endl
<< " // we never release the global reference to '" << pname << "'." << endl
<< " struct callbackinfo *cbinfo = (struct callbackinfo *)malloc(sizeof(struct callbackinfo));" << endl
<< " cbinfo->env = env;" << endl
<< " cbinfo->cb = (*env)->NewGlobalRef(env, " << pname << ");" << endl;
} else if (ty->isPointerType()) {
QualType targetty = ty->getPointeeType();
if (is_isl_class(targetty)) {
string islType(extract_type(targetty));
c_os << " " << islType << " *_" << argName << ';' << endl
<< " " << islType << " **" << argName << " = "
<< "(*env)->IsSameObject(env, " << pname << ", NULL) ? NULL : &_"
<< argName << ';' << endl;
} else if (targetty->isIntegerType()) {
c_os << " int " << argName << "[1];" << endl;
}
} else {
c_os << " int " << argName << " = " << pname << ";" << endl;
}
}
c_os << " ";
if (!is_void)
c_os << retty.getAsString() << " res = ";
c_os << fullname << "(";
for (int i = 0; i < num_params-drop_user; ++i) {
if (i > 0)
c_os << ", ";
if (i == callback) {
c_os << fullname << "_callback" << dec << i;
} else {
c_os << "arg" << dec << i;
}
}
if (callback >= 0) // set user arg for callback to "cbinfo"
c_os << ", cbinfo";
else if (drop_user) // set user arg without callback (e.g. for isl_id_alloc) to NULL
c_os << ", NULL";
c_os << ");" << endl;
if ((callback >= 0) && (fullname.find("ast") == string::npos)) {
c_os << " (*env)->DeleteGlobalRef(env, cbinfo->cb);" << endl
<< " free(cbinfo);" << endl;
}
c_os << " int exception_pending = (*env)->ExceptionCheck(env) == JNI_TRUE;" << endl;
for (int i = 0; i < num_params-drop_user; ++i) {
const ParmVarDecl *param = method->getParamDecl(i);
QualType ty = param->getOriginalType();
const string &pname = param->getNameAsString();
const string argName = string("arg") + to_string(i);
if (is_string(ty)) {
c_os << " (*env)->ReleaseStringUTFChars(env, " << pname
<< ", " << argName << ");" << endl;
} else if (ty->isPointerType()) {
QualType targetty = ty->getPointeeType();
if (is_isl_class(targetty)) {
c_os << " if (!exception_pending && " << argName << " != NULL)" << endl
<< " (*env)->SetLongArrayRegion(env, " << pname
<< ", 0, 1, (jlong *)" << argName << ");" << endl;
} else if (targetty->isIntegerType()) {
c_os << " if (!exception_pending) {" << endl
<< " jint j_" << argName << " = " << argName << "[0];" << endl
<< " (*env)->SetIntArrayRegion(env, " << pname
<< ", 0, 1, &j_" << argName << ");" << endl
<< " }" << endl;
}
}
}
if (is_isl_class(retty)) {
c_os << " return " << islptr2jlong("res") << ';' << endl;
} else if (is_string(retty)) {
c_os << " jobject jstr = (*env)->NewStringUTF(env, res);" << endl;
if (gives(method))
c_os << " free(res);" << endl;
c_os << " return jstr;" << endl;
} else if (!is_void) {
c_os << " return res;" << endl;
}
c_os << "}" << endl;
}
/* Print part of the constructor for this isl_class.
*
* When 'asNamedConstructor' is true, generate a static
* method with a name matching the isl function name
* (e.g., Set.readFromStr(...)); otherwise, generate
* a constructor (e.g., Set.Set(...)).
* To avoid ambiguties, only a few constructor functions
* can be represented by constructors of the class (because
* several constructors can have the same argument list, e.g.
* isl_set_universe and isl_set_empty).
*/
void java_generator::print_constructor(ostream &os, isl_class &clazz,
FunctionDecl *cons,
bool asNamedConstructor)
{
const string fullname = cons->getName();
const string cname = methodname2java(clazz, fullname);
const string jclass = type2java(clazz.name);
int ctxArg = -1, ctxSrc = -1;
int num_params = cons->getNumParams();
int drop_user = has_user_pointer(cons) ? 1 : 0;
int is_ctx = clazz.name.compare("isl_ctx") == 0;
string super;
bool subclass = is_subclass(clazz.type, super);
if (!asNamedConstructor)
os << " // " << fullname << endl;
os << " public ";
if (asNamedConstructor)
os << "static ";
os << type2java(clazz.name);
if (asNamedConstructor)
os << " " << cname;
os << "(";
// Check if there is an argument which provides us with
// the isl context.
for (int i = 0; i < num_params-drop_user; ++i) {
QualType ty = cons->getParamDecl(i)->getOriginalType();
if (is_isl_ctx(ty))
ctxArg = i;
else if (is_isl_class(ty))
ctxSrc = i;
}
// When there is no isl class argument that can give us the
// isl context, there must be an explicit isl context argument
// (except when the class is "isl_ctx").
if (!is_ctx && ctxSrc == -1 && ctxArg == -1) {
cerr << "Cannot generate binding for '" << fullname
<< "':" << endl << " no context argument and no argument "
"to take the context from." << endl;
exit(1);
}
bool firstArg = true;
for (int i = 0; i < num_params-drop_user; ++i) {
if (i == ctxArg && ctxSrc >= 0) // drop context argument
continue;
ParmVarDecl *param = cons->getParamDecl(i);
if (!firstArg)
os << ", ";
else
firstArg = false;
const string &pname = param->getNameAsString();
if (pname.compare("ctx") == 0)
os << "final ";
os << paramtype2java(param) << " " << pname;
}
os << ") {" << endl;
string ctx;
if (!is_ctx) {
if (ctxSrc >= 0)
ctx = cons->getParamDecl(ctxSrc)->getNameAsString() + ".ctx";
else
ctx = cons->getParamDecl(ctxArg)->getNameAsString();
}
if (subclass && !asNamedConstructor) {
os << " super(" << ctx << ", 0);" << endl;
}
// Ensure context (if present) is available as "ctx"
bool ctx_present = ctxArg >= 0
&& cons->getParamDecl(ctxArg)->getNameAsString().compare("ctx") == 0;
if (!is_ctx && !ctx_present) {
os << " final Ctx ctx = " << ctx << ";" << endl;
}
os << " synchronized(" << (is_ctx ? "Ctx.class" : "ctx") << ") {" << endl;
if (!is_ctx) {
// Look for already collected java wrapper objects and free connected
// isl structure.
os << " ctx.freeIslC();" << endl;
}
for (int i = 0; i < num_params-drop_user; ++i) {
if (i == ctxArg)
continue;
ParmVarDecl *param = cons->getParamDecl(i);
prepare_argument(cons, i, os, param);
}
os << " ";
if (asNamedConstructor)
os << "long ";
os << "ptr = Impl." << fullname << '(';
for (int i = 0; i < num_params-drop_user; ++i) {
if (i > 0)
os << ", ";
if (i == ctxArg) {
os << "ctx.ptr";
} else {
ParmVarDecl *param = cons->getParamDecl(i);
print_argument(os, param);
}
}
os << ");" << endl;
os << " if (ptr == 0L) {" << endl;
if (!is_ctx)
os << " Impl.isl_ctx_reset_error(ctx.ptr);" << endl;
os << " throw new IslException(\"" << fullname
<< " returned a NULL pointer.\");" << endl
<< " }" << endl;
for (int i = 0; i < num_params-drop_user; ++i) {
const ParmVarDecl *param = cons->getParamDecl(i);
handle_result_argument(os, param);
}
if (!is_ctx)
os << " ctx.checkError();" << endl;
if (asNamedConstructor) {
os << " return new " << jclass << "(";
if (!is_ctx)
os << "ctx, ";
os << "ptr);" << endl;
}
os << " }" << endl
<< " }" << endl;
}
/* Print out the definition of this isl_class.
*
* We first check if this isl_class is a subclass of some other class.
* If it is, we make sure the superclass is printed out first.
*
* Then we print a constructor with several cases, one for constructing
* a Python object from a return value and one for each function that
* was marked as a constructor.
*
* Next, we print out some common methods and the methods corresponding
* to functions that are not marked as constructors.
*
* Finally, we tell ctypes about the types of the arguments of the
* constructor functions and the return types of those function returning
* an isl object.
*/
void java_generator::print_class(isl_class &clazz)
{
const string &name = clazz.name;
string super;
string p_name = type2java(name);
set<FunctionDecl *>::iterator in;
bool subclass = is_subclass(clazz.type, super);
bool is_ctx = clazz.is_ctx();
// We do not free objects of classes that have in-place update
// (e.g., isl_band). These values exist only in dependence of
// parent objects and are freed when the parent object goes away.
bool must_be_freed = !is_inplace(clazz);
ostream &os = outputfile(packagePath + p_name + ".java");
os << commonHeader;
if (is_ctx)
os << "import java.lang.ref.Reference;" << endl;
os << "public class " << p_name;
if (subclass)
os << " extends " << type2java(super);
os << " {" << endl;
if (!subclass) {
if (is_ctx) {
os << " final ReferenceQueue<Object> refQ = new ReferenceQueue<Object>();" << endl
<< " final DLnkdPhntmRef refList = DLnkdPhntmRef.createListDelims();" << endl;
} else {
os << " DLnkdPhntmRef ref;" << endl;
os << " final protected Ctx ctx;" << endl;
}
os << " protected long ptr;" << endl;
if (is_ctx)
os << " " << p_name << "(long cPtr) {" << endl;
else
os << " " << p_name << "(Ctx ctx, long cPtr) {" << endl;
os << " assert cPtr != 0L;" << endl;
if (!is_ctx) {
os << " this.ctx = ctx;" << endl;
if (must_be_freed) {
os << " ref = createPhRef(ctx, cPtr);" << endl
<< " ref.insertAfter(ctx.refList);" << endl;
} else {
os << " ref = null;" << endl;
}
}
os << " this.ptr = cPtr;" << endl
<< " }" << endl;
if (!is_ctx)
os << " public Ctx getCtx() { return ctx; }" << endl;
} else { // Ctx is not a subclass
os << " " << p_name << "(Ctx ctx, long cPtr) {" << endl
<< " super(ctx, cPtr);" << endl
<< " }" << endl;
}
if (!is_ctx)
os << " long makePtr0() { " << endl
<< " long p = this.ptr;" << endl
<< " this.ptr = 0L;" << endl
<< " if (this.ref.ptr != 0L)" << endl
<< " this.ref.remove();" << endl
<< " this.ref.ptr = 0L;" << endl
<< " return p;" << endl
<< " }" << endl;
for (in = clazz.constructors.begin(); in != clazz.constructors.end();
++in) {
// TODO: Unnamed constructors do not work with the phantom references
// print_constructor(os, clazz, *in, false);
print_constructor(os, clazz, *in, true);
print_method_jni(*in);
}
for (in = clazz.named_constructors.begin(); in != clazz.named_constructors.end();
++in) {
print_constructor(os, clazz, *in, true);
print_method_jni(*in);
}
if (must_be_freed) {
if (is_ctx)
// When the context becomes garbage, there may still be wrapper objects
// for C-side isl objects around (which must also be garbage because
// they hold a reference to the context) which have not been added to the
// phantom reference queue. Therefore, we free all C-side objects
// (by iterating over our list of phantom references) when
// the context is finalized (there is no need to poll the reference queue
// because all the objects to be freed are still in the list of
// phantom references).
os << " protected void finalize() {" << endl
<< " synchronized(this) {" << endl
<< " DLnkdPhntmRef r = refList.next();" << endl
<< " while (r != refList) {" << endl
<< " r.freeCPtr();" << endl
<< " r = r.next();" << endl
<< " }" << endl
<< " Impl." << name << "_free(ptr);" << endl
<< " }" << endl
<< " }" << endl;
else
os << " private static final class FinalDLnkdPhntmRef extends DLnkdPhntmRef {" << endl
<< " FinalDLnkdPhntmRef(Object referent, ReferenceQueue<? super Object> refQ, long ptr) {" << endl
<< " super(referent, refQ, ptr);" << endl
<< " }" << endl
<< " void freeCPtr() {" << endl
<< " Impl." << name << "_free(ptr);" << endl
<< " }" << endl
<< " }" << endl
<< " protected DLnkdPhntmRef createPhRef(Ctx ctx, long cPtr) {" << endl
<< " return new FinalDLnkdPhntmRef(this, ctx.refQ, cPtr);" << endl
<< " }" << endl;
}
if (can_be_printed(clazz)) {
os << " public String toString() {" << endl
<< " Printer p = Printer.toStr(this.ctx);" << endl
<< " p = p.print" << p_name << "(this);" << endl
<< " return p.getStr();" << endl << " }" << endl;
}
// Print methods to convert the runtime type to any
// of the super classes. E.g., for BasicSet we have
// asBasicSet(), asSet() and asUnionSet().
// Print a method to convert to the own type and walk
// up the superclass relation to print methods for all
// superclasses of the current type.
os << " public " << p_name << " as" << p_name
<< "() { return this; }" << endl;
if (subclass) {
isl_class *superclass = &classes[super];
while (superclass) {
string supername = type2java(superclass->name);
os << " public " << supername << " as" << supername
<< "() {" << endl
<< " return " << supername << ".from" << p_name
<< "(this);" << endl
<< " }" << endl;
string supersuper;
if (is_subclass(superclass->type, supersuper)) {
superclass = &classes[supersuper];
} else {
superclass = 0;
}
}
}
os << endl;
for (in = clazz.methods.begin(); in != clazz.methods.end(); ++in)
print_method(os, clazz, *in, subclass, super);
os << "\n";
if (name.compare("isl_val") == 0)
print_additional_val_methods(os);
if (name.compare("isl_ctx") == 0)
print_additional_ctx_methods(os);
os << "}" << endl;
// bool has_copy = name.compare("isl_schedule") != 0 && name.compare("isl_printer") != 0
// && !clazz.is_ctx();
bool has_copy = name.compare("isl_printer") != 0
&& !clazz.is_ctx();
// Add isl_* functions to Impl interface.
ostream &impl_os = outputfile(packagePath + "Impl.java");
impl_os << " static native void " << name << "_free(long islobject);" << endl;
if (has_copy) {
impl_os << " static native long "
<< name << "_copy(long islobject);" << endl;
}
ostream &c_os = outputfile(jniSrc);
c_os << jnifn(name + "_free", "void") << ", jlong ptr)" << "{" << endl
<< " " << name << " *p = " << jlong2islptr("ptr", name) << ';' << endl
<< " " << name << "_free(p);" << endl
<< "}" << endl;
if (has_copy) {
c_os << jnifn(name + "_copy", "jlong") << ", jlong ptr)" << '{' << endl
<< " " << name + " *p = " << jlong2islptr("ptr", name) << ';' << endl
<< " p = " << name << "_copy(p);" << endl
<< " return " << islptr2jlong("p") << ';' << endl
<< "}" << endl;
}
}
void java_generator::generate()
{
generateClasses();
generateEnums();
}
void java_generator::generateClasses()
{
const char *isl_includes[] =
{ "aff", "aff_type", "arg", "ast_build", "ast", "ast_type",
"band", "constraint", "ctx", "flow", "hash",
"id", "id_to_ast_expr", "id_to_pw_aff", "ilp", "list",
"local_space", "lp", "map", "map_to_basic_set", "map_type",
"mat", "multi", "obj", "options", "point", "polynomial",
"polynomial_type", "printer", "schedule", "set", "set_type",
"space", "stdint", "stream", "union_map", "union_map_type",
"union_set", "union_set_type", "val", "vec", "vertices", "schedule_node"
};
ostream &c_os = outputfile(jniSrc);
c_os << "#include <jni.h>" << endl;
for (unsigned i=0; i<sizeof(isl_includes)/sizeof(*isl_includes); ++i) {
c_os << "#include <isl/" << isl_includes[i] << ".h>" << endl;
}
for (unsigned nArgs = 1; nArgs <= 3; ++nArgs) {
ostringstream intfname_oss;
intfname_oss << "Callback" << dec << nArgs;
const string intfname = intfname_oss.str();
ostringstream args_oss, tys_oss, jni_args_oss;
for (unsigned i = 1; i <= nArgs; ++i) {
if (i > 1) {
args_oss << ", ";
jni_args_oss << ", ";
tys_oss << ",";
}
args_oss << "ArgTy" << dec << i << " arg" << dec << i;
jni_args_oss << "long arg" << dec << i;
tys_oss << "ArgTy" << dec << i;
}
const string args = args_oss.str();
const string jni_args = jni_args_oss.str();
const string tys = tys_oss.str();
{
ostream &os = outputfile(packagePath + string("Void") +
intfname + string(".java"));
os << commonHeader << "public interface Void"
<< intfname << "<" << tys << "> {" << endl
<< " void apply(" << args << ");" << endl << "}"
<< endl;
}
{
ostream &os =
outputfile(packagePath /* + string("Ex") */ +
intfname + string(".java"));
os << commonHeader << "public interface " << intfname
<< "<" << tys << ",RetTy> {" << endl
<< " RetTy apply(" << args << ");" << endl << "}"
<< endl;
}
{
ostream &os =
outputfile(packagePath + string("JNI") +
intfname + string(".java"));
os << commonHeader << "public interface JNI" << intfname
<< " {" << endl
<< " long apply(" << jni_args << ");" << endl << "}"
<< endl;
}
{
ostream &os =
outputfile(packagePath + string("Int") +
intfname + string(".java"));
os << commonHeader << "public interface Int" << intfname
<< "<" << tys << "> {" << endl
<< " int apply(" << args << ");" << endl << "}"
<< endl;
}
{
ostream &os =
outputfile(packagePath + string("JNIInt") +
intfname + string(".java"));
os << commonHeader << "public interface JNIInt" << intfname
<< " {" << endl
<< " int apply(" << jni_args << ");" << endl << "}"
<< endl;
}
}
ostream &os_impl = outputfile(packagePath + "Impl.java");
os_impl << commonHeader << "class Impl {" << endl
<< " static { isl.Init.loadNative(); }" << endl
<< " static native int isl_ctx_last_error(long ctx);" << endl
<< " static native void isl_ctx_reset_error(long ctx);" << endl;
ostream &os_c = outputfile(jniSrc);
os_c << "struct callbackinfo {" << endl
<< " JNIEnv *env;" << endl
<< " jobject cb;" << endl
<< "};" << endl;
map<string, isl_class>::iterator ci;
for (int i = 1; i <= 3; ++i) {
os_c << "static jmethodID " << jniCallbackApplyMID(i) << " = NULL;" << endl;
os_c << "static jmethodID " << jniIntCallbackApplyMID(i) << " = NULL;" << endl;
}
/*
os_c << jnifn("isl_ctx_alloc", "jobject") << ") {"
<< " isl_ctx *ctx = isl_ctx_alloc();" << endl
<< " jobject octx;" << endl
<< jniMkPtr("ctx", "isl_ctx", "octx")
<< " return octx;" << endl
<< "}" << endl;
*/
os_c << jnifn("isl_ctx_last_error", "jint") << ", jlong lctx) {" << endl
<< " isl_ctx *ctx = " << jlong2islptr("lctx", "isl_ctx") << ';' << endl
<< " return isl_ctx_last_error(ctx);" << endl
<< "}" << endl;
os_c << jnifn("isl_ctx_reset_error", "void") << ", jlong lctx) {" << endl
<< " isl_ctx *ctx = " << jlong2islptr("lctx", "isl_ctx") << ';' << endl
<< " isl_ctx_reset_error(ctx);" << endl
<< "}" << endl;
{
ostream &os = outputfile(packagePath + "IslException.java");
os << commonHeader
<< "public class IslException extends RuntimeException {"
<< endl
<< " public IslException(String msg) { super(msg); }"
<< endl << "}" << endl;
}
for (ci = classes.begin(); ci != classes.end(); ++ci) {
print_class(ci->second);
}
os_impl << "}" << endl;
}
void java_generator::print_enum(const isl_enum &enu)
{
const string e_name = type2java(enu.name);
ostream &os = outputfile(packagePath + e_name + ".java");
os << commonHeader;
os << "public enum " << e_name << " {" << endl;
map<string, int>::const_iterator it;
for (it = enu.values.begin(); it != enu.values.end(); ++it) {
os << " " << enumval2java(enu, it->first) << "(" << it->second
<< ")," << endl;
}
os << " ;" << endl << " int value;" << endl << " " << e_name
<< "(int value) { this.value = value; }" << endl << "}" << endl;
}
void java_generator::generateEnums()
{
map<string, isl_enum>::iterator ei;
for (ei = enums.begin(); ei != enums.end(); ++ei)
print_enum(ei->second);
}
java_generator::java_generator(set<RecordDecl *> &types,
set<FunctionDecl *> &functions,
set<EnumDecl *> &enums)
: generator(types, functions, enums)
{
}
| 33.338426 | 114 | 0.571059 | [
"object"
] |
2c67f2429f984c7ec356e2ae7a2e2504e85f455f | 4,458 | cpp | C++ | modelConvert/source/ModelChecker.cpp | sormo/simpleSDL | 79a830a013f911c4670c86ccf68bd068a887670d | [
"MIT"
] | null | null | null | modelConvert/source/ModelChecker.cpp | sormo/simpleSDL | 79a830a013f911c4670c86ccf68bd068a887670d | [
"MIT"
] | null | null | null | modelConvert/source/ModelChecker.cpp | sormo/simpleSDL | 79a830a013f911c4670c86ccf68bd068a887670d | [
"MIT"
] | null | null | null | #include "ModelChecker.h"
#include <iostream>
#include "TangentSpace.h"
#include "VboIndexer.h"
void ValidateWindingOrders(glm::vec3 * positions, glm::vec3 * normals, std::vector<uint16_t> & indices)
{
for (size_t i = 0; i < indices.size(); i += 3)
{
uint16_t a = indices[i];
uint16_t b = indices[i + 1];
uint16_t c = indices[i + 2];
glm::vec3 N = glm::cross(positions[b] - positions[a], positions[c] - positions[a]);
float w = glm::dot(N, positions[a] - normals[a]);
// want CCW for front face
if (w < 0.0f)
{
std::iter_swap(std::begin(indices) + i + 1, std::begin(indices) + i + 2);
}
}
}
void UnIndexMesh(ModelData::MeshT & mesh)
{
size_t size = mesh.indices.size();
if (size == 0)
return;
std::vector<ModelData::Vec3> positions(size);
std::vector<ModelData::Vec3> normals(size);
std::vector<ModelData::Vec2> texCoords(size);
std::vector<ModelData::Vec3> tangents(size);
std::vector<ModelData::Vec3> bitangents(size);
for (size_t i = 0; i < size; ++i)
{
positions[i] = mesh.positions[mesh.indices[i]];
normals[i] = mesh.normals[mesh.indices[i]];
if (!mesh.texCoords.empty())
texCoords[i] = mesh.texCoords[mesh.indices[i]];
if (!mesh.tangents.empty())
{
tangents[i] = mesh.tangents[mesh.indices[i]];
bitangents[i] = mesh.bitangents[mesh.indices[i]];
}
}
mesh.positions = positions;
mesh.normals = normals;
if (!mesh.texCoords.empty())
mesh.texCoords = texCoords;
if (!mesh.tangents.empty())
{
mesh.tangents = tangents;
mesh.bitangents = bitangents;
}
mesh.indices.clear();
}
void ComputeTangentSpace(ModelData::MeshT & mesh)
{
size_t dataSize = mesh.positions.size();
std::vector<glm::vec3> tangents, bitangents;
ComputeTangentsAndBitangents((const glm::vec3*)mesh.positions.data(),
(const glm::vec2*)mesh.texCoords.data(), dataSize, tangents, bitangents);
mesh.tangents.resize(dataSize);
memcpy(mesh.tangents.data(), tangents.data(), sizeof(glm::vec3)*dataSize);
mesh.bitangents.resize(dataSize);
memcpy(mesh.bitangents.data(), bitangents.data(), sizeof(glm::vec3)*dataSize);
}
void ComputeIndices(ModelData::MeshT & mesh)
{
// just index it
auto result = VboIndex((const glm::vec3*)mesh.positions.data(),
(const glm::vec2*)mesh.texCoords.data(),
(const glm::vec3*)mesh.normals.data(),
(const glm::vec3*)mesh.tangents.data(),
(const glm::vec3*)mesh.bitangents.data(), mesh.positions.size());
size_t newDataSize = result.vertices.size();
size_t newIndicesSize = result.indices.size();
mesh.indices.resize(newIndicesSize);
memcpy(mesh.indices.data(), result.indices.data(), sizeof(uint16_t)*newIndicesSize);
mesh.positions.resize(newDataSize);
memcpy(mesh.positions.data(), result.vertices.data(), sizeof(glm::vec3)*newDataSize);
mesh.texCoords.resize(newDataSize);
memcpy(mesh.texCoords.data(), result.uvs.data(), sizeof(glm::vec2)*newDataSize);
mesh.normals.resize(newDataSize);
memcpy(mesh.normals.data(), result.normals.data(), sizeof(glm::vec3)*newDataSize);
mesh.tangents.resize(newDataSize);
memcpy(mesh.tangents.data(), result.tangents.data(), sizeof(glm::vec3)*newDataSize);
mesh.bitangents.resize(newDataSize);
memcpy(mesh.bitangents.data(), result.bitangents.data(), sizeof(glm::vec3)*newDataSize);
}
bool CheckModel(ModelData::ModelT & model)
{
auto it = model.meshes.begin();
while (it != model.meshes.end())
{
if (it->get()->positions.empty())
{
std::cout << "No positions. Invalid mesh. Remove ..." << std::endl;
it = model.meshes.erase(it);
continue;
}
if (it->get()->tangents.empty())
{
if (!it->get()->texCoords.empty())
{
std::cout << "No tangent space. Recompute ..." << std::endl;
UnIndexMesh(*it->get());
ComputeTangentSpace(*it->get());
}
}
if (it->get()->indices.empty())
{
ComputeIndices(*it->get());
}
ValidateWindingOrders((glm::vec3*)it->get()->positions.data(), (glm::vec3*)it->get()->normals.data(), it->get()->indices);
it++;
}
return true;
}
| 30.326531 | 130 | 0.602064 | [
"mesh",
"vector",
"model"
] |
2c69a4da8739b5ecb55f348937e58b9c5d801200 | 4,725 | hpp | C++ | generator/osm_source.hpp | vmihaylenko/omim | 00087f340e723fc611cbc82e0ae898b9053b620a | [
"Apache-2.0"
] | null | null | null | generator/osm_source.hpp | vmihaylenko/omim | 00087f340e723fc611cbc82e0ae898b9053b620a | [
"Apache-2.0"
] | 1 | 2019-05-14T15:26:55.000Z | 2019-05-16T11:00:33.000Z | generator/osm_source.hpp | vmihaylenko/omim | 00087f340e723fc611cbc82e0ae898b9053b620a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "generator/emitter_interface.hpp"
#include "generator/generate_info.hpp"
#include "generator/intermediate_data.hpp"
#include "generator/translator_interface.hpp"
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
struct OsmElement;
class FeatureParams;
namespace generator
{
class SourceReader
{
struct Deleter
{
bool m_needDelete;
Deleter(bool needDelete = true) : m_needDelete(needDelete) {}
void operator()(std::istream * s) const
{
if (m_needDelete)
delete s;
}
};
std::unique_ptr<std::istream, Deleter> m_file;
public:
SourceReader();
explicit SourceReader(std::string const & filename);
explicit SourceReader(std::istringstream & stream);
uint64_t Read(char * buffer, uint64_t bufferSize);
};
class LoaderWrapper
{
public:
LoaderWrapper(feature::GenerateInfo & info);
cache::IntermediateDataReader & GetReader();
private:
cache::IntermediateDataReader m_reader;
};
class CacheLoader
{
public:
CacheLoader(feature::GenerateInfo & info);
cache::IntermediateDataReader & GetCache();
private:
feature::GenerateInfo & m_info;
std::unique_ptr<LoaderWrapper> m_loader;
DISALLOW_COPY(CacheLoader);
};
// This function is needed to generate intermediate data from OSM elements.
// The translators collection contains translators that translate the OSM element into
// some intermediate representation.
//
// To better understand the generation process of this step,
// we are looking at generation using the example of generation for countries.
//
// To start the generation we make the following calls:
// 1. feature::GenerateInfo genInfo;
// ...
// 2. CacheLoader cacheLoader(genInfo);
// 3. TranslatorCollection translators;
// 4. auto emitter = CreateEmitter(EmitterType::Country, genInfo);
// 5. translators.Append(CreateTranslator(TranslatorType::Country, emitter, cacheLoader.GetCache(), genInfo));
// 6. GenerateRaw(genInfo, translators);
//
// In line 5, we create and add a translator for countries to the translator collection.
// TranslatorCountry is inheritor of Translator.
//
// Translator contains several important entities: FeatureMaker, FilterCollection, CollectorCollection
// and Emitter. In short,
// * FeatureMaker - an object that can create FeatureBuilder1 from OSM element,
// * FilterCollection - an object that contains a group of filters that may or may not pass OSM elements
// and FeatureBuilder1s,
// * CollectorCollection - an object that contains a group of collectors that collect additional
// information about OSM elements and FeatureBuilder1s (most often it is information that cannot
// be saved in FeatureBuilder1s from OSM element),
// * Emitter - an object that converts an element and saves it.
//
// The most important method is Translator::Emit. Please read it to understand how generation works.
// The order of calls is very important. First, the FilterCollection will filter the OSM elements,
// then call the CollectorCollection for OSM elements, then build the FeatureBuilder1 element
// form OSM element, then FilterCollection will filter the FeatureBuilder1, then call the
// CollectorCollection for the FeatureBuilder1, and then FeatureBuilder1 will fall into the emitter.
//
// TranslatorCountry contains for it specific filters, collectors, emitter and FeatureMaker.
// For example, there are FilterPlanet, which only passes relations with types multipolygon or boundary,
// and CameraNodeProcessor, which collects information about the cameras on the roads.
//
// In line 4, we create emitter for countries.
// The emitter is an important entity that needs to transform FeatureBuilder1 and save them in some way.
// The emitter can filter objects and change the representation of an object based on drawing rules
// and other application rules.
// In EmitterCountry stages are divided into layers. The layers are connected in a chain.
// For example, there are RepresentationLayer, which may change the presentation of the FeatureBuilder1
// depending on the rules of the application, and BookingLayer, which mixes information from booking.
// You can read a more detailed look into the appropriate class code.
bool GenerateRaw(feature::GenerateInfo & info, TranslatorInterface & translators);
bool GenerateRegionFeatures(feature::GenerateInfo & info);
bool GenerateGeoObjectsFeatures(feature::GenerateInfo & info);
bool GenerateIntermediateData(feature::GenerateInfo & info);
void ProcessOsmElementsFromO5M(SourceReader & stream, std::function<void(OsmElement *)> processor);
void ProcessOsmElementsFromXML(SourceReader & stream, std::function<void(OsmElement *)> processor);
} // namespace generator
| 38.414634 | 110 | 0.776085 | [
"object",
"vector",
"transform"
] |
ef18b25416206c1fff74d5f0f0ee91af3f559df0 | 2,716 | hpp | C++ | ray_tracing__advance/offscreen.hpp | wangxihao/vk_raytracing_tutorial_KHR | b3e6d848074291399be3c5e41456ac92924f8657 | [
"Apache-2.0"
] | 1 | 2021-08-10T07:24:16.000Z | 2021-08-10T07:24:16.000Z | ray_tracing__advance/offscreen.hpp | wangxihao/vk_raytracing_tutorial_KHR | b3e6d848074291399be3c5e41456ac92924f8657 | [
"Apache-2.0"
] | null | null | null | ray_tracing__advance/offscreen.hpp | wangxihao/vk_raytracing_tutorial_KHR | b3e6d848074291399be3c5e41456ac92924f8657 | [
"Apache-2.0"
] | 1 | 2021-08-10T07:24:06.000Z | 2021-08-10T07:24:06.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. 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.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#include <vulkan/vulkan.hpp>
#include "nvvk/debug_util_vk.hpp"
#include "nvvk/descriptorsets_vk.hpp"
#include "nvvk/resourceallocator_vk.hpp"
//--------------------------------------------------------------------------------------------------
// Class to render in off-screen framebuffers. Instead of rendering directly to the
// screen back buffer, this class create the output frame buffer 'createFramebuffer',
// and use the pipeline from 'createPipeline' to render a quad 'draw' with the colorTexture
// image
class Offscreen
{
public:
void setup(const vk::Device& device,
const vk::PhysicalDevice& physicalDevice,
nvvk::ResourceAllocator* allocator,
uint32_t queueFamily);
void destroy();
void createFramebuffer(VkExtent2D& size);
void createPipeline(vk::RenderPass& renderPass);
void createDescriptor();
void updateDescriptorSet();
void draw(vk::CommandBuffer cmdBuf, VkExtent2D& size);
const vk::RenderPass& renderPass() { return m_renderPass; }
const vk::Framebuffer& frameBuffer() { return m_framebuffer; }
const nvvk::Texture& colorTexture() { return m_colorTexture; }
private:
nvvk::DescriptorSetBindings m_dsetLayoutBinding;
vk::DescriptorPool m_descPool;
vk::DescriptorSetLayout m_dsetLayout;
vk::DescriptorSet m_dset;
vk::Pipeline m_pipeline;
vk::PipelineLayout m_pipelineLayout;
vk::RenderPass m_renderPass;
vk::Framebuffer m_framebuffer;
nvvk::Texture m_colorTexture;
vk::Format m_colorFormat{vk::Format::eR32G32B32A32Sfloat};
nvvk::Texture m_depthTexture;
vk::Format m_depthFormat{vk::Format::eX8D24UnormPack32};
nvvk::ResourceAllocator* m_alloc{
nullptr}; // Allocator for buffer, images, acceleration structures
vk::Device m_device;
int m_graphicsQueueIndex{0};
nvvk::DebugUtil m_debug; // Utility to name objects
};
| 37.205479 | 100 | 0.685199 | [
"render"
] |
ef23a49ea36189fd923297dab72f0b472d7b2e58 | 10,266 | hpp | C++ | include/etl/expr/batch_softmax_expr.hpp | BeatWolf/etl | 32e8153b38e0029176ca4fe2395b7fa6babe3189 | [
"MIT"
] | 1 | 2020-02-19T13:13:10.000Z | 2020-02-19T13:13:10.000Z | include/etl/expr/batch_softmax_expr.hpp | BeatWolf/etl | 32e8153b38e0029176ca4fe2395b7fa6babe3189 | [
"MIT"
] | null | null | null | include/etl/expr/batch_softmax_expr.hpp | BeatWolf/etl | 32e8153b38e0029176ca4fe2395b7fa6babe3189 | [
"MIT"
] | null | null | null | //=======================================================================
// Copyright (c) 2014-2018 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/expr/base_temporary_expr.hpp"
namespace etl {
/*!
* \brief A batch softmax function expression
*
* \tparam A The unary sub type
*/
template <typename A, bool Stable>
struct batch_softmax_expr : base_temporary_expr_un<batch_softmax_expr<A, Stable>, A> {
using value_type = value_t<A>; ///< The type of value of the expression
using this_type = batch_softmax_expr<A, Stable>; ///< The type of this expression
using base_type = base_temporary_expr_un<this_type, A>; ///< The base type
using sub_traits = decay_traits<A>; ///< The traits of the sub type
static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order
/*!
* \brief Construct a new expression
* \param a The sub expression
*/
explicit batch_softmax_expr(A a) : base_type(a) {
//Nothing else to init
}
/*!
* \brief Validate the function dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C>
static void check([[maybe_unused]] const A& a, [[maybe_unused]] const C& c) {
static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
static constexpr etl::order order_rhs = decay_traits<A>::storage_order;
static_assert(order_lhs == order_rhs, "Cannot change storage order");
static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
if constexpr (all_fast<A, C>) {
static_assert(decay_traits<A>::size() == decay_traits<C>::size(), "Invalid size");
} else {
cpp_assert(etl::size(a) == etl::size(c), "Invalid size");
}
}
// Assignment functions
/*!
* \brief Select the best possible implementation for the batch softmax operation
*
* This routine does not consider the local context
*/
template <typename C>
constexpr static batch_softmax_impl select_default_impl(bool no_gpu) {
if (cudnn_enabled && all_homogeneous<A, C> && all_floating<A, C> && !no_gpu) {
return batch_softmax_impl::CUDNN;
}
return batch_softmax_impl::STD;
}
#ifdef ETL_MANUAL_SELECT
/*!
* \brief Select the best possible implementation for the batch softmax operation
*/
template <typename C>
static batch_softmax_impl select_impl() {
return select_default_impl<C>(local_context().cpu);
}
#else
/*!
* \brief Select the best possible implementation for the batch softmax operation
*/
template <typename C>
constexpr static batch_softmax_impl select_impl() {
return select_default_impl<C>(false);
}
#endif
/*!
* \brief Assign to a matrix of the same storage order
* \param c The expression to which assign
*/
template <typename C, cpp_enable_iff(decay_traits<C>::storage_order == storage_order)>
void assign_to(C&& c) const {
static_assert(all_etl_expr<A, C>, "Function expression only supported for ETL expressions");
auto& a = this->a();
standard_evaluator::pre_assign_rhs(a);
check(a, c);
constexpr_select auto impl = select_impl<C>();
if
constexpr_select(impl == batch_softmax_impl::CUDNN) {
decltype(auto) a_gpu = smart_forward_gpu(a);
if constexpr (Stable) {
impl::cudnn::stable_softmax(a_gpu, c);
} else {
impl::cudnn::softmax(a_gpu, c);
}
}
else if
constexpr_select(impl == batch_softmax_impl::STD) {
if constexpr (Stable) {
for (size_t i = 0; i < etl::dim<0>(c); ++i) {
c(i) = exp(a(i)) / sum(exp(a(i)));
}
} else {
for (size_t i = 0; i < etl::dim<0>(c); ++i) {
auto m = max(a(i));
c(i) = exp(a(i) - m) / sum(exp(a(i) - m));
}
}
}
else {
cpp_unreachable("Invalid selection for batch_softmax");
}
}
/*!
* \brief Assign to a matrix of a different storage order
* \param c The expression to which assign
*/
template <typename C, cpp_enable_iff(decay_traits<C>::storage_order != storage_order)>
void assign_to(C&& c) const {
std_assign_evaluate(*this, c);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
/*!
* \brief Print a representation of the expression on the given stream
* \param os The output stream
* \param expr The expression to print
* \return the output stream
*/
friend std::ostream& operator<<(std::ostream& os, const batch_softmax_expr& expr) {
return os << "batch_softmax(" << expr._a << ")";
}
};
/*!
* \brief Traits for an unary function expression
* \tparam A The unary sub type
*/
template <typename A, bool Stable>
struct etl_traits<etl::batch_softmax_expr<A, Stable>> {
using expr_t = etl::batch_softmax_expr<A, Stable>; ///< The expression type
using sub_expr_t = std::decay_t<A>; ///< The sub expression type
using sub_traits = etl_traits<sub_expr_t>; ///< The sub traits
using value_type = value_t<A>; ///< The value type of the expression
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = false; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr bool is_linear = true; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = true; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = true; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = true; ///< Indicates if the expression is padded
static constexpr bool is_temporary = true; ///< Indicates if the expression needs a evaluator visitor
static constexpr bool gpu_computable = is_gpu_t<value_type> && cuda_enabled; ///< Indicates if the expression can be computed on GPU
static constexpr order storage_order = sub_traits::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = std::true_type;
/*!
* \brief Returns the DDth dimension of the expression
* \return the DDth dimension of the expression
*/
template <size_t DD>
static constexpr size_t dim() {
return decay_traits<A>::template dim<DD>();
}
/*!
* \brief Returns the dth dimension of the expression
* \param e The sub expression
* \param d The dimension to get
* \return the dth dimension of the expression
*/
static size_t dim(const expr_t& e, size_t d) {
return etl::dim(e._a, d);
}
/*!
* \brief Returns the size of the expression
* \param e The sub expression
* \return the size of the expression
*/
static size_t size(const expr_t& e) {
return etl::size(e._a);
}
/*!
* \brief Returns the size of the expression
* \return the size of the expression
*/
static constexpr size_t size() {
return decay_traits<A>::size();
}
/*!
* \brief Returns the number of dimensions of the expression
* \return the number of dimensions of the expression
*/
static constexpr size_t dimensions() {
return decay_traits<A>::dimensions();
}
};
} //end of namespace etl
| 36.147887 | 139 | 0.584161 | [
"vector"
] |
ef2677567b443193994ecc25d791e9c7c5c6fd4d | 25,771 | hpp | C++ | HotSpot1.7-JVM-Linux-x86/src/share/vm/oops/cpCacheOop.hpp | codefollower/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 184 | 2015-01-04T03:38:20.000Z | 2022-03-30T05:47:21.000Z | HotSpot1.7/src/share/vm/oops/cpCacheOop.hpp | doczyw/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 1 | 2016-01-17T09:18:17.000Z | 2016-01-17T09:18:17.000Z | HotSpot1.7/src/share/vm/oops/cpCacheOop.hpp | doczyw/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 101 | 2015-01-16T23:46:31.000Z | 2022-03-30T05:47:06.000Z | /*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_OOPS_CPCACHEOOP_HPP
#define SHARE_VM_OOPS_CPCACHEOOP_HPP
#include "interpreter/bytecodes.hpp"
#include "memory/allocation.hpp"
#include "oops/arrayOop.hpp"
#include "utilities/array.hpp"
// A ConstantPoolCacheEntry describes an individual entry of the constant
// pool cache. There's 2 principal kinds of entries: field entries for in-
// stance & static field access, and method entries for invokes. Some of
// the entry layout is shared and looks as follows:
//
// bit number |31 0|
// bit length |-8--|-8--|---16----|
// --------------------------------
// _indices [ b2 | b1 | index ] index = constant_pool_index (!= 0, normal entries only)
// _indices [ index | 00000 ] index = main_entry_index (secondary entries only)
// _f1 [ entry specific ] method, klass, or oop (MethodType or CallSite)
// _f2 [ entry specific ] vtable index or vfinal method
// _flags [tos|0|00|00|00|f|v|f2|unused|field_index] (for field entries)
// bit length [ 4 |1|1 |1 | 1|1|1| 1|---5--|----16-----]
// _flags [tos|M|vf|fv|ea|f|0|f2|unused|00000|psize] (for method entries)
// bit length [ 4 |1|1 |1 | 1|1|1| 1|---5--|--8--|--8--]
// --------------------------------
//
// with:
// index = original constant pool index
// b1 = bytecode 1
// b2 = bytecode 2
// psize = parameters size (method entries only)
// field_index = index into field information in holder instanceKlass
// The index max is 0xffff (max number of fields in constant pool)
// and is multiplied by (instanceKlass::next_offset) when accessing.
// t = TosState (see below)
// f = field is marked final (see below)
// f2 = virtual but final (method entries only: is_vfinal())
// v = field is volatile (see below)
// m = invokeinterface used for method in class Object (see below)
// h = RedefineClasses/Hotswap bit (see below)
//
// The flags after TosState have the following interpretation:
// bit 27: 0 for fields, 1 for methods
// f flag true if field is marked final
// v flag true if field is volatile (only for fields)
// f2 flag true if f2 contains an oop (e.g., virtual final method)
// fv flag true if invokeinterface used for method in class Object
//
// The flags 31, 30, 29, 28 together build a 4 bit number 0 to 8 with the
// following mapping to the TosState states:
//
// btos: 0
// ctos: 1
// stos: 2
// itos: 3
// ltos: 4
// ftos: 5
// dtos: 6
// atos: 7
// vtos: 8
//
// Entry specific: field entries:
// _indices = get (b1 section) and put (b2 section) bytecodes, original constant pool index
// _f1 = field holder (as a java.lang.Class, not a klassOop)
// _f2 = field offset in bytes
// _flags = field type information, original FieldInfo index in field holder
// (field_index section)
//
// Entry specific: method entries:
// _indices = invoke code for f1 (b1 section), invoke code for f2 (b2 section),
// original constant pool index
// _f1 = methodOop for non-virtual calls, unused by virtual calls.
// for interface calls, which are essentially virtual but need a klass,
// contains klassOop for the corresponding interface.
// for invokedynamic, f1 contains a site-specific CallSite object (as an appendix)
// for invokehandle, f1 contains a site-specific MethodType object (as an appendix)
// (upcoming metadata changes will move the appendix to a separate array)
// _f2 = vtable/itable index (or final methodOop) for virtual calls only,
// unused by non-virtual. The is_vfinal flag indicates this is a
// method pointer for a final method, not an index.
// _flags = method type info (t section),
// virtual final bit (vfinal),
// parameter size (psize section)
//
// Note: invokevirtual & invokespecial bytecodes can share the same constant
// pool entry and thus the same constant pool cache entry. All invoke
// bytecodes but invokevirtual use only _f1 and the corresponding b1
// bytecode, while invokevirtual uses only _f2 and the corresponding
// b2 bytecode. The value of _flags is shared for both types of entries.
//
// The fields are volatile so that they are stored in the order written in the
// source code. The _indices field with the bytecode must be written last.
class ConstantPoolCacheEntry VALUE_OBJ_CLASS_SPEC {
friend class VMStructs;
friend class constantPoolCacheKlass;
friend class constantPoolOopDesc; //resolve_constant_at_impl => set_f1
private:
volatile intx _indices; // constant pool index & rewrite bytecodes
volatile oop _f1; // entry specific oop field
volatile intx _f2; // entry specific int/oop field
volatile intx _flags; // flags
#ifdef ASSERT
bool same_methodOop(oop cur_f1, oop f1);
#endif
void set_bytecode_1(Bytecodes::Code code);
void set_bytecode_2(Bytecodes::Code code);
void set_f1(oop f1) {
oop existing_f1 = _f1; // read once
assert(existing_f1 == NULL || existing_f1 == f1, "illegal field change");
oop_store(&_f1, f1);
}
void release_set_f1(oop f1);
void set_f2(intx f2) { assert(_f2 == 0 || _f2 == f2, "illegal field change"); _f2 = f2; }
void set_f2_as_vfinal_method(methodOop f2) { assert(_f2 == 0 || _f2 == (intptr_t) f2, "illegal field change"); assert(is_vfinal(), "flags must be set"); _f2 = (intptr_t) f2; }
int make_flags(TosState state, int option_bits, int field_index_or_method_params);
void set_flags(intx flags) { _flags = flags; }
bool init_flags_atomic(intx flags);
void set_field_flags(TosState field_type, int option_bits, int field_index) {
assert((field_index & field_index_mask) == field_index, "field_index in range");
set_flags(make_flags(field_type, option_bits | (1 << is_field_entry_shift), field_index));
}
void set_method_flags(TosState return_type, int option_bits, int method_params) {
assert((method_params & parameter_size_mask) == method_params, "method_params in range");
set_flags(make_flags(return_type, option_bits, method_params));
}
bool init_method_flags_atomic(TosState return_type, int option_bits, int method_params) {
assert((method_params & parameter_size_mask) == method_params, "method_params in range");
return init_flags_atomic(make_flags(return_type, option_bits, method_params));
}
public:
// specific bit definitions for the flags field:
// (Note: the interpreter must use these definitions to access the CP cache.)
enum {
// high order bits are the TosState corresponding to field type or method return type
tos_state_bits = 4,
tos_state_mask = right_n_bits(tos_state_bits),
tos_state_shift = BitsPerInt - tos_state_bits, // see verify_tos_state_shift below
// misc. option bits; can be any bit position in [16..27]
is_vfinal_shift = 20,
is_volatile_shift = 21,
is_final_shift = 22,
has_appendix_shift = 23,
has_method_type_shift = 24,
is_forced_virtual_shift = 25,
is_field_entry_shift = 26,
// low order bits give field index (for FieldInfo) or method parameter size:
field_index_bits = 16,
field_index_mask = right_n_bits(field_index_bits),
parameter_size_bits = 8, // subset of field_index_mask, range is 0..255
parameter_size_mask = right_n_bits(parameter_size_bits),
option_bits_mask = ~(((-1) << tos_state_shift) | (field_index_mask | parameter_size_mask))
};
// specific bit definitions for the indices field:
enum {
main_cp_index_bits = 2*BitsPerByte,
main_cp_index_mask = right_n_bits(main_cp_index_bits),
bytecode_1_shift = main_cp_index_bits,
bytecode_1_mask = right_n_bits(BitsPerByte), // == (u1)0xFF
bytecode_2_shift = main_cp_index_bits + BitsPerByte,
bytecode_2_mask = right_n_bits(BitsPerByte), // == (u1)0xFF
// the secondary cp index overlaps with bytecodes 1 and 2:
secondary_cp_index_shift = bytecode_1_shift,
secondary_cp_index_bits = BitsPerInt - main_cp_index_bits
};
// Initialization
void initialize_entry(int original_index); // initialize primary entry
void initialize_secondary_entry(int main_index); // initialize secondary entry
void set_field( // sets entry to resolved field state
Bytecodes::Code get_code, // the bytecode used for reading the field
Bytecodes::Code put_code, // the bytecode used for writing the field
KlassHandle field_holder, // the object/klass holding the field
int orig_field_index, // the original field index in the field holder
int field_offset, // the field offset in words in the field holder
TosState field_type, // the (machine) field type
bool is_final, // the field is final
bool is_volatile // the field is volatile
);
void set_method( // sets entry to resolved method entry
Bytecodes::Code invoke_code, // the bytecode used for invoking the method
methodHandle method, // the method/prototype if any (NULL, otherwise)
int vtable_index // the vtable index if any, else negative
);
void set_interface_call(
methodHandle method, // Resolved method
int index // Method index into interface
);
void set_method_handle(
constantPoolHandle cpool, // holding constant pool (required for locking)
methodHandle method, // adapter for invokeExact, etc.
Handle appendix, // stored in f1; could be a java.lang.invoke.MethodType
Handle method_type // stored in f1 (of secondary entry); is a java.lang.invoke.MethodType
);
void set_dynamic_call(
constantPoolHandle cpool, // holding constant pool (required for locking)
methodHandle method, // adapter for this call site
Handle appendix, // stored in f1; could be a java.lang.invoke.CallSite
Handle method_type // stored in f1 (of secondary entry); is a java.lang.invoke.MethodType
);
// Common code for invokedynamic and MH invocations.
// The "appendix" is an optional call-site-specific parameter which is
// pushed by the JVM at the end of the argument list. This argument may
// be a MethodType for the MH.invokes and a CallSite for an invokedynamic
// instruction. However, its exact type and use depends on the Java upcall,
// which simply returns a compiled LambdaForm along with any reference
// that LambdaForm needs to complete the call. If the upcall returns a
// null appendix, the argument is not passed at all.
//
// The appendix is *not* represented in the signature of the symbolic
// reference for the call site, but (if present) it *is* represented in
// the methodOop bound to the site. This means that static and dynamic
// resolution logic needs to make slightly different assessments about the
// number and types of arguments.
void set_method_handle_common(
constantPoolHandle cpool, // holding constant pool (required for locking)
Bytecodes::Code invoke_code, // _invokehandle or _invokedynamic
methodHandle adapter, // invoker method (f2)
Handle appendix, // appendix such as CallSite, MethodType, etc. (f1)
Handle method_type // MethodType (f1 of secondary entry)
);
methodOop method_if_resolved(constantPoolHandle cpool);
oop appendix_if_resolved(constantPoolHandle cpool);
oop method_type_if_resolved(constantPoolHandle cpool);
void set_parameter_size(int value);
// Which bytecode number (1 or 2) in the index field is valid for this bytecode?
// Returns -1 if neither is valid.
static int bytecode_number(Bytecodes::Code code) {
switch (code) {
case Bytecodes::_getstatic : // fall through
case Bytecodes::_getfield : // fall through
case Bytecodes::_invokespecial : // fall through
case Bytecodes::_invokestatic : // fall through
case Bytecodes::_invokehandle : // fall through
case Bytecodes::_invokedynamic : // fall through
case Bytecodes::_invokeinterface : return 1;
case Bytecodes::_putstatic : // fall through
case Bytecodes::_putfield : // fall through
case Bytecodes::_invokevirtual : return 2;
default : break;
}
return -1;
}
// Has this bytecode been resolved? Only valid for invokes and get/put field/static.
bool is_resolved(Bytecodes::Code code) const {
switch (bytecode_number(code)) {
case 1: return (bytecode_1() == code);
case 2: return (bytecode_2() == code);
}
return false; // default: not resolved
}
// Accessors
bool is_secondary_entry() const { return (_indices & main_cp_index_mask) == 0; }
int main_entry_index() const { assert(is_secondary_entry(), "must be secondary entry");
return ((uintx)_indices >> secondary_cp_index_shift); }
int primary_entry_indices() const { assert(!is_secondary_entry(), "must be main entry");
return _indices; }
int constant_pool_index() const { return (primary_entry_indices() & main_cp_index_mask); }
Bytecodes::Code bytecode_1() const { return Bytecodes::cast((primary_entry_indices() >> bytecode_1_shift)
& bytecode_1_mask); }
Bytecodes::Code bytecode_2() const { return Bytecodes::cast((primary_entry_indices() >> bytecode_2_shift)
& bytecode_2_mask); }
methodOop f1_as_method() const { oop f1 = _f1; assert(f1 == NULL || f1->is_method(), ""); return methodOop(f1); }
klassOop f1_as_klass() const { oop f1 = _f1; assert(f1 == NULL || f1->is_klass(), ""); return klassOop(f1); }
oop f1_as_klass_mirror() const { oop f1 = f1_as_instance(); return f1; } // i.e., return a java_mirror
oop f1_as_instance() const { oop f1 = _f1; assert(f1 == NULL || f1->is_instance() || f1->is_array(), ""); return f1; }
oop f1_appendix() const { assert(has_appendix(), ""); return f1_as_instance(); }
bool is_f1_null() const { oop f1 = _f1; return f1 == NULL; } // classifies a CPC entry as unbound
int f2_as_index() const { assert(!is_vfinal(), ""); return (int) _f2; }
methodOop f2_as_vfinal_method() const { assert(is_vfinal(), ""); return methodOop(_f2); }
int field_index() const { assert(is_field_entry(), ""); return (_flags & field_index_mask); }
int parameter_size() const { assert(is_method_entry(), ""); return (_flags & parameter_size_mask); }
bool is_volatile() const { return (_flags & (1 << is_volatile_shift)) != 0; }
bool is_final() const { return (_flags & (1 << is_final_shift)) != 0; }
bool has_appendix() const { return (_flags & (1 << has_appendix_shift)) != 0; }
bool has_method_type() const { return (_flags & (1 << has_method_type_shift)) != 0; }
bool is_forced_virtual() const { return (_flags & (1 << is_forced_virtual_shift)) != 0; }
bool is_vfinal() const { return (_flags & (1 << is_vfinal_shift)) != 0; }
bool is_method_entry() const { return (_flags & (1 << is_field_entry_shift)) == 0; }
bool is_field_entry() const { return (_flags & (1 << is_field_entry_shift)) != 0; }
bool is_byte() const { return flag_state() == btos; }
bool is_char() const { return flag_state() == ctos; }
bool is_short() const { return flag_state() == stos; }
bool is_int() const { return flag_state() == itos; }
bool is_long() const { return flag_state() == ltos; }
bool is_float() const { return flag_state() == ftos; }
bool is_double() const { return flag_state() == dtos; }
bool is_object() const { return flag_state() == atos; }
TosState flag_state() const { assert((uint)number_of_states <= (uint)tos_state_mask+1, "");
return (TosState)((_flags >> tos_state_shift) & tos_state_mask); }
// Code generation support
static WordSize size() { return in_WordSize(sizeof(ConstantPoolCacheEntry) / HeapWordSize); }
static ByteSize size_in_bytes() { return in_ByteSize(sizeof(ConstantPoolCacheEntry)); }
static ByteSize indices_offset() { return byte_offset_of(ConstantPoolCacheEntry, _indices); }
static ByteSize f1_offset() { return byte_offset_of(ConstantPoolCacheEntry, _f1); }
static ByteSize f2_offset() { return byte_offset_of(ConstantPoolCacheEntry, _f2); }
static ByteSize flags_offset() { return byte_offset_of(ConstantPoolCacheEntry, _flags); }
// GC Support
void oops_do(void f(oop*));
void oop_iterate(OopClosure* blk);
void oop_iterate_m(OopClosure* blk, MemRegion mr);
void follow_contents();
void adjust_pointers();
#ifndef SERIALGC
// Parallel Old
void follow_contents(ParCompactionManager* cm);
#endif // SERIALGC
void update_pointers();
// RedefineClasses() API support:
// If this constantPoolCacheEntry refers to old_method then update it
// to refer to new_method.
// trace_name_printed is set to true if the current call has
// printed the klass name so that other routines in the adjust_*
// group don't print the klass name.
bool adjust_method_entry(methodOop old_method, methodOop new_method,
bool * trace_name_printed);
bool check_no_old_or_obsolete_entries();
bool is_interesting_method_entry(klassOop k);
// Debugging & Printing
void print (outputStream* st, int index) const;
void verify(outputStream* st) const;
static void verify_tos_state_shift() {
// When shifting flags as a 32-bit int, make sure we don't need an extra mask for tos_state:
assert((((u4)-1 >> tos_state_shift) & ~tos_state_mask) == 0, "no need for tos_state mask");
}
};
// A constant pool cache is a runtime data structure set aside to a constant pool. The cache
// holds interpreter runtime information for all field access and invoke bytecodes. The cache
// is created and initialized before a class is actively used (i.e., initialized), the indivi-
// dual cache entries are filled at resolution (i.e., "link") time (see also: rewriter.*).
class constantPoolCacheOopDesc: public oopDesc {
friend class VMStructs;
private:
int _length;
constantPoolOop _constant_pool; // the corresponding constant pool
// Sizing
debug_only(friend class ClassVerifier;)
public:
int length() const { return _length; }
private:
void set_length(int length) { _length = length; }
static int header_size() { return sizeof(constantPoolCacheOopDesc) / HeapWordSize; }
static int object_size(int length) { return align_object_size(header_size() + length * in_words(ConstantPoolCacheEntry::size())); }
int object_size() { return object_size(length()); }
// Helpers
constantPoolOop* constant_pool_addr() { return &_constant_pool; }
ConstantPoolCacheEntry* base() const { return (ConstantPoolCacheEntry*)((address)this + in_bytes(base_offset())); }
friend class constantPoolCacheKlass;
friend class ConstantPoolCacheEntry;
public:
// Initialization
void initialize(intArray& inverse_index_map);
// Secondary indexes.
// They must look completely different from normal indexes.
// The main reason is that byte swapping is sometimes done on normal indexes.
// Also, some of the CP accessors do different things for secondary indexes.
// Finally, it is helpful for debugging to tell the two apart.
static bool is_secondary_index(int i) { return (i < 0); }
static int decode_secondary_index(int i) { assert(is_secondary_index(i), ""); return ~i; }
static int encode_secondary_index(int i) { assert(!is_secondary_index(i), ""); return ~i; }
// Accessors
void set_constant_pool(constantPoolOop pool) { oop_store_without_check((oop*)&_constant_pool, (oop)pool); }
constantPoolOop constant_pool() const { return _constant_pool; }
// Fetches the entry at the given index.
// The entry may be either primary or secondary.
// In either case the index must not be encoded or byte-swapped in any way.
ConstantPoolCacheEntry* entry_at(int i) const {
assert(0 <= i && i < length(), "index out of bounds");
return base() + i;
}
// Fetches the secondary entry referred to by index.
// The index may be a secondary index, and must not be byte-swapped.
ConstantPoolCacheEntry* secondary_entry_at(int i) const {
int raw_index = i;
if (is_secondary_index(i)) { // correct these on the fly
raw_index = decode_secondary_index(i);
}
assert(entry_at(raw_index)->is_secondary_entry(), "not a secondary entry");
return entry_at(raw_index);
}
// Given a primary or secondary index, fetch the corresponding primary entry.
// Indirect through the secondary entry, if the index is encoded as a secondary index.
// The index must not be byte-swapped.
ConstantPoolCacheEntry* main_entry_at(int i) const {
int primary_index = i;
if (is_secondary_index(i)) {
// run through an extra level of indirection:
int raw_index = decode_secondary_index(i);
primary_index = entry_at(raw_index)->main_entry_index();
}
assert(!entry_at(primary_index)->is_secondary_entry(), "only one level of indirection");
return entry_at(primary_index);
}
int index_of(ConstantPoolCacheEntry* e) {
assert(base() <= e && e < base() + length(), "oob");
int cpc_index = (e - base());
assert(entry_at(cpc_index) == e, "sanity");
return cpc_index;
}
ConstantPoolCacheEntry* find_secondary_entry_for(ConstantPoolCacheEntry* e) {
const int cpc_index = index_of(e);
if (e->is_secondary_entry()) {
ConstantPoolCacheEntry* e2 = entry_at(cpc_index + 1);
assert(e->main_entry_index() == e2->main_entry_index(), "");
return e2;
} else {
for (int i = length() - 1; i >= 0; i--) {
ConstantPoolCacheEntry* e2 = entry_at(i);
if (cpc_index == e2->main_entry_index())
return e2;
}
}
fatal("no secondary entry found");
return NULL;
}
// Code generation
static ByteSize base_offset() { return in_ByteSize(sizeof(constantPoolCacheOopDesc)); }
static ByteSize entry_offset(int raw_index) {
int index = raw_index;
if (is_secondary_index(raw_index))
index = decode_secondary_index(raw_index);
return (base_offset() + ConstantPoolCacheEntry::size_in_bytes() * index);
}
// RedefineClasses() API support:
// If any entry of this constantPoolCache points to any of
// old_methods, replace it with the corresponding new_method.
// trace_name_printed is set to true if the current call has
// printed the klass name so that other routines in the adjust_*
// group don't print the klass name.
void adjust_method_entries(methodOop* old_methods, methodOop* new_methods,
int methods_length, bool * trace_name_printed);
bool check_no_old_or_obsolete_entries();
void dump_cache();
};
#endif // SHARE_VM_OOPS_CPCACHEOOP_HPP
| 51.439122 | 181 | 0.642738 | [
"object"
] |
ef36494e8ea8dae3050b4e6478c18315f37511a3 | 3,028 | hpp | C++ | source/Structure/custom_plugins/plugins/HIL_server/serial_asio.hpp | Guiraffo/ProVANT_Simulator | ef2260204b13f39a9f83ad2ab88a9552a0699bff | [
"MIT"
] | null | null | null | source/Structure/custom_plugins/plugins/HIL_server/serial_asio.hpp | Guiraffo/ProVANT_Simulator | ef2260204b13f39a9f83ad2ab88a9552a0699bff | [
"MIT"
] | null | null | null | source/Structure/custom_plugins/plugins/HIL_server/serial_asio.hpp | Guiraffo/ProVANT_Simulator | ef2260204b13f39a9f83ad2ab88a9552a0699bff | [
"MIT"
] | null | null | null | #include <boost/asio.hpp>
#include <boost/thread.hpp>
class SerialClass
{
public:
// Class constructor
SerialClass() : port(io), quitFlag(false)
{
}
// Class destructor
~SerialClass()
{
{
// Stop the I/O services
io.stop();
// Wait for the thread to finish
runner.join();
}
}
// Connection method that will setup the serial port
bool connect(const std::string& port_name, int baud = 9600)
{
try
{
using namespace boost::asio;
port.open(port_name);
// Setup port
port.set_option(serial_port::baud_rate(baud));
port.set_option(serial_port::flow_control(serial_port::flow_control::none));
if (port.is_open())
{
// Start io-service in a background thread.
// boost::bind binds the ioservice instance
// with the method call
runner = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
startReceive();
}
}
catch (boost::system::system_error& e)
{
std::cout << "Error: " << e.what() << std::endl;
std::cout << "Info: " << boost::diagnostic_information(e) << std::endl;
return 1;
}
return port.is_open();
}
// The method that will be called to issue a new
// asynchronous read
void startReceive()
{
using namespace boost::asio;
// Issue a async receive and give it a callback
// onData that should be called when "\r\n"
// is matched.
// async_read_until(port, buffer,"\r\n",functor);
// async_read_until(port, buffer,"\r\n",boost::bind(&SerialClass::onData,this, _1,_2));
async_read(port, buffer, boost::asio::transfer_at_least(1), boost::bind(&SerialClass::onData, this, _1, _2));
}
void onData(const boost::system::error_code& e, std::size_t size)
{
if (!e)
{
std::istream is(&buffer);
std::string data(size, '\0');
is.read(&data[0], size);
std::cout << "Received data:" << data;
// If we receive quit()\r\n indicate
// end of operations
quitFlag = (data.compare("quit()\r\n") == 0);
};
startReceive();
};
// Function for sending a data string
void send(const std::string& text)
{
boost::asio::write(port, boost::asio::buffer(text));
}
// function for reading
/*void read()
{
boost::asio::read(port,boost::asio::buffer(input),boost::asio::transfer_exactly(48));
}*/
// Quit Function
bool quit()
{
return quitFlag;
}
// Pointer of the callback function that will be executed when data
// arrives.
boost::function<void(const boost::system::error_code& e, std::size_t size)> functor;
// Buffer in which to read the serial data
boost::asio::streambuf buffer;
// quit Flag
bool quitFlag;
// vetor de dados de entrada
std::vector<double> input;
private:
// Boost.Asio I/O service required for asynchronous
// operation
boost::asio::io_service io;
// Serial port accessor class
boost::asio::serial_port port;
// Background thread
boost::thread runner;
};
| 25.661017 | 113 | 0.620542 | [
"vector"
] |
ef3bd1b31d3b381c310f4db102965382649765ae | 5,884 | cc | C++ | src/optimizer.cc | jvanstraten/openql-ci-test | a8ff9c8c30991ff4ac81551a698a7e1c40471910 | [
"Apache-2.0"
] | null | null | null | src/optimizer.cc | jvanstraten/openql-ci-test | a8ff9c8c30991ff4ac81551a698a7e1c40471910 | [
"Apache-2.0"
] | null | null | null | src/optimizer.cc | jvanstraten/openql-ci-test | a8ff9c8c30991ff4ac81551a698a7e1c40471910 | [
"Apache-2.0"
] | null | null | null | /**
* @file optimizer.h
* @date 11/2016
* @author Nader Khammassi
* @brief optimizer interface and its implementation
* @todo implementations should be in separate files for better readability
*/
#include "utils.h"
#include "circuit.h"
#include "kernel.h"
#include "optimizer.h"
namespace ql
{
/**
* optimizer interface
*/
class optimizer
{
public:
virtual circuit optimize(circuit& c) = 0;
};
/**
* rotation fuser
*/
class rotations_merging : public optimizer
{
public:
circuit optimize(circuit& ic /*, bool verbose=false */)
{
circuit c=ic;
// if (verbose) COUT("optimizing circuit...");
for (size_t i=c.size(); i>1; i--)
{
// println("window size : " << i);
c = optimize_sliding_window(c,i);
if (c.size()<i) break;
}
if (c.size()>1)
c = optimize_sliding_window(c,2);
// if (verbose) COUT("optimization done.");
return c;
}
protected:
ql::cmat_t fuse(ql::cmat_t& m1, ql::cmat_t& m2)
{
ql::cmat_t res;
ql::complex_t * x = m1.m;
ql::complex_t * y = m2.m;
ql::complex_t * r = res.m;
// m1.dump();
// m2.dump();
r[0] = x[0]*y[0] + x[1]*y[2];
r[1] = x[0]*y[1] + x[1]*y[3];
r[2] = x[2]*y[0] + x[3]*y[2];
r[3] = x[2]*y[1] + x[3]*y[3];
// res.dump();
return res;
}
#define __epsilon__ (1e-4)
bool is_id(ql::cmat_t& mat)
{
// mat.dump();
ql::complex_t * m = mat.m;
if ((std::abs(std::abs(m[0].real())-1.0))>__epsilon__) return false;
if ((std::abs(m[0].imag()) )>__epsilon__) return false;
if ((std::abs(m[1].real()) )>__epsilon__) return false;
if ((std::abs(m[1].imag()) )>__epsilon__) return false;
if ((std::abs(m[2].real()) )>__epsilon__) return false;
if ((std::abs(m[2].imag()) )>__epsilon__) return false;
if ((std::abs(std::abs(m[3].real())-1.0))>__epsilon__) return false;
if ((std::abs(m[3].imag()) )>__epsilon__) return false;
return true;
}
bool is_identity(ql::circuit& c)
{
if (c.size()==1)
return false;
ql::cmat_t m = c[0]->mat();
for (size_t i=1; i<c.size(); ++i)
{
ql::cmat_t m2 = c[i]->mat();
m = fuse(m,m2);
}
return (is_id(m));
}
ql::circuit optimize_sliding_window(ql::circuit& c, size_t window_size)
{
ql::circuit oc;
std::vector<int> id_pos;
for (size_t i=0; i<c.size()-window_size+1; ++i)
{
ql::circuit w;
w.insert(w.begin(),c.begin()+i,c.begin()+i+window_size);
if (is_identity(w))
id_pos.push_back(i);
}
if (id_pos.empty())
{
return ql::circuit(c);
}
// println("id pos:");
// for (size_t i=0; i<id_pos.size(); i++)
// println(id_pos[i]);
if (id_pos.size()==1)
{
// COUT("rotations cancelling...");
size_t pos = id_pos[0];
size_t i=0;
while (i<c.size())
{
if (i==pos)
i+=window_size;
else
{
oc.push_back(c[i]);
i++;
}
}
return oc;
}
// COUT("removing overlapping windows...");
std::vector<int> pid;
// int prev = id_pos[0];
// COUT("rotation cancelling...");
size_t pos = id_pos[0];
size_t ip = 0;
size_t i=0;
while (i<c.size())
{
if (i==pos)
{
i+=window_size;
ip++;
if (ip<id_pos.size())
pos=id_pos[ip];
}
else
{
oc.push_back(c[i]);
i++;
}
}
return oc;
}
};
inline void rotation_optimize_kernel(ql::quantum_kernel& kernel, const ql::quantum_platform & platform)
{
DOUT("kernel " << kernel.name << " optimize_kernel(): circuit before optimizing: ");
print(kernel.c);
DOUT("... end circuit");
ql::rotations_merging rm;
if (contains_measurements(kernel.c))
{
DOUT("kernel contains measurements ...");
// decompose the circuit
std::vector<circuit*> cs = split_circuit(kernel.c);
std::vector<circuit > cs_opt;
for (size_t i=0; i<cs.size(); ++i)
{
if (!contains_measurements(*cs[i]))
{
circuit opt = rm.optimize(*cs[i]);
cs_opt.push_back(opt);
}
else
cs_opt.push_back(*cs[i]);
}
// for (int i=0; i<cs_opt.size(); ++i)
// print(cs_opt[i]);
kernel.c.clear( );
for (size_t i=0; i<cs_opt.size(); ++i)
for (size_t j=0; j<cs_opt[i].size(); j++)
kernel.c.push_back(cs_opt[i][j]);
}
else
{
kernel.c = rm.optimize(kernel.c);
}
kernel.cycles_valid = false;
DOUT("kernel " << kernel.name << " rotation_optimize(): circuit after optimizing: ");
print(kernel.c);
DOUT("... end circuit");
}
// rotation_optimize pass
void rotation_optimize(ql::quantum_program* programp, const ql::quantum_platform& platform, std::string passname)
{
if( ql::options::get("optimize") == "yes" )
{
IOUT("optimizing quantum kernels...");
for (size_t k=0; k<programp->kernels.size(); ++k)
rotation_optimize_kernel(programp->kernels[k], platform);
}
}
}
| 26.745455 | 117 | 0.466689 | [
"vector"
] |
ef42ca572144339ebd0154814d3a4b5dd268529b | 2,542 | hpp | C++ | include/eve/function/minimum.hpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 340 | 2020-09-16T21:12:48.000Z | 2022-03-28T15:40:33.000Z | third-party/eve/function/minimum.hpp | aguinet/ecsimd | cba9e7fe76601b98cbaeea317b6c4e671272e70b | [
"Apache-2.0"
] | 383 | 2020-09-17T06:56:35.000Z | 2022-03-13T15:58:53.000Z | third-party/eve/function/minimum.hpp | aguinet/ecsimd | cba9e7fe76601b98cbaeea317b6c4e671272e70b | [
"Apache-2.0"
] | 28 | 2021-02-27T23:11:23.000Z | 2022-03-25T12:31:29.000Z | /*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/detail/overload.hpp>
namespace eve
{
//================================================================================================
//! @addtogroup reduction
//! @{
//! @var minimum
//!
//! @brief Callable object computing minimal element.
//!
//! **Required header:** `#include <eve/function/minimum.hpp>`
//!
//! #### Members Functions
//!
//! | Member | Effect |
//! |:-------------|:-----------------------------------------------------------|
//! | `operator()` | computes the minimal element of a real value |
//! | `operator[]` | Construct a masked version of current function object |
//!
//! ---
//!
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
//! auto operator()( real_value x) const noexcept;
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//!
//! **Parameters**
//!
//!`x`: a [real value](@ref eve::real_value)
//!
//! **Return value**
//!
//!returns a [scalar value](@ref eve::scalar_value) containing the minimal element
//!
//! ---
//!
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
//! auto operator[]( conditional_expression auto cond ) const noexcept;
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//!
//! Higher-order function generating a masked version of eve::minimum
//!
//! **Parameters**
//!
//! `cond` : conditional expression
//!
//! **Return value**
//!
//! A Callable object so that the expression `minimum[cond](x)` is equivalent to `minimum(if_else(cond, x, valmax(as(x))))`
//!
//! ---
//!
//! #### Supported decorators
//!
//! no decorators are supported
//!
//! #### Example
//!
//! @godbolt{doc/core/minimum.cpp}
//!
//! @}
//================================================================================================
EVE_MAKE_CALLABLE(minimum_, minimum);
}
#include <eve/arch.hpp>
#include <eve/module/real/algorithm/function/regular/generic/minimum.hpp>
#if defined(EVE_INCLUDE_ARM_HEADER)
# include <eve/module/real/algorithm/function/regular/simd/arm/neon/minimum.hpp>
#endif
#if defined(EVE_INCLUDE_X86_HEADER)
# include <eve/module/real/algorithm/function/regular/simd/x86/minimum.hpp>
#endif
| 30.261905 | 126 | 0.45358 | [
"object",
"vector"
] |
ef45d51165f446c06e84e2134ecec4670331ea33 | 5,355 | cpp | C++ | OpenSees/SRC/reliability/FEsensitivity/SensitivityAlgorithm.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | 8 | 2019-03-05T16:25:10.000Z | 2020-04-17T14:12:03.000Z | SRC/reliability/FEsensitivity/SensitivityAlgorithm.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | null | null | null | SRC/reliability/FEsensitivity/SensitivityAlgorithm.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 3 | 2019-09-21T03:11:11.000Z | 2020-01-19T07:29:37.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 2001, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** Reliability module developed by: **
** Terje Haukaas (haukaas@ce.berkeley.edu) **
** Armen Der Kiureghian (adk@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.13 $
// $Date: 2008-08-26 16:15:47 $
// $Source: /usr/local/cvs/OpenSees/SRC/reliability/FEsensitivity/SensitivityAlgorithm.cpp,v $
//
// Written by Terje Haukaas (haukaas@ce.berkeley.edu)
//
#include <SensitivityAlgorithm.h>
#include <ReliabilityDomain.h>
#include <Integrator.h>
#include <LinearSOE.h>
#include <EquiSolnAlgo.h>
#include <Vector.h>
#include <Domain.h>
#include <Parameter.h>
#include <ParameterIter.h>
SensitivityAlgorithm::SensitivityAlgorithm(Domain *passedDomain,
EquiSolnAlgo *passedAlgorithm,
Integrator *passedSensitivityIntegrator,
int passedAnalysisTypeTag):
theDomain(passedDomain), theAlgorithm(passedAlgorithm),
analysisTypeTag(passedAnalysisTypeTag)
{
}
SensitivityAlgorithm::~SensitivityAlgorithm()
{
}
/*
int
SensitivityAlgorithm::computeSensitivities(void)
{
if (theAlgorithm == 0) {
opserr << "ERROR the FE algorithm must be defined before ";
opserr << "the sensitivity algorithm\n";
return -1;
}
// Get pointer to the system of equations (SOE)
LinearSOE *theSOE = theAlgorithm->getLinearSOEptr();
if (theSOE == 0) {
opserr << "ERROR the FE linearSOE must be defined before ";
opserr << "the sensitivity algorithm\n";
return -1;
}
// Get pointer to incremental integrator
IncrementalIntegrator *theIncInt = theAlgorithm->getIncrementalIntegratorPtr();
// IncrementalIntegrator *theIncIntSens=theAlgorithm->getIncrementalIntegratorPtr();//Abbas
if (theIncInt == 0 ) {
opserr << "ERROR the FE integrator must be defined before ";
opserr << "the sensitivity algorithm\n";
return -1;
}
// Form current tangent at converged state
// (would be nice with an if-statement here in case
// the current tangent is already formed)
if (theIncInt->formIndependentSensitivityLHS(CURRENT_TANGENT) < 0){
opserr << "WARNING SensitivityAlgorithm::computeGradients() -";
opserr << "the Integrator failed in formTangent()\n";
return -1;
}
// Zero out the old right-hand side of the SOE
theSOE->zeroB();
Integrator* theSensitivityIntegrator = theIncInt;
// Form the part of the RHS which are indepent of parameter
theSensitivityIntegrator->formIndependentSensitivityRHS();
ParameterIter ¶mIter = theDomain->getParameters();
// opserr<<" get parameters "<<theDomain->getParameters()<<endln;//Abbas.......
Parameter *theParam;
// De-activate all parameters
while ((theParam = paramIter()) != 0)
theParam->activate(false);
// Now, compute sensitivity wrt each parameter
int numGrads = theDomain->getNumParameters();
//opserr<<"the numGrads is "<<numGrads<<endln;//Abbas...............................
paramIter = theDomain->getParameters();
while ((theParam = paramIter()) != 0) {
// Activate this parameter
theParam->activate(true);
// Zero the RHS vector
theSOE->zeroB();
// Get the grad index for this parameter
int gradIndex = theParam->getGradIndex();
// Form the RHS
theSensitivityIntegrator->formSensitivityRHS(gradIndex);
// Solve for displacement sensitivity
theSOE->solve();
// Save sensitivity to nodes
theSensitivityIntegrator->saveSensitivity( theSOE->getX(), gradIndex, numGrads );
// Commit unconditional history variables (also for elastic problems; strain sens may be needed anyway)
theSensitivityIntegrator->commitSensitivity(gradIndex, numGrads);
// De-activate this parameter for next sensitivity calc
theParam->activate(false);
}
return 0;
}
*/
/*
bool
SensitivityAlgorithm::shouldComputeAtEachStep(void)
{
return (analysisTypeTag == 1);
}
*/
| 33.892405 | 106 | 0.586928 | [
"vector"
] |
ef53c23496f0a17ac674b5c0f07174c9e8811427 | 412 | cc | C++ | fechas/src/fecha.cc | ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-RamiroDifonti | 9608f1ae675847ed08850a2e6bb10e88d2976abb | [
"MIT"
] | null | null | null | fechas/src/fecha.cc | ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-RamiroDifonti | 9608f1ae675847ed08850a2e6bb10e88d2976abb | [
"MIT"
] | null | null | null | fechas/src/fecha.cc | ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-RamiroDifonti | 9608f1ae675847ed08850a2e6bb10e88d2976abb | [
"MIT"
] | null | null | null | #include <iostream>
#include "fecha.h"
#include <string>
#include <fstream>
int main(int argc, char* argv[]){
Usage(argc, argv);
Foreword(argv);
std::vector<int> dias= Archivos_dias(argv);
std::vector<int> meses= Archivos_meses(argv);
std::vector<int> anios= Archivos_anios(argv);
std::vector<int> fechas_ordenadas = my_days.Ordenador(dias,meses,anios);
my_days.Archivo_salida(fechas_ordenadas);
} | 29.428571 | 74 | 0.728155 | [
"vector"
] |
ef590b9a5dac76d8b7cc19416b63ef4a7968bc1a | 1,486 | hpp | C++ | src/bitmap_image.hpp | YzolaPhilo/bitmap4Cpp | 0f5d3af2af6f48b67e1ad24bdeab280e49cdd5c2 | [
"MIT"
] | null | null | null | src/bitmap_image.hpp | YzolaPhilo/bitmap4Cpp | 0f5d3af2af6f48b67e1ad24bdeab280e49cdd5c2 | [
"MIT"
] | null | null | null | src/bitmap_image.hpp | YzolaPhilo/bitmap4Cpp | 0f5d3af2af6f48b67e1ad24bdeab280e49cdd5c2 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <string>
#include <vector>
class bitmap_image {
private:
std::string _file_name_;
unsigned int _width_;
unsigned int _height_;
unsigned int _stride_;
channel_mode _channel_mode_;
bitcount_mode _bitcount;
std::vector<unsigned char> data_;
public:
bitmap_image(const std::string& filename)
: _file_name_(filename),
_width_(0),
_height_(0),
_channel_mode_(bgr_mode) {
//load_bitmap();
}
bitmap_image(const unsigned int width, const unsigned int height)
: _file_name_(""),
_width_(width),
_height_(height),
_channel_mode_(bgr_mode),
_bitcount(bit8){
//create_bitmap();
}
bitmap_image(const unsigned int width, const unsigned int height, bitcount_mode bitcount)
: _file_name_(""),
_width_(width),
_height_(height),
_channel_mode_(bgr_mode) {
//create_bitmap();
}
bitmap_image(const unsigned int width, const unsigned int heigh, bitcount_mode bitcount, ...)
: _file_name_(""),
_width_(width),
_height_(height),
_channel_mode_(bgr_mode) {
//create_bitmap();
}
public:
enum channel_mode {
rgb_mode = 0,
bgr_mode = 1
};
enum color_plane {
blue_plane = 0,
green_plane = 1,
red_plane = 2
};
static enum bitcount_mode {
bit8 = 0,
bit24 = 1
};
struct rgb_t {
unsigned char red;
unsigned char green;
unsigned char blue;
};
}; | 18.345679 | 94 | 0.705249 | [
"vector"
] |
ef599a220dc7521c047710cf761e2c142f2da052 | 1,156 | cpp | C++ | 10. Base Class Pointer Derived Class Object/02. base_class_ptr_derived_class_object.cpp | ManthanUgemuge/Deep-Dive-in-CPP-Abdul-Bari | 36aacdca116628264724cc2624d64fcb1e0c1148 | [
"MIT"
] | 1 | 2022-02-15T21:11:42.000Z | 2022-02-15T21:11:42.000Z | 10. Base Class Pointer Derived Class Object/02. base_class_ptr_derived_class_object.cpp | ManthanUgemuge/Deep-Dive-in-CPP-Abdul-Bari | 36aacdca116628264724cc2624d64fcb1e0c1148 | [
"MIT"
] | null | null | null | 10. Base Class Pointer Derived Class Object/02. base_class_ptr_derived_class_object.cpp | ManthanUgemuge/Deep-Dive-in-CPP-Abdul-Bari | 36aacdca116628264724cc2624d64fcb1e0c1148 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class Base
{
public:
void fun1() { cout << "Fun1 of base." << endl; }
};
class Child : public Base
{
public:
void fun2() { cout << "Fun2 of child." << endl; }
};
int main()
{
/*
Child c; // Creating an object of child class and calling both fun1 and fun2.
c.fun1();
c.fun2();
*/
//-------------------------------------------------------------------------------------
//Taking a base class pointer and assigning to it the address of child class object c.
Child c;
Base *ptr = &c;
ptr->fun1();
// ptr->fun2(); // Gives error Base class has no member fun2().
// Here object is child class and ptr is of Base class so it has only functions of Base class accessible.
// Trying to create a pointer to child class and pointing it to base or parent class not possible as below
/*
Base test_object;
Child *ptr = &test_object; // Gives an error that a value of type base can't be used to initialize a value of type child*.
*/
return 0;
}
// Base class pointer pointing to the child class object can only call to the functions of base class.
| 31.243243 | 126 | 0.597751 | [
"object"
] |
ef63be075852768624633d47bc0c03238ba1479b | 13,622 | cpp | C++ | Meduza/Source/Core/Scripting/LuaFunctions.cpp | NWagter/Meduza | d1df99061381fa1c7665d09e275ddc0060a6ac8d | [
"MIT"
] | 6 | 2020-10-17T10:50:13.000Z | 2022-02-25T20:14:23.000Z | Meduza/Source/Core/Scripting/LuaFunctions.cpp | NWagter/Meduza | d1df99061381fa1c7665d09e275ddc0060a6ac8d | [
"MIT"
] | null | null | null | Meduza/Source/Core/Scripting/LuaFunctions.cpp | NWagter/Meduza | d1df99061381fa1c7665d09e275ddc0060a6ac8d | [
"MIT"
] | 1 | 2020-05-06T12:02:47.000Z | 2020-05-06T12:02:47.000Z | #include "MePCH.h"
#include "Core/Scripting/LuaFunctions.h"
#include "MeduzaIncluder.h"
#include "Physics/Components/ColliderComponent.h"
#include "Core/Scripting/ScriptComponent.h"
#include "Platform/General/FileSystem/FileSystem.h"
#include "Platform/General/TextureLibrary.h"
#include "Platform/General/Resources/TextureBase.h"
void Me::Scripting::LuaFunctions::RegisterFunctions(lua_State* a_luaState)
{
lua_register(a_luaState, "_DestroyEnt", lua_DestroyEnt);
lua_register(a_luaState, "_GetEntityByName", lua_GetEntityByName);
lua_register(a_luaState, "_Translate", lua_Translate);
lua_register(a_luaState, "_SetLocation", lua_SetLocation);
lua_register(a_luaState, "_GetLocation", lua_GetLocation);
lua_register(a_luaState, "__GetDistance", lua_GetDistance);
lua_register(a_luaState, "_Move", lua_Move);
lua_register(a_luaState, "_Rotate", lua_Rotate);
lua_register(a_luaState, "_SetRotation", lua_SetRotation);
lua_register(a_luaState, "_SetScale", lua_SetScale);
lua_register(a_luaState, "_FlipX", lua_FlipX);
lua_register(a_luaState, "_FlipY", lua_FlipY);
lua_register(a_luaState, "_OnKeyUp", lua_OnKeyUp);
lua_register(a_luaState, "_OnKeyDown", lua_OnKeyDown);
lua_register(a_luaState, "_OnTriggerEntityName", lua_OnTriggerEntityName);
lua_register(a_luaState, "_OnCollisionEntityName", lua_OnCollisionEntityName);
lua_register(a_luaState, "_InstantiatePrefab", lua_InstantiatePrefab);
lua_register(a_luaState, "_CallFunction", lua_CallFunction);
lua_register(a_luaState, "_SetUV", lua_SetUV);
}
int Me::Scripting::LuaFunctions::lua_DestroyEnt(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
EntityManager::GetEntityManager()->DestroyEntity(ent);
lua_pushnumber(a_luaState, 1);
return 1;
}
int Me::Scripting::LuaFunctions::lua_GetEntityByName(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
std::string name = lua_tostring(a_luaState, 1);
EntityFilter filter;
filter.insert(TagComponent::s_componentID);
filter.insert(Physics::ColliderTagComponent::s_componentID);
filter.insert(Physics::PhysicsComponent::s_componentID);
EntityManager* eManager = EntityManager::GetEntityManager();
std::vector<EntityID> ents = eManager->GetEntities(filter);
for(auto e : ents)
{
TagComponent* t = eManager->GetComponent<TagComponent>(e);
if(t->m_tag == name)
{
lua_pushnumber(a_luaState, (uint64_t)e);
return 1;
}
}
lua_pushnumber(a_luaState, 0);
return 0;
}
int Me::Scripting::LuaFunctions::lua_Translate(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
trans->m_translation += Math::Vec3(x,y,z);
return 0;
}
int Me::Scripting::LuaFunctions::lua_Rotate(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
trans->m_rotation += Math::Vec3(x,y,z);
return 0;
}
int Me::Scripting::LuaFunctions::lua_GetLocation(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
if(trans == nullptr)
return -1;
lua_newtable(a_luaState);
lua_pushstring(a_luaState, "x");
lua_pushnumber(a_luaState, trans->m_translation.m_x);
lua_settable(a_luaState, -3);
lua_pushstring(a_luaState, "y");
lua_pushnumber(a_luaState, trans->m_translation.m_y);
lua_settable(a_luaState, -3);
lua_pushstring(a_luaState, "z");
lua_pushnumber(a_luaState, trans->m_translation.m_z);
lua_settable(a_luaState, -3);
luaL_getmetatable(a_luaState, "VectorMetaTable");
lua_setmetatable(a_luaState, -2);
return 1;
}
int Me::Scripting::LuaFunctions::lua_GetDistance(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 2) return -1;
EntityID entA = (EntityID)lua_tonumber(a_luaState, 1);
EntityID entB = (EntityID)lua_tonumber(a_luaState, 2);
auto transA = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(entA);
auto transB = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(entB);
float distance = Math::Distance(transA->m_translation, transB->m_translation);
lua_pushnumber(a_luaState, distance);
return 1;
}
int Me::Scripting::LuaFunctions::lua_Move(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
Me::Math::Mat4 transform = Me::Math::Mat4().Rotation(trans->m_rotation);
Me::Math::Vec3 right = transform.GetRight() * x;
Me::Math::Vec3 up = transform.GetUp() * y;
Me::Math::Vec3 forward = transform.GetForward() * z;
Me::Math::Vec3 movement = forward + right + up;
trans->m_translation = trans->m_translation + (movement);
return 0;
}
int Me::Scripting::LuaFunctions::lua_SetLocation(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
trans->m_translation = Math::Vec3(x,y,z);
return 0;
}
int Me::Scripting::LuaFunctions::lua_SetRotation(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
trans->m_rotation = Math::Vec3(x,y,z);
return 0;
}
int Me::Scripting::LuaFunctions::lua_SetScale(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
trans->m_scale = Math::Vec3(x,y,z);
return 0;
}
int Me::Scripting::LuaFunctions::lua_FlipX(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
auto scale = trans->m_scale;
scale.m_x = -scale.m_x;
trans->m_scale = scale;
return 0;
}
int Me::Scripting::LuaFunctions::lua_FlipY(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(ent);
auto scale = trans->m_scale;
scale.m_y = -scale.m_y;
trans->m_scale = scale;
return 0;
}
int Me::Scripting::LuaFunctions::lua_OnKeyUp(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
Me::Event::KeyCode key = (Me::Event::KeyCode)lua_tonumber(a_luaState, -1);
if(Event::EventSystem::GetEventSystem()->KeyUp(key))
{
lua_pushnumber(a_luaState, 1);
}
else
{
lua_pushnumber(a_luaState, 0);
}
return 1;
}
int Me::Scripting::LuaFunctions::lua_OnKeyDown(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 1) return -1;
Me::Event::KeyCode key = (Me::Event::KeyCode)lua_tonumber(a_luaState, -1);
if(Event::EventSystem::GetEventSystem()->KeyDown(key))
{
lua_pushnumber(a_luaState, 1);
}
else
{
lua_pushnumber(a_luaState, 0);
}
return 1;
}
int Me::Scripting::LuaFunctions::lua_OnTriggerEntityName(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 2) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
std::string name = lua_tostring(a_luaState, 2);
EntityFilter filter;
filter.insert(TagComponent::s_componentID);
filter.insert(Physics::ColliderTagComponent::s_componentID);
filter.insert(Physics::PhysicsComponent::s_componentID);
EntityManager* eManager = EntityManager::GetEntityManager();
std::vector<EntityID> ents = eManager->GetEntities(filter);
for(auto e : ents)
{
TagComponent* t = eManager->GetComponent<TagComponent>(e);
if(t->m_tag == name || name.empty())
{
Physics::PhysicsComponent* c = eManager->GetComponent<Physics::PhysicsComponent>(ent);
for(auto data : c->m_triggered)
{
if(data.m_entity == e)
{
lua_pushnumber(a_luaState, (int)e);
return 1;
}
}
}
}
lua_pushnumber(a_luaState, -1);
return -1;
}
int Me::Scripting::LuaFunctions::lua_OnCollisionEntityName(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 2) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
std::string name = lua_tostring(a_luaState, 2);
EntityFilter filter;
filter.insert(TagComponent::s_componentID);
filter.insert(Physics::ColliderTagComponent::s_componentID);
filter.insert(Physics::PhysicsComponent::s_componentID);
EntityManager* eManager = EntityManager::GetEntityManager();
std::vector<EntityID> ents = eManager->GetEntities(filter);
for(auto e : ents)
{
TagComponent* t = eManager->GetComponent<TagComponent>(e);
if(t->m_tag == name)
{
Physics::PhysicsComponent* c = eManager->GetComponent<Physics::PhysicsComponent>(e);
for(auto data : c->m_collided)
{
if(data.m_entity == ent)
{
lua_pushnumber(a_luaState, (int)e);
return 1;
}
}
}
}
lua_pushnumber(a_luaState, -1);
return -1;
}
int Me::Scripting::LuaFunctions::lua_InstantiatePrefab(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
std::string path = lua_tostring(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
size_t pos = path.find("Assets"); //find location of word
path.erase(0,pos); //delete everything prior to location found
std::replace(path.begin(), path.end(), '\\', '/');
EntityID newEntity = Serialization::Serializer::GetInstance()->DeserializeEntity(path);
auto trans = EntityManager::GetEntityManager()->GetComponent<TransformComponent>(newEntity);
if(trans == nullptr)
{
return -1;
}
trans->m_translation = Math::Vec3(x,y,z);
lua_pushnumber(a_luaState, (uint64_t)newEntity);
return 1;
}
int Me::Scripting::LuaFunctions::lua_CallFunction(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 4) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
std::string script = lua_tostring(a_luaState, 2);
std::string function = lua_tostring(a_luaState, 3);
EntityID entFrom = (EntityID)lua_tonumber(a_luaState, 4);
auto sC = EntityManager::GetEntityManager()->GetComponent<ScriptComponent>(ent);
if(sC == nullptr || sC->m_luastates.empty())
{
return -1;
}
lua_State* lScript = nullptr;
for(size_t i = 0; i < sC->m_scripts.size(); i++)
{
if(Files::FileSystem::GetFileName(sC->m_scripts[i]) == script)
{
lScript = sC->m_luastates.at(i);
break;
}
}
if(lScript == nullptr)
{
return -1;
}
lua_getglobal(lScript, function.c_str());
if(lua_isfunction(lScript, -1) )
{
lua_pushnumber(lScript, (uint64_t)entFrom);
lua_pcall(lScript,1,0,0);
}
return 1;
}
int Me::Scripting::LuaFunctions::lua_SetUV(lua_State* a_luaState)
{
if(lua_gettop(a_luaState) != 5) return -1;
EntityID ent = (EntityID)lua_tonumber(a_luaState, 1);
float x = lua_tonumber(a_luaState, 2);
float y = lua_tonumber(a_luaState, 3);
float z = lua_tonumber(a_luaState, 4);
float w = lua_tonumber(a_luaState, 5);
auto rC = EntityManager::GetEntityManager()->GetComponent<RenderComponent>(ent);
if(rC != nullptr && rC->m_texture > 0)
{
Math::Vec2 size = Resources::TextureLibrary::GetTexture(rC->m_texture)->GetSize();
rC->m_textureCoords = Animation::GetUV(Math::Vec4(x,y,z,w), size);
}
return 1;
} | 28.982979 | 98 | 0.670019 | [
"vector",
"transform"
] |
ef6404275de5279a4985566379ebc91b590fee09 | 3,495 | cpp | C++ | src/besiq_glm.cpp | hoehleatsu/besiq | 94959e2819251805e19311ce377919e6bccb7bf9 | [
"BSD-3-Clause"
] | 1 | 2015-10-21T14:22:12.000Z | 2015-10-21T14:22:12.000Z | src/besiq_glm.cpp | hoehleatsu/besiq | 94959e2819251805e19311ce377919e6bccb7bf9 | [
"BSD-3-Clause"
] | 2 | 2019-05-26T20:52:31.000Z | 2019-05-28T16:19:49.000Z | src/besiq_glm.cpp | hoehleatsu/besiq | 94959e2819251805e19311ce377919e6bccb7bf9 | [
"BSD-3-Clause"
] | 2 | 2016-11-06T14:58:37.000Z | 2019-05-26T14:03:13.000Z | #include <iostream>
#include <armadillo>
#include <glm/models/binomial.hpp>
#include <glm/models/normal.hpp>
#include <cpp-argparse/OptionParser.h>
#include <besiq/method/glm_method.hpp>
#include <besiq/method/method.hpp>
#include "common_options.hpp"
using namespace arma;
using namespace optparse;
const std::string USAGE = "besiq-glm [OPTIONS] pairs genotype_plink_prefix";
const std::string DESCRIPTION = "Generalized linear models for genetic interactions.";
int
main(int argc, char *argv[])
{
OptionParser parser = create_common_options( USAGE, DESCRIPTION, true );
char const* const model_choices[] = { "binomial", "normal" };
char const* const link_choices[] = { "logit", "logc", "odds", "identity", "log" };
char const* const factor_choices[] = { "factor", "additive", "tukey", "noia" };
OptionGroup group = OptionGroup( parser, "Options for glm", "These options will change the behavior of the glm model." );
group.add_option( "-m", "--model" ).choices( &model_choices[ 0 ], &model_choices[ 2 ] ).metavar( "model" ).help( "The model to use for the phenotype, 'binomial' or 'normal', default = 'binomial'." ).set_default( "binomial" );
group.add_option( "-l", "--link-function" ).choices( &link_choices[ 0 ], &link_choices[ 5 ] ).metavar( "link" ).help( "The link function, or scale, that is used for the penetrance: 'logit' log(p/(1-p)), 'logc' log(1 - p), 'odds' p/(1-p), 'identity' p, 'log' log(p)." );
group.add_option( "-f", "--factor" ).choices( &factor_choices[ 0 ], &factor_choices[ 4 ] ).help( "Determines how to code the SNPs, in 'factor' no order of the alleles is assumed, in 'additive' the SNPs are coded as the number of minor alleles, in 'tukey' the coding is the same as factor except that a single parameter for the interaction is used, 'noia' the model is divided into additive and dominance interactions." ).set_default( "factor" );
group.add_option( "--fast" ).help( "Faster but less robust matrix inversion, generally a speedup of 2 can be expected." ).action( "store_true" );
parser.add_option_group( group );
Values options = parser.parse_args( argc, argv );
if( parser.args( ).size( ) != 2 )
{
parser.print_help( );
exit( 1 );
}
shared_ptr<common_options> parsed_data = parse_common_options( options, parser.args( ) );
parsed_data->data->phenotype.elem( arma::find_nonfinite( parsed_data->data->phenotype ) ).zeros( );
parsed_data->data->fast_inversion = options.is_set( "fast" );
model_matrix *model_matrix = make_model_matrix( options[ "factor" ], parsed_data->data->covariate_matrix, parsed_data->data->phenotype.n_elem );
method_type *m = NULL;
if( options[ "model" ] == "binomial" )
{
std::string link = "logit";
if( options.is_set( "link_function" ) )
{
link = options[ "link_function" ];
}
binomial *model = new binomial( link );
m = new glm_method( parsed_data->data, *model, *model_matrix );
}
else if( options[ "model" ] == "normal" )
{
std::string link = "identity";
if( options.is_set( "link_function" ) )
{
link = options[ "link_function" ];
}
normal *model = new normal( link );
m = new glm_method( parsed_data->data, *model, *model_matrix );
}
run_method( *m, parsed_data->genotypes, *parsed_data->pairs, *parsed_data->result_file );
delete m;
delete model_matrix;
return 0;
}
| 44.240506 | 449 | 0.656652 | [
"model"
] |
ef64661405677603263999ffa949cf5ccc2f9e1f | 18,983 | cc | C++ | hyperion/cfcompute/cfcompute.cc | mpokorny/legms | 8ea5d1899ac5e2658ebe481b706430474685bb2d | [
"Apache-2.0"
] | 2 | 2021-02-03T00:40:55.000Z | 2021-02-03T13:30:31.000Z | hyperion/cfcompute/cfcompute.cc | mpokorny/legms | 8ea5d1899ac5e2658ebe481b706430474685bb2d | [
"Apache-2.0"
] | null | null | null | hyperion/cfcompute/cfcompute.cc | mpokorny/legms | 8ea5d1899ac5e2658ebe481b706430474685bb2d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Associated Universities, Inc. Washington DC, USA.
*
* 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 <hyperion/synthesis/PSTermTable.h>
#include <hyperion/synthesis/WTermTable.h>
#include <hyperion/synthesis/ATermTable.h>
#include <hyperion/synthesis/CFPhysicalTable.h>
#include <hyperion/synthesis/ProductCFTable.h>
using namespace hyperion::synthesis;
using namespace hyperion;
using namespace Legion;
namespace cc = casacore;
using namespace std::complex_literals;
enum {
CFCOMPUTE_TASK_ID,
SHOW_GRID_TASK_ID,
};
#define ZC(F, S, N, C) ZCoeff{\
0, F, cc::Stokes::S, \
zernike_inverse_index(N).first, zernike_inverse_index(N).second, C}
std::vector<ZCoeff> zc{
ZC(2.052e9, RR, 0, 0.37819f + 0.00002if),
ZC(2.052e9, RR, 1, 0.01628f + 0.00047if),
ZC(2.052e9, RR, 2, -0.09923f + -0.10694if),
ZC(2.052e9, RR, 3, -0.39187f + 0.14695if),
ZC(2.052e9, RR, 4, -0.13131f + -0.00091if),
ZC(2.052e9, RR, 5, 0.01133f + -0.00092if),
ZC(2.052e9, RR, 6, 0.00102f + 0.00192if),
ZC(2.052e9, RR, 7, 0.01859f + -0.00012if),
ZC(2.052e9, RR, 8, -0.11248f + -0.05952if),
ZC(2.052e9, RR, 9, 0.26306f + 0.17708if),
ZC(2.052e9, RR, 10, 0.69350f + -0.26642if),
ZC(2.052e9, RR, 11, -0.03680f + 0.01169if),
ZC(2.052e9, RR, 12, -0.29097f + 0.00009if),
ZC(2.052e9, RR, 13, 0.00339f + 0.00033if),
ZC(2.052e9, RR, 14, -0.06400f + 0.00003if),
ZC(2.052e9, RR, 15, -0.00677f + 0.00264if),
ZC(2.052e9, RR, 16, 0.00589f + -0.00239if),
ZC(2.052e9, RR, 17, -0.01686f + -0.00083if),
ZC(2.052e9, RR, 18, -0.08941f + -0.03308if),
ZC(2.052e9, RR, 19, 0.14236f + 0.09008if),
ZC(2.052e9, RR, 20, -0.00497f + 0.00497if),
ZC(2.052e9, RR, 21, 0.15580f + -0.06187if),
ZC(2.052e9, RR, 22, 0.03711f + -0.00733if),
ZC(2.052e9, RR, 23, 0.05036f + -0.01948if),
ZC(2.052e9, RR, 24, 0.10280f + 0.00141if),
ZC(2.052e9, RR, 25, -0.01427f + 0.00114if),
ZC(2.052e9, RR, 26, 0.13969f + 0.00059if),
ZC(2.052e9, RR, 27, 0.00058f + 0.00019if),
ZC(2.052e9, RR, 28, -0.00119f + -0.00111if),
ZC(2.052e9, RR, 29, 0.00694f + -0.00259if),
ZC(2.052e9, RR, 30, -0.00683f + -0.00186if),
ZC(2.052e9, RR, 31, -0.00070f + -0.00161if),
ZC(2.052e9, RR, 32, -0.02364f + -0.04063if),
ZC(2.052e9, RR, 33, 0.05053f + 0.02714if),
ZC(2.052e9, RR, 34, 0.00652f + -0.00628if),
ZC(2.052e9, RR, 35, -0.15033f + -0.09639if),
ZC(2.052e9, RR, 36, -0.03384f + 0.00533if),
ZC(2.052e9, RR, 37, 0.00513f + -0.00445if),
ZC(2.052e9, RR, 38, -0.00770f + 0.00211if),
ZC(2.052e9, RR, 39, 0.00647f + -0.00278if),
ZC(2.052e9, RR, 40, -0.02438f + -0.00152if),
ZC(2.052e9, RR, 41, 0.00422f + -0.00167if),
ZC(2.052e9, RR, 42, -0.04437f + -0.00022if),
ZC(2.052e9, RR, 43, -0.00595f + 0.00014if),
ZC(2.052e9, RR, 44, -0.08273f + 0.00019if),
ZC(2.052e9, RR, 45, -0.00992f + 0.00086if),
ZC(2.052e9, RR, 46, 0.00541f + -0.00039if),
ZC(2.052e9, RR, 47, 0.00341f + 0.00008if),
ZC(2.052e9, RR, 48, -0.00214f + 0.00619if),
ZC(2.052e9, RR, 49, -0.00764f + 0.00319if),
ZC(2.052e9, RR, 50, -0.01077f + 0.01481if),
ZC(2.052e9, RR, 51, 0.00811f + 0.00655if),
ZC(2.052e9, RR, 52, 0.00167f + 0.00230if),
ZC(2.052e9, RR, 53, -0.02934f + -0.01891if),
ZC(2.052e9, RR, 54, 0.05106f + 0.03961if),
ZC(2.052e9, RR, 55, 0.00461f + 0.00036if),
ZC(2.052e9, RR, 56, 0.02158f + -0.00070if),
ZC(2.052e9, RR, 57, 0.00122f + 0.00022if),
ZC(2.052e9, RR, 58, -0.00541f + 0.00050if),
ZC(2.052e9, RR, 59, -0.00383f + 0.00122if),
ZC(2.052e9, RR, 60, 0.06256f + 0.00081if),
ZC(2.052e9, RR, 61, 0.00303f + 0.00109if),
ZC(2.052e9, RR, 62, -0.04991f + -0.00042if),
ZC(2.052e9, RR, 63, 0.00538f + -0.00042if),
ZC(2.052e9, RR, 64, 0.09183f + -0.00002if),
ZC(2.052e9, RR, 65, 0.00234f + 0.00002if),
ZC(2.052e9, RL, 0, -25.80661f + 0.06602if),
ZC(2.052e9, RL, 1, -0.65152f + -1.00155if),
ZC(2.052e9, RL, 2, -15.04070f + 41.52323if),
ZC(2.052e9, RL, 3, -186.20722f + 24.34289if),
ZC(2.052e9, RL, 4, 18.62878f + 0.07767if),
ZC(2.052e9, RL, 5, 1.03500f + 0.04380if),
ZC(2.052e9, RL, 6, 1.38037f + 2.91762if),
ZC(2.052e9, RL, 7, 0.52933f + -2.25038if),
ZC(2.052e9, RL, 8, -15.05019f + 48.04883if),
ZC(2.052e9, RL, 9, 35.20039f + -96.21997if),
ZC(2.052e9, RL, 10, 333.31978f + -42.80111if),
ZC(2.052e9, RL, 11, -23.80762f + 2.54675if),
ZC(2.052e9, RL, 12, -13.08137f + -0.13430if),
ZC(2.052e9, RL, 13, -34.23562f + 0.51758if),
ZC(2.052e9, RL, 14, 3.75519f + -0.35850if),
ZC(2.052e9, RL, 15, -0.35673f + 1.18708if),
ZC(2.052e9, RL, 16, -0.74078f + -6.97377if),
ZC(2.052e9, RL, 17, 1.32906f + 2.61703if),
ZC(2.052e9, RL, 18, -10.89611f + 31.58441if),
ZC(2.052e9, RL, 19, 17.94895f + -57.77273if),
ZC(2.052e9, RL, 20, -0.89739f + 3.52072if),
ZC(2.052e9, RL, 21, 64.83839f + -8.97041if),
ZC(2.052e9, RL, 22, 16.67755f + -1.95098if),
ZC(2.052e9, RL, 23, 22.84547f + -3.04019if),
ZC(2.052e9, RL, 24, -3.13330f + 0.34980if),
ZC(2.052e9, RL, 25, 20.27727f + 0.05112if),
ZC(2.052e9, RL, 26, 7.86434f + 0.39691if),
ZC(2.052e9, RL, 27, 7.57648f + 0.15748if),
ZC(2.052e9, RL, 28, -0.13053f + -0.42633if),
ZC(2.052e9, RL, 29, -0.10469f + 2.24020if),
ZC(2.052e9, RL, 30, 0.62816f + 6.13542if),
ZC(2.052e9, RL, 31, -0.77741f + -0.19489if),
ZC(2.052e9, RL, 32, -2.81552f + 0.69070if),
ZC(2.052e9, RL, 33, 6.44841f + -17.54858if),
ZC(2.052e9, RL, 34, 0.22423f + -0.59755if),
ZC(2.052e9, RL, 35, -19.50908f + 54.87752if),
ZC(2.052e9, RL, 36, -3.58408f + 0.84919if),
ZC(2.052e9, RL, 37, 2.63395f + 0.01330if),
ZC(2.052e9, RL, 38, -4.51402f + 0.87025if),
ZC(2.052e9, RL, 39, 2.29331f + -0.35031if),
ZC(2.052e9, RL, 40, -2.21066f + -0.45484if),
ZC(2.052e9, RL, 41, -6.12727f + -0.16934if),
ZC(2.052e9, RL, 42, 8.00712f + -0.09759if),
ZC(2.052e9, RL, 43, -6.65897f + -0.57116if),
ZC(2.052e9, RL, 44, -12.73984f + -0.49130if),
ZC(2.052e9, RL, 45, -0.57588f + -1.81337if),
ZC(2.052e9, RL, 46, 0.62120f + -2.30787if),
ZC(2.052e9, RL, 47, 1.41000f + -4.25086if),
ZC(2.052e9, RL, 48, -1.19747f + -1.83575if),
ZC(2.052e9, RL, 49, -0.60233f + 1.97311if),
ZC(2.052e9, RL, 50, -1.50148f + 4.89920if),
ZC(2.052e9, RL, 51, 1.23064f + -2.45920if),
ZC(2.052e9, RL, 52, 0.69755f + 4.16094if),
ZC(2.052e9, RL, 53, -3.88263f + 11.09111if),
ZC(2.052e9, RL, 54, 6.24459f + -20.45131if),
ZC(2.052e9, RL, 55, -1.95306f + -0.04489if),
ZC(2.052e9, RL, 56, -1.37097f + 0.04812if),
ZC(2.052e9, RL, 57, 2.74444f + -0.27308if),
ZC(2.052e9, RL, 58, 0.58533f + -0.76869if),
ZC(2.052e9, RL, 59, -6.01217f + 0.34919if),
ZC(2.052e9, RL, 60, 7.50058f + 0.24948if),
ZC(2.052e9, RL, 61, 3.57798f + -0.23103if),
ZC(2.052e9, RL, 62, -13.12083f + 0.07727if),
ZC(2.052e9, RL, 63, 4.11820f + 0.67011if),
ZC(2.052e9, RL, 64, 10.69056f + 0.17448if),
ZC(2.052e9, RL, 65, 4.66236f + -0.07345if),
ZC(2.052e9, LR, 0, -24.99897f + 0.06202if),
ZC(2.052e9, LR, 1, -0.67741f + -2.89692if),
ZC(2.052e9, LR, 2, -22.03341f + 18.41248if),
ZC(2.052e9, LR, 3, -268.71116f + 19.09900if),
ZC(2.052e9, LR, 4, 16.87455f + -0.03516if),
ZC(2.052e9, LR, 5, 0.76369f + -0.04144if),
ZC(2.052e9, LR, 6, 1.39703f + 2.57244if),
ZC(2.052e9, LR, 7, 0.30889f + -0.74684if),
ZC(2.052e9, LR, 8, -23.23877f + 27.58344if),
ZC(2.052e9, LR, 9, 51.42289f + -49.69930if),
ZC(2.052e9, LR, 10, 480.64330f + -34.43130if),
ZC(2.052e9, LR, 11, -29.90342f + 1.91919if),
ZC(2.052e9, LR, 12, -10.76355f + 0.09642if),
ZC(2.052e9, LR, 13, -33.66236f + 0.29802if),
ZC(2.052e9, LR, 14, 2.16650f + -0.16708if),
ZC(2.052e9, LR, 15, -0.51364f + -1.22897if),
ZC(2.052e9, LR, 16, -0.52481f + -2.90719if),
ZC(2.052e9, LR, 17, 1.40361f + -0.11373if),
ZC(2.052e9, LR, 18, -15.19495f + 15.62002if),
ZC(2.052e9, LR, 19, 27.06347f + -26.61686if),
ZC(2.052e9, LR, 20, -1.15298f + -1.85528if),
ZC(2.052e9, LR, 21, 98.50320f + -8.07025if),
ZC(2.052e9, LR, 22, 19.77717f + -1.00834if),
ZC(2.052e9, LR, 23, 33.53663f + -2.48772if),
ZC(2.052e9, LR, 24, -3.29014f + 0.29252if),
ZC(2.052e9, LR, 25, 19.26223f + 0.43511if),
ZC(2.052e9, LR, 26, 9.93516f + -0.17523if),
ZC(2.052e9, LR, 27, 5.72509f + -0.08472if),
ZC(2.052e9, LR, 28, -0.43423f + 2.04602if),
ZC(2.052e9, LR, 29, -0.02363f + 3.98447if),
ZC(2.052e9, LR, 30, 0.42752f + 3.40931if),
ZC(2.052e9, LR, 31, -0.64922f + 0.74964if),
ZC(2.052e9, LR, 32, -4.05905f + -3.84284if),
ZC(2.052e9, LR, 33, 9.29950f + -9.25395if),
ZC(2.052e9, LR, 34, 0.06991f + 4.47719if),
ZC(2.052e9, LR, 35, -28.90019f + 27.68897if),
ZC(2.052e9, LR, 36, -6.74281f + 1.22119if),
ZC(2.052e9, LR, 37, 9.45561f + 0.46380if),
ZC(2.052e9, LR, 38, -6.15714f + 0.56670if),
ZC(2.052e9, LR, 39, 3.74609f + -0.33597if),
ZC(2.052e9, LR, 40, -3.46545f + -0.44572if),
ZC(2.052e9, LR, 41, -5.84630f + -0.13484if),
ZC(2.052e9, LR, 42, 5.32861f + 0.23153if),
ZC(2.052e9, LR, 43, -5.89859f + 0.11522if),
ZC(2.052e9, LR, 44, -11.97309f + -0.93312if),
ZC(2.052e9, LR, 45, -0.91883f + 0.19888if),
ZC(2.052e9, LR, 46, 0.78500f + -6.59305if),
ZC(2.052e9, LR, 47, 1.65358f + -3.35719if),
ZC(2.052e9, LR, 48, -1.00453f + -2.80342if),
ZC(2.052e9, LR, 49, -0.68997f + 2.00094if),
ZC(2.052e9, LR, 50, -1.72370f + 2.59812if),
ZC(2.052e9, LR, 51, 1.34669f + -0.42930if),
ZC(2.052e9, LR, 52, 0.93263f + 0.77580if),
ZC(2.052e9, LR, 53, -5.65750f + 5.42056if),
ZC(2.052e9, LR, 54, 9.94611f + -7.90033if),
ZC(2.052e9, LR, 55, -2.80800f + 0.23331if),
ZC(2.052e9, LR, 56, 1.90653f + -0.24550if),
ZC(2.052e9, LR, 57, -1.10131f + -0.41898if),
ZC(2.052e9, LR, 58, 0.47834f + -0.53619if),
ZC(2.052e9, LR, 59, -7.26214f + -0.13598if),
ZC(2.052e9, LR, 60, 7.84777f + 0.02842if),
ZC(2.052e9, LR, 61, 3.39186f + -0.41548if),
ZC(2.052e9, LR, 62, -10.96003f + 0.39200if),
ZC(2.052e9, LR, 63, 5.03114f + 0.08369if),
ZC(2.052e9, LR, 64, 10.56528f + 0.43006if),
ZC(2.052e9, LR, 65, 3.14053f + -0.01114if),
ZC(2.052e9, LL, 0, 0.37761f + 0.00000if),
ZC(2.052e9, LL, 1, 0.01628f + -0.02645if),
ZC(2.052e9, LL, 2, -0.07972f + 0.07925if),
ZC(2.052e9, LL, 3, -0.75420f + 0.26384if),
ZC(2.052e9, LL, 4, -0.13261f + 0.00091if),
ZC(2.052e9, LL, 5, 0.01219f + 0.00238if),
ZC(2.052e9, LL, 6, 0.00105f + -0.00164if),
ZC(2.052e9, LL, 7, 0.01858f + 0.02544if),
ZC(2.052e9, LL, 8, -0.09017f + 0.01234if),
ZC(2.052e9, LL, 9, 0.21847f + -0.07088if),
ZC(2.052e9, LL, 10, 1.36273f + -0.47233if),
ZC(2.052e9, LL, 11, -0.07123f + 0.02620if),
ZC(2.052e9, LL, 12, -0.28977f + 0.00105if),
ZC(2.052e9, LL, 13, 0.00334f + 0.00095if),
ZC(2.052e9, LL, 14, -0.06581f + -0.00006if),
ZC(2.052e9, LL, 15, -0.00588f + 0.00327if),
ZC(2.052e9, LL, 16, 0.00673f + 0.00178if),
ZC(2.052e9, LL, 17, -0.01683f + 0.00897if),
ZC(2.052e9, LL, 18, -0.07708f + 0.00169if),
ZC(2.052e9, LL, 19, 0.11816f + -0.03748if),
ZC(2.052e9, LL, 20, -0.00594f + -0.00045if),
ZC(2.052e9, LL, 21, 0.30369f + -0.10381if),
ZC(2.052e9, LL, 22, 0.04042f + -0.01481if),
ZC(2.052e9, LL, 23, 0.09780f + -0.03381if),
ZC(2.052e9, LL, 24, 0.10355f + 0.00091if),
ZC(2.052e9, LL, 25, -0.01356f + -0.00086if),
ZC(2.052e9, LL, 26, 0.14030f + 0.00000if),
ZC(2.052e9, LL, 27, 0.00178f + 0.00002if),
ZC(2.052e9, LL, 28, -0.00255f + -0.00361if),
ZC(2.052e9, LL, 29, 0.00628f + -0.00372if),
ZC(2.052e9, LL, 30, -0.00736f + -0.00050if),
ZC(2.052e9, LL, 31, -0.00084f + -0.01341if),
ZC(2.052e9, LL, 32, -0.02006f + -0.00953if),
ZC(2.052e9, LL, 33, 0.04297f + -0.01177if),
ZC(2.052e9, LL, 34, 0.00686f + 0.00580if),
ZC(2.052e9, LL, 35, -0.12508f + 0.03523if),
ZC(2.052e9, LL, 36, -0.01539f + 0.00664if),
ZC(2.052e9, LL, 37, 0.01723f + -0.00545if),
ZC(2.052e9, LL, 38, -0.01439f + 0.00342if),
ZC(2.052e9, LL, 39, 0.01303f + -0.00433if),
ZC(2.052e9, LL, 40, -0.02536f + -0.00228if),
ZC(2.052e9, LL, 41, 0.00448f + -0.00145if),
ZC(2.052e9, LL, 42, -0.04408f + 0.00041if),
ZC(2.052e9, LL, 43, -0.00730f + -0.00011if),
ZC(2.052e9, LL, 44, -0.08711f + -0.00008if),
ZC(2.052e9, LL, 45, -0.00767f + 0.00250if),
ZC(2.052e9, LL, 46, 0.00847f + 0.00397if),
ZC(2.052e9, LL, 47, 0.00302f + 0.00128if),
ZC(2.052e9, LL, 48, -0.00269f + 0.00080if),
ZC(2.052e9, LL, 49, -0.00770f + 0.00089if),
ZC(2.052e9, LL, 50, -0.01020f + 0.02487if),
ZC(2.052e9, LL, 51, 0.00636f + -0.00119if),
ZC(2.052e9, LL, 52, 0.00263f + -0.00103if),
ZC(2.052e9, LL, 53, -0.02428f + 0.00800if),
ZC(2.052e9, LL, 54, 0.03852f + -0.02041if),
ZC(2.052e9, LL, 55, 0.00256f + -0.00003if),
ZC(2.052e9, LL, 56, -0.00686f + 0.00080if),
ZC(2.052e9, LL, 57, -0.00230f + 0.00056if),
ZC(2.052e9, LL, 58, 0.00411f + 0.00005if),
ZC(2.052e9, LL, 59, -0.00397f + 0.00059if),
ZC(2.052e9, LL, 60, 0.06297f + 0.00070if),
ZC(2.052e9, LL, 61, 0.00234f + 0.00153if),
ZC(2.052e9, LL, 62, -0.04909f + 0.00045if),
ZC(2.052e9, LL, 63, 0.00602f + 0.00025if),
ZC(2.052e9, LL, 64, 0.09658f + -0.00066if),
ZC(2.052e9, LL, 65, 0.00484f + -0.00030if),
};
template <unsigned INDEX_RANK>
using cf_col_t =
PhysicalColumnTD<
ValueType<complex<float>>::DataType,
INDEX_RANK,
INDEX_RANK + 2,
AffineAccessor>;
#define CF_TABLE_AXES \
CF_BASELINE_CLASS, CF_PARALLACTIC_ANGLE, CF_FREQUENCY, CF_W, CF_STOKES_OUT, CF_STOKES_IN
void
show_grid_task(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
const CFTableBase::ShowValuesTaskArgs& args =
*static_cast<const CFTableBase::ShowValuesTaskArgs*>(task->args);
std::cout << "!!!!" << args.title << "!!!!" << std::endl;
auto pt =
PhysicalTable::create_all_unsafe(
rt,
{args.tdesc},
task->regions,
regions)[0];
auto columns = pt.columns();
std::vector<cf_table_axes_t> index_axes;
for (auto& ia : pt.index_axes())
index_axes.push_back(static_cast<cf_table_axes_t>(ia));
std::vector<std::shared_ptr<PhysicalColumn>> index_columns;
for (auto& ia : index_axes)
index_columns.push_back(columns.at(cf_table_axis_name(ia)));
auto cs_x_col =
GridCoordinateTable::CoordColumn<Legion::AffineAccessor>(
*pt.column(GridCoordinateTable::COORD_X_NAME).value());
auto cs_y_col =
GridCoordinateTable::CoordColumn<Legion::AffineAccessor>(
*pt.column(GridCoordinateTable::COORD_Y_NAME).value());
auto cs_x_rect = cs_x_col.rect();
auto grid_size = cs_x_rect.hi[2] - cs_x_rect.lo[2] + 1;
auto cs_x = cs_x_col.template accessor<LEGION_READ_ONLY>();
auto cs_y = cs_y_col.template accessor<LEGION_READ_ONLY>();
Point<3> index;
for (size_t i = 0; i < 1; ++i)
index[i] = -1;
PointInRectIterator<3> pir(cs_x_rect, false);
while (pir()) {
for (size_t i = 0; i < 1; ++i)
index[i] = pir[i];
std::cout << "*** " << cf_table_axis_name(index_axes[0])
<< ": ";
CFTableBase::show_index_value(*index_columns[0], pir[0]);
std::cout << std::endl;
for (coord_t i = 0; i < grid_size; ++i) {
for (coord_t j = 0; j < grid_size; ++j) {
auto x = cs_x[*pir];
auto y = cs_y[*pir++];
std::cout << "(" << x << "," << y << ") ";
}
std::cout << std::endl;
}
}
}
[[maybe_unused]] static void
show_grid(
Context ctx,
Runtime* rt,
const std::string& title,
const GridCoordinateTable& table) {
auto colreqs = Column::default_requirements_mapped;
auto reqs =
table.requirements(
ctx,
rt,
ColumnSpacePartition(),
{{GridCoordinateTable::COORD_X_NAME, colreqs},
{GridCoordinateTable::COORD_Y_NAME, colreqs},
{cf_table_axis<CF_PARALLACTIC_ANGLE>::name, colreqs}},
CXX_OPTIONAL_NAMESPACE::nullopt);
CFTableBase::ShowValuesTaskArgs args;
args.tdesc = std::get<2>(reqs);
args.title = title;
TaskLauncher task(SHOW_GRID_TASK_ID, TaskArgument(&args, sizeof(args)));
for (auto& r : std::get<0>(reqs))
task.add_region_requirement(r);
rt->execute_task(ctx, task);
}
void
cfcompute_task(
const Task*,
const std::vector<PhysicalRegion>&,
Context ctx,
Runtime* rt) {
const size_t grid_size = 5;
const double cf_radius = static_cast<double>(grid_size) / 2;
GridCoordinateTable ps_coords(ctx, rt, grid_size, {0.0});
ps_coords.compute_coordinates(ctx, rt, cc::LinearCoordinate(2), cf_radius);
PSTermTable ps_tbl(ctx, rt, grid_size, {0.08, 0.16});
ps_tbl.compute_cfs(ctx, rt, ps_coords);
ps_tbl.show_cf_values(ctx, rt, "PSTerm");
ps_coords.destroy(ctx, rt);
GridCoordinateTable w_coords(ctx, rt, grid_size, {0.0});
w_coords.compute_coordinates(ctx, rt, cc::LinearCoordinate(2), 2.0);
WTermTable w_tbl(ctx, rt, grid_size, {2.2, 22.2, 222.2});
w_tbl.compute_cfs(ctx, rt, w_coords);
w_tbl.show_cf_values(ctx, rt, "WTerm");
w_coords.destroy(ctx, rt);
std::vector<typename cf_table_axis<CF_PARALLACTIC_ANGLE>::type>
parallactic_angles{0.0, 3.1415926 / 4.0};
GridCoordinateTable a_coords(ctx, rt, grid_size, parallactic_angles);
a_coords.compute_coordinates(ctx, rt, cc::LinearCoordinate(2), 1.0);
ATermTable a_tbl(
ctx,
rt,
grid_size,
{0},
parallactic_angles,
{2.052e9},
{cc::Stokes::RR},
{cc::Stokes::RR});
a_tbl.compute_cfs(ctx, rt, a_coords, zc);
a_tbl.show_cf_values(ctx, rt, "ATerm");
a_coords.destroy(ctx, rt);
auto cf_tbl =
ProductCFTable<CF_TABLE_AXES>::create_and_fill(
ctx,
rt,
ColumnSpacePartition(),
a_tbl,
w_tbl,
ps_tbl);
cf_tbl.show_cf_values(ctx, rt, "Pre-FFT CF");
cf_tbl.apply_fft(ctx, rt, 1, true, true, FFTW_MEASURE, 5.0);
cf_tbl.show_cf_values(ctx, rt, "Post-FFT CF");
std::cout << "+++++ DONE +++++" << std::endl;
ps_tbl.destroy(ctx, rt);
w_tbl.destroy(ctx, rt);
a_tbl.destroy(ctx, rt);
cf_tbl.destroy(ctx, rt);
}
int
main(int argc, char* argv[]) {
hyperion::preregister_all();
{
TaskVariantRegistrar registrar(CFCOMPUTE_TASK_ID, "cfcompute_task");
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<cfcompute_task>(
registrar,
"cfcompute_task");
Runtime::set_top_level_task_id(CFCOMPUTE_TASK_ID);
}
{
TaskVariantRegistrar registrar(SHOW_GRID_TASK_ID, "show_grid_task");
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<show_grid_task>(
registrar,
"show_grid_task");
}
synthesis::CFTableBase::preregister_all();
synthesis::ProductCFTable<CF_TABLE_AXES>::preregister_tasks();
return Runtime::start(argc, argv);
}
// Local Variables:
// mode: c++
// c-basic-offset: 2
// fill-column: 80
// indent-tabs-mode: nil
// End:
| 38.740816 | 90 | 0.624137 | [
"vector"
] |
ef673b0250dfa98a64342a235aeb80c5d46ff632 | 512 | cpp | C++ | sites/leetcode/852_peak_index_in_a_mountain_array/1.cpp | NoelBird/chocochip | 7ab9477b9e4153927805c9473ee44a15d809b549 | [
"MIT"
] | null | null | null | sites/leetcode/852_peak_index_in_a_mountain_array/1.cpp | NoelBird/chocochip | 7ab9477b9e4153927805c9473ee44a15d809b549 | [
"MIT"
] | null | null | null | sites/leetcode/852_peak_index_in_a_mountain_array/1.cpp | NoelBird/chocochip | 7ab9477b9e4153927805c9473ee44a15d809b549 | [
"MIT"
] | null | null | null | class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int left = 0;
int right = arr.size()-1;
while(left <= right)
{
int mid = left + (right-left)/2;
if(arr[mid-1] < arr[mid] && arr[mid] > arr[mid+1])
{
return mid;
}
else if(arr[mid-1]<arr[mid])
left = mid+1;
else
right = mid;
}
return right;
}
}; | 23.272727 | 62 | 0.396484 | [
"vector"
] |
ef6a451197ce41a1e8299c8bf09f77fc3cfbd134 | 5,842 | cpp | C++ | src/LuminoEngine/src/UI/Controls/UIDialog.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null | src/LuminoEngine/src/UI/Controls/UIDialog.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null | src/LuminoEngine/src/UI/Controls/UIDialog.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null |
#include "Internal.hpp"
#include <LuminoEngine/UI/UIRenderView.hpp>
#include <LuminoEngine/UI/Controls/UIButton.hpp>
#include <LuminoEngine/UI/Layout/UILayoutPanel.hpp>
#include <LuminoEngine/UI/UIAdorner.hpp>
#include <LuminoEngine/UI/Controls/UIDialog.hpp>
namespace ln {
//==============================================================================
// UIDialog
UIDialog::UIDialog()
: m_adorner(nullptr)
, m_opend(false)
{
}
void UIDialog::init()
{
UIElement::init();
specialElementFlags().set(detail::UISpecialElementFlags::Popup);
// UIAdorner で左上を PlacementTarget と合わせてもらう
setHAlignment(UIHAlignment::Left);
setVAlignment(UIVAlignment::Top);
}
void UIDialog::open()
{
if (!m_opend)
{
if (!m_adorner) {
m_adorner = makeObject<UIDialogAdorner>(this);
}
UIFrameRenderView* renderView = getRenderView();
if (renderView) {
renderView->adornerLayer()->add(m_adorner);
}
m_opend = true;
}
}
void UIDialog::close()
{
if (m_opend)
{
if (m_adorner)
{
UIFrameRenderView* renderView = getRenderView();
if (renderView) {
renderView->adornerLayer()->remove(m_adorner);
}
m_adorner = nullptr;
}
m_opend = false;
}
}
void UIDialog::setupDialogButtons(UIDialogButtons buttons)
{
m_dialogButtons.clear();
switch (buttons)
{
case UIDialogButtons::OK:
addDialogButton(UIDialogButtonRole::Accept, u"OK");
break;
case UIDialogButtons::OKCancel:
addDialogButton(UIDialogButtonRole::Accept, u"OK");
addDialogButton(UIDialogButtonRole::Reject, u"Cancel");
break;
case UIDialogButtons::YesNo:
addDialogButton(UIDialogButtonRole::Accept, u"Yes");
addDialogButton(UIDialogButtonRole::Discard, u"No");
break;
case UIDialogButtons::YesNoCancel:
addDialogButton(UIDialogButtonRole::Accept, u"Yes");
addDialogButton(UIDialogButtonRole::Discard, u"No");
addDialogButton(UIDialogButtonRole::Reject, u"Cancel");
break;
default:
LN_UNREACHABLE();
break;
}
}
void UIDialog::addDialogButton(UIDialogButtonRole role, const String& text)
{
if (!m_dialogButtonsLayout) {
m_dialogButtonsLayout = ln::makeObject<UIBoxLayout>();
m_dialogButtonsLayout->setOrientation(UILayoutOrientation::Horizontal);
addVisualChild(m_dialogButtonsLayout);
}
auto button = ln::makeObject<ln::UIButton>();
button->setText(text);
button->connectOnClicked(bind(this, &UIDialog::handleDialogButtonClicked));
m_dialogButtonsLayout->addChild(button);
}
void UIDialog::handleDialogButtonClicked()
{
close();
}
Size UIDialog::measureOverride(UILayoutContext* layoutContext, const Size& constraint)
{
Size baseSize = UIContainerElement::measureOverride(layoutContext, constraint);
if (m_dialogButtonsLayout) {
m_dialogButtonsLayout->measureLayout(layoutContext, constraint);
Size buttonsSize = m_dialogButtonsLayout->desiredSize();
return baseSize;
//return Size(
// std::max(baseSize.width, buttonsSize.height),
// baseSize.height + buttonsSize.height);
}
else {
return baseSize;
}
}
Size UIDialog::arrangeOverride(UILayoutContext* layoutContext, const Rect& finalArea)
{
const auto finalSize = finalArea.getSize();
Size baseSize = UIContainerElement::arrangeOverride(layoutContext, finalArea);
if (m_dialogButtonsLayout) {
Size buttonsSize = m_dialogButtonsLayout->desiredSize();
Rect buttonsRect(
std::max(0.0f, finalSize.width - buttonsSize.width),
std::max(0.0f, finalSize.height - buttonsSize.height),
std::min(buttonsSize.width, finalSize.width),
std::min(buttonsSize.height, finalSize.height));
m_dialogButtonsLayout->arrangeLayout(layoutContext, buttonsRect);
}
return baseSize;
}
//==============================================================================
// UIDialogAdorner
UIDialogAdorner::UIDialogAdorner()
{
}
void UIDialogAdorner::init(UIDialog* popup)
{
UIAdorner::init(nullptr);
setBackgroundColor(Color(0, 0, 0, 0.5f));
m_popup = popup;
//addVisualChild(m_popup);
}
void UIDialogAdorner::onRoutedEvent(UIEventArgs* e)
{
if (e->type() == UIEvents::MouseDownEvent) {
m_popup->close();
e->handled = true;
return;
}
return UIAdorner::onRoutedEvent(e);
}
Size UIDialogAdorner::measureOverride(UILayoutContext* layoutContext, const Size& constraint)
{
m_popup->measureLayout(layoutContext, constraint);
return Size::max(m_popup->desiredSize(), UIElement::measureOverride(layoutContext, constraint));
}
Size UIDialogAdorner::arrangeOverride(UILayoutContext* layoutContext, const Rect& finalArea)
{
const auto finalSize = finalArea.getSize();
UIElement::arrangeOverride(layoutContext, finalArea);
auto desiredSize = m_popup->desiredSize();
Rect rect;
rect.x = (finalSize.width - desiredSize.width) / 2;
rect.y = (finalSize.height - desiredSize.height) / 2;
rect.width = desiredSize.width;
rect.height = desiredSize.height;
m_popup->arrangeLayout(layoutContext, rect);
return finalSize;
}
void UIDialogAdorner::onUpdateLayout(UILayoutContext* layoutContext)
{
m_popup->updateFinalLayoutHierarchical(layoutContext, m_combinedFinalRenderTransform);
}
UIElement* UIDialogAdorner::lookupMouseHoverElement(const Point& frameClientPosition)
{
// popup は UIAdorner の VisualChildren ではないため、直接呼び出す必要がある
if (m_popup) {
UIElement* element = m_popup->lookupMouseHoverElement(frameClientPosition);
if (element) {
return element;
}
}
return UIAdorner::lookupMouseHoverElement(frameClientPosition);
}
void UIDialogAdorner::render(UIRenderingContext* context, const Matrix& parentTransform)
{
UIAdorner::render(context, parentTransform);
// popup は UIAdorner の VisualChildren ではないため、直接呼び出す必要がある
if (m_popup) {
m_popup->render(context, parentTransform);
}
}
} // namespace ln
| 26.197309 | 100 | 0.709346 | [
"render"
] |
ef6bf9d79db3aed1d26b236357169e15e0a687ed | 3,493 | cpp | C++ | src/geode/mesh/builder/solid_facets_builder.cpp | Geode-solutions/OpenGeode | e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc | [
"MIT"
] | 64 | 2019-08-02T14:31:01.000Z | 2022-03-30T07:46:50.000Z | src/geode/mesh/builder/solid_facets_builder.cpp | Geode-solutions/OpenGeode | e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc | [
"MIT"
] | 395 | 2019-08-02T17:15:10.000Z | 2022-03-31T15:10:27.000Z | src/geode/mesh/builder/solid_facets_builder.cpp | Geode-solutions/OpenGeode | e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc | [
"MIT"
] | 8 | 2019-08-19T21:32:15.000Z | 2022-03-06T18:41:10.000Z | /*
* Copyright (c) 2019 - 2021 Geode-solutions
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <geode/mesh/builder/solid_facets_builder.h>
#include <geode/basic/attribute_manager.h>
#include <geode/mesh/builder/mesh_builder_factory.h>
#include <geode/mesh/core/solid_facets.h>
#include <geode/mesh/core/solid_mesh.h>
namespace geode
{
template < index_t dimension >
SolidFacetsBuilder< dimension >::SolidFacetsBuilder(
SolidFacets< dimension >& facets )
: facets_( &facets )
{
}
template < index_t dimension >
index_t SolidFacetsBuilder< dimension >::find_or_create_facet(
PolyhedronFacetVertices facet_vertices )
{
return facets_->find_or_create_facet( std::move( facet_vertices ), {} );
}
template < index_t dimension >
std::vector< index_t >
SolidFacetsBuilder< dimension >::delete_isolated_facets()
{
return facets_->remove_isolated_facets( {} );
}
template < index_t dimension >
std::vector< index_t >
SolidFacetsBuilder< dimension >::update_facet_vertices(
absl::Span< const index_t > old2new )
{
return facets_->update_facet_vertices( old2new, {} );
}
template < index_t dimension >
void SolidFacetsBuilder< dimension >::update_facet_vertex(
PolyhedronFacetVertices facet_vertices,
index_t facet_vertex_id,
index_t new_vertex_id )
{
OPENGEODE_ASSERT( facet_vertex_id < facet_vertices.size(),
"[SolidFacetsBuilder::update_facet_vertex] "
"Accessing an invalid vertex in facet" );
facets_->update_facet_vertex(
std::move( facet_vertices ), facet_vertex_id, new_vertex_id, {} );
}
template < index_t dimension >
void SolidFacetsBuilder< dimension >::remove_facet(
PolyhedronFacetVertices facet_vertices )
{
facets_->remove_facet( std::move( facet_vertices ), {} );
}
template < index_t dimension >
std::vector< index_t > SolidFacetsBuilder< dimension >::delete_facets(
const std::vector< bool >& to_delete )
{
return facets_->delete_facets( to_delete, {} );
}
template < index_t dimension >
void SolidFacetsBuilder< dimension >::copy(
const SolidFacets< dimension >& facets )
{
facets_->overwrite_facets( facets, {} );
}
template class opengeode_mesh_api SolidFacetsBuilder< 3 >;
} // namespace geode
| 35.282828 | 80 | 0.695677 | [
"mesh",
"vector"
] |
ef7e7c1b6023296dc8fca100be95eba8f7494bcb | 1,105 | hpp | C++ | converter/src/log/logger.hpp | redthing1/Tiled2GBA | 2272309292c6a2a0dee2a4e7cc81c2e97fab6157 | [
"MIT"
] | 14 | 2018-06-25T09:22:21.000Z | 2021-12-11T20:06:25.000Z | converter/src/log/logger.hpp | redthing1/Tiled2GBA | 2272309292c6a2a0dee2a4e7cc81c2e97fab6157 | [
"MIT"
] | 20 | 2018-06-23T21:36:35.000Z | 2021-05-25T16:21:14.000Z | converter/src/log/logger.hpp | redthing1/Tiled2GBA | 2272309292c6a2a0dee2a4e7cc81c2e97fab6157 | [
"MIT"
] | 2 | 2020-02-26T13:51:31.000Z | 2021-09-30T07:02:33.000Z | #ifndef LOGGER_H
#define LOGGER_H
#include <ostream>
#include <string>
using namespace std;
typedef enum LogLevel {
INFO = 0,
WARN = 1,
ERROR = 2
} LogLevel;
/**
* Simple logger.
*/
class Logger {
public:
/**
* Return a singleton instance of the logger.
* @return The singleton instance
*/
static Logger* getInstance();
/**
* Set the level of messages displayed to the user.
* @param level The log level.
*/
void setLogLevel(LogLevel level);
/**
* Log a message of a particular level.
* @param level The logging level.
* @param message The message to log.
*/
void log(LogLevel level, const string &message);
/**
* Log a message by using this object as a functor.
* @param level The logging level.
* @param message The message to log.
*/
virtual void operator() (LogLevel level, const string &message);
private:
explicit Logger(ostream &logStream, LogLevel level);
string levelToString(LogLevel level);
ostream &d_logStream;
LogLevel d_level;
};
#endif // LOGGER_H | 20.462963 | 68 | 0.636199 | [
"object"
] |
ef87abbeed2e2d030a9969d684468e093619a26c | 4,947 | cc | C++ | dali/operators/util/axis_args.cc | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2022-02-17T19:54:05.000Z | 2022-02-17T19:54:08.000Z | dali/operators/util/axis_args.cc | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/util/axis_args.cc | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dali/operators/util/axis_args.h"
#include <vector>
namespace dali {
AxisArgs::AxisArgs(const OpSpec &spec, const char *axis_index_arg, const char *axis_name_arg,
unsigned int flags)
: flags_(flags) {
bool has_axis_index_arg = axis_index_arg && spec.ArgumentDefined(axis_index_arg);
bool has_axis_name_arg = axis_name_arg && spec.HasArgument(axis_name_arg);
if (has_axis_index_arg && has_axis_name_arg) {
DALI_FAIL(
make_string("\"", axis_index_arg, "\" and \"", axis_name_arg, "\" are mutually exclusive"));
}
if (axis_index_arg) // unique_ptr serves as optional
axes_ = std::make_unique<ArgValue<int, 1>>(axis_index_arg, spec);
per_sample_axes_ = axis_index_arg && spec.HasTensorArgument(axis_index_arg);
bool allow_empty = flags_ & AllowEmpty;
if (!allow_empty && !axis_index_arg && !axis_name_arg) {
DALI_FAIL("At least one argument name must be provided if allow_empty is false.");
}
if (!per_sample_axes_) {
if ((has_axis_name_arg || !has_axis_index_arg) && axis_name_arg) {
use_axis_names_ = spec.TryGetArgument(axis_names_, axis_name_arg);
if (use_axis_names_ && !allow_empty && axis_names_.empty())
DALI_FAIL(make_string("Can't have empty axes. Check argument name: ", axis_name_arg));
}
if (!use_axis_names_ && axis_index_arg) {
std::vector<int> tmp; // TODO(janton): support SmallVector in TryGetRepeatedArgument
if (spec.TryGetRepeatedArgument(tmp, axis_index_arg))
const_axes_ = {tmp.begin(), tmp.end()};
if (!allow_empty && const_axes_.empty())
DALI_FAIL(make_string("Can't have empty axes. Check argument name: ", axis_index_arg));
}
}
}
void AxisArgs::Acquire(const OpSpec &spec, const ArgumentWorkspace &ws, int nsamples, int ndim) {
if (per_sample_axes_) {
assert(axes_);
axes_->Acquire(spec, ws, nsamples);
shape_ = axes_->get().shape;
} else if (use_axis_names_) {
shape_ = uniform_list_shape(nsamples, TensorShape<1>(axis_names_.size()));
} else {
shape_ = uniform_list_shape(nsamples, TensorShape<1>(const_axes_.size()));
}
if (flags_ & AllIfEmpty) {
TensorShape<1> sh(ndim);
if (shape_.num_elements() == 0) {
shape_ = uniform_list_shape(nsamples, sh);
} else {
for (int i = 0; i < shape_.size(); i++) {
if (volume(shape_.tensor_shape_span(i)) == 0)
shape_.set_tensor_shape(i, sh);
}
}
}
}
TensorListShape<1> AxisArgs::AxesShape() {
return shape_;
}
SmallVector<int, 6> AxisArgs::Get(int data_idx, int ndim, const TensorLayout &layout) {
SmallVector<int, 6> axes;
if (per_sample_axes_) {
assert(axes_);
auto view = (*axes_)[data_idx];
int n = view.shape.num_elements();
axes.resize(n);
for (int i = 0; i < n; i++)
axes[i] = view.data[i];
} else if (use_axis_names_) {
axes = GetDimIndices(layout, axis_names_);
} else {
axes = const_axes_;
}
Process(ndim, axes);
return axes;
}
void AxisArgs::Process(int ndim, SmallVector<int, 6> &axes) {
if (axes.empty()) {
if (!(flags_ & AllowEmpty))
DALI_FAIL("Need to specify at least one axis");
if (flags_ & AllIfEmpty) {
axes.resize(ndim);
std::iota(axes.begin(), axes.end(), 0);
}
}
if (flags_ & AllowNegative) {
for (auto &axis : axes) {
DALI_ENFORCE(axis >= -ndim && axis < ndim,
make_string("Axis ", axis, " out of range. Expected range is [", -ndim, ", ",
ndim - 1, "] for a ", ndim, "D input"));
if (axis < 0)
axis += ndim;
}
} else {
for (auto &axis : axes) {
DALI_ENFORCE(axis >= 0 && axis < ndim,
make_string("Axis ", axis, " out of range. Expected range is [0, ", ndim - 1,
"] for a ", ndim, "D input"));
}
}
if (!(flags_ & AllowEmpty) && axes.empty())
DALI_FAIL("Need to specify at least one axis");
SmallVector<bool, 6> axes_check;
for (auto axis : axes) {
if (axes_check[axis])
DALI_FAIL(make_string("Axis index ", axis,
" occurs more than once in ``axes`` "
"(might include negative indices referring to the same axis"));
axes_check[axis] = true;
}
}
} // namespace dali
| 34.354167 | 100 | 0.637154 | [
"shape",
"vector"
] |
ef8acf6cb24a6e985565a607285dccee4dd1c568 | 27,078 | cxx | C++ | main/framework/source/dispatch/closedispatcher.cxx | jimjag/openoffice | 74746a22d8cc22b031b00fcd106f4496bf936c77 | [
"Apache-2.0"
] | 1 | 2019-12-27T19:25:34.000Z | 2019-12-27T19:25:34.000Z | main/framework/source/dispatch/closedispatcher.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 1 | 2019-11-25T04:29:25.000Z | 2019-11-25T04:29:25.000Z | main/framework/source/dispatch/closedispatcher.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 6 | 2019-11-19T00:28:25.000Z | 2019-11-22T06:48:49.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_______________________________________________
// my own includes
#include <dispatch/closedispatcher.hxx>
#include <pattern/frame.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
#include <framework/framelistanalyzer.hxx>
#include <services.h>
#include <general.h>
//_______________________________________________
// interface includes
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/CommandGroup.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/awt/XTopWindow.hpp>
#include <com/sun/star/document/XActionLockable.hpp>
#include "com/sun/star/beans/XFastPropertySet.hpp"
#include <toolkit/helper/vclunohelper.hxx>
//_______________________________________________
// includes of other projects
#include <vcl/window.hxx>
#include <vcl/svapp.hxx>
#include <vos/mutex.hxx>
#include <unotools/moduleoptions.hxx>
//_______________________________________________
// namespace
namespace framework{
#ifdef fpf
#error "Who uses \"fpf\" as define. It will overwrite my namespace alias ..."
#endif
namespace fpf = ::framework::pattern::frame;
//_______________________________________________
// non exported const
static ::rtl::OUString URL_CLOSEDOC = DECLARE_ASCII(".uno:CloseDoc" );
static ::rtl::OUString URL_CLOSEWIN = DECLARE_ASCII(".uno:CloseWin" );
static ::rtl::OUString URL_CLOSEFRAME = DECLARE_ASCII(".uno:CloseFrame");
//_______________________________________________
// declarations
DEFINE_XINTERFACE_4(CloseDispatcher ,
OWeakObject ,
DIRECT_INTERFACE(css::lang::XTypeProvider ),
DIRECT_INTERFACE(css::frame::XNotifyingDispatch ),
DIRECT_INTERFACE(css::frame::XDispatch ),
DIRECT_INTERFACE(css::frame::XDispatchInformationProvider))
// Note: XStatusListener is an implementation detail. Hide it for scripting!
DEFINE_XTYPEPROVIDER_4(CloseDispatcher ,
css::lang::XTypeProvider ,
css::frame::XDispatchInformationProvider,
css::frame::XNotifyingDispatch ,
css::frame::XDispatch )
//-----------------------------------------------
CloseDispatcher::CloseDispatcher(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xFrame ,
const ::rtl::OUString& sTarget)
: ThreadHelpBase (&Application::GetSolarMutex() )
, ::cppu::OWeakObject( )
, m_xSMGR (xSMGR )
, m_aAsyncCallback (LINK( this, CloseDispatcher, impl_asyncCallback))
, m_lStatusListener (m_aLock.getShareableOslMutex() )
{
m_xCloseFrame = CloseDispatcher::static_impl_searchRightTargetFrame(xFrame, sTarget);
}
//-----------------------------------------------
CloseDispatcher::~CloseDispatcher()
{
}
//-----------------------------------------------
void SAL_CALL CloseDispatcher::dispatch(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments)
throw(css::uno::RuntimeException)
{
dispatchWithNotification(aURL, lArguments, css::uno::Reference< css::frame::XDispatchResultListener >());
}
//-----------------------------------------------
css::uno::Sequence< sal_Int16 > SAL_CALL CloseDispatcher::getSupportedCommandGroups()
throw(css::uno::RuntimeException)
{
css::uno::Sequence< sal_Int16 > lGroups(2);
lGroups[0] = css::frame::CommandGroup::VIEW;
lGroups[1] = css::frame::CommandGroup::DOCUMENT;
return lGroups;
}
//-----------------------------------------------
css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL CloseDispatcher::getConfigurableDispatchInformation(sal_Int16 nCommandGroup)
throw(css::uno::RuntimeException)
{
if (nCommandGroup == css::frame::CommandGroup::VIEW)
{
/* Attention: Dont add .uno:CloseFrame here. Because its not really
a configurable feature ... and further it does not have
a valid UIName entry inside the GenericCommands.xcu ... */
css::uno::Sequence< css::frame::DispatchInformation > lViewInfos(1);
lViewInfos[0].Command = URL_CLOSEWIN;
lViewInfos[0].GroupId = css::frame::CommandGroup::VIEW;
return lViewInfos;
}
else
if (nCommandGroup == css::frame::CommandGroup::DOCUMENT)
{
css::uno::Sequence< css::frame::DispatchInformation > lDocInfos(1);
lDocInfos[0].Command = URL_CLOSEDOC;
lDocInfos[0].GroupId = css::frame::CommandGroup::DOCUMENT;
return lDocInfos;
}
return css::uno::Sequence< css::frame::DispatchInformation >();
}
//-----------------------------------------------
void SAL_CALL CloseDispatcher::addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/,
const css::util::URL& /*aURL*/ )
throw(css::uno::RuntimeException)
{
}
//-----------------------------------------------
void SAL_CALL CloseDispatcher::removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/,
const css::util::URL& /*aURL*/ )
throw(css::uno::RuntimeException)
{
}
//-----------------------------------------------
void SAL_CALL CloseDispatcher::dispatchWithNotification(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener )
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
// This reference indicates, that we was already called before and
// our asynchronous process was not finished yet.
// We have to reject double calls. Otherwhise we risk,
// that we try to close an already closed resource ...
// And its no problem to do nothing then. The UI user will try it again, if
// non of these jobs was successfully.
if (m_xSelfHold.is())
{
aWriteLock.unlock();
// <- SAFE ------------------------------
implts_notifyResultListener(
xListener,
css::frame::DispatchResultState::DONTKNOW,
css::uno::Any());
return;
}
// First we have to check, if this dispatcher is used right. Means if valid URLs are used.
// If not - we have to break this operation. But an optional listener must be informed.
// BTW: We save the information about the requested operation. Because
// we need it later.
if (aURL.Complete.equals(URL_CLOSEDOC))
m_eOperation = E_CLOSE_DOC;
else
if (aURL.Complete.equals(URL_CLOSEWIN))
m_eOperation = E_CLOSE_WIN;
else
if (aURL.Complete.equals(URL_CLOSEFRAME))
m_eOperation = E_CLOSE_FRAME;
else
{
aWriteLock.unlock();
// <- SAFE ------------------------------
implts_notifyResultListener(
xListener,
css::frame::DispatchResultState::FAILURE,
css::uno::Any());
return;
}
// OK - URLs are the right ones.
// But we can't execute synchronously :-)
// May we are called from a generic key-input handler,
// which isn't aware that this call kill its own environment ...
// Do it asynchronous everytimes!
// But dont forget to hold usself alive.
// We are called back from an environment, which doesn't know an uno reference.
// They call us back by using our c++ interface.
m_xResultListener = xListener;
m_xSelfHold = css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
aWriteLock.unlock();
// <- SAFE ----------------------------------
sal_Bool bIsSynchron = sal_False;
for (sal_Int32 nArgs=0; nArgs<lArguments.getLength(); nArgs++ )
{
if ( lArguments[nArgs].Name.equalsAscii("SynchronMode") )
{
lArguments[nArgs].Value >>= bIsSynchron;
break;
}
}
if ( bIsSynchron )
impl_asyncCallback(0);
else
m_aAsyncCallback.Post(0);
}
//-----------------------------------------------
/**
@short asynchronous callback
@descr We start all actions inside this object asnychronoue.
(see comments there).
Now we do the following:
- close all views to the same document, if needed and possible
- make the current frame empty
! This step is necessary to handle errors during closing the
document inside the frame. May the document shows a dialog and
the user ignore it. Then the state of the office can be changed
during we try to close frame and document.
- check the environment (menas count open frames - exlcuding our
current one)
- decide then, if we must close this frame only, establish the backing mode
or shutdown the whole application.
*/
IMPL_LINK( CloseDispatcher, impl_asyncCallback, void*, EMPTYARG )
{
try
{
// Allow calling of XController->suspend() everytimes.
// Dispatch is an UI functionality. We implement such dispatch object here.
// And further XController->suspend() was designed to bring an UI ...
sal_Bool bAllowSuspend = sal_True;
sal_Bool bControllerSuspended = sal_False;
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
// Closing of all views, related to the same document, is allowed
// only if the dispatched URL was ".uno:CloseDoc"!
sal_Bool bCloseAllViewsToo = (m_eOperation == E_CLOSE_DOC);
// BTW: Make some copies, which are needed later ...
EOperation eOperation = m_eOperation;
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
css::uno::Reference< css::frame::XFrame > xCloseFrame (m_xCloseFrame.get(), css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchResultListener > xListener = m_xResultListener;
aReadLock.unlock();
// <- SAFE ----------------------------------
// frame already dead ?!
// Nothing to do !
if (! xCloseFrame.is())
return 0;
sal_Bool bCloseFrame = sal_False;
sal_Bool bEstablishBackingMode = sal_False;
sal_Bool bTerminateApp = sal_False;
// Analyze the environment a first time.
// If we found some special cases, we can
// make some decisions erliar!
css::uno::Reference< css::frame::XFramesSupplier > xDesktop(xSMGR->createInstance(SERVICENAME_DESKTOP), css::uno::UNO_QUERY_THROW);
FrameListAnalyzer aCheck1(xDesktop, xCloseFrame, FrameListAnalyzer::E_HELP | FrameListAnalyzer::E_BACKINGCOMPONENT);
// a) If the curent frame (where the close dispatch was requested for) does not have
// any parent frame ... it will close this frame only. Such frame isn't part of the
// global desktop tree ... and such frames are used as "implementation details" only.
// E.g. the live previews of our wizards doing such things. And then the owner of the frame
// is responsible for closing the application or accepting closing of the application
// by others.
if ( ! xCloseFrame->getCreator().is())
bCloseFrame = sal_True;
else
// b) The help window can't disagree with any request.
// Because it doesn't implement a controller - it uses a window only.
// Further t can't be the last open frame - if we do all other things
// right inside this CloseDispatcher implementation.
// => close it!
if (aCheck1.m_bReferenceIsHelp)
bCloseFrame = sal_True;
else
// c) If we are already in "backing mode", we have to terminate
// the application, if this special frame is closed.
// It doesn't matter, how many other frames (can be the help or hidden frames only)
// are open then.
// => terminate the application!
if (aCheck1.m_bReferenceIsBacking)
bTerminateApp = sal_True;
else
// d) Otherwhise we have to: close all views to the same document, close the
// document inside our own frame and decide then again, what has to be done!
{
if (implts_prepareFrameForClosing(m_xCloseFrame, bAllowSuspend, bCloseAllViewsToo, bControllerSuspended))
{
// OK; this frame is empty now.
// Check the environment again to decide, what is the next step.
FrameListAnalyzer aCheck2(xDesktop, xCloseFrame, FrameListAnalyzer::E_ALL);
// c1) there is as minimum 1 frame open, which is visible and contains a document
// different from our one. And its not the help!
// => close our frame only - nothing else.
if (aCheck2.m_lOtherVisibleFrames.getLength()>0)
bCloseFrame = sal_True;
else
// c2) if we close the current view ... but not all other views
// to the same document, we must close the current frame only!
// Because implts_closeView() suspended this view only - does not
// close the frame.
if (
(!bCloseAllViewsToo ) &&
(aCheck2.m_lModelFrames.getLength() > 0)
)
bCloseFrame = sal_True;
else
// c3) there is no other (visible) frame open ...
// The help module will be ignored everytimes!
// But we have to decide if we must terminate the
// application or establish the backing mode now.
// And that depends from the dispatched URL ...
{
if (eOperation == E_CLOSE_FRAME)
bTerminateApp = sal_True;
else if( SvtModuleOptions().IsModuleInstalled(SvtModuleOptions::E_SSTARTMODULE) )
bEstablishBackingMode = sal_True;
else
bTerminateApp = sal_True;
}
}
}
// Do it now ...
sal_Bool bSuccess = sal_False;
if (bCloseFrame)
bSuccess = implts_closeFrame();
else
if (bEstablishBackingMode)
#if defined QUARTZ
{
// on mac close down, quickstarter keeps the process alive
// however if someone has shut down the quickstarter
// behave as any other platform
bool bQuickstarterRunning = false;
// get quickstart service
try
{
css::uno::Reference< css::beans::XFastPropertySet > xSet( xSMGR->createInstance(IMPLEMENTATIONNAME_QUICKLAUNCHER), css::uno::UNO_QUERY_THROW );
if( xSet.is() )
{
css::uno::Any aVal( xSet->getFastPropertyValue( 0 ) );
sal_Bool bState = sal_False;
if( aVal >>= bState )
bQuickstarterRunning = bState;
}
}
catch( css::uno::Exception& )
{
}
bSuccess = bQuickstarterRunning ? implts_terminateApplication() : implts_establishBackingMode();
}
#else
bSuccess = implts_establishBackingMode();
#endif
else
if (bTerminateApp)
bSuccess = implts_terminateApplication();
if (
( ! bSuccess ) &&
( bControllerSuspended )
)
{
css::uno::Reference< css::frame::XController > xController = xCloseFrame->getController();
if (xController.is())
xController->suspend(sal_False);
}
// inform listener
sal_Int16 nState = css::frame::DispatchResultState::FAILURE;
if (bSuccess)
nState = css::frame::DispatchResultState::SUCCESS;
implts_notifyResultListener(xListener, nState, css::uno::Any());
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
// This method was called asynchronous from our main thread by using a pointer.
// We reached this method only, by using a reference to ourself :-)
// Further this member is used to detect still running and not yet finished
// ansynchronous operations. So its time now to release this reference.
// But hold it temp alive. Otherwise we die before we can finish this method really :-))
css::uno::Reference< css::uno::XInterface > xTempHold = m_xSelfHold;
m_xSelfHold.clear();
m_xResultListener.clear();
aWriteLock.unlock();
// <- SAFE ----------------------------------
}
catch(const css::lang::DisposedException&)
{
LOG_ERROR("CloseDispatcher::impl_asyncCallback", "Congratulation! You found the reason for bug #120310#. Please contact the right developer and show him a scenario, which trigger this bug. THX.")
}
return 0;
}
//-----------------------------------------------
sal_Bool CloseDispatcher::implts_prepareFrameForClosing(const css::uno::Reference< css::frame::XFrame >& xFrame ,
sal_Bool bAllowSuspend ,
sal_Bool bCloseAllOtherViewsToo,
sal_Bool& bControllerSuspended )
{
// Frame already dead ... so this view is closed ... is closed ... is ... .-)
if (! xFrame.is())
return sal_True;
// Close all views to the same document ... if forced to do so.
// But dont touch our own frame here!
// We must do so ... because the may be following controller->suspend()
// will show the "save/discard/cancel" dialog for the last view only!
if (bCloseAllOtherViewsToo)
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
aReadLock.unlock();
// <- SAFE ----------------------------------
css::uno::Reference< css::frame::XFramesSupplier > xDesktop(xSMGR->createInstance(SERVICENAME_DESKTOP), css::uno::UNO_QUERY_THROW);
FrameListAnalyzer aCheck(xDesktop, xFrame, FrameListAnalyzer::E_ALL);
sal_Int32 c = aCheck.m_lModelFrames.getLength();
sal_Int32 i = 0;
for (i=0; i<c; ++i)
{
if (!fpf::closeIt(aCheck.m_lModelFrames[i], sal_False))
return sal_False;
}
}
// If allowed - inform user about modified documents or
// still running jobs (e.g. printing).
if (bAllowSuspend)
{
css::uno::Reference< css::frame::XController > xController = xFrame->getController();
if (xController.is()) // some views dont uses a controller .-( (e.g. the help window)
{
bControllerSuspended = xController->suspend(sal_True);
if (! bControllerSuspended)
return sal_False;
}
}
// dont remove the component really by e.g. calling setComponent(null, null).
// It's enough to suspend the controller.
// If we close the frame later this controller doesn't show the same dialog again.
return sal_True;
}
//-----------------------------------------------
sal_Bool CloseDispatcher::implts_closeFrame()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::frame::XFrame > xFrame (m_xCloseFrame.get(), css::uno::UNO_QUERY);
aReadLock.unlock();
// <- SAFE ----------------------------------
// frame already dead ? => so it's closed ... it's closed ...
if ( ! xFrame.is() )
return sal_True;
// dont deliver owner ship; our "UI user" will try it again if it failed.
// OK - he will get an empty frame then. But normaly an empty frame
// should be closeable always :-)
if (!fpf::closeIt(xFrame, sal_False))
return sal_False;
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_xCloseFrame = css::uno::WeakReference< css::frame::XFrame >();
aWriteLock.unlock();
// <- SAFE ----------------------------------
return sal_True;
}
//-----------------------------------------------
sal_Bool CloseDispatcher::implts_establishBackingMode()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
css::uno::Reference< css::frame::XFrame > xFrame (m_xCloseFrame.get(), css::uno::UNO_QUERY);
aReadLock.unlock();
// <- SAFE ----------------------------------
if (!xFrame.is())
return sal_False;
css::uno::Reference < css::document::XActionLockable > xLock( xFrame, css::uno::UNO_QUERY );
if ( xLock.is() && xLock->isActionLocked() )
return sal_False;
css::uno::Reference< css::awt::XWindow > xContainerWindow = xFrame->getContainerWindow();
css::uno::Sequence< css::uno::Any > lArgs(1);
lArgs[0] <<= xContainerWindow;
css::uno::Reference< css::frame::XController > xBackingComp(
xSMGR->createInstanceWithArguments(SERVICENAME_STARTMODULE, lArgs),
css::uno::UNO_QUERY_THROW);
// Attention: You MUST(!) call setComponent() before you call attachFrame().
css::uno::Reference< css::awt::XWindow > xBackingWin(xBackingComp, css::uno::UNO_QUERY);
xFrame->setComponent(xBackingWin, xBackingComp);
xBackingComp->attachFrame(xFrame);
xContainerWindow->setVisible(sal_True);
return sal_True;
}
//-----------------------------------------------
sal_Bool CloseDispatcher::implts_terminateApplication()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
aReadLock.unlock();
// <- SAFE ----------------------------------
css::uno::Reference< css::frame::XDesktop > xDesktop(
xSMGR->createInstance(SERVICENAME_DESKTOP), css::uno::UNO_QUERY_THROW);
return xDesktop->terminate();
}
//-----------------------------------------------
void CloseDispatcher::implts_notifyResultListener(const css::uno::Reference< css::frame::XDispatchResultListener >& xListener,
sal_Int16 nState ,
const css::uno::Any& aResult )
{
if (!xListener.is())
return;
css::frame::DispatchResultEvent aEvent(
css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY),
nState,
aResult);
xListener->dispatchFinished(aEvent);
}
//-----------------------------------------------
css::uno::Reference< css::frame::XFrame > CloseDispatcher::static_impl_searchRightTargetFrame(const css::uno::Reference< css::frame::XFrame >& xFrame ,
const ::rtl::OUString& sTarget)
{
if (sTarget.equalsIgnoreAsciiCaseAscii("_self"))
return xFrame;
OSL_ENSURE((sTarget.getLength() < 1), "CloseDispatch used for unexpected target. Magic things will happen now .-)");
css::uno::Reference< css::frame::XFrame > xTarget = xFrame;
while(sal_True)
{
// a) top frames wil be closed
if (xTarget->isTop())
return xTarget;
// b) even child frame containing top level windows (e.g. query designer of database) will be closed
css::uno::Reference< css::awt::XWindow > xWindow = xTarget->getContainerWindow();
css::uno::Reference< css::awt::XTopWindow > xTopWindowCheck(xWindow, css::uno::UNO_QUERY);
if (xTopWindowCheck.is())
{
// b1) Note: Toolkit interface XTopWindow sometimes is used by real VCL-child-windows also .-)
// Be sure that these window is really a "top system window".
// Attention ! Checking Window->GetParent() isn't the right approach here.
// Because sometimes VCL create "implicit border windows" as parents even we created
// a simple XWindow using the toolkit only .-(
::vos::OGuard aSolarLock(&Application::GetSolarMutex());
Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
if (
(pWindow ) &&
(pWindow->IsSystemWindow())
)
return xTarget;
}
// c) try to find better results on parent frame
// If no parent frame exists (because this frame is used outside the desktop tree)
// the given frame must be used directly.
css::uno::Reference< css::frame::XFrame > xParent(xTarget->getCreator(), css::uno::UNO_QUERY);
if ( ! xParent.is())
return xTarget;
// c1) check parent frame inside next loop ...
xTarget = xParent;
}
}
} // namespace framework
| 41.658462 | 203 | 0.577886 | [
"object"
] |
ef8ebe6eece18cccf8b1994587a34b12762bd918 | 8,651 | cc | C++ | src/developer/debug/zxdb/client/step_into_thread_controller_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/developer/debug/zxdb/client/step_into_thread_controller_unittest.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/developer/debug/zxdb/client/step_into_thread_controller_unittest.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/debug/zxdb/client/step_into_thread_controller.h"
#include "src/developer/debug/zxdb/client/inline_thread_controller_test.h"
#include "src/developer/debug/zxdb/client/process.h"
#include "src/developer/debug/zxdb/client/thread.h"
#include "src/developer/debug/zxdb/symbols/input_location.h"
#include "src/developer/debug/zxdb/symbols/line_details.h"
namespace zxdb {
namespace {
// This override of MockModuleSymbols allows us to respond with different addresses depending on
// whether prologue skipping was requested or not (the normal mock doesn't provide this level of
// control).
class StepIntoMockModuleSymbols : public MockModuleSymbols {
public:
// IP of beginning of function where the prologue will be queried.
static const uint64_t kNestedBegin;
// IP of first non-prologue instruction of the function above.
static const uint64_t kNestedPrologueEnd;
// ModuleSymbols overrides.
std::vector<Location> ResolveInputLocation(const SymbolContext& symbol_context,
const InputLocation& input_location,
const ResolveOptions& options) const override {
if (input_location.type == InputLocation::Type::kAddress &&
input_location.address == kNestedBegin) {
// This is the address in question.
if (options.skip_function_prologue)
return {Location(Location::State::kSymbolized, kNestedPrologueEnd)};
return {Location(Location::State::kSymbolized, kNestedBegin)};
}
return MockModuleSymbols::ResolveInputLocation(symbol_context, input_location, options);
}
protected:
FRIEND_MAKE_REF_COUNTED(StepIntoMockModuleSymbols);
FRIEND_REF_COUNTED_THREAD_SAFE(StepIntoMockModuleSymbols);
StepIntoMockModuleSymbols() : MockModuleSymbols("file.so") {
AddLineDetails(
InlineThreadControllerTest::kTopInlineFunctionRange.begin(),
LineDetails(InlineThreadControllerTest::kTopInlineFileLine,
{LineDetails::LineEntry(InlineThreadControllerTest::kTopInlineFunctionRange)}));
}
~StepIntoMockModuleSymbols() override {}
};
const uint64_t StepIntoMockModuleSymbols::kNestedBegin =
InlineThreadControllerTest::kTopInlineFunctionRange.begin();
const uint64_t StepIntoMockModuleSymbols::kNestedPrologueEnd = kNestedBegin + 4;
class StepIntoThreadControllerTest : public InlineThreadControllerTest {
public:
void DoStepTest(bool skip_prologue) {
constexpr uint64_t kBeginAddr = kSymbolizedModuleAddress + 0x1000;
constexpr uint64_t kEndAddr = kSymbolizedModuleAddress + 0x1010;
constexpr uint64_t kStackFramePrevious = 0x5010;
constexpr uint64_t kStackFrameInitial = 0x5000;
constexpr uint64_t kStackFrameNested = 0x4090;
constexpr uint64_t kStackFrameNestedPrologueCall = 0x4080;
// Set up the thread to be stopped at the beginning of our range.
debug_ipc::NotifyException exception;
exception.type = debug_ipc::ExceptionType::kSingleStep;
exception.thread.id = {.process = process()->GetKoid(), .thread = thread()->GetKoid()};
exception.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
exception.thread.frames.emplace_back(kBeginAddr, kStackFrameInitial, kStackFrameInitial);
exception.thread.frames.emplace_back(kBeginAddr - 10, kStackFramePrevious, kStackFramePrevious);
InjectException(exception);
// Start the "step into" over that range.
auto step_into = std::make_unique<StepIntoThreadController>(
AddressRanges(AddressRange(kBeginAddr, kEndAddr)));
bool continued = false;
step_into->set_should_skip_prologue(skip_prologue);
thread()->ContinueWith(std::move(step_into), [&continued](const Err& err) {
if (!err.has_error())
continued = true;
});
// That should have resumed the thread.
EXPECT_TRUE(continued);
EXPECT_EQ(1, mock_remote_api()->GetAndResetResumeCount());
// Stop at the beginning of a new stack frame (this adds to the previous stack frame still in th
// exception record).
exception.thread.frames.emplace(exception.thread.frames.begin(),
StepIntoMockModuleSymbols::kNestedBegin, kStackFrameNested,
kStackFrameNested);
InjectException(exception);
if (!skip_prologue) {
// When not skipping prologues, the thread should stop since we're in a new frame.
EXPECT_EQ(0, mock_remote_api()->GetAndResetResumeCount());
return;
}
// When skipping prologues, it should continue through the prologue.
EXPECT_EQ(1, mock_remote_api()->GetAndResetResumeCount());
// Test a function call from within the prologue. This corresponds to things like asan
// bookkeeping functions that should be skipped. Here we generate some random unsymbolized
// code address for the prologue call.
exception.thread.frames.emplace(exception.thread.frames.begin(),
kEndAddr + 0x8, // Call address, arbitrary.
kStackFrameNestedPrologueCall, kStackFrameNestedPrologueCall);
InjectException(exception);
EXPECT_EQ(1, mock_remote_api()->GetAndResetResumeCount()); // Skip prologue call.
// Delete the nested prologue call from the stack.
exception.thread.frames.erase(exception.thread.frames.begin());
// Report a stop at the end of the prologue. This just updates the same stack frame still in the
// exception record.
exception.thread.frames.front().ip = StepIntoMockModuleSymbols::kNestedPrologueEnd;
InjectException(exception);
// That should have stopped.
EXPECT_EQ(0, mock_remote_api()->GetAndResetResumeCount());
}
protected:
// ThreadControllerTest override:
fxl::RefPtr<MockModuleSymbols> MakeModuleSymbols() override {
return fxl::MakeRefCounted<StepIntoMockModuleSymbols>();
}
};
} // namespace
TEST_F(StepIntoThreadControllerTest, SkipPrologue) { DoStepTest(true); }
TEST_F(StepIntoThreadControllerTest, WithPrologue) { DoStepTest(false); }
// Inlines should never have prologues skipped. The prologue finder has a fallback that it will
// find a prologue even if one isn't explicitly noted to handle some GCC-generated code. If called
// on an inline routine, it will skip the first line.
TEST_F(StepIntoThreadControllerTest, Inline) {
// Recall the top frame from GetStack() is inline.
auto mock_frames = GetStack();
// Stepping into the 0th frame from the first. These are the source locations.
FileLine file_line = mock_frames[1]->GetLocation().file_line();
InjectExceptionWithStack(process()->GetKoid(), thread()->GetKoid(),
debug_ipc::ExceptionType::kSingleStep,
MockFrameVectorToFrameVector(std::move(mock_frames)), true);
// Hide the inline frame at the top so we're about to step into it.
Stack& stack = thread()->GetStack();
stack.SetHideAmbiguousInlineFrameCount(1);
// Do the "step into".
auto step_into_controller = std::make_unique<StepIntoThreadController>(StepMode::kSourceLine);
bool continued = false;
thread()->ContinueWith(std::move(step_into_controller), [&continued](const Err& err) {
if (!err.has_error())
continued = true;
});
EXPECT_TRUE(continued);
// That should have requested a synthetic exception which will be sent out asynchronously.
EXPECT_EQ(0, mock_remote_api()->GetAndResetResumeCount()); // Nothing yet.
loop().RunUntilNoTasks();
// The operation should have unhidden the inline stack frame rather than actually affecting the
// backend.
EXPECT_EQ(0, mock_remote_api()->GetAndResetResumeCount());
EXPECT_EQ(0u, stack.hide_ambiguous_inline_frame_count());
}
// If the program is killed out from under us, we can get an exception with no stack. This should
// stop and not crash.
TEST_F(StepIntoThreadControllerTest, NoStack) {
InjectExceptionWithStack(process()->GetKoid(), thread()->GetKoid(),
debug_ipc::ExceptionType::kSingleStep, {}, true);
auto step_into_controller = std::make_unique<StepIntoThreadController>(StepMode::kSourceLine);
std::optional<Err> result;
thread()->ContinueWith(std::move(step_into_controller),
[&result](const Err& err) { result = err; });
loop().RunUntilNoTasks();
EXPECT_EQ(0, mock_remote_api()->GetAndResetResumeCount());
EXPECT_TRUE(result);
EXPECT_EQ("Can't step, no frames.", result->msg());
}
} // namespace zxdb
| 43.691919 | 100 | 0.724887 | [
"vector"
] |
ef9051d14511d28cf1783dc8c0f8ebf593d44c6a | 51,984 | cpp | C++ | wrap/tests/expected/geometry_wrapper.cpp | alexhagiopol/GTSAM | c397fac199d0202c7abb1cd8e6005731658f56e8 | [
"BSD-3-Clause"
] | 105 | 2017-12-02T14:39:49.000Z | 2022-02-19T18:20:25.000Z | trunk/wrap/tests/expected/geometry_wrapper.cpp | shaolinbit/PPP-BayesTree | 6f469775277a1a33447bf4c19603c796c2c63c75 | [
"MIT"
] | 5 | 2018-09-04T15:15:59.000Z | 2020-09-08T08:51:02.000Z | trunk/wrap/tests/expected/geometry_wrapper.cpp | shaolinbit/PPP-BayesTree | 6f469775277a1a33447bf4c19603c796c2c63c75 | [
"MIT"
] | 31 | 2018-01-10T03:21:28.000Z | 2021-08-06T06:18:35.000Z | #include <wrap/matlab.h>
#include <map>
#include <boost/serialization/export.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <folder/path/to/Test.h>
typedef MyTemplate<gtsam::Point2> MyTemplatePoint2;
typedef MyTemplate<Matrix> MyTemplateMatrix;
typedef MyVector<3> MyVector3;
typedef MyVector<12> MyVector12;
typedef MyFactor<gtsam::Pose2, Matrix> MyFactorPosePoint2;
BOOST_CLASS_EXPORT_GUID(gtsam::Point2, "gtsamPoint2");
BOOST_CLASS_EXPORT_GUID(gtsam::Point3, "gtsamPoint3");
typedef std::set<boost::shared_ptr<gtsam::Point2>*> Collector_gtsamPoint2;
static Collector_gtsamPoint2 collector_gtsamPoint2;
typedef std::set<boost::shared_ptr<gtsam::Point3>*> Collector_gtsamPoint3;
static Collector_gtsamPoint3 collector_gtsamPoint3;
typedef std::set<boost::shared_ptr<Test>*> Collector_Test;
static Collector_Test collector_Test;
typedef std::set<boost::shared_ptr<MyBase>*> Collector_MyBase;
static Collector_MyBase collector_MyBase;
typedef std::set<boost::shared_ptr<MyTemplatePoint2>*> Collector_MyTemplatePoint2;
static Collector_MyTemplatePoint2 collector_MyTemplatePoint2;
typedef std::set<boost::shared_ptr<MyTemplateMatrix>*> Collector_MyTemplateMatrix;
static Collector_MyTemplateMatrix collector_MyTemplateMatrix;
typedef std::set<boost::shared_ptr<MyVector3>*> Collector_MyVector3;
static Collector_MyVector3 collector_MyVector3;
typedef std::set<boost::shared_ptr<MyVector12>*> Collector_MyVector12;
static Collector_MyVector12 collector_MyVector12;
typedef std::set<boost::shared_ptr<MyFactorPosePoint2>*> Collector_MyFactorPosePoint2;
static Collector_MyFactorPosePoint2 collector_MyFactorPosePoint2;
void _deleteAllObjects()
{
mstream mout;
std::streambuf *outbuf = std::cout.rdbuf(&mout);
bool anyDeleted = false;
{ for(Collector_gtsamPoint2::iterator iter = collector_gtsamPoint2.begin();
iter != collector_gtsamPoint2.end(); ) {
delete *iter;
collector_gtsamPoint2.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_gtsamPoint3::iterator iter = collector_gtsamPoint3.begin();
iter != collector_gtsamPoint3.end(); ) {
delete *iter;
collector_gtsamPoint3.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_Test::iterator iter = collector_Test.begin();
iter != collector_Test.end(); ) {
delete *iter;
collector_Test.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_MyBase::iterator iter = collector_MyBase.begin();
iter != collector_MyBase.end(); ) {
delete *iter;
collector_MyBase.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_MyTemplatePoint2::iterator iter = collector_MyTemplatePoint2.begin();
iter != collector_MyTemplatePoint2.end(); ) {
delete *iter;
collector_MyTemplatePoint2.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_MyTemplateMatrix::iterator iter = collector_MyTemplateMatrix.begin();
iter != collector_MyTemplateMatrix.end(); ) {
delete *iter;
collector_MyTemplateMatrix.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_MyVector3::iterator iter = collector_MyVector3.begin();
iter != collector_MyVector3.end(); ) {
delete *iter;
collector_MyVector3.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_MyVector12::iterator iter = collector_MyVector12.begin();
iter != collector_MyVector12.end(); ) {
delete *iter;
collector_MyVector12.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_MyFactorPosePoint2::iterator iter = collector_MyFactorPosePoint2.begin();
iter != collector_MyFactorPosePoint2.end(); ) {
delete *iter;
collector_MyFactorPosePoint2.erase(iter++);
anyDeleted = true;
} }
if(anyDeleted)
cout <<
"WARNING: Wrap modules with variables in the workspace have been reloaded due to\n"
"calling destructors, call 'clear all' again if you plan to now recompile a wrap\n"
"module, so that your recompiled module is used instead of the old one." << endl;
std::cout.rdbuf(outbuf);
}
void _geometry_RTTIRegister() {
const mxArray *alreadyCreated = mexGetVariablePtr("global", "gtsam_geometry_rttiRegistry_created");
if(!alreadyCreated) {
std::map<std::string, std::string> types;
types.insert(std::make_pair(typeid(MyBase).name(), "MyBase"));
types.insert(std::make_pair(typeid(MyTemplatePoint2).name(), "MyTemplatePoint2"));
types.insert(std::make_pair(typeid(MyTemplateMatrix).name(), "MyTemplateMatrix"));
mxArray *registry = mexGetVariable("global", "gtsamwrap_rttiRegistry");
if(!registry)
registry = mxCreateStructMatrix(1, 1, 0, NULL);
typedef std::pair<std::string, std::string> StringPair;
for(const StringPair& rtti_matlab: types) {
int fieldId = mxAddField(registry, rtti_matlab.first.c_str());
if(fieldId < 0)
mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly");
mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str());
mxSetFieldByNumber(registry, 0, fieldId, matlabName);
}
if(mexPutVariable("global", "gtsamwrap_rttiRegistry", registry) != 0)
mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly");
mxDestroyArray(registry);
mxArray *newAlreadyCreated = mxCreateNumericMatrix(0, 0, mxINT8_CLASS, mxREAL);
if(mexPutVariable("global", "gtsam_geometry_rttiRegistry_created", newAlreadyCreated) != 0)
mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly");
mxDestroyArray(newAlreadyCreated);
}
}
void gtsamPoint2_collectorInsertAndMakeBase_0(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<gtsam::Point2> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_gtsamPoint2.insert(self);
}
void gtsamPoint2_constructor_1(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<gtsam::Point2> Shared;
Shared *self = new Shared(new gtsam::Point2());
collector_gtsamPoint2.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void gtsamPoint2_constructor_2(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<gtsam::Point2> Shared;
double x = unwrap< double >(in[0]);
double y = unwrap< double >(in[1]);
Shared *self = new Shared(new gtsam::Point2(x,y));
collector_gtsamPoint2.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void gtsamPoint2_deconstructor_3(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("delete_gtsamPoint2",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_gtsamPoint2::iterator item;
item = collector_gtsamPoint2.find(self);
if(item != collector_gtsamPoint2.end()) {
delete self;
collector_gtsamPoint2.erase(item);
}
}
void gtsamPoint2_argChar_4(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("argChar",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
char a = unwrap< char >(in[1]);
obj->argChar(a);
}
void gtsamPoint2_argUChar_5(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("argUChar",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
unsigned char a = unwrap< unsigned char >(in[1]);
obj->argUChar(a);
}
void gtsamPoint2_dim_6(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("dim",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
out[0] = wrap< int >(obj->dim());
}
void gtsamPoint2_eigenArguments_7(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("eigenArguments",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
Vector v = unwrap< Vector >(in[1]);
Matrix m = unwrap< Matrix >(in[2]);
obj->eigenArguments(v,m);
}
void gtsamPoint2_returnChar_8(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("returnChar",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
out[0] = wrap< char >(obj->returnChar());
}
void gtsamPoint2_vectorConfusion_9(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<VectorNotEigen> SharedVectorNotEigen;
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("vectorConfusion",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
out[0] = wrap_shared_ptr(SharedVectorNotEigen(new VectorNotEigen(obj->vectorConfusion())),"VectorNotEigen", false);
}
void gtsamPoint2_x_10(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("x",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
out[0] = wrap< double >(obj->x());
}
void gtsamPoint2_y_11(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> Shared;
checkArguments("y",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point2>(in[0], "ptr_gtsamPoint2");
out[0] = wrap< double >(obj->y());
}
void gtsamPoint3_collectorInsertAndMakeBase_12(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<gtsam::Point3> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_gtsamPoint3.insert(self);
}
void gtsamPoint3_constructor_13(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<gtsam::Point3> Shared;
double x = unwrap< double >(in[0]);
double y = unwrap< double >(in[1]);
double z = unwrap< double >(in[2]);
Shared *self = new Shared(new gtsam::Point3(x,y,z));
collector_gtsamPoint3.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void gtsamPoint3_deconstructor_14(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> Shared;
checkArguments("delete_gtsamPoint3",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_gtsamPoint3::iterator item;
item = collector_gtsamPoint3.find(self);
if(item != collector_gtsamPoint3.end()) {
delete self;
collector_gtsamPoint3.erase(item);
}
}
void gtsamPoint3_norm_15(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> Shared;
checkArguments("norm",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point3>(in[0], "ptr_gtsamPoint3");
out[0] = wrap< double >(obj->norm());
}
void gtsamPoint3_string_serialize_16(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> Shared;
checkArguments("string_serialize",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<gtsam::Point3>(in[0], "ptr_gtsamPoint3");
ostringstream out_archive_stream;
boost::archive::text_oarchive out_archive(out_archive_stream);
out_archive << *obj;
out[0] = wrap< string >(out_archive_stream.str());
}
void gtsamPoint3_StaticFunctionRet_17(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> SharedPoint3;
typedef boost::shared_ptr<gtsam::Point3> Shared;
checkArguments("gtsamPoint3.StaticFunctionRet",nargout,nargin,1);
double z = unwrap< double >(in[0]);
out[0] = wrap_shared_ptr(SharedPoint3(new gtsam::Point3(gtsam::Point3::StaticFunctionRet(z))),"gtsam.Point3", false);
}
void gtsamPoint3_staticFunction_18(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> Shared;
checkArguments("gtsamPoint3.staticFunction",nargout,nargin,0);
out[0] = wrap< double >(gtsam::Point3::staticFunction());
}
void gtsamPoint3_string_deserialize_19(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> Shared;
checkArguments("gtsamPoint3.string_deserialize",nargout,nargin,1);
string serialized = unwrap< string >(in[0]);
istringstream in_archive_stream(serialized);
boost::archive::text_iarchive in_archive(in_archive_stream);
Shared output(new gtsam::Point3());
in_archive >> *output;
out[0] = wrap_shared_ptr(output,"gtsam.Point3", false);
}
void Test_collectorInsertAndMakeBase_20(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Test> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_Test.insert(self);
}
void Test_constructor_21(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Test> Shared;
Shared *self = new Shared(new Test());
collector_Test.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Test_constructor_22(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Test> Shared;
double a = unwrap< double >(in[0]);
Matrix b = unwrap< Matrix >(in[1]);
Shared *self = new Shared(new Test(a,b));
collector_Test.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Test_deconstructor_23(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("delete_Test",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_Test::iterator item;
item = collector_Test.find(self);
if(item != collector_Test.end()) {
delete self;
collector_Test.erase(item);
}
}
void Test_arg_EigenConstRef_24(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("arg_EigenConstRef",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Matrix value = unwrap< Matrix >(in[1]);
obj->arg_EigenConstRef(value);
}
void Test_create_MixedPtrs_25(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("create_MixedPtrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
pair< Test, SharedTest > pairResult = obj->create_MixedPtrs();
out[0] = wrap_shared_ptr(SharedTest(new Test(pairResult.first)),"Test", false);
out[1] = wrap_shared_ptr(pairResult.second,"Test", false);
}
void Test_create_ptrs_26(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("create_ptrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
pair< SharedTest, SharedTest > pairResult = obj->create_ptrs();
out[0] = wrap_shared_ptr(pairResult.first,"Test", false);
out[1] = wrap_shared_ptr(pairResult.second,"Test", false);
}
void Test_print_27(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("print",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
obj->print();
}
void Test_return_Point2Ptr_28(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_Point2Ptr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
bool value = unwrap< bool >(in[1]);
out[0] = wrap_shared_ptr(obj->return_Point2Ptr(value),"gtsam.Point2", false);
}
void Test_return_Test_29(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_Test",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
boost::shared_ptr<Test> value = unwrap_shared_ptr< Test >(in[1], "ptr_Test");
out[0] = wrap_shared_ptr(SharedTest(new Test(obj->return_Test(value))),"Test", false);
}
void Test_return_TestPtr_30(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_TestPtr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
boost::shared_ptr<Test> value = unwrap_shared_ptr< Test >(in[1], "ptr_Test");
out[0] = wrap_shared_ptr(obj->return_TestPtr(value),"Test", false);
}
void Test_return_bool_31(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_bool",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
bool value = unwrap< bool >(in[1]);
out[0] = wrap< bool >(obj->return_bool(value));
}
void Test_return_double_32(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_double",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
double value = unwrap< double >(in[1]);
out[0] = wrap< double >(obj->return_double(value));
}
void Test_return_field_33(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_field",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Test& t = *unwrap_shared_ptr< Test >(in[1], "ptr_Test");
out[0] = wrap< bool >(obj->return_field(t));
}
void Test_return_int_34(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_int",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
int value = unwrap< int >(in[1]);
out[0] = wrap< int >(obj->return_int(value));
}
void Test_return_matrix1_35(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_matrix1",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Matrix value = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->return_matrix1(value));
}
void Test_return_matrix2_36(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_matrix2",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Matrix value = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->return_matrix2(value));
}
void Test_return_pair_37(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_pair",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Vector v = unwrap< Vector >(in[1]);
Matrix A = unwrap< Matrix >(in[2]);
pair< Vector, Matrix > pairResult = obj->return_pair(v,A);
out[0] = wrap< Vector >(pairResult.first);
out[1] = wrap< Matrix >(pairResult.second);
}
void Test_return_ptrs_38(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_ptrs",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
boost::shared_ptr<Test> p1 = unwrap_shared_ptr< Test >(in[1], "ptr_Test");
boost::shared_ptr<Test> p2 = unwrap_shared_ptr< Test >(in[2], "ptr_Test");
pair< SharedTest, SharedTest > pairResult = obj->return_ptrs(p1,p2);
out[0] = wrap_shared_ptr(pairResult.first,"Test", false);
out[1] = wrap_shared_ptr(pairResult.second,"Test", false);
}
void Test_return_size_t_39(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_size_t",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
size_t value = unwrap< size_t >(in[1]);
out[0] = wrap< size_t >(obj->return_size_t(value));
}
void Test_return_string_40(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_string",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
string value = unwrap< string >(in[1]);
out[0] = wrap< string >(obj->return_string(value));
}
void Test_return_vector1_41(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_vector1",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Vector value = unwrap< Vector >(in[1]);
out[0] = wrap< Vector >(obj->return_vector1(value));
}
void Test_return_vector2_42(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_vector2",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Vector value = unwrap< Vector >(in[1]);
out[0] = wrap< Vector >(obj->return_vector2(value));
}
void MyBase_collectorInsertAndMakeBase_43(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyBase> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_MyBase.insert(self);
}
void MyBase_upcastFromVoid_44(int nargout, mxArray *out[], int nargin, const mxArray *in[]) {
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyBase> Shared;
boost::shared_ptr<void> *asVoid = *reinterpret_cast<boost::shared_ptr<void>**> (mxGetData(in[0]));
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
Shared *self = new Shared(boost::static_pointer_cast<MyBase>(*asVoid));
*reinterpret_cast<Shared**>(mxGetData(out[0])) = self;
}
void MyBase_deconstructor_45(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyBase> Shared;
checkArguments("delete_MyBase",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_MyBase::iterator item;
item = collector_MyBase.find(self);
if(item != collector_MyBase.end()) {
delete self;
collector_MyBase.erase(item);
}
}
void MyTemplatePoint2_collectorInsertAndMakeBase_46(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_MyTemplatePoint2.insert(self);
typedef boost::shared_ptr<MyBase> SharedBase;
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<SharedBase**>(mxGetData(out[0])) = new SharedBase(*self);
}
void MyTemplatePoint2_upcastFromVoid_47(int nargout, mxArray *out[], int nargin, const mxArray *in[]) {
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
boost::shared_ptr<void> *asVoid = *reinterpret_cast<boost::shared_ptr<void>**> (mxGetData(in[0]));
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
Shared *self = new Shared(boost::static_pointer_cast<MyTemplatePoint2>(*asVoid));
*reinterpret_cast<Shared**>(mxGetData(out[0])) = self;
}
void MyTemplatePoint2_constructor_48(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
Shared *self = new Shared(new MyTemplatePoint2());
collector_MyTemplatePoint2.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
typedef boost::shared_ptr<MyBase> SharedBase;
out[1] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<SharedBase**>(mxGetData(out[1])) = new SharedBase(*self);
}
void MyTemplatePoint2_deconstructor_49(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("delete_MyTemplatePoint2",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_MyTemplatePoint2::iterator item;
item = collector_MyTemplatePoint2.find(self);
if(item != collector_MyTemplatePoint2.end()) {
delete self;
collector_MyTemplatePoint2.erase(item);
}
}
void MyTemplatePoint2_accept_T_50(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("accept_T",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
gtsam::Point2& value = *unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
obj->accept_T(value);
}
void MyTemplatePoint2_accept_Tptr_51(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("accept_Tptr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
boost::shared_ptr<gtsam::Point2> value = unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
obj->accept_Tptr(value);
}
void MyTemplatePoint2_create_MixedPtrs_52(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("create_MixedPtrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
pair< gtsam::Point2, SharedPoint2 > pairResult = obj->create_MixedPtrs();
out[0] = wrap_shared_ptr(SharedPoint2(new gtsam::Point2(pairResult.first)),"gtsam.Point2", false);
out[1] = wrap_shared_ptr(pairResult.second,"gtsam.Point2", false);
}
void MyTemplatePoint2_create_ptrs_53(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("create_ptrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
pair< SharedPoint2, SharedPoint2 > pairResult = obj->create_ptrs();
out[0] = wrap_shared_ptr(pairResult.first,"gtsam.Point2", false);
out[1] = wrap_shared_ptr(pairResult.second,"gtsam.Point2", false);
}
void MyTemplatePoint2_return_T_54(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("return_T",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
boost::shared_ptr<gtsam::Point2> value = unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
out[0] = wrap_shared_ptr(SharedPoint2(new gtsam::Point2(obj->return_T(value))),"gtsam.Point2", false);
}
void MyTemplatePoint2_return_Tptr_55(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("return_Tptr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
boost::shared_ptr<gtsam::Point2> value = unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
out[0] = wrap_shared_ptr(obj->return_Tptr(value),"gtsam.Point2", false);
}
void MyTemplatePoint2_return_ptrs_56(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("return_ptrs",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
boost::shared_ptr<gtsam::Point2> p1 = unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
boost::shared_ptr<gtsam::Point2> p2 = unwrap_shared_ptr< gtsam::Point2 >(in[2], "ptr_gtsamPoint2");
pair< SharedPoint2, SharedPoint2 > pairResult = obj->return_ptrs(p1,p2);
out[0] = wrap_shared_ptr(pairResult.first,"gtsam.Point2", false);
out[1] = wrap_shared_ptr(pairResult.second,"gtsam.Point2", false);
}
void MyTemplatePoint2_templatedMethod_57(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("templatedMethodMatrix",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
Matrix t = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->templatedMethod<Matrix>(t));
}
void MyTemplatePoint2_templatedMethod_58(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("templatedMethodPoint2",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
gtsam::Point2& t = *unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
out[0] = wrap_shared_ptr(SharedPoint2(new gtsam::Point2(obj->templatedMethod<gtsam::Point2>(t))),"gtsam.Point2", false);
}
void MyTemplatePoint2_templatedMethod_59(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> SharedPoint3;
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("templatedMethodPoint3",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
gtsam::Point3& t = *unwrap_shared_ptr< gtsam::Point3 >(in[1], "ptr_gtsamPoint3");
out[0] = wrap_shared_ptr(SharedPoint3(new gtsam::Point3(obj->templatedMethod<gtsam::Point3>(t))),"gtsam.Point3", false);
}
void MyTemplatePoint2_templatedMethod_60(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplatePoint2> Shared;
checkArguments("templatedMethodVector",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplatePoint2>(in[0], "ptr_MyTemplatePoint2");
Vector t = unwrap< Vector >(in[1]);
out[0] = wrap< Vector >(obj->templatedMethod<Vector>(t));
}
void MyTemplateMatrix_collectorInsertAndMakeBase_61(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_MyTemplateMatrix.insert(self);
typedef boost::shared_ptr<MyBase> SharedBase;
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<SharedBase**>(mxGetData(out[0])) = new SharedBase(*self);
}
void MyTemplateMatrix_upcastFromVoid_62(int nargout, mxArray *out[], int nargin, const mxArray *in[]) {
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
boost::shared_ptr<void> *asVoid = *reinterpret_cast<boost::shared_ptr<void>**> (mxGetData(in[0]));
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
Shared *self = new Shared(boost::static_pointer_cast<MyTemplateMatrix>(*asVoid));
*reinterpret_cast<Shared**>(mxGetData(out[0])) = self;
}
void MyTemplateMatrix_constructor_63(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
Shared *self = new Shared(new MyTemplateMatrix());
collector_MyTemplateMatrix.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
typedef boost::shared_ptr<MyBase> SharedBase;
out[1] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<SharedBase**>(mxGetData(out[1])) = new SharedBase(*self);
}
void MyTemplateMatrix_deconstructor_64(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("delete_MyTemplateMatrix",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_MyTemplateMatrix::iterator item;
item = collector_MyTemplateMatrix.find(self);
if(item != collector_MyTemplateMatrix.end()) {
delete self;
collector_MyTemplateMatrix.erase(item);
}
}
void MyTemplateMatrix_accept_T_65(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("accept_T",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Matrix value = unwrap< Matrix >(in[1]);
obj->accept_T(value);
}
void MyTemplateMatrix_accept_Tptr_66(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("accept_Tptr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Matrix value = unwrap< Matrix >(in[1]);
obj->accept_Tptr(value);
}
void MyTemplateMatrix_create_MixedPtrs_67(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("create_MixedPtrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
pair< Matrix, SharedMatrix > pairResult = obj->create_MixedPtrs();
out[0] = wrap< Matrix >(pairResult.first);
{
SharedMatrix* ret = new SharedMatrix(pairResult.second);
out[1] = wrap_shared_ptr(ret,"Matrix");
}
}
void MyTemplateMatrix_create_ptrs_68(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("create_ptrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
pair< SharedMatrix, SharedMatrix > pairResult = obj->create_ptrs();
{
SharedMatrix* ret = new SharedMatrix(pairResult.first);
out[0] = wrap_shared_ptr(ret,"Matrix");
}
{
SharedMatrix* ret = new SharedMatrix(pairResult.second);
out[1] = wrap_shared_ptr(ret,"Matrix");
}
}
void MyTemplateMatrix_return_T_69(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("return_T",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Matrix value = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->return_T(value));
}
void MyTemplateMatrix_return_Tptr_70(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("return_Tptr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Matrix value = unwrap< Matrix >(in[1]);
{
SharedMatrix* ret = new SharedMatrix(obj->return_Tptr(value));
out[0] = wrap_shared_ptr(ret,"Matrix");
}
}
void MyTemplateMatrix_return_ptrs_71(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("return_ptrs",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Matrix p1 = unwrap< Matrix >(in[1]);
Matrix p2 = unwrap< Matrix >(in[2]);
pair< SharedMatrix, SharedMatrix > pairResult = obj->return_ptrs(p1,p2);
{
SharedMatrix* ret = new SharedMatrix(pairResult.first);
out[0] = wrap_shared_ptr(ret,"Matrix");
}
{
SharedMatrix* ret = new SharedMatrix(pairResult.second);
out[1] = wrap_shared_ptr(ret,"Matrix");
}
}
void MyTemplateMatrix_templatedMethod_72(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("templatedMethodMatrix",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Matrix t = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->templatedMethod<Matrix>(t));
}
void MyTemplateMatrix_templatedMethod_73(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point2> SharedPoint2;
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("templatedMethodPoint2",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
gtsam::Point2& t = *unwrap_shared_ptr< gtsam::Point2 >(in[1], "ptr_gtsamPoint2");
out[0] = wrap_shared_ptr(SharedPoint2(new gtsam::Point2(obj->templatedMethod<gtsam::Point2>(t))),"gtsam.Point2", false);
}
void MyTemplateMatrix_templatedMethod_74(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<gtsam::Point3> SharedPoint3;
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("templatedMethodPoint3",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
gtsam::Point3& t = *unwrap_shared_ptr< gtsam::Point3 >(in[1], "ptr_gtsamPoint3");
out[0] = wrap_shared_ptr(SharedPoint3(new gtsam::Point3(obj->templatedMethod<gtsam::Point3>(t))),"gtsam.Point3", false);
}
void MyTemplateMatrix_templatedMethod_75(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyTemplateMatrix> Shared;
checkArguments("templatedMethodVector",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<MyTemplateMatrix>(in[0], "ptr_MyTemplateMatrix");
Vector t = unwrap< Vector >(in[1]);
out[0] = wrap< Vector >(obj->templatedMethod<Vector>(t));
}
void MyVector3_collectorInsertAndMakeBase_76(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyVector3> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_MyVector3.insert(self);
}
void MyVector3_constructor_77(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyVector3> Shared;
Shared *self = new Shared(new MyVector3());
collector_MyVector3.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void MyVector3_deconstructor_78(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyVector3> Shared;
checkArguments("delete_MyVector3",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_MyVector3::iterator item;
item = collector_MyVector3.find(self);
if(item != collector_MyVector3.end()) {
delete self;
collector_MyVector3.erase(item);
}
}
void MyVector12_collectorInsertAndMakeBase_79(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyVector12> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_MyVector12.insert(self);
}
void MyVector12_constructor_80(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyVector12> Shared;
Shared *self = new Shared(new MyVector12());
collector_MyVector12.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void MyVector12_deconstructor_81(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyVector12> Shared;
checkArguments("delete_MyVector12",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_MyVector12::iterator item;
item = collector_MyVector12.find(self);
if(item != collector_MyVector12.end()) {
delete self;
collector_MyVector12.erase(item);
}
}
void MyFactorPosePoint2_collectorInsertAndMakeBase_82(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyFactorPosePoint2> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_MyFactorPosePoint2.insert(self);
}
void MyFactorPosePoint2_constructor_83(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<MyFactorPosePoint2> Shared;
size_t key1 = unwrap< size_t >(in[0]);
size_t key2 = unwrap< size_t >(in[1]);
double measured = unwrap< double >(in[2]);
boost::shared_ptr<gtsam::noiseModel::Base> noiseModel = unwrap_shared_ptr< gtsam::noiseModel::Base >(in[3], "ptr_gtsamnoiseModelBase");
Shared *self = new Shared(new MyFactorPosePoint2(key1,key2,measured,noiseModel));
collector_MyFactorPosePoint2.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void MyFactorPosePoint2_deconstructor_84(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<MyFactorPosePoint2> Shared;
checkArguments("delete_MyFactorPosePoint2",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_MyFactorPosePoint2::iterator item;
item = collector_MyFactorPosePoint2.find(self);
if(item != collector_MyFactorPosePoint2.end()) {
delete self;
collector_MyFactorPosePoint2.erase(item);
}
}
void aGlobalFunction_85(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
checkArguments("aGlobalFunction",nargout,nargin,0);
out[0] = wrap< Vector >(aGlobalFunction());
}
void overloadedGlobalFunction_86(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
checkArguments("overloadedGlobalFunction",nargout,nargin,1);
int a = unwrap< int >(in[0]);
out[0] = wrap< Vector >(overloadedGlobalFunction(a));
}
void overloadedGlobalFunction_87(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
checkArguments("overloadedGlobalFunction",nargout,nargin,2);
int a = unwrap< int >(in[0]);
double b = unwrap< double >(in[1]);
out[0] = wrap< Vector >(overloadedGlobalFunction(a,b));
}
void mexFunction(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mstream mout;
std::streambuf *outbuf = std::cout.rdbuf(&mout);
_geometry_RTTIRegister();
int id = unwrap<int>(in[0]);
try {
switch(id) {
case 0:
gtsamPoint2_collectorInsertAndMakeBase_0(nargout, out, nargin-1, in+1);
break;
case 1:
gtsamPoint2_constructor_1(nargout, out, nargin-1, in+1);
break;
case 2:
gtsamPoint2_constructor_2(nargout, out, nargin-1, in+1);
break;
case 3:
gtsamPoint2_deconstructor_3(nargout, out, nargin-1, in+1);
break;
case 4:
gtsamPoint2_argChar_4(nargout, out, nargin-1, in+1);
break;
case 5:
gtsamPoint2_argUChar_5(nargout, out, nargin-1, in+1);
break;
case 6:
gtsamPoint2_dim_6(nargout, out, nargin-1, in+1);
break;
case 7:
gtsamPoint2_eigenArguments_7(nargout, out, nargin-1, in+1);
break;
case 8:
gtsamPoint2_returnChar_8(nargout, out, nargin-1, in+1);
break;
case 9:
gtsamPoint2_vectorConfusion_9(nargout, out, nargin-1, in+1);
break;
case 10:
gtsamPoint2_x_10(nargout, out, nargin-1, in+1);
break;
case 11:
gtsamPoint2_y_11(nargout, out, nargin-1, in+1);
break;
case 12:
gtsamPoint3_collectorInsertAndMakeBase_12(nargout, out, nargin-1, in+1);
break;
case 13:
gtsamPoint3_constructor_13(nargout, out, nargin-1, in+1);
break;
case 14:
gtsamPoint3_deconstructor_14(nargout, out, nargin-1, in+1);
break;
case 15:
gtsamPoint3_norm_15(nargout, out, nargin-1, in+1);
break;
case 16:
gtsamPoint3_string_serialize_16(nargout, out, nargin-1, in+1);
break;
case 17:
gtsamPoint3_StaticFunctionRet_17(nargout, out, nargin-1, in+1);
break;
case 18:
gtsamPoint3_staticFunction_18(nargout, out, nargin-1, in+1);
break;
case 19:
gtsamPoint3_string_deserialize_19(nargout, out, nargin-1, in+1);
break;
case 20:
Test_collectorInsertAndMakeBase_20(nargout, out, nargin-1, in+1);
break;
case 21:
Test_constructor_21(nargout, out, nargin-1, in+1);
break;
case 22:
Test_constructor_22(nargout, out, nargin-1, in+1);
break;
case 23:
Test_deconstructor_23(nargout, out, nargin-1, in+1);
break;
case 24:
Test_arg_EigenConstRef_24(nargout, out, nargin-1, in+1);
break;
case 25:
Test_create_MixedPtrs_25(nargout, out, nargin-1, in+1);
break;
case 26:
Test_create_ptrs_26(nargout, out, nargin-1, in+1);
break;
case 27:
Test_print_27(nargout, out, nargin-1, in+1);
break;
case 28:
Test_return_Point2Ptr_28(nargout, out, nargin-1, in+1);
break;
case 29:
Test_return_Test_29(nargout, out, nargin-1, in+1);
break;
case 30:
Test_return_TestPtr_30(nargout, out, nargin-1, in+1);
break;
case 31:
Test_return_bool_31(nargout, out, nargin-1, in+1);
break;
case 32:
Test_return_double_32(nargout, out, nargin-1, in+1);
break;
case 33:
Test_return_field_33(nargout, out, nargin-1, in+1);
break;
case 34:
Test_return_int_34(nargout, out, nargin-1, in+1);
break;
case 35:
Test_return_matrix1_35(nargout, out, nargin-1, in+1);
break;
case 36:
Test_return_matrix2_36(nargout, out, nargin-1, in+1);
break;
case 37:
Test_return_pair_37(nargout, out, nargin-1, in+1);
break;
case 38:
Test_return_ptrs_38(nargout, out, nargin-1, in+1);
break;
case 39:
Test_return_size_t_39(nargout, out, nargin-1, in+1);
break;
case 40:
Test_return_string_40(nargout, out, nargin-1, in+1);
break;
case 41:
Test_return_vector1_41(nargout, out, nargin-1, in+1);
break;
case 42:
Test_return_vector2_42(nargout, out, nargin-1, in+1);
break;
case 43:
MyBase_collectorInsertAndMakeBase_43(nargout, out, nargin-1, in+1);
break;
case 44:
MyBase_upcastFromVoid_44(nargout, out, nargin-1, in+1);
break;
case 45:
MyBase_deconstructor_45(nargout, out, nargin-1, in+1);
break;
case 46:
MyTemplatePoint2_collectorInsertAndMakeBase_46(nargout, out, nargin-1, in+1);
break;
case 47:
MyTemplatePoint2_upcastFromVoid_47(nargout, out, nargin-1, in+1);
break;
case 48:
MyTemplatePoint2_constructor_48(nargout, out, nargin-1, in+1);
break;
case 49:
MyTemplatePoint2_deconstructor_49(nargout, out, nargin-1, in+1);
break;
case 50:
MyTemplatePoint2_accept_T_50(nargout, out, nargin-1, in+1);
break;
case 51:
MyTemplatePoint2_accept_Tptr_51(nargout, out, nargin-1, in+1);
break;
case 52:
MyTemplatePoint2_create_MixedPtrs_52(nargout, out, nargin-1, in+1);
break;
case 53:
MyTemplatePoint2_create_ptrs_53(nargout, out, nargin-1, in+1);
break;
case 54:
MyTemplatePoint2_return_T_54(nargout, out, nargin-1, in+1);
break;
case 55:
MyTemplatePoint2_return_Tptr_55(nargout, out, nargin-1, in+1);
break;
case 56:
MyTemplatePoint2_return_ptrs_56(nargout, out, nargin-1, in+1);
break;
case 57:
MyTemplatePoint2_templatedMethod_57(nargout, out, nargin-1, in+1);
break;
case 58:
MyTemplatePoint2_templatedMethod_58(nargout, out, nargin-1, in+1);
break;
case 59:
MyTemplatePoint2_templatedMethod_59(nargout, out, nargin-1, in+1);
break;
case 60:
MyTemplatePoint2_templatedMethod_60(nargout, out, nargin-1, in+1);
break;
case 61:
MyTemplateMatrix_collectorInsertAndMakeBase_61(nargout, out, nargin-1, in+1);
break;
case 62:
MyTemplateMatrix_upcastFromVoid_62(nargout, out, nargin-1, in+1);
break;
case 63:
MyTemplateMatrix_constructor_63(nargout, out, nargin-1, in+1);
break;
case 64:
MyTemplateMatrix_deconstructor_64(nargout, out, nargin-1, in+1);
break;
case 65:
MyTemplateMatrix_accept_T_65(nargout, out, nargin-1, in+1);
break;
case 66:
MyTemplateMatrix_accept_Tptr_66(nargout, out, nargin-1, in+1);
break;
case 67:
MyTemplateMatrix_create_MixedPtrs_67(nargout, out, nargin-1, in+1);
break;
case 68:
MyTemplateMatrix_create_ptrs_68(nargout, out, nargin-1, in+1);
break;
case 69:
MyTemplateMatrix_return_T_69(nargout, out, nargin-1, in+1);
break;
case 70:
MyTemplateMatrix_return_Tptr_70(nargout, out, nargin-1, in+1);
break;
case 71:
MyTemplateMatrix_return_ptrs_71(nargout, out, nargin-1, in+1);
break;
case 72:
MyTemplateMatrix_templatedMethod_72(nargout, out, nargin-1, in+1);
break;
case 73:
MyTemplateMatrix_templatedMethod_73(nargout, out, nargin-1, in+1);
break;
case 74:
MyTemplateMatrix_templatedMethod_74(nargout, out, nargin-1, in+1);
break;
case 75:
MyTemplateMatrix_templatedMethod_75(nargout, out, nargin-1, in+1);
break;
case 76:
MyVector3_collectorInsertAndMakeBase_76(nargout, out, nargin-1, in+1);
break;
case 77:
MyVector3_constructor_77(nargout, out, nargin-1, in+1);
break;
case 78:
MyVector3_deconstructor_78(nargout, out, nargin-1, in+1);
break;
case 79:
MyVector12_collectorInsertAndMakeBase_79(nargout, out, nargin-1, in+1);
break;
case 80:
MyVector12_constructor_80(nargout, out, nargin-1, in+1);
break;
case 81:
MyVector12_deconstructor_81(nargout, out, nargin-1, in+1);
break;
case 82:
MyFactorPosePoint2_collectorInsertAndMakeBase_82(nargout, out, nargin-1, in+1);
break;
case 83:
MyFactorPosePoint2_constructor_83(nargout, out, nargin-1, in+1);
break;
case 84:
MyFactorPosePoint2_deconstructor_84(nargout, out, nargin-1, in+1);
break;
case 85:
aGlobalFunction_85(nargout, out, nargin-1, in+1);
break;
case 86:
overloadedGlobalFunction_86(nargout, out, nargin-1, in+1);
break;
case 87:
overloadedGlobalFunction_87(nargout, out, nargin-1, in+1);
break;
}
} catch(const std::exception& e) {
mexErrMsgTxt(("Exception from gtsam:\n" + std::string(e.what()) + "\n").c_str());
}
std::cout.rdbuf(outbuf);
}
| 38.852018 | 137 | 0.721741 | [
"vector"
] |
ef9316503aa5ba277888d50c7d13e02e5e3ff8cb | 474 | cpp | C++ | Contests/USACO Solutions/2016-17/Feb 2017/Bronze/17 Feb B3.cpp | nocrizwang/USACO | 8a922f8d4b3bc905da97f53f9a447debe97d5e81 | [
"CC0-1.0"
] | 1,760 | 2017-05-21T21:07:06.000Z | 2022-03-29T13:15:08.000Z | Contests/USACO Solutions/2016-17/Feb 2017/Bronze/17 Feb B3.cpp | nocrizwang/USACO | 8a922f8d4b3bc905da97f53f9a447debe97d5e81 | [
"CC0-1.0"
] | 12 | 2018-01-24T02:41:53.000Z | 2022-03-17T13:09:26.000Z | Contests/USACO Solutions/2016-17/Feb 2017/Bronze/17 Feb B3.cpp | nocrizwang/USACO | 8a922f8d4b3bc905da97f53f9a447debe97d5e81 | [
"CC0-1.0"
] | 473 | 2017-07-06T04:53:41.000Z | 2022-03-28T13:03:28.000Z | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
#define FOR(i, a, b) for (int i=a; i<b; i++)
#define F0R(i, a) for (int i=0; i<a; i++)
#define f first
#define s second
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
int n, ans = 0; cin >> n;
vector<pi> cow(n);
F0R(i,n) cin >> cow[i].f >> cow[i].s;
sort(cow.begin(),cow.end());
F0R(i,n) {
int cur = cow[i].f;
FOR(j,i,n) cur += cow[j].s;
ans = max(ans,cur);
}
cout << ans;
}
| 18.96 | 44 | 0.567511 | [
"vector"
] |
ef9616983d868499b9128747ad1e974b7b4d1753 | 1,852 | cpp | C++ | COCI/coci08c6p4.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | COCI/coci08c6p4.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | COCI/coci08c6p4.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define gc getchar_unlocked()
#define pc(x) putchar_unlocked(x)
template<typename T> void scan(T &x){x = 0;register bool _=0;register T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;}
template<typename T> void printn(T n){register bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=n%10+48;n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);}
template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);}
template<typename T> void print(T n){printn(n);pc(10);}
template<typename First, typename ... Ints> void print(First arg, Ints... rest){printn(arg);pc(32);print(rest...);}
using namespace std;
vector<int> v[3];
int n, sep;
queue<int> out;
int main(){
scan(n);
for(int i = 0,a; i < n; i++){
scan(a);
v[a%3].push_back(a);
}
int a = v[0].size(), b = v[1].size(), c = v[2].size();
if((b && c && !a) || (a-1 > b+c))
return !printf("impossible\n");
if(b == n || c == n){
for(int i: v[1])
printf("%d ", i);
for(int i: v[2])
printf("%d ", i);
//.-.
pc(10);
return 0;
}
sep = v[0].back();
v[0].pop_back();
for(int i: v[1]){
if(!v[0].empty()){
out.push(v[0].back());
v[0].pop_back();
}
out.push(i);
}
out.push(sep);
for(int i: v[2]){
out.push(i);
if(!v[0].empty()){
out.push(v[0].back());
v[0].pop_back();
}
}
while(!out.empty()){
printf("%d ", out.front());
out.pop();
}
pc(10);
return 0;
} | 26.84058 | 193 | 0.456803 | [
"vector"
] |
aab39c30b0631532d76fdbd6061dd22d506a5667 | 1,629 | cpp | C++ | compiler/parser/ast_generate_impl/asign_generate.cpp | cosocaf/Pick | e21a3ff204e8cf60a40985ebda73d90f087205a9 | [
"MIT"
] | 6 | 2021-05-17T14:03:18.000Z | 2021-08-06T11:43:12.000Z | compiler/parser/ast_generate_impl/asign_generate.cpp | cosocaf/Pick | e21a3ff204e8cf60a40985ebda73d90f087205a9 | [
"MIT"
] | null | null | null | compiler/parser/ast_generate_impl/asign_generate.cpp | cosocaf/Pick | e21a3ff204e8cf60a40985ebda73d90f087205a9 | [
"MIT"
] | null | null | null | #include "ast.h"
#include "utils/vector_utils.h"
namespace pickc::parser
{
Result<ExpressionNode*, std::vector<std::string>> ASTGenerator::asignGenerate()
{
auto begin = currentTokenIter();
auto left = compGenerate();
if(!left) return error(left.err());
auto op = nextToken();
if(!op || !includes({ TokenKind::Asign, TokenKind::AddAsign, TokenKind::SubAsign, TokenKind::MulAsign, TokenKind::DivAsign, TokenKind::ModAsign }, op.get().kind)) {
backToken(true);
left.get()->tokens = std::vector(begin, currentTokenIter() + 1);
return ok(left.get());
}
if(!nextToken()) {
delete left.get();
return error(createEOTError("式が必要です。"));
}
auto right = exprGenerate();
if(!right) {
delete left.get();
return error(right.err());
}
AsignNode* node = nullptr;
switch(op.get().kind) {
case TokenKind::Asign:
node = new AsignNode(left.get(), right.get());
break;
case TokenKind::AddAsign:
node = new AddAsignNode(left.get(), right.get());
break;
case TokenKind::SubAsign:
node = new SubAsignNode(left.get(), right.get());
break;
case TokenKind::MulAsign:
node = new MulAsignNode(left.get(), right.get());
break;
case TokenKind::DivAsign:
node = new DivAsignNode(left.get(), right.get());
break;
case TokenKind::ModAsign:
node = new ModAsignNode(left.get(), right.get());
break;
default:
assert(false);
}
node->tokens = std::vector(begin, currentTokenIter() + 1);
return ok(node);
}
} | 30.166667 | 168 | 0.595457 | [
"vector"
] |
aab4324eff8a3397429c31a4a86653f4cac3ea58 | 16,928 | cpp | C++ | src/Test/TestData.cpp | rm-jooho/Simd-rm | c08628e47a8901903781bd0e3e8e875ae0ac8042 | [
"MIT"
] | 1 | 2018-12-14T06:19:36.000Z | 2018-12-14T06:19:36.000Z | src/Test/TestData.cpp | rm-jooho/Simd-rm | c08628e47a8901903781bd0e3e8e875ae0ac8042 | [
"MIT"
] | 1 | 2019-04-25T23:24:56.000Z | 2019-04-25T23:24:56.000Z | src/Test/TestData.cpp | rm-jooho/Simd-rm | c08628e47a8901903781bd0e3e8e875ae0ac8042 | [
"MIT"
] | 1 | 2020-01-31T03:16:34.000Z | 2020-01-31T03:16:34.000Z | /*
* Tests for Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Test/TestData.h"
#include "Test/TestLog.h"
#if defined(_MSC_VER)
#include <filesystem>
#else
#endif
namespace Test
{
String Data::Path(const String & name) const
{
return _path + "/" + name + ".txt";
}
bool Data::CreatePath(const String & path) const
{
#if defined(_MSC_VER)
#if _MSC_VER < 1900
if (!std::tr2::sys::exists(std::tr2::sys::path(path)))
{
if (!std::tr2::sys::create_directories(std::tr2::sys::path(path)))
{
TEST_LOG_SS(Error, "Can't create path '" << path << "'!");
return false;
}
}
#else
if (!std::experimental::filesystem::exists(std::experimental::filesystem::path(path)))
{
if (!std::experimental::filesystem::create_directories(std::experimental::filesystem::path(path)))
{
TEST_LOG_SS(Error, "Can't create path '" << path << "'!");
return false;
}
}
#endif
return true;
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
system((std::string("mkdir -p ") + path).c_str());
return true;
#pragma GCC diagnostic pop
#else
#error This platform is unsupported!
#endif
}
template <class T> bool Data::SaveArray(const T * data, size_t size, const String & name) const
{
if (!CreatePath(_path))
return false;
String path = Path(name);
std::ofstream ofs(path);
if (ofs.bad())
{
TEST_LOG_SS(Error, "Can't create file '" << path << "'!");
return false;
}
try
{
ofs << size << std::endl;
if (sizeof(T) < sizeof(int))
{
for (size_t i = 0; i < size; ++i)
ofs << (int)data[i] << " ";
}
else
{
for (size_t i = 0; i < size; ++i)
ofs << data[i] << " ";
}
ofs << std::endl;
}
catch (std::exception e)
{
TEST_LOG_SS(Error, "Can't save array to file '" << path << "', because there is an exception: " << e.what());
ofs.close();
return false;
}
ofs.close();
return true;
}
template <class T> bool Data::LoadArray(T * data, size_t size, const String & name) const
{
String path = Path(name);
std::ifstream ifs(path);
if (ifs.bad())
{
TEST_LOG_SS(Error, "Can't open file '" << path << "'!");
return false;
}
try
{
uint64_t value;
ifs >> value;
if (value != (uint64_t)size)
throw std::runtime_error("Invalid sums size!");
if (sizeof(T) < sizeof(int))
{
int tmp;
for (size_t i = 0; i < size; ++i)
{
ifs >> tmp;
data[i] = (T)tmp;
}
}
else
{
for (size_t i = 0; i < size; ++i)
ifs >> data[i];
}
}
catch (std::exception e)
{
TEST_LOG_SS(Error, "Can't load array from file '" << path << "', because there is an exception: " << e.what());
ifs.close();
return false;
}
ifs.close();
return true;
}
Data::Data(const String & test)
{
std::stringstream path;
path << ROOT_PATH << "/test/";
for (size_t i = 0; i < test.size(); ++i)
{
if (test[i] == '<')
path << '_';
else if (test[i] == '>')
path << "";
else
path << test[i];
}
_path = path.str();
}
bool Data::Save(const View & image, const String & name) const
{
if (!CreatePath(_path))
return false;
String path = Path(name);
std::ofstream ofs(path);
if (ofs.bad())
{
TEST_LOG_SS(Error, "Can't create file '" << path << "'!");
return false;
}
try
{
size_t channelCount = image.ChannelCount();
size_t channelSize = image.ChannelSize();
size_t pixelSize = image.PixelSize();
ofs << (int)image.format << " " << image.width << " " << image.height << std::endl;
if (image.format != View::Float && image.format != View::Double)
{
ofs << std::hex;
for (size_t row = 0; row < image.height; ++row)
{
for (size_t col = 0; col < image.width; ++col)
{
for (size_t channel = 0; channel < channelCount; ++channel)
{
const uint8_t * data = image.data + row*image.stride + col*pixelSize + channel*channelSize;
for (size_t i = 0; i < channelSize; ++i)
{
#ifdef SIMD_BIG_ENDIAN
ofs << (int)(data[i] >> 4);
ofs << (int)(data[i] & 0xF);
#else
ofs << (int)(data[channelSize - i - 1] >> 4);
ofs << (int)(data[channelSize - i - 1] & 0xF);
#endif
}
ofs << " ";
}
ofs << " ";
}
ofs << std::endl;
}
}
else
{
for (size_t row = 0; row < image.height; ++row)
{
for (size_t col = 0; col < image.width; ++col)
{
if (image.format == View::Float)
ofs << image.At<float>(col, row);
else
ofs << image.At<double>(col, row);
ofs << " ";
}
ofs << std::endl;
}
}
}
catch (std::exception e)
{
TEST_LOG_SS(Error, "Can't save image to file '" << path << "', because there is an exception: " << e.what());
ofs.close();
return false;
}
ofs.close();
return true;
}
bool Data::Load(View & image, const String & name) const
{
String path = Path(name);
std::ifstream ifs(path);
if (ifs.bad())
{
TEST_LOG_SS(Error, "Can't open file '" << path << "'!");
return false;
}
try
{
size_t channelCount = image.ChannelCount();
size_t channelSize = image.ChannelSize();
size_t pixelSize = image.PixelSize();
uint64_t value;
ifs >> value;
if (value != (uint64_t)image.format)
throw std::runtime_error("Invalid image format!");
ifs >> value;
if (value != (uint64_t)image.width)
throw std::runtime_error("Invalid image width!");
ifs >> value;
if (value != (uint64_t)image.height)
throw std::runtime_error("Invalid image height!");
if (image.format != View::Float && image.format != View::Double)
{
ifs >> std::hex;
for (size_t row = 0; row < image.height; ++row)
{
for (size_t col = 0; col < image.width; ++col)
{
for (size_t channel = 0; channel < channelCount; ++channel)
{
uint8_t * data = image.data + row*image.stride + col*pixelSize + channel*channelSize;
ifs >> value;
for (size_t i = 0; i < channelSize; ++i)
{
#ifdef SIMD_BIG_ENDIAN
data[i] = (value >> 8 * (channelSize - i - 1)) & 0xFF;
#else
data[i] = (value >> 8 * i) & 0xFF;
#endif
}
}
}
}
}
else
{
for (size_t row = 0; row < image.height; ++row)
{
for (size_t col = 0; col < image.width; ++col)
{
if (image.format == View::Float)
ifs >> image.At<float>(col, row);
else
ifs >> image.At<double>(col, row);
}
}
}
}
catch (std::exception e)
{
TEST_LOG_SS(Error, "Can't load image from file '" << path << "', because there is an exception: " << e.what());
ifs.close();
return false;
}
ifs.close();
return true;
}
bool Data::Save(const uint64_t & value, const String & name) const
{
return SaveArray(&value, 1, name);
}
bool Data::Load(uint64_t & value, const String & name) const
{
return LoadArray(&value, 1, name);
}
bool Data::Save(const int64_t & value, const String & name) const
{
return SaveArray(&value, 1, name);
}
bool Data::Load(int64_t & value, const String & name) const
{
uint64_t _value;
bool result = LoadArray(&_value, 1, name);
value = (int64_t)_value;
return result;
}
bool Data::Save(const uint32_t & value, const String & name) const
{
return SaveArray(&value, 1, name);
}
bool Data::Load(uint32_t & value, const String & name) const
{
return LoadArray(&value, 1, name);
}
bool Data::Save(const uint8_t & value, const String & name) const
{
uint32_t _value = value;
return SaveArray(&_value, 1, name);
}
bool Data::Load(uint8_t & value, const String & name) const
{
uint32_t _value;
bool result = LoadArray(&_value, 1, name);
value = (uint8_t)_value;
return result;
}
bool Data::Save(const double & value, const String & name) const
{
return SaveArray(&value, 1, name);
}
bool Data::Load(double & value, const String & name) const
{
return LoadArray(&value, 1, name);
}
bool Data::Save(const float & value, const String & name) const
{
return SaveArray(&value, 1, name);
}
bool Data::Load(float & value, const String & name) const
{
return LoadArray(&value, 1, name);
}
bool Data::Save(const Sums & sums, const String & name) const
{
return SaveArray(sums.data(), sums.size(), name);
}
bool Data::Load(Sums & sums, const String & name) const
{
return LoadArray(sums.data(), sums.size(), name);
}
bool Data::Save(const Histogram & histogram, const String & name) const
{
return SaveArray(histogram, Simd::HISTOGRAM_SIZE, name);
}
bool Data::Load(Histogram & histogram, const String & name) const
{
return LoadArray(histogram, Simd::HISTOGRAM_SIZE, name);
}
bool Data::Save(const Sums64 & sums, const String & name) const
{
return SaveArray(sums.data(), sums.size(), name);
}
bool Data::Load(Sums64 & sums, const String & name) const
{
return LoadArray(sums.data(), sums.size(), name);
}
bool Data::Save(const Rect & rect, const String & name) const
{
return SaveArray((const ptrdiff_t *)&rect, 4, name);
}
bool Data::Load(Rect & rect, const String & name) const
{
return LoadArray((ptrdiff_t *)&rect, 4, name);
}
bool Data::Save(const std::vector<uint8_t> & data, const String & name) const
{
return SaveArray(data.data(), data.size(), name);
}
bool Data::Load(std::vector<uint8_t> & data, const String & name) const
{
return LoadArray(data.data(), data.size(), name);
}
bool Data::Save(const Buffer32f & buffer, const String & name) const
{
return SaveArray(buffer.data(), buffer.size(), name);
}
bool Data::Load(Buffer32f & buffer, const String & name) const
{
return LoadArray(buffer.data(), buffer.size(), name);
}
String Data::Description(SimdCompareType type)
{
switch (type)
{
case SimdCompareEqual:
return "_Equal";
case SimdCompareNotEqual:
return "_NotEqual";
case SimdCompareGreater:
return "_Greater";
case SimdCompareGreaterOrEqual:
return "_GreaterOrEqual";
case SimdCompareLesser:
return "_Lesser";
case SimdCompareLesserOrEqual:
return "_LesserOrEqual";
}
assert(0);
return "_Unknown";
}
String Data::Description(SimdOperationBinary8uType type)
{
switch (type)
{
case SimdOperationBinary8uAverage:
return "_Average";
case SimdOperationBinary8uAnd:
return "_And";
case SimdOperationBinary8uOr:
return "_Or";
case SimdOperationBinary8uMaximum:
return "_Maximum";
case SimdOperationBinary8uMinimum:
return "_Minimum";
case SimdOperationBinary8uSaturatedSubtraction:
return "_SaturatedSubtraction";
case SimdOperationBinary8uSaturatedAddition:
return "_SaturatedAddition";
}
assert(0);
return "_Unknown";
}
String Data::Description(SimdOperationBinary16iType type)
{
switch (type)
{
case SimdOperationBinary16iAddition:
return "_Addition";
case SimdOperationBinary16iSubtraction:
return "_Subtraction";
}
assert(0);
return "_Unknown";
}
String Data::Description(View::Format format)
{
switch (format)
{
case View::None:
return "_None";
case View::Gray8:
return "_Gray8";
case View::Uv16:
return "_Uv16";
case View::Bgr24:
return "_Bgr24";
case View::Bgra32:
return "_Bgra32";
case View::Int16:
return "_Int16";
case View::Int32:
return "_Int32";
case View::Int64:
return "_Int64";
case View::Float:
return "_Float";
case View::Double:
return "_Double";
case View::BayerGrbg:
return "_BayerGrgb";
case View::BayerGbrg:
return "_BayerGbgr";
case View::BayerRggb:
return "_BayerRggb";
case View::BayerBggr:
return "_BayerBggr";
case View::Hsv24:
return "_Hsv24";
case View::Hsl24:
return "_Hsl24";
}
assert(0);
return "_Unknown";
}
}
| 30.778182 | 124 | 0.474421 | [
"vector"
] |
aabaf89c61121fa00d7350b8345c2f7602f5ba7a | 5,733 | cpp | C++ | src/data/ReTextureCreator.cpp | danielbui78/reality | 7ecd01b71f28e581becfe5093fab3ddcd6d9b2c1 | [
"BSD-3-Clause"
] | 2 | 2021-12-25T17:24:03.000Z | 2022-03-14T05:07:51.000Z | src/data/ReTextureCreator.cpp | danielbui78/reality | 7ecd01b71f28e581becfe5093fab3ddcd6d9b2c1 | [
"BSD-3-Clause"
] | null | null | null | src/data/ReTextureCreator.cpp | danielbui78/reality | 7ecd01b71f28e581becfe5093fab3ddcd6d9b2c1 | [
"BSD-3-Clause"
] | 2 | 2021-12-10T05:33:04.000Z | 2021-12-10T16:38:54.000Z | /*
Reality plug-in
Copyright (c) Pret-a-3D/Paolo Ciccone 2012. All rights reserved.
*/
#include "ReTextureCreator.h"
#include "textures/ReMix.h"
#include "textures/ReGrayscale.h"
#include "textures/ReImageMap.h"
#include "textures/ReMath.h"
#include "textures/ReColorMath.h"
#include "textures/ReFresnelColor.h"
#include "textures/ReBand.h"
#include "textures/ReClouds.h"
#include "textures/ReMarble.h"
#include "textures/ReWood.h"
#include "textures/ReDistortedNoise.h"
#include "textures/ReCheckers.h"
#include "textures/ReFBM.h"
#include "textures/ReInvertMap.h"
#include "textures/ReBricks.h"
#include "importers/qt/ReQtTextureImporterFactory.h"
#include "ReTextureContainer.h"
#include "ReTools.h"
namespace Reality {
ReTexture* TextureCreator::createTexture( const QString texName,
const ReTextureType texType,
ReTextureContainer* parentMat,
const ReTexture::ReTextureDataType dataType )
{
ReTexture* tex = NULL;
switch(texType) {
case TexImageMap: {
tex = new ImageMap(texName, parentMat, "", dataType);
break;
}
case TexMath: {
tex = new ReMath(texName, parentMat);
break;
}
case TexColorMath: {
tex = new ReColorMath(texName, parentMat);
break;
}
case TexBand: {
tex = new ReBand(texName, parentMat);
break;
}
case TexBricks: {
tex = new Bricks(texName, parentMat, dataType);
break;
}
case TexCheckers: {
tex = new ReCheckers(texName, parentMat);
break;
}
case TexClouds: {
tex = new Clouds(texName, parentMat);
break;
}
case TexConstant: {
tex = new ReConstant(texName, parentMat);
tex->setTextureDataType(dataType);
break;
}
case TexFBM: {
tex = new ReFBM(texName, parentMat);
break;
}
case TexFresnelColor: {
tex = new ReFresnelColor(texName, parentMat);
break;
}
case TexMarble: {
tex = new ReMarble(texName, parentMat);
break;
}
case TexWood: {
tex = new ReWood(texName, parentMat);
break;
}
case TexMix: {
tex = new ReMixTexture(texName, parentMat, dataType);
break;
}
case TexMultiMix: {
tex = new MultiMix(texName, parentMat);
break;
}
case TexDistortedNoise: {
tex = new ReDistortedNoise(texName, parentMat);
break;
}
case TexInvertMap: {
tex = new InvertMap(texName, parentMat);
break;
}
case TexGrayscale: {
tex = new ReGrayscale(texName, parentMat);
break;
}
case TexUndefined: {
// Nothing yet, throw an exception?
}
}
return tex;
}
ReTexture* TextureCreator::createTexture( const QString texName,
const ReTexturePtr baseTex )
{
ReTexture* tex = NULL;
switch(baseTex->type) {
case TexImageMap: {
tex = new ImageMap(baseTex);
break;
}
case TexMath: {
tex = new ReMath(baseTex);
break;
}
case TexColorMath: {
tex = new ReColorMath(baseTex);
break;
}
case TexBand: {
tex = new ReBand(baseTex);
break;
}
case TexBricks: {
tex = new Bricks(baseTex);
break;
}
case TexCheckers: {
tex = new ReCheckers(baseTex);
break;
}
case TexClouds: {
tex = new Clouds(baseTex);
break;
}
case TexConstant: {
tex = new ReConstant(baseTex);
break;
}
case TexFBM: {
tex = new ReFBM(baseTex);
break;
}
case TexFresnelColor: {
tex = new ReFresnelColor(baseTex);
break;
}
case TexMarble: {
tex = new ReMarble(baseTex);
break;
}
case TexMix: {
tex = new ReMixTexture(baseTex);
break;
}
case TexMultiMix: {
tex = new MultiMix(baseTex);
break;
}
case TexDistortedNoise: {
tex = new ReDistortedNoise(baseTex);
break;
}
case TexWood: {
tex = new ReWood(baseTex);
break;
}
case TexInvertMap: {
tex = new InvertMap(baseTex);
break;
}
case TexGrayscale: {
tex = new ReGrayscale(baseTex);
break;
}
case TexUndefined: {
// Nothing yet, throw an exception?
}
}
tex->setName(texName);
return tex;
}
ReTexturePtr TextureCreator::createTexture( const QVariantMap& data,
ReTextureContainer* parentMat )
{
ReTexturePtr tex;
QString texName = data.value("name").toString();
ReTextureType texType = static_cast<ReTextureType>(data.value("type").toInt());
tex = ReTexturePtr(
createTexture( texName,
texType,
parentMat )
);
ReQtTextureImporterPtr texImporter = ReQtTextureImporterFactory::getImporter(texType);
texImporter->restoreTexture(tex, data);
return tex;
}
ReTexturePtr TextureCreator::deserialize( QDataStream& dataStream,
ReTextureContainer* parentMat )
{
// Save the position before looking ahead
quint64 currentPos = dataStream.device()->pos();
quint16 type, dataType;
QString name;
dataStream >> type >> name >> dataType;
// Restore the original position
dataStream.device()->seek(currentPos);
ReTexture* tex = createTexture( name,
static_cast<ReTextureType>(type),
parentMat,
static_cast<ReTexture::ReTextureDataType>(dataType) );
if (tex) {
tex->deserialize(dataStream);
}
return ReTexturePtr(tex);
}
} | 24.60515 | 88 | 0.587127 | [
"3d"
] |
aabb2a8145ec37352913db218edda7ea0c1530ad | 4,275 | cpp | C++ | src/LLP/permissions.cpp | beuschl/LLL-TAO | 639b9a3e010db3938095b015da35d3fd845d2666 | [
"MIT"
] | null | null | null | src/LLP/permissions.cpp | beuschl/LLL-TAO | 639b9a3e010db3938095b015da35d3fd845d2666 | [
"MIT"
] | null | null | null | src/LLP/permissions.cpp | beuschl/LLL-TAO | 639b9a3e010db3938095b015da35d3fd845d2666 | [
"MIT"
] | null | null | null | /*__________________________________________________________________________________________
(c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++
(c) Copyright The Nexus Developers 2014 - 2019
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
"ad vocem populi" - To the Voice of the People
____________________________________________________________________________________________*/
#include <LLP/include/permissions.h>
#include <LLP/include/port.h>
#include <Util/include/args.h>
#include <Util/include/string.h>
#include <Util/include/debug.h>
/* IP Filtering Definitions. IP's are Filtered By Ports. */
bool CheckPermissions(const std::string &strAddress, uint16_t nPort)
{
/* Bypass localhost addresses first. */
if(strAddress == "127.0.0.1" || strAddress == "::1")
return true;
/* Split the Address into String Vector. */
std::vector<std::string> vAddress = Split(strAddress, '.');
if(vAddress.size() != 4)
return debug::error("Address size not at least 4 bytes.");
/* Determine whether or not the current port is open by default, or closed requiring an llpallowip whitelist.
* Ports open by default can also use a whitelist, and will no longer be treated as open for other addresses */
bool fOpen = false;
if(config::fTestNet.load())
{
/* Testnet ports open only for testnet */
if(nPort == static_cast<uint16_t>(config::GetArg(std::string("-serverport"), (TRITIUM_TESTNET_PORT + (config::GetArg("-testnet", 0) - 1))))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-serversslport"), (TRITIUM_TESTNET_SSL_PORT + (config::GetArg("-testnet", 0) - 1))))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-port"), (TRITIUM_TESTNET_PORT + (config::GetArg("-testnet", 0) - 1))))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-sslport"), (TRITIUM_TESTNET_SSL_PORT + (config::GetArg("-testnet", 0) - 1))))
|| nPort == static_cast<uint16_t>(TESTNET_TIME_LLP_PORT)
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-p2pport"), TESTNET_P2P_PORT ))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-p2psslport"), TESTNET_P2P_SSL_PORT )))
fOpen = true;
}
else
{
/* Mainnet ports open only for mainnet */
if(nPort == static_cast<uint16_t>(config::GetArg(std::string("-serverport"), TRITIUM_MAINNET_PORT))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-serversslport"), TRITIUM_MAINNET_SSL_PORT))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-port"), TRITIUM_MAINNET_PORT))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-sslport"), TRITIUM_MAINNET_SSL_PORT))
|| nPort == static_cast<uint16_t>(MAINNET_TIME_LLP_PORT)
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-p2pport"), MAINNET_P2P_PORT ))
|| nPort == static_cast<uint16_t>(config::GetArg(std::string("-p2psslport"), MAINNET_P2P_SSL_PORT )))
fOpen = true;
}
/* If no llpallowip whitelist defined for a default open port then we assume permission */
if(config::mapIPFilters[nPort].size() == 0 && fOpen)
return true;
/* Check against the llpallowip list from config / commandline parameters. */
for(const auto& strIPFilter : config::mapIPFilters[nPort])
{
/* Split the components of the IP so that we can check for wildcard ranges. */
std::vector<std::string> vCheck = Split(strIPFilter, '.');
/* Skip invalid inputs. */
if(vCheck.size() != 4)
continue;
/* Check the components of IP address. */
bool fIPMatches = true;
for(uint8_t nByte = 0; nByte < 4; ++nByte)
{
if(vCheck[nByte] != "*" && vCheck[nByte] != vAddress[nByte])
fIPMatches = false;
}
/* if the IP matches then the address being checked is on the whitelist */
if(fIPMatches)
return true;
}
return false;
}
| 46.467391 | 158 | 0.645146 | [
"vector"
] |
aacd8a3ed3d1a25658b8d9f8f8be34fd8148754d | 7,059 | hpp | C++ | include/glowl/Texture.hpp | moritz-h/glowl | 8f8a366a1ab3a68f8d3c1410a09eb0185d9ac75c | [
"MIT"
] | null | null | null | include/glowl/Texture.hpp | moritz-h/glowl | 8f8a366a1ab3a68f8d3c1410a09eb0185d9ac75c | [
"MIT"
] | null | null | null | include/glowl/Texture.hpp | moritz-h/glowl | 8f8a366a1ab3a68f8d3c1410a09eb0185d9ac75c | [
"MIT"
] | null | null | null | /*
* Texture.hpp
*
* MIT License
* Copyright (c) 2019 Michael Becher
*/
#ifndef GLOWL_TEXTURE_HPP
#define GLOWL_TEXTURE_HPP
#include <string>
#include <vector>
#include "glinclude.h"
namespace glowl
{
struct TextureLayout
{
TextureLayout() : internal_format(0), width(0), height(0), depth(0), format(0), type(0), levels(0) {}
/**
* \param internal_format Specifies the (sized) internal format of a texture (e.g. GL_RGBA32F)
* \param width Specifies the width of the texture in pixels.
* \param height Specifies the height of the texture in pixels. Will be ignored by Texture1D.
* \param depth Specifies the depth of the texture in pixels. Will be ignored by Texture1D and Texture2D.
* \param format Specifies the format of the texture (e.g. GL_RGBA)
* \param type Specifies the type of the texture (e.g. GL_FLOAT)
*/
TextureLayout(GLint internal_format,
int width,
int height,
int depth,
GLenum format,
GLenum type,
GLsizei levels)
: internal_format(internal_format),
width(width),
height(height),
depth(depth),
format(format),
type(type),
levels(levels)
{
}
/**
* \param internal_format Specifies the (sized) internal format of a texture (e.g. GL_RGBA32F)
* \param width Specifies the width of the texture in pixels.
* \param height Specifies the height of the texture in pixels. Will be ignored by Texture1D.
* \param depth Specifies the depth of the texture in pixels. Will be ignored by Texture1D and Texture2D.
* \param format Specifies the format of the texture (e.g. GL_RGBA)
* \param type Specifies the type of the texture (e.g. GL_FLOAT)
* \param int_parameters A list of integer texture parameters, each given by a pair of name and value (e.g.
* {{GL_TEXTURE_SPARSE_ARB,GL_TRUE},{...},...} \param int_parameters A list of float texture parameters, each
* given by a pair of name and value (e.g. {{GL_TEXTURE_MAX_ANISOTROPY_EX,4.0f},{...},...}
*/
TextureLayout(GLint internal_format,
int width,
int height,
int depth,
GLenum format,
GLenum type,
GLsizei levels,
std::vector<std::pair<GLenum, GLint>> const& int_parameters,
std::vector<std::pair<GLenum, GLfloat>> const& float_parameters)
: internal_format(internal_format),
width(width),
height(height),
depth(depth),
format(format),
type(type),
levels(levels),
int_parameters(int_parameters),
float_parameters(float_parameters)
{
}
TextureLayout(GLint internal_format,
int width,
int height,
int depth,
GLenum format,
GLenum type,
GLsizei levels,
std::vector<std::pair<GLenum, GLint>>&& int_parameters,
std::vector<std::pair<GLenum, GLfloat>>&& float_parameters)
: internal_format(internal_format),
width(width),
height(height),
depth(depth),
format(format),
type(type),
levels(levels),
int_parameters(int_parameters),
float_parameters(float_parameters)
{
}
GLint internal_format;
int width;
int height;
int depth;
GLenum format;
GLenum type;
GLsizei levels;
std::vector<std::pair<GLenum, GLint>> int_parameters;
std::vector<std::pair<GLenum, GLfloat>> float_parameters;
};
/**
* \class Texture
*
* \brief Abstract base class for various OpenGL texture Objects (2D,3D,2DArray).
*
* \author Michael Becher
*/
class Texture
{
protected:
std::string m_id; ///< Identifier set by application to help identifying textures
GLuint m_name; ///< OpenGL texture name given by glCreateTexture
#ifndef GLOWL_NO_ARB_BINDLESS_TEXTURE
GLuint64 m_texture_handle; ///< Actual OpenGL texture handle (used for bindless)
#endif
GLenum m_internal_format;
GLenum m_format;
GLenum m_type;
GLsizei m_levels;
// TODO: Store texture parameters as well ?
public:
Texture(std::string id, GLint internal_format, GLenum format, GLenum type, GLsizei levels)
: m_id(id), m_internal_format(internal_format), m_format(format), m_type(type), m_levels(levels) {}
virtual ~Texture() {}
Texture(const Texture&) = delete;
virtual void bindTexture() const = 0;
void bindImage(GLuint location, GLenum access) const
{
glBindImageTexture(location, m_name, 0, GL_TRUE, 0, access, m_internal_format);
}
#ifndef GLOWL_NO_ARB_BINDLESS_TEXTURE
void makeResident()
{
glMakeTextureHandleResidentARB(m_texture_handle);
}
void makeNonResident()
{
glMakeTextureHandleNonResidentARB(m_texture_handle);
}
#endif
virtual void updateMipmaps() = 0;
virtual TextureLayout getTextureLayout() const = 0;
std::string getId() const
{
return m_id;
}
GLuint getName() const
{
return m_name;
}
#ifndef GLOWL_NO_ARB_BINDLESS_TEXTURE
GLuint64 getTextureHandle() const
{
return m_texture_handle;
}
GLuint64 getImageHandle(GLint level, GLboolean layered, GLint layer) const
{
return glGetImageHandleARB(m_name, level, layered, layer, m_internal_format);
}
#endif
GLenum getInternalFormat() const
{
return m_internal_format;
}
GLenum getFormat() const
{
return m_format;
}
GLenum getType() const
{
return m_type;
}
};
} // namespace glowl
#endif // GLOWL_TEXTURE_HPP
| 35.119403 | 117 | 0.518204 | [
"vector",
"3d"
] |
aad16e6f35ad038f7e0363f783e6368b8c4d6ec8 | 295 | cpp | C++ | base/source/spec/SynapseAlias.cpp | Kobrs/ncs | 0ae53ad7bf378675161e23a25e09468d6b383ab0 | [
"BSD-2-Clause"
] | 9 | 2015-06-20T16:22:23.000Z | 2021-04-13T10:12:48.000Z | base/source/spec/SynapseAlias.cpp | Kobrs/ncs | 0ae53ad7bf378675161e23a25e09468d6b383ab0 | [
"BSD-2-Clause"
] | null | null | null | base/source/spec/SynapseAlias.cpp | Kobrs/ncs | 0ae53ad7bf378675161e23a25e09468d6b383ab0 | [
"BSD-2-Clause"
] | 6 | 2015-07-26T00:20:07.000Z | 2021-03-12T06:43:56.000Z | #include <ncs/spec/SynapseAlias.h>
namespace ncs {
namespace spec {
SynapseAlias::SynapseAlias(const std::vector<SynapseGroup*>& groups)
: groups_(groups) {
}
const std::vector<SynapseGroup*>& SynapseAlias::getGroups() const {
return groups_;
}
} // namespace spec
} // namespace ncs
| 15.526316 | 68 | 0.715254 | [
"vector"
] |
aad467efb3ed69152540317a63fde2ce67c394bd | 56,500 | cpp | C++ | parser/east.cpp | PowerAngelXD/EytionPlusPlus | 36fc7caf67d2ef6a35fb0d0cdaddbefc8a24af90 | [
"MIT"
] | 13 | 2022-01-15T00:41:33.000Z | 2022-03-17T13:02:58.000Z | parser/east.cpp | PowerAngelXD/EytionPlusPlus | 36fc7caf67d2ef6a35fb0d0cdaddbefc8a24af90 | [
"MIT"
] | null | null | null | parser/east.cpp | PowerAngelXD/EytionPlusPlus | 36fc7caf67d2ef6a35fb0d0cdaddbefc8a24af90 | [
"MIT"
] | null | null | null | #include "east.h"
//astParser
east::astParser::astParser(std::vector<epplex::Token> tg_) : tg(tg_) {}
epplex::Token* east::astParser::peek(int pos_){
return new epplex::Token(this->tg[this->pos + pos_]);
}
epplex::Token* east::astParser::token(){
return new epplex::Token(this->tg[this->pos++]);
}
east::WholeExprNode* east::astParser::gen_wholeExprNode(){
if(east::WholeExprNode::is(*this)){
east::WholeExprNode* node = new east::WholeExprNode;
if(east::AssignExprNode::is(*this)) node->assignexpr = gen_assignExprNode();
else if(east::ValExprNode::is(*this)) node->valexpr = gen_valExprNode();
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::ValExprNode* east::astParser::gen_valExprNode(){
east::ValExprNode* node = new east::ValExprNode;
if(east::ListExprNode::is(*this))
node->listexpr = gen_listExprNode();
else if(east::BoolExprNode::is(*this))
node->boolexpr = gen_boolExprNode();
else if(east::FuncDefineExprNode::is(*this))
node->fdefexpr = gen_fdefExprNode();
else
node->addexpr = gen_addExprNode();
return node;
}
east::AddOpNode* east::astParser::gen_addOpNode(){
if(east::AddOpNode::is(*this)){
east::AddOpNode* node = new east::AddOpNode;
node->op = token();
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '+' or '-'!", tg[pos].line, tg[pos].column);
}
east::MulOpNode* east::astParser::gen_mulOpNode(){
if(east::MulOpNode::is(*this)){
east::MulOpNode* node = new east::MulOpNode;
node->op = token();
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '/', '*' or '%'!", tg[pos].line, tg[pos].column);
}
east::CmpOpNode* east::astParser::gen_cmpOpNode(){
if(east::CmpOpNode::is(*this)){
east::CmpOpNode* node = new east::CmpOpNode;
node->op = token();
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '==', '!=', '>', '<', '>=' or '<='!", tg[pos].line, tg[pos].column);
}
east::BoolOpNode* east::astParser::gen_boolOpNode(){
if(east::BoolOpNode::is(*this)){
east::BoolOpNode* node = new east::BoolOpNode;
node->op = token();
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '||' or '&&'!", tg[pos].line, tg[pos].column);
}
east::IndexOpNode* east::astParser::gen_indexOpNode(){
if(east::IndexOpNode::is(*this)){
east::IndexOpNode* node = new east::IndexOpNode;
node->left = token();
if(AddExprNode::is(*this)) node->begin = gen_addExprNode();
else throw epperr::Epperr("SyntaxError", "Expect an Add-expression!", tg[pos].line, tg[pos].column);
if(peek()->content == ":"){
node ->spliter = token();
if(AddExprNode::is(*this)) node->end = gen_addExprNode();
else throw epperr::Epperr("SyntaxError", "Expect an Add-expression!", tg[pos].line, tg[pos].column);
}
if(peek()->content == "]") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect an Add-expression!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '['", tg[pos].line, tg[pos].column);
}
east::EquOpNode* east::astParser::gen_equOpNode(){
if(east::EquOpNode::is(*this)){
east::EquOpNode* node = new east::EquOpNode;
node->op = token();
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '='", tg[pos].line, tg[pos].column);
}
east::AssignExprNode* east::astParser::gen_assignExprNode(){
if(east::AssignExprNode::is(*this)){
east::AssignExprNode* node = new east::AssignExprNode;
node->iden = gen_identifierNode();
if(peek()->content == "=") node->op = gen_equOpNode();
else throw epperr::Epperr("SyntaxError", "Expect '='!", tg[pos].line, tg[pos].column);
node->val = gen_valExprNode();
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Assign statement format", tg[pos].line, tg[pos].column);
}
east::BifNode* east::astParser::gen_bifNode(){
if(east::BifNode::is(*this)){
east::BifNode* node = new east::BifNode;
if(east::LenExprNode::is(*this)) node->len = gen_lenExprNode();
else if(east::TypeOfExprNode::is(*this)) node->typef = gen_tpofExprNode();
else if(east::TypeToExprNode::is(*this)) node->tyt = gen_tytExprNode();
else if(east::InputExprNode::is(*this)) node->input = gen_inputExprNode();
else if(east::PrintoLnExprNode::is(*this)) node->print = gen_polnExprNode();
else if(east::BifInstanceNode::is(*this)) node->bifi = gen_bifiExprNode();
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Non existent built-in function", tg[pos].line, tg[pos].column);
}
east::PrimExprNode* east::astParser::gen_primExprNode(){
if(east::PrimExprNode::is(*this)){
east::PrimExprNode* node = new east::PrimExprNode;
if(east::FuncCallExprNode::is(*this)) node->fcall = gen_fcallExprNode();
else if(peek()->content == "null") node->null = token();
else if(east::SelfIaDExprNode::is(*this)) node->siad = gen_siadExprNode();
else if(east::BifNode::is(*this)) node->bif= gen_bifNode();
else if(peek()->type == "__IDENTIFIER__") node->iden = gen_identifierNode();
else if(peek()->type == "__NUMBER__") node->number = token();
else if(peek()->type == "__STRING__") node->str = token();
else if(peek()->type == "__CHAR__") node->ch = token();
else if(peek()->content == "true" || peek()->content == "false") node->boolconst = token();
else if(peek()->content == "(") {
node->left = token();
if(east::AddExprNode::is(*this)){
node->addexpr = gen_addExprNode();
}
else if(east::BoolExprNode::is(*this)){
node->boolexpr = gen_boolExprNode();
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!!", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
}
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::SelfIaDExprNode* east::astParser::gen_siadExprNode(){
if(east::SelfIaDExprNode::is(*this)){
east::SelfIaDExprNode* node = new east::SelfIaDExprNode;
if(peek()->content == "++" || peek()->content == "--") {
node->op = token();
node->isFront = true;
}
else node->iden = gen_identifierNode();
if(node->isFront == true && peek()->type == "__IDENTIFIER__") node->iden = gen_identifierNode();
else if(peek()->content == "++" || peek()->content == "--") node->op = token();
else throw epperr::Epperr("SyntaxErrror", "Expect '++', '--' or an identifier!", tg[pos].line, tg[pos].column);;
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::FuncCallExprNode* east::astParser::gen_fcallExprNode(){
if(east::FuncCallExprNode::is(*this)){
east::FuncCallExprNode* node = new east::FuncCallExprNode;
node->func_name = gen_identifierNode();token();
if(east::ValExprNode::is(*this)) node->act_paras.push_back(gen_valExprNode());
bool begin = false;
while(true){
if(peek()->content != ",") break;
token();
node->act_paras.push_back(gen_valExprNode());
}
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::InputExprNode* east::astParser::gen_inputExprNode(){
if(east::InputExprNode::is(*this)){
east::InputExprNode* node = new east::InputExprNode;
node->mark = token();
if(peek()->content == "(") token();
else throw epperr::Epperr("SyntaxErrror", "Expect '('!", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->expr = gen_valExprNode();
else ;
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::TypeOfExprNode* east::astParser::gen_tpofExprNode(){
if(east::TypeOfExprNode::is(*this)){
east::TypeOfExprNode* node = new east::TypeOfExprNode;
node->mark = token();
if(peek()->content == "(") token();
else throw epperr::Epperr("SyntaxErrror", "Expect '('!", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->expr = gen_valExprNode();
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::LenExprNode* east::astParser::gen_lenExprNode(){
if(east::LenExprNode::is(*this)){
east::LenExprNode* node = new east::LenExprNode;
node->mark = token();
if(peek()->content == "(") token();
else throw epperr::Epperr("SyntaxErrror", "Expect '('!", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->expr = gen_valExprNode();
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::PrintoLnExprNode* east::astParser::gen_polnExprNode(){
if(east::PrintoLnExprNode::is(*this)){
east::PrintoLnExprNode* node = new east::PrintoLnExprNode;
node->mark = token();
if(peek()->content == "(") token();
else throw epperr::Epperr("SyntaxErrror", "Expect '('!", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->expr = gen_valExprNode();
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::TypeToExprNode* east::astParser::gen_tytExprNode(){
if(east::TypeToExprNode::is(*this)){
east::TypeToExprNode* node = new east::TypeToExprNode;
node->mark = token();
if(peek()->content == "(") token();
else throw epperr::Epperr("SyntaxErrror", "Expect '('!", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->expr = gen_valExprNode();
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::BifInstanceNode* east::astParser::gen_bifiExprNode(){
if(east::BifInstanceNode::is(*this)){
east::BifInstanceNode* node = new east::BifInstanceNode;
node->mark = token();
if(peek()->content == "(") token();
else throw epperr::Epperr("SyntaxErrror", "Expect '('!", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)){
node->paras.push_back(gen_valExprNode());
while(true){
if(peek()->content != ",") break;
node->dots.push_back(token());
node->paras.push_back(gen_valExprNode());
}
}
if(peek()->content == ")") token();
else throw epperr::Epperr("SyntaxErrror", "Expect ')'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::IdentifierNode* east::astParser::gen_identifierNode(){
if(east::IdentifierNode::is(*this)){
east::IdentifierNode* node = new east::IdentifierNode;
if(peek(1)->content == "["){
east::IdentifierNode* n = new east::IdentifierNode("__ARRE__");
n->idens.push_back(token());
if(east::IndexOpNode::is(*this)){
n->indexops.push_back(gen_indexOpNode());
while(true){
if(peek()->content != "[") break;
n->indexops.push_back(gen_indexOpNode());
}
}
node = n;
}
else{
east::IdentifierNode* n = new east::IdentifierNode("__PURE__");
n->idens.push_back(token());
while(true){
if(peek()->content != ".") break;
n->dots.push_back(token());
n->idens.push_back(token());
}
node = n;
}
return node;
}
else throw epperr::Epperr("SyntaxErrror", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::AddExprNode* east::astParser::gen_addExprNode(){
if(east::AddExprNode::is(*this)){
east::AddExprNode* node = new east::AddExprNode;
node->muls.push_back(gen_mulExprNode());
while(true){
if(!east::AddOpNode::is(*this)) break;
node->ops.push_back(gen_addOpNode());
node->muls.push_back(gen_mulExprNode());
}
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::MulExprNode* east::astParser::gen_mulExprNode(){
if(east::MulExprNode::is(*this)){
east::MulExprNode* node = new east::MulExprNode;
node->prims.push_back(gen_primExprNode());
while(true){
if(!east::MulOpNode::is(*this)) break;
node->ops.push_back(gen_mulOpNode());
node->prims.push_back(gen_primExprNode());
}
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::CmpExprNode* east::astParser::gen_cmpExprNode(){
if(east::CmpExprNode::is(*this)){
east::CmpExprNode* node = new east::CmpExprNode;
node->expr = gen_addExprNode();
if(east::CmpOpNode::is(*this)) node->op = gen_cmpOpNode();
if(east::AddExprNode::is((*this))) node->target = gen_addExprNode();
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::BoolExprNode* east::astParser::gen_boolExprNode(){
if(east::BoolExprNode::is(*this)){
east::BoolExprNode* node = new east::BoolExprNode;
if(peek()->content == "!") node->notsign = token();
node->cmps.push_back(gen_cmpExprNode());
while(true){
if(!east::BoolOpNode::is(*this)) break;
node->ops.push_back(gen_boolOpNode());
node->cmps.push_back(gen_cmpExprNode());
}
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
east::ListExprNode* east::astParser::gen_listExprNode(){
if(east::ListExprNode::is(*this)){
east::ListExprNode* node = new east::ListExprNode;
node->left = token();
node->arrayelts.push_back(gen_valExprNode());
while(true){
if(peek()->content != ",") break;
token();
node->arrayelts.push_back(gen_valExprNode());
}
if(peek()->content == "]") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ']'!", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "Expect '['!", tg[pos].line, tg[pos].column);
}
east::FuncDefineExprNode* east::astParser::gen_fdefExprNode(){
if(east::FuncDefineExprNode::is(*this)){
east::FuncDefineExprNode* node = new east::FuncDefineExprNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('!", tg[pos].line, tg[pos].column);
while(true){
if(peek()->type != "__IDENTIFIER__") break;
node->paras.push_back(new east::FuncDefineExprNode::Para(token(),token(),token()));
if(peek()->content == ",") node->dots.push_back(token());
}
for(int i = 0; i<node->paras.size(); i++){
if(node->paras[i]->type->content == "integer" || node->paras[i]->type->content == "string" || node->paras[i]->type->content == "boolean" || node->paras[i]->type->content == "decimal" || node->paras[i]->type->content == "char");
else throw epperr::Epperr("SyntaxError", "Expect type specifier !", tg[pos].line, tg[pos].column);
}
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'!", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", tg[pos].line, tg[pos].column);
}
//stmt
east::StatNode* east::astParser::gen_statNode(){
if(east::StatNode::is(*this)){
east::StatNode* node = new east::StatNode;
while(east::StmtNode::is(*this)){
node->stmts.emplace_back(gen_stmtNode());
}
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the stmt!", tg[pos].line, tg[pos].column);
}
east::StmtNode* east::astParser::gen_stmtNode(){
if(east::StmtNode::is(*this)){
east::StmtNode* node = new east::StmtNode;
if(east::ExprStmtNode::is(*this)) node->exprstmt = gen_exprStmtNode();
else if(east::OutStmtNode::is(*this)) node->outstmt = gen_outStmtNode();
else if(east::VorcStmtNode::is(*this)) node->vorcstmt = gen_vorcStmtNode();
else if(east::DeleteStmtNode::is(*this)) node->deletestmt = gen_delStmtNode();
else if(east::BlockStmtNode::is(*this)) node->blockstmt = gen_blockStmtNode();
else if(east::IfStmtNode::is(*this)) node->ifstmt = gen_ifStmtNode();
else if(east::ElseifStmtNode::is(*this)) node->elifstmt = gen_elifStmtNode();
else if(east::ElseStmtNode::is(*this)) node->elsestmt = gen_elseStmtNode();
else if(east::BreakStmtNode::is(*this)) node->brkstmt = gen_brkStmtNode();
else if(east::WhileStmtNode::is(*this)) node->whilestmt = gen_whileStmtNode();
else if(east::RepeatStmtNode::is(*this)) node->reptstmt = gen_reptStmtNode();
else if(east::ForEachStmtNode::is(*this)) node->foreachstmt = gen_foreachStmtNode();
else if(east::ForStmtNode::is(*this)) node->forstmt = gen_forStmtNode();
else if(east::AreaStmtNode::is(*this)) node->areastmt = gen_areaStmtNode();
else if(east::ReturnStmtNode::is(*this)) node->returnstmt = gen_retStmtNode();
return node;
}
else throw epperr::Epperr("SyntaxError", "Unknown type of the stmt!", tg[pos].line, tg[pos].column);
}
east::ExprStmtNode* east::astParser::gen_exprStmtNode(){
if(east::ExprStmtNode::is(*this)){
east::ExprStmtNode* node = new east::ExprStmtNode;
if(east::BifNode::is(*this)) node->expr = gen_valExprNode();
else if(east::SelfIaDExprNode::is(*this)) node->expr = gen_valExprNode();
else if(east::AssignExprNode::is(*this)) node->assign = gen_assignExprNode();
else if(east::FuncCallExprNode::is(*this)) node->expr = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "It is not a proper statement format", tg[pos].line, tg[pos].column);
if(peek()->content == ";") node->end = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Expression statement format", tg[pos].line, tg[pos].column);
}
east::ReturnStmtNode* east::astParser::gen_retStmtNode(){
if(east::ReturnStmtNode::is(*this)){
east::ReturnStmtNode* node = new east::ReturnStmtNode;
node->mark = token();
if(east::ValExprNode::is(*this)) node->value = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
if(peek()->content == ";") node->end = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
return node;
}
}
east::OutStmtNode* east::astParser::gen_outStmtNode(){
if(east::OutStmtNode::is(*this)){
east::OutStmtNode* node = new east::OutStmtNode;
node->mark = token();
if(east::ValExprNode::is(*this)) node->content = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "Requires an expression", tg[pos].line, tg[pos].column);
if(peek()->content == ";") node->end = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Out statement format", tg[pos].line, tg[pos].column);
}
east::VorcStmtNode* east::astParser::gen_vorcStmtNode(){
if(east::VorcStmtNode::is(*this)){
east::VorcStmtNode* node = new east::VorcStmtNode;
bool ready_type = false;
node->mark = token();
if(peek()->type == "__IDENTIFIER__") node->iden = token();
else throw epperr::Epperr("SyntaxError", "When defining a variable or constant, a name must be specified", tg[pos].line, tg[pos].column);
if(peek()->content == ":") {node->type_exp = token(); ready_type = true;}
if(peek()->content == "int" || peek()->content == "deci" || peek()->content == "string" || peek()->content == "char" || peek()->content == "bool" && ready_type) node->type = token();
else if(peek()->content == "int" || peek()->content == "deci" || peek()->content == "string" || peek()->content == "char" || peek()->content == "bool" && !ready_type)
throw epperr::Epperr("SyntaxError", "Type declarators cannot be used without a type description", tg[pos].line, tg[pos].column);
if(peek()->content == "=") node->equ = token();
else throw epperr::Epperr("SyntaxError", "Expect '='", tg[pos].line, tg[pos].column);
node->value = gen_valExprNode();
if(peek()->content == ";") node->end = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Define-variable or Define-constant statement format", tg[pos].line, tg[pos].column);
}
east::DeleteStmtNode* east::astParser::gen_delStmtNode(){
if(east::DeleteStmtNode::is(*this)){
east::DeleteStmtNode* node = new east::DeleteStmtNode;
node->mark = token();
if(east::IdentifierNode::is(*this)) node->iden = gen_identifierNode();
else throw epperr::Epperr("SyntaxError", "requires an identifier to delete", tg[pos].line, tg[pos].column);
if(peek()->content == ";") node->end = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Delete statement format", tg[pos].line, tg[pos].column);
}
east::BlockStmtNode* east::astParser::gen_blockStmtNode(){
if(east::BlockStmtNode::is(*this)){
east::BlockStmtNode* node = new east::BlockStmtNode;
node->left = token();
if(east::StatNode::is(*this)) node->body = gen_statNode();
else;
if(peek()->content == "}") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect '}'", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Block statement format", tg[pos].line, tg[pos].column);
}
east::IfStmtNode* east::astParser::gen_ifStmtNode(){
if(east::IfStmtNode::is(*this)){
east::IfStmtNode* node = new east::IfStmtNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->cond = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "requires a boolean expression to supply to the if statement", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "There is at least one statement under the if statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper If statement format", tg[pos].line, tg[pos].column);
}
east::ElseifStmtNode* east::astParser::gen_elifStmtNode(){
if(east::ElseifStmtNode::is(*this)){
east::ElseifStmtNode* node = new east::ElseifStmtNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->cond = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "requires a boolean expression to supply to the elif statement", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "There is at least one statement under the elif statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Else-If statement format", tg[pos].line, tg[pos].column);
}
east::ElseStmtNode* east::astParser::gen_elseStmtNode(){
if(east::ElseStmtNode::is(*this)){
east::ElseStmtNode* node = new east::ElseStmtNode;
node->mark = token();
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "There is at least one statement under the else statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Else statement format", tg[pos].line, tg[pos].column);
}
east::BreakStmtNode* east::astParser::gen_brkStmtNode(){
if(east::BreakStmtNode::is(*this)){
east::BreakStmtNode* node = new east::BreakStmtNode;
node->mark = token();
if(peek()->content == ";") node->end = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Break statement format", tg[pos].line, tg[pos].column);
}
east::ForEachStmtNode* east::astParser::gen_foreachStmtNode(){
if(east::ForEachStmtNode::is(*this)){
east::ForEachStmtNode* node = new east::ForEachStmtNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('", tg[pos].line, tg[pos].column);
if(peek()->content == "var") node->var_mark = token();
else throw epperr::Epperr("SyntaxError", "Expect keyword: 'var'", tg[pos].line, tg[pos].column);
if(peek()->type == "__IDENTIFIER__") node->iden = token();
else throw epperr::Epperr("SyntaxError", "Expect an identifier", tg[pos].line, tg[pos].column);
if(peek()->content == ":") node->mh = token();
else throw epperr::Epperr("SyntaxError", "Expect ':'", tg[pos].line, tg[pos].column);
if(peek()->type == "__IDENTIFIER__" || east::ListExprNode::is(*this)) node->ariden = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "Expect an identifier", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "There is at least one statement under the for_each statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper For_each statement format", tg[pos].line, tg[pos].column);
}
east::AreaStmtNode* east::astParser::gen_areaStmtNode(){
if(east::AreaStmtNode::is(*this)){
east::AreaStmtNode* node = new east::AreaStmtNode;
node->mark = token();
if(peek()->type == "__IDENTIFIER__") node->iden = token();
else throw epperr::Epperr("SyntaxError", "Expect an identifier", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else throw epperr::Epperr("SyntaxError", "There is block_stmt under the area statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Area statement format", tg[pos].line, tg[pos].column);
}
east::WhileStmtNode* east::astParser::gen_whileStmtNode(){
if(east::WhileStmtNode::is(*this)){
east::WhileStmtNode* node = new east::WhileStmtNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->cond = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "requires a boolean expression to supply to the if statement", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "There is at least one statement under the if statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper While statement format", tg[pos].line, tg[pos].column);
}
east::RepeatStmtNode* east::astParser::gen_reptStmtNode(){
if(east::RepeatStmtNode::is(*this)){
east::RepeatStmtNode* node = new east::RepeatStmtNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->cond = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "requires a boolean expression to supply to the if statement", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'", tg[pos].line, tg[pos].column);
if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "There is at least one statement under the if statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper Repeat statement format", tg[pos].line, tg[pos].column);
}
east::ForStmtNode* east::astParser::gen_forStmtNode(){
if(east::ForStmtNode::is(*this)){
east::ForStmtNode* node = new east::ForStmtNode;
node->mark = token();
if(peek()->content == "(") node->left = token();
else throw epperr::Epperr("SyntaxError", "Expect '('", tg[pos].line, tg[pos].column);
if(peek()->content == "var") node->var_mark = token();
if(peek()->type == "__IDENTIFIER__") node->iden = gen_identifierNode();
else throw epperr::Epperr("SyntaxError", "Expect an identifier", tg[pos].line, tg[pos].column);
if(peek()->content == "=") node->eq = token();
else throw epperr::Epperr("SyntaxError", "Expect '='", tg[pos].line, tg[pos].column);
if(east::ValExprNode::is(*this)) node->val = gen_valExprNode();
else throw epperr::Epperr("SyntaxError", "Expect a value", tg[pos].line, tg[pos].column);
if(peek()->content == ";") node->separate_sym1 = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
if(east::BoolExprNode::is(*this)) node->cond = gen_boolExprNode();
else throw epperr::Epperr("SyntaxError", "Expect a boolean expression", tg[pos].line, tg[pos].column);
if(peek()->content == ";") node->separate_sym2 = token();
else throw epperr::Epperr("SyntaxError", "Expect ';'", tg[pos].line, tg[pos].column);
if(east::StmtNode::is(*this)) node->dostc = gen_stmtNode();
else throw epperr::Epperr("SyntaxError", "Expect a sentence!", tg[pos].line, tg[pos].column);
if(peek()->content == ")") node->right = token();
else throw epperr::Epperr("SyntaxError", "Expect ')'", tg[pos].line, tg[pos].column);
if(east::StmtNode::is(*this)) node->stc = gen_stmtNode();
else if(east::BlockStmtNode::is(*this)) node->body = gen_blockStmtNode();
else throw epperr::Epperr("SyntaxError", "Expect a statement", tg[pos].line, tg[pos].column);
return node;
}
else throw epperr::Epperr("SyntaxError", "It is not a proper For statement format", tg[pos].line, tg[pos].column);
}
//
//identifier node
east::IdentifierNode::IdentifierNode(std::string type_) : type(type_){
}
std::string east::IdentifierNode::to_string(){
if(this->type == "__PURE__"){
std::string ret = "identifier_node(PURE): {[";
ret += this->idens[0]->simply_format() + ", ";
for(int i = 0; i < this->dots.size(); i++){
ret += this->dots[i]->simply_format() + ", ";
ret += this->idens[i + 1]->simply_format() + ", ";
}
ret += "]}";
return ret;
}
else if(this->type == "__ARRE__"){
std::string ret = "identifier_node(ARRE): {" + this->idens[0]->content + ", index: ";
ret += this->indexops[0]->to_string() + ", ";
for(int i = 1; i < this->indexops.size(); i++){
ret += this->indexops[i]->to_string() + ", ";
}
ret += "]}";
return ret;
}
return "__UNKNOWN__";
}
std::string east::IdentifierNode::getIdenType(){
return this->type;
}
bool east::IdentifierNode::is(east::astParser ap){
return ap.peek()->type == "__IDENTIFIER__" && ((ap.peek(1)->content != "++" || ap.peek(1)->content != "--")||ap.peek(1)->content == "[");
}
//
//assign expr node
std::string east::AssignExprNode::to_string(){
return "assign_expr: {[" + iden->to_string() + "]" + this->op->to_string() + ", " + this->val->to_string() + "}";
}
bool east::AssignExprNode::is(east::astParser ap){
if(east::IdentifierNode::is(ap)){
int temp = ap.pos;
ap.gen_identifierNode();
if(ap.peek()->content == "=") {ap.pos = temp; return true;}
else {ap.pos = temp; return false;}
}
return false;
}
//
//whole expr node
std::string east::WholeExprNode::to_string(){
if(this->assignexpr !=nullptr)
return "whole_expr: {" + assignexpr->to_string() + "}";
else if(this->valexpr != nullptr)
return "whole_expr: {" + valexpr->to_string() + "}";
else return "null";
}
bool east::WholeExprNode::is(east::astParser ap){
return east::AssignExprNode::is(ap) ||east::ValExprNode::is(ap);
}
//
//expr node
std::string east::ValExprNode::to_string(){
if(this->addexpr != nullptr) return this->addexpr->to_string();
else if(this->boolexpr != nullptr) return this->boolexpr->to_string();
else if(this->listexpr != nullptr) return this->listexpr->to_string();
else if(this->fdefexpr != nullptr) return this->fdefexpr->to_string();
else if(this->scopeexpr != nullptr) return this->scopeexpr->to_string();
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", 0, 0);
}
bool east::ValExprNode::is(east::astParser ap){
return east::AddExprNode::is(ap) || east::BoolExprNode::is(ap) || east::ListExprNode::is(ap) || east::FuncDefineExprNode::is(ap) || east::ScopeExprNode::is(ap);
}
//
//bifnode
std::string east::BifNode::to_string(){
if(this->len != nullptr) return "bif_node: {" + this->len->to_string() + "}";
else if(this->print != nullptr) return "bif_node: {" + this->print->to_string() + "}";
else if(this->tyt != nullptr) return "bif_node: {" + this->tyt->to_string() + "}";
else if(this->typef != nullptr) return "bif_node: {" + this->typef->to_string() + "}";
else if(this->input != nullptr) return "bif_node: {" + this->input->to_string() + "}";
else if(this->bifi != nullptr) return "bif_node: {" + this->bifi->to_string() + "}";
else throw epperr::Epperr("SyntaxError", "Unknown type of the expr!", 0, 0);
}
bool east::BifNode::is(east::astParser ap){
return LenExprNode::is(ap) || PrintoLnExprNode::is(ap) || TypeToExprNode::is(ap) || TypeOfExprNode::is(ap) || InputExprNode::is(ap) || BifInstanceNode::is(ap);
}
//
//prim node
std::string east::PrimExprNode::to_string(){
if(null != nullptr)
return "prim_expr(NULL): {" + this->null->simply_format() + "}";
else if(number != nullptr)
return "prim_expr(NUMBER): {" + this->number->simply_format() + "}";
else if(iden != nullptr)
return "prim_expr(IDENTIFIER): {" + this->iden->to_string() + "}";
else if(boolconst != nullptr)
return "prim_expr(BOOL_CONST): {" + this->boolconst->simply_format() + "}";
else if(ch != nullptr)
return "prim_expr(CHAR): {" + this->ch->simply_format() + "}";
else if(str != nullptr)
return "prim_expr(STRING): {" + this->str->simply_format() + "}";
else if(addexpr != nullptr)
return "prim_expr(ADDEXPR): {" + this->addexpr->to_string() + "}";
else if(boolexpr != nullptr)
return "prim_expr(BOOLEXPR): {" + this->boolexpr->to_string() + "}";
else if(bif != nullptr)
return "prim_expr(BIF): {" + this->bif->to_string() + "}";
else if(fcall != nullptr)
return "prim_expr(FUNC_CALL): {" + this->fcall->to_string() + "}";
else if(siad != nullptr)
return "prim_expr(SIAD): {" + this->siad->to_string() + "}";
else return "__NULL__";
}
bool east::PrimExprNode::is(east::astParser ap){
return ap.peek()->type == "__IDENTIFIER__" || ap.peek()->type == "__NUMBER__" || ap.peek()->type == "__STRING__"||
ap.peek()->type == "__CHAR__"|| ap.peek()->content == "(" || east::BifNode::is(ap) ||
ap.peek()->content == "true"||ap.peek()->content == "false" || ap.peek()->content == "null"|| ap.peek()->type == "__BIFIDEN__" || east::FuncCallExprNode::is(ap) ||
east::SelfIaDExprNode::is(ap);
}
//
//add op node
std::string east::AddOpNode::to_string(){
return "add_op: {" + this->op->simply_format() + "}";
}
bool east::AddOpNode::is(east::astParser ap){
return ap.peek()->content == "+" || ap.peek()->content == "-";
}
//
//equ op node
std::string east::EquOpNode::to_string(){
return "equ_op: {" + this->op->simply_format() + "}";
}
bool east::EquOpNode::is(east::astParser ap){
return ap.peek()->content == "=";
}
//
//mul op node
std::string east::MulOpNode::to_string(){
return "mul_op: {" + this->op->simply_format() + "}";
}
bool east::MulOpNode::is(east::astParser ap){
return ap.peek()->content == "*" || ap.peek()->content == "/"|| ap.peek()->content == "%";
}
//
//cmp op node
std::string east::CmpOpNode::to_string(){
return "cmp_op: {" + this->op->simply_format() + "}";
}
bool east::CmpOpNode::is(east::astParser ap){
return ap.peek()->content == "==" || ap.peek()->content == "!=" || ap.peek()->content == ">=" || ap.peek()->content == "<="
|| ap.peek()->content == ">" || ap.peek()->content == "<";
}
//
//bool op node
std::string east::BoolOpNode::to_string(){
return "bool_op: {" + this->op->simply_format() + "}";
}
bool east::BoolOpNode::is(east::astParser ap){
return ap.peek()->content == "&&" || ap.peek()->content == "||";
}
//
//index op node
std::string east::IndexOpNode::to_string(){
return "index_op: {" + this->begin->to_string() + (this->spliter!=nullptr?", ":"") + (this->spliter!=nullptr?this->end->to_string():"");
}
bool east::IndexOpNode::is(east::astParser ap){
return ap.peek()->content == "[";
}
//
//cmp expr node
std::string east::CmpExprNode::to_string(){
if(op != nullptr)
return "cmp_expr: {" + this->expr->to_string() + ", symbol:" + this->op->to_string() + ", " + this->target->to_string() + "}";
else
return "cmp_expr: {" + this->expr->to_string()+ "}";
}
bool east::CmpExprNode::is(east::astParser ap){
if(ap.peek()->content == "true" || ap.peek()->content == "false") return true;
int temp = ap.pos;
if(east::AddExprNode::is(ap)) {
ap.gen_addExprNode();
if(east::CmpOpNode::is(ap)) {ap.pos = temp; return true;}
else return false;
}
else return false;
}
//
//bool expr node
std::string east::BoolExprNode::to_string(){
std::string ret = "bool_expr: {[";
ret += this->cmps[0]->to_string();
for(int i = 0; i < this->ops.size(); i++){
ret += this->ops[i]->to_string() + ", ";
ret += this->cmps[i + 1]->to_string() + ", ";
}
ret += "]}";
return ret;
}
bool east::BoolExprNode::is(east::astParser ap){
return ap.peek()->content == "!" || east::CmpExprNode::is(ap);
}
//
//mul expr node
std::string east::MulExprNode::to_string(){
std::string ret = "mul_expr: {[";
ret += this->prims[0]->to_string();
for(int i = 0; i < this->ops.size(); i++){
ret += this->ops[i]->to_string() + ", ";
ret += this->prims[i + 1]->to_string() + ", ";
}
ret += "]}";
return ret;
}
bool east::MulExprNode::is(east::astParser ap){
return east::PrimExprNode::is(ap);
}
//
//selfiad expr node
std::string east::SelfIaDExprNode::to_string(){
return "selfiad_expr: {" + this->op->simply_format() + ", " + this->iden->to_string() + "}";
}
bool east::SelfIaDExprNode::is(east::astParser ap){
if(ap.peek()->content == "++" || ap.peek()->content == "--") return true;
else if(east::IdentifierNode::is(ap)){
int temp = ap.pos;
ap.gen_identifierNode();
if(ap.peek()->content == "++" || ap.peek()->content == "--") {ap.pos = temp; return true;}
else {ap.pos = temp; return false;}
return false;
}
return false;
}
//add expr node
std::string east::AddExprNode::to_string(){
std::string ret = "add_expr: {[";
ret += this->muls[0]->to_string();
for(int i = 0; i < this->ops.size(); i++){
ret += this->ops[i]->to_string() + ", ";
ret += this->muls[i + 1]->to_string() + ", ";
}
ret += "]}";
return ret;
}
bool east::AddExprNode::is(east::astParser ap){
return east::PrimExprNode::is(ap);
}
//
//list expr node
std::string east::ListExprNode::to_string(){
std::string ret = "list_expr: {" + this->left->simply_format() + ", [";
ret += arrayelts[0]->to_string();
for(int i = 0; i<arrayelts.size(); i++){
ret += arrayelts[i]->to_string();
}
ret += "], ";
ret += this->right->simply_format() + "}";
return ret;
}
bool east::ListExprNode::is(astParser ap){
return ap.peek()->content == "[";
}
//
//scope expr node
std::string east::ScopeExprNode::to_string(){
std::string ret = "scope_expr: {" + this->left->simply_format() + ", body:[";
ret += this->body->stmts[0]->to_string();
for(int i = 0; i<this->body->stmts.size(); i++){
ret += this->body->stmts[i]->to_string();
}
ret += "]}";
return ret;
}
bool east::ScopeExprNode::is(east::astParser ap){
return ap.peek()->content == "{";
}
//
//typeof expr node
std::string east::TypeOfExprNode::to_string(){
return "typeof_expr: {" + mark->simply_format() + ", " + expr->to_string() + "}";
}
bool east::TypeOfExprNode::is(east::astParser ap){
return ap.peek()->content == "typeof";
}
//
//typeto expr node
std::string east::TypeToExprNode::to_string(){
return "typeto_expr: {" + mark->simply_format() + ", " + expr->to_string() + "}";
}
bool east::TypeToExprNode::is(east::astParser ap){
return ap.peek()->content == "str" || ap.peek()->content == "int" || ap.peek()->content == "deci" || ap.peek()->content == "bool";
}
//
//printoln expr node
std::string east::PrintoLnExprNode::to_string(){
return "print/ln_expr: {" + mark->simply_format() + ", " + expr->to_string() + "}";
}
bool east::PrintoLnExprNode::is(east::astParser ap){
return ap.peek()->content == "print" || ap.peek()->content == "println";
}
//
//bif instance node
std::string east::BifInstanceNode::to_string(){
std::string ret = "bif_ins: {" + this->mark->simply_format() + ", para:[";
if(paras.empty()){
ret+= "]}";
}
else{
ret += paras[0]->to_string();
for(int i = 0; i<dots.size(); i++){
ret += paras[i + 1]->to_string();
}
ret += "]}";
}
return ret;
}
bool east::BifInstanceNode::is(astParser ap){
return ap.peek()->type == "__BIFIDEN__";
}
//
//func define expr node
std::string east::FuncDefineExprNode::Para::to_string(){
return "para_node: {" + this->name->simply_format() + ", " + this->type->simply_format() + "}";
}
east::FuncDefineExprNode::Para::Para(epplex::Token* _name, epplex::Token* _mh, epplex::Token* _type): name(_name), mh(_mh), type(_type) {}
std::string east::FuncDefineExprNode::to_string(){
std::string ret = "func_define_expr: {" + mark->simply_format() + ",[";
if(paras.empty()){
ret += "], " + body->to_string() + "}";
}
else {
ret += paras[0]->to_string();
for(int i = 0; i<paras.size(); i++){
ret += paras[i]->to_string();
}
ret += "], " + body->to_string() + "}";
}
return ret;
}
bool east::FuncDefineExprNode::is(east::astParser ap){
return ap.peek()->content == "func";
}
//
//func call expr node
std::string east::FuncCallExprNode::to_string(){
std::string ret = "func_call_expr: {" + func_name->to_string() + ",[";
if(act_paras.empty()){
ret += "]}";
}
else{
ret += act_paras[0]->to_string();
for(int i = 0; i<act_paras.size(); i++){
ret += act_paras[i]->to_string();
}
ret += "]}";
}
return ret;
}
bool east::FuncCallExprNode::is(east::astParser ap){
if(east::IdentifierNode::is(ap)){
int temp = ap.pos;
ap.gen_identifierNode();
if(ap.peek()->content == "(") {ap.pos = temp; return true;}
else {ap.pos = temp; return false;}
}
return false;
}
//
//len expr node
std::string east::LenExprNode::to_string(){
return "len_expr: {" + mark->simply_format() + ", " + expr->to_string() + "}";
}
bool east::LenExprNode::is(east::astParser ap){
return ap.peek()->content == "len";
}
//
//input expr node
std::string east::InputExprNode::to_string(){
if(expr != nullptr)
return "input_expr: {" + mark->simply_format() + ", " + expr->to_string() + "}";
else
return "input_expr: {" + mark->simply_format() + "}";
}
bool east::InputExprNode::is(east::astParser ap){
return ap.peek()->content == "input";
}
//
//stmt node
east::StmtNode::StmtNode(BlockStmtNode* stmt) : blockstmt(stmt) { }
std::string east::StmtNode::to_string(){
if(outstmt != nullptr) return "stmt_node: {" + this->outstmt->to_string() + "}";
else if(vorcstmt != nullptr) return "stmt_node: {" + this->vorcstmt->to_string() + "}";
else if(deletestmt != nullptr) return "stmt_node: {" + this->deletestmt->to_string() + "}";
else if(ifstmt != nullptr) return "stmt_node: {" + this->ifstmt->to_string() + "}";
else if(elifstmt != nullptr) return "stmt_node: {" + this->elifstmt->to_string() + "}";
else if(elsestmt != nullptr) return "stmt_node: {" + this->elsestmt->to_string() + "}";
else if(blockstmt != nullptr) return "stmt_node: {" + this->blockstmt->to_string() + "}";
else if(brkstmt != nullptr) return "stmt_node: {" + this->brkstmt->to_string() + "}";
else if(whilestmt != nullptr) return "stmt_node: {" + this->whilestmt->to_string() + "}";
else if(reptstmt != nullptr) return "stmt_node: {" + this->reptstmt->to_string() + "}";
else if(foreachstmt != nullptr) return "stmt_node: {" + this->foreachstmt->to_string() + "}";
else if(areastmt != nullptr) return "stmt_node: {" + this->areastmt->to_string() + "}";
else if(forstmt != nullptr) return "stmt_node: {" + this->forstmt->to_string() + "}";
else if(exprstmt != nullptr) return "stmt_node: {" + this->exprstmt->to_string() + "}";
else if(returnstmt != nullptr) return "stmt_node: {" + this->returnstmt->to_string() + "}";
else return "__NULL__";
}
bool east::StmtNode::is(east::astParser ap){
return east::OutStmtNode::is(ap) || east::VorcStmtNode::is(ap) || east::DeleteStmtNode::is(ap)
|| east::BlockStmtNode::is(ap) || east::IfStmtNode::is(ap) || east::RepeatStmtNode::is(ap) || east::WhileStmtNode::is(ap)
|| east::BreakStmtNode::is(ap) || east::ElseStmtNode::is(ap) || east::ElseifStmtNode::is(ap) || east::ForEachStmtNode::is(ap)
|| east::AreaStmtNode::is(ap) || east::ExprStmtNode::is(ap) || east::ForStmtNode::is(ap) || east::ReturnStmtNode::is(ap);
}
//
//stat node
std::string east::StatNode::to_string(){
std::string ret = "stat_node: {[";
for(auto stmt : stmts){
ret += stmt->to_string() + ", ";
}
ret += "]}";
return ret;
}
bool east::StatNode::is(east::astParser ap){
return east::StmtNode::is(ap);
}
//
//out stmt node
std::string east::OutStmtNode::to_string(){
return "out_stmt: { " + this->mark->simply_format() + ", " + this->content->to_string() + ", " + this->end->simply_format();
}
bool east::OutStmtNode::is(east::astParser ap){
return ap.peek()->content == "out";
}
//
//vorc stmt node
std::string east::VorcStmtNode::to_string(){
return "vorc_stmt: {" + this->mark->simply_format() + "," + this->iden->simply_format() + (this->type!=nullptr?", " + this->type->simply_format():"") + ", " + this->equ->simply_format() + ", " + this->value->to_string() + ", " + this->end->simply_format() + "}";
}
bool east::VorcStmtNode::is(east::astParser ap){
return ap.peek()->content == "var" || ap.peek()->content == "const";
}
//
//block stmt node
std::string east::BlockStmtNode::to_string(){
std::string ret = "block_stmt: {" + this->left->simply_format() + ", body:[";
if(this->body == nullptr)goto end;
ret += this->body->stmts[0]->to_string();
for(int i = 0; i<this->body->stmts.size(); i++){
ret += this->body->stmts[i]->to_string();
}
end:
ret += "]}";
return ret;
}
bool east::BlockStmtNode::is(astParser ap){
return ap.peek()->content == "{";
}
//
//delete stmt node
std::string east::DeleteStmtNode::to_string(){
return "delete_stmt: {" + this->mark->simply_format() + ", " + this->iden->to_string() + ", " + end->simply_format() + "}";
}
bool east::DeleteStmtNode::is(east::astParser ap){
return ap.peek()->content == "delete";
}
//
//if stmt node
std::string east::IfStmtNode::to_string(){
if(body != nullptr)
return "if_stmt: {" + this->mark->simply_format() + ", " + this->cond->to_string() + ", " + this->body->to_string() + "}";
else
return "if_stmt: {" + this->mark->simply_format() + ", " + this->cond->to_string() + ", " + this->stc->to_string() + "}";
}
bool east::IfStmtNode::is(east::astParser ap){
return ap.peek()->content == "if";
}
//
//if stmt node
std::string east::ElseifStmtNode::to_string(){
if(body != nullptr)
return "elif_stmt: {" + this->mark->simply_format() + ", " + this->cond->to_string() + ", " + this->body->to_string() + "}";
else
return "elif_stmt: {" + this->mark->simply_format() + ", " + this->cond->to_string() + ", " + this->stc->to_string() + "}";
}
bool east::ElseifStmtNode::is(east::astParser ap){
return ap.peek()->content == "elif";
}
//
//else stmt node
std::string east::ElseStmtNode::to_string(){
if(body != nullptr)
return "if_stmt: {" + this->mark->simply_format() + ", " + this->body->to_string() + "}";
else
return "if_stmt: {" + this->mark->simply_format() + ", " + this->stc->to_string() + "}";
}
bool east::ElseStmtNode::is(east::astParser ap){
return ap.peek()->content == "else";
}
//
//while stmt node
std::string east::WhileStmtNode::to_string(){
return "while_stmt: {" + mark->simply_format() + ", " = cond->to_string() + ", " + body->to_string() + "}";
}
bool east::WhileStmtNode::is(east::astParser ap){
return ap.peek()->content == "while";
}
//
//repeat stmt node
std::string east::RepeatStmtNode::to_string(){
return "repeat_stmt: {" + mark->simply_format() + ", " = cond->to_string() + ", " + body->to_string() + "}";
}
bool east::RepeatStmtNode::is(east::astParser ap){
return ap.peek()->content == "repeat";
}
//
//break stmt node
std::string east::BreakStmtNode::to_string(){
return "break_stmt: {" + mark->simply_format() + "}";
}
bool east::BreakStmtNode::is(east::astParser ap){
return ap.peek()->content == "break";
}
//
//for_each stmt node
std::string east::ForEachStmtNode::to_string(){
return "for_each_stmt_node: {" + mark->simply_format() + ", " + iden->simply_format() + ", " + ariden->to_string() + ", " + (this->stc!=nullptr?stc->to_string():body->to_string()) + "}";
}
bool east::ForEachStmtNode::is(east::astParser ap){
return ap.peek()->content == "for_each";
}
//
//area stmt node
std::string east::AreaStmtNode::to_string(){
return "area_stmt_node: {" + mark->simply_format() + ", " + iden->simply_format() + ", " + body->to_string() + "}";
}
bool east::AreaStmtNode::is(east::astParser ap){
return ap.peek()->content == "area";
}
//
//expr stmt node
std::string east::ExprStmtNode::to_string(){
return "expr_stmt: {" + (assign == nullptr?expr->to_string():assign->to_string()) + "}";
}
bool east::ExprStmtNode::is(east::astParser ap){
return SelfIaDExprNode::is(ap) || FuncCallExprNode::is(ap) || BifNode::is(ap) || AssignExprNode::is(ap);
}
//
//for stmt node
std::string east::ForStmtNode::to_string(){
return "for_stmt: {" + this->mark->simply_format() + ", " + this->iden->to_string() + ", " + this->val->to_string() + ", " + this->cond->to_string() + ", " + dostc->to_string() + "}";
}
bool east::ForStmtNode::is(east::astParser ap){
return ap.peek()->content == "for";
}
//
//return stmt node
std::string east::ReturnStmtNode::to_string(){
return "return_stmt: {" + this->value->to_string() + "}";
}
bool east::ReturnStmtNode::is(astParser ap){
return ap.peek()->content == "return";
}
// | 44.770206 | 267 | 0.601274 | [
"vector"
] |
aaee16de2240b17f97192f2289eb9ff800105280 | 33,815 | cc | C++ | content/browser/loader/redirect_to_file_resource_handler_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-05-24T13:52:28.000Z | 2021-05-24T13:53:10.000Z | content/browser/loader/redirect_to_file_resource_handler_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/loader/redirect_to_file_resource_handler_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-03-12T07:58:10.000Z | 2019-08-31T04:53:58.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/loader/redirect_to_file_resource_handler.h"
#include <algorithm>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_piece.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/loader/mock_resource_loader.h"
#include "content/browser/loader/temporary_file_stream.h"
#include "content/browser/loader/test_resource_handler.h"
#include "content/public/common/resource_response.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/base/completion_callback.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/mime_sniffer.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "storage/browser/blob/shareable_file_reference.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace content {
namespace {
// The maximum size for which the initial read will always be sync, even when
// the wrote completes asynchronously. See
// RedirectToFileResourceHandler::BufIsFull().
const int kMaxInitialSyncReadSize =
RedirectToFileResourceHandler::kInitialReadBufSize -
2 * net::kMaxBytesToSniff - 1;
// Used to indicate whether FileStream operations and the lower-layer
// TestResourceHandler operations should complete immediately or by
// asynchronously invoking a callback. Each test is run with all operations set
// by default to each mode, though some tests override the mode of some
// operations.
enum class CompletionMode {
SYNC,
ASYNC,
};
// Mock in-memory net::FileStream implementation that can be configured to
// return errors and complete operations synchronously or asynchronously.
class MockFileStream : public net::FileStream {
public:
struct OperationResult {
OperationResult(int result, CompletionMode completion_mode)
: result(result), completion_mode(completion_mode) {}
OperationResult()
: OperationResult(net::ERR_UNEXPECTED, CompletionMode::SYNC) {}
int result;
CompletionMode completion_mode;
};
MockFileStream() : FileStream(base::ThreadTaskRunnerHandle::Get()) {}
~MockFileStream() override {
EXPECT_EQ(expect_closed_, closed_);
// Most of these tests write 32k or more, which is a bit much for the
// command line.
EXPECT_TRUE(expected_written_data_ == written_data_);
}
// net::FileStream implementation:
int Open(const base::FilePath& path,
int open_flags,
const net::CompletionCallback& callback) override {
return ReturnResult(open_result_, callback);
}
int Close(const net::CompletionCallback& callback) override {
EXPECT_FALSE(closed_);
int result = ReturnResult(
close_result_,
base::BindRepeating(&MockFileStream::SetClosedAndRunCallback,
base::Unretained(this), callback));
if (result != net::ERR_IO_PENDING)
closed_ = true;
return result;
}
bool IsOpen() const override {
NOTREACHED();
return false;
}
int Seek(int64_t offset,
const net::Int64CompletionCallback& callback) override {
NOTREACHED();
return net::ERR_UNEXPECTED;
}
int Read(net::IOBuffer* buf,
int buf_len,
const net::CompletionCallback& callback) override {
NOTREACHED();
return net::ERR_UNEXPECTED;
}
int Write(net::IOBuffer* buf,
int buf_len,
const net::CompletionCallback& callback) override {
// 0-byte writes aren't allowed.
EXPECT_GT(buf_len, 0);
OperationResult write_result = next_write_result_;
next_write_result_ = all_write_results_;
if (write_result.result > buf_len)
write_result.result = buf_len;
if (write_result.result > 0)
written_data_ += std::string(buf->data(), write_result.result);
return ReturnResult(write_result, callback);
}
int Flush(const net::CompletionCallback& callback) override {
NOTREACHED();
return net::ERR_UNEXPECTED;
}
void set_open_result(OperationResult open_result) {
open_result_ = open_result;
}
void set_close_result(OperationResult close_result) {
close_result_ = close_result;
}
// Sets the result for all write operations. Returned result is capped at
// number of bytes the consumer actually tried to write. Overrides
// |next_write_result_|.
void set_all_write_results(OperationResult all_write_results) {
next_write_result_ = all_write_results_ = all_write_results;
}
// Sets the result of only the next write operation.
void set_next_write_result(OperationResult next_write_result) {
next_write_result_ = next_write_result;
}
void set_expected_written_data(const std::string& expected_written_data) {
expected_written_data_ = expected_written_data;
}
// Sets whether the file should expect to be closed.
void set_expect_closed(bool expect_closed) { expect_closed_ = expect_closed; }
private:
void SetClosedAndRunCallback(const net::CompletionCallback& callback,
int result) {
EXPECT_FALSE(closed_);
closed_ = true;
callback.Run(result);
}
int ReturnResult(OperationResult result,
const net::CompletionCallback& callback) {
if (result.completion_mode == CompletionMode::SYNC)
return result.result;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, result.result));
return net::ERR_IO_PENDING;
}
OperationResult open_result_;
OperationResult close_result_;
OperationResult next_write_result_;
OperationResult all_write_results_;
std::string expected_written_data_;
std::string written_data_;
bool expect_closed_ = false;
bool closed_ = false;
DISALLOW_COPY_AND_ASSIGN(MockFileStream);
};
class RedirectToFileResourceHandlerTest
: public testing::TestWithParam<CompletionMode> {
public:
RedirectToFileResourceHandlerTest()
: thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP),
url_request_(
url_request_context_.CreateRequest(GURL("foo://bar/"),
net::DEFAULT_PRIORITY,
&url_request_delegate_,
TRAFFIC_ANNOTATION_FOR_TESTS)) {
base::CreateTemporaryFile(&temp_file_path_);
std::unique_ptr<TestResourceHandler> test_handler =
base::MakeUnique<TestResourceHandler>();
test_handler->set_expect_on_data_downloaded(true);
if (GetParam() == CompletionMode::ASYNC) {
// Don't defer OnResponseCompleted, by default, since that's really
// unusual.
test_handler->set_defer_on_response_started(true);
test_handler->set_defer_on_will_start(true);
}
test_handler_ = test_handler->GetWeakPtr();
redirect_to_file_handler_ = base::MakeUnique<RedirectToFileResourceHandler>(
std::move(test_handler), url_request_.get());
mock_loader_ =
base::MakeUnique<MockResourceLoader>(redirect_to_file_handler_.get());
redirect_to_file_handler_->SetCreateTemporaryFileStreamFunctionForTesting(
base::Bind(&RedirectToFileResourceHandlerTest::
SetCreateTemporaryFileStreamCallback,
base::Unretained(this)));
file_stream_ = base::MakeUnique<MockFileStream>();
file_stream_->set_open_result(
MockFileStream::OperationResult(net::OK, GetParam()));
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), GetParam()));
file_stream_->set_close_result(
MockFileStream::OperationResult(net::OK, GetParam()));
}
~RedirectToFileResourceHandlerTest() override {
EXPECT_FALSE(test_handler_->on_read_completed_called());
// This should post a task to delete the temporary file.
redirect_to_file_handler_.reset();
mock_loader_.reset();
url_request_.reset();
// This should delete the temporary file, and ensure
// MockFileStream::Cancel() is called.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(base::PathExists(temp_file_path_));
}
// Creates a test string of the specified length, and sets that as the
// expected data written to |file_stream_|.
std::string CreateTestData(size_t length) {
std::string test_data;
test_data.reserve(length);
for (size_t i = 0; i < length; ++i)
test_data.push_back(static_cast<char>(i % 256));
file_stream_->set_expected_written_data(test_data);
return test_data;
}
// The "CreateTemporaryFileStream" method invoked by the
// RedirectToFileResourceHandler. Just sets a callback that will be invoked
// directly.
void SetCreateTemporaryFileStreamCallback(
const CreateTemporaryFileStreamCallback& create_file_stream_callback) {
create_file_stream_callback_ = create_file_stream_callback;
}
// Simulates starting the request, the response starting, and stream creation
// completing with the specified error code. Has |test_handler_| resume the
// request, if needed. Returns final status of |mock_loader_|.
MockResourceLoader::Status StartAndCreateStream(base::File::Error file_error)
WARN_UNUSED_RESULT {
DCHECK(file_stream_);
EXPECT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnWillStart(url_request_->url()));
file_stream_->set_expect_closed(file_error == base::File::FILE_OK);
if (file_error != base::File::FILE_OK)
file_stream_ = nullptr;
base::ResetAndReturn(&create_file_stream_callback_)
.Run(file_error, std::move(file_stream_),
// Not really used by the test, but the ResourceHandler expects it
// to be non-null.
storage::ShareableFileReference::GetOrCreate(
temp_file_path_,
storage::ShareableFileReference::DELETE_ON_FINAL_RELEASE,
base::ThreadTaskRunnerHandle::Get().get())
.get());
// If this is an async test, |test_handler_| will defer the OnWillStart
// event on success (On error, its OnWillStart method is not called).
if (file_error == base::File::FILE_OK &&
GetParam() == CompletionMode::ASYNC) {
EXPECT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->status());
test_handler_->Resume();
mock_loader_->WaitUntilIdleOrCanceled();
}
EXPECT_NE(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->status());
return mock_loader_->status();
}
// Convenience wrapper for MockLoader methods that will Resume |test_handler_|
// and wait for it to resume the request if running an async test.
MockResourceLoader::Status OnResponseStartedAndWaitForResult()
WARN_UNUSED_RESULT {
mock_loader_->OnResponseStarted(make_scoped_refptr(new ResourceResponse()));
if (GetParam() == CompletionMode::ASYNC) {
EXPECT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->status());
test_handler_->Resume();
mock_loader_->WaitUntilIdleOrCanceled();
}
EXPECT_NE(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->status());
return mock_loader_->status();
}
// Utility method that simulates a final 0-byte read and response completed
// events, and checks that completion is handled correctly. Expects all data
// to already have been written to the file.
void CompleteRequestSuccessfully(int expected_total_bytes_downloaded) {
// The loader should be idle and all the data should have already been
// processed.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->status());
EXPECT_EQ(expected_total_bytes_downloaded,
test_handler_->total_bytes_downloaded());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(""));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::OK)));
EXPECT_EQ(expected_total_bytes_downloaded,
test_handler_->total_bytes_downloaded());
EXPECT_EQ(net::URLRequestStatus::SUCCESS,
test_handler_->final_status().status());
}
protected:
TestBrowserThreadBundle thread_bundle_;
base::FilePath temp_file_path_;
net::TestURLRequestContext url_request_context_;
net::TestDelegate url_request_delegate_;
base::WeakPtr<TestResourceHandler> test_handler_;
std::unique_ptr<net::URLRequest> url_request_;
std::unique_ptr<MockResourceLoader> mock_loader_;
std::unique_ptr<RedirectToFileResourceHandler> redirect_to_file_handler_;
std::unique_ptr<MockFileStream> file_stream_;
CreateTemporaryFileStreamCallback create_file_stream_callback_;
};
TEST_P(RedirectToFileResourceHandlerTest, EmptyBody) {
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
CompleteRequestSuccessfully(0);
}
TEST_P(RedirectToFileResourceHandlerTest, SingleBodyRead) {
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data));
// Wait for the write to complete, in the async case.
base::RunLoop().RunUntilIdle();
CompleteRequestSuccessfully(test_data.size());
}
TEST_P(RedirectToFileResourceHandlerTest, ManySequentialBodyReads) {
const size_t kBytesPerRead = 128;
std::string test_data =
CreateTestData(RedirectToFileResourceHandler::kInitialReadBufSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
for (size_t offset = 0; offset < test_data.length();
offset += kBytesPerRead) {
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
size_t length = std::min(kBytesPerRead, test_data.length() - offset);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(
base::StringPiece(test_data.data() + offset, length)));
// Spin the message loop, to allow async writes to complete.
base::RunLoop().RunUntilIdle();
}
CompleteRequestSuccessfully(test_data.size());
}
TEST_P(RedirectToFileResourceHandlerTest, PartialWrites) {
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
file_stream_->set_all_write_results(MockFileStream::OperationResult(
RedirectToFileResourceHandler::kInitialReadBufSize / 50, GetParam()));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data));
// Wait for the writes to complete, in the async case.
base::RunLoop().RunUntilIdle();
CompleteRequestSuccessfully(test_data.size());
}
// Same as above, but read enough data to defer reading the body.
TEST_P(RedirectToFileResourceHandlerTest, PartialWrites2) {
std::string test_data =
CreateTestData(RedirectToFileResourceHandler::kInitialReadBufSize);
// Async reads, as otherwise reading won't be defered.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
RedirectToFileResourceHandler::kInitialReadBufSize / 50,
CompletionMode::ASYNC));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnReadCompleted(test_data));
// Wait for the writes to complete.
base::RunLoop().RunUntilIdle();
CompleteRequestSuccessfully(test_data.size());
}
TEST_P(RedirectToFileResourceHandlerTest, ReceiveDataWhileWritingBody) {
const int kFirstWriteSize = 100;
// This test only makes sense when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
// Will use multiple writes, with a combined size such that they don't
// saturate the buffer.
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(
MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(0, kFirstWriteSize)));
// Next read completes before first write succeeds.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(
kFirstWriteSize, sizeof(test_data) - kFirstWriteSize)));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
// Wait for both writes to succeed.
base::RunLoop().RunUntilIdle();
CompleteRequestSuccessfully(test_data.size());
}
TEST_P(RedirectToFileResourceHandlerTest, ReceiveDataAndDeferWhileWritingBody) {
const int kFirstWriteSize = 100;
// This test only makes sense when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
// Will use multiple writes, with a combined size such that they saturate the
// buffer.
std::string test_data =
CreateTestData(RedirectToFileResourceHandler::kInitialReadBufSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(
MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(0, kFirstWriteSize)));
// Next read completes before first write succeeds.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnReadCompleted(test_data.substr(
kFirstWriteSize, sizeof(test_data) - kFirstWriteSize)));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
// Wait for both writes to succeed.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->status());
CompleteRequestSuccessfully(test_data.size());
}
TEST_P(RedirectToFileResourceHandlerTest,
ExpandBufferCapacityManySequentialBodyReads) {
// The buffer is only resized when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
const int kInitialReadSize =
RedirectToFileResourceHandler::kInitialReadBufSize;
const int kMaxReadSize = RedirectToFileResourceHandler::kMaxReadBufSize;
int next_read_size = kInitialReadSize;
int total_read_bytes = 0;
// Populate |read_sizes| with expected buffer sizes if each previous read
// filled the entire buffer.
std::vector<size_t> read_sizes;
while (true) {
total_read_bytes += next_read_size;
read_sizes.push_back(next_read_size);
if (next_read_size == kMaxReadSize)
break;
next_read_size = std::min(2 * next_read_size, kMaxReadSize);
}
// Once the max is reached, do another round to make sure it isn't increased.
total_read_bytes += kMaxReadSize;
read_sizes.push_back(kMaxReadSize);
std::string test_data = CreateTestData(total_read_bytes);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
int offset = 0;
for (int read_size : read_sizes) {
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnReadCompleted(
base::StringPiece(test_data.data() + offset, read_size)));
offset += read_size;
EXPECT_EQ(read_size, redirect_to_file_handler_->GetBufferSizeForTesting());
base::RunLoop().RunUntilIdle();
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->status());
}
CompleteRequestSuccessfully(test_data.size());
}
TEST_P(RedirectToFileResourceHandlerTest, CompletedWhileWritingBody) {
// This test only makes sense when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
// While data is being written to the disk, the request completes.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(""));
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::OK)));
// Wait for the write to complete and the final status sent to the
// TestHandler.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(static_cast<int>(test_data.size()),
test_handler_->total_bytes_downloaded());
EXPECT_EQ(net::URLRequestStatus::SUCCESS,
test_handler_->final_status().status());
}
TEST_P(RedirectToFileResourceHandlerTest,
CompletedWhileWritingBodyAndWritePending) {
const int kFirstWriteSize = 100;
// This test only makes sense when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
// Will use multiple writes, with a combined size such that they don't
// saturate the buffer.
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(
MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(0, kFirstWriteSize)));
// Next read completes before first write succeeds.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(
kFirstWriteSize, sizeof(test_data) - kFirstWriteSize)));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
// While the first write is still going on, the request completes.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(""));
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::OK)));
// Wait for both writes to complete and the final status to be sent to the
// TestHandler.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(static_cast<int>(test_data.size()),
test_handler_->total_bytes_downloaded());
EXPECT_EQ(net::URLRequestStatus::SUCCESS,
test_handler_->final_status().status());
}
TEST_P(RedirectToFileResourceHandlerTest, SingleBodyReadAndFail) {
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data));
// Wait for the write to complete.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(static_cast<int>(test_data.size()),
test_handler_->total_bytes_downloaded());
// Next read fails and request is torn down synchronously.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::ERR_FAILED)));
EXPECT_FALSE(test_handler_->final_status().is_success());
EXPECT_EQ(net::ERR_FAILED, test_handler_->final_status().error());
}
TEST_P(RedirectToFileResourceHandlerTest, FailedWhileWritingBody) {
// This test only makes sense when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
// While data is being written to the disk, the request fails.
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::ERR_FAILED)));
// Wait for the write to complete and the final status sent to the
// TestHandler.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(static_cast<int>(test_data.size()),
test_handler_->total_bytes_downloaded());
EXPECT_FALSE(test_handler_->final_status().is_success());
EXPECT_EQ(net::ERR_FAILED, test_handler_->final_status().error());
}
TEST_P(RedirectToFileResourceHandlerTest,
FailededWhileWritingBodyAndWritePending) {
const int kFirstWriteSize = 100;
// This test only makes sense when reads are async.
file_stream_->set_all_write_results(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), CompletionMode::ASYNC));
// Will use multiple writes, with a combined size such that they don't
// saturate the buffer.
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(
MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(0, kFirstWriteSize)));
// Next read completes before first write succeeds.
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(test_data.substr(
kFirstWriteSize, sizeof(test_data) - kFirstWriteSize)));
// While the first write is still going on, the request fails.
ASSERT_EQ(MockResourceLoader::Status::CALLBACK_PENDING,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::ERR_FAILED)));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
// Wait for both writes to complete and the final status to be sent to the
// TestHandler.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(static_cast<int>(test_data.size()),
test_handler_->total_bytes_downloaded());
EXPECT_FALSE(test_handler_->final_status().is_success());
EXPECT_EQ(net::ERR_FAILED, test_handler_->final_status().error());
}
TEST_P(RedirectToFileResourceHandlerTest, CreateFileFails) {
ASSERT_EQ(MockResourceLoader::Status::CANCELED,
StartAndCreateStream(base::File::FILE_ERROR_FAILED));
EXPECT_EQ(0, test_handler_->on_response_completed_called());
EXPECT_EQ(net::ERR_FAILED, mock_loader_->error_code());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::ERR_FAILED)));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
EXPECT_FALSE(test_handler_->final_status().is_success());
EXPECT_EQ(net::ERR_FAILED, test_handler_->final_status().error());
}
TEST_P(RedirectToFileResourceHandlerTest, FirstWriteFails) {
std::string test_data = CreateTestData(kMaxInitialSyncReadSize);
file_stream_->set_expected_written_data("");
file_stream_->set_next_write_result(
MockFileStream::OperationResult(net::ERR_FAILED, GetParam()));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
mock_loader_->OnReadCompleted(test_data);
// Wait for the write to complete, in the async case.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(MockResourceLoader::Status::CANCELED, mock_loader_->status());
EXPECT_EQ(net::ERR_FAILED, mock_loader_->error_code());
EXPECT_EQ(0, test_handler_->on_response_completed_called());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::ERR_FAILED)));
EXPECT_EQ(0, test_handler_->total_bytes_downloaded());
EXPECT_FALSE(test_handler_->final_status().is_success());
EXPECT_EQ(net::ERR_FAILED, test_handler_->final_status().error());
}
TEST_P(RedirectToFileResourceHandlerTest, SecondWriteFails) {
const int kFirstWriteSize = kMaxInitialSyncReadSize;
std::string test_data =
CreateTestData(RedirectToFileResourceHandler::kInitialReadBufSize);
file_stream_->set_expected_written_data(test_data.substr(0, kFirstWriteSize));
file_stream_->set_all_write_results(
MockFileStream::OperationResult(net::ERR_FAILED, GetParam()));
file_stream_->set_next_write_result(MockFileStream::OperationResult(
std::numeric_limits<int>::max(), GetParam()));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
StartAndCreateStream(base::File::FILE_OK));
ASSERT_EQ(MockResourceLoader::Status::IDLE,
OnResponseStartedAndWaitForResult());
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnReadCompleted(
base::StringPiece(test_data.data(), kFirstWriteSize)));
ASSERT_EQ(MockResourceLoader::Status::IDLE, mock_loader_->OnWillRead());
mock_loader_->OnReadCompleted(base::StringPiece(
test_data.data() + kFirstWriteSize, test_data.size() - kFirstWriteSize));
// Wait for the write to complete, in the async case.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(MockResourceLoader::Status::CANCELED, mock_loader_->status());
EXPECT_EQ(net::ERR_FAILED, mock_loader_->error_code());
EXPECT_EQ(0, test_handler_->on_response_completed_called());
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseCompleted(
net::URLRequestStatus::FromError(net::ERR_FAILED)));
EXPECT_EQ(kFirstWriteSize, test_handler_->total_bytes_downloaded());
EXPECT_FALSE(test_handler_->final_status().is_success());
EXPECT_EQ(net::ERR_FAILED, test_handler_->final_status().error());
}
INSTANTIATE_TEST_CASE_P(/* No prefix needed */,
RedirectToFileResourceHandlerTest,
testing::Values(CompletionMode::SYNC,
CompletionMode::ASYNC));
} // namespace
} // namespace content
| 40.352029 | 80 | 0.731776 | [
"vector"
] |
aaf7373df97ffe7f96d71e9c258178e44e872392 | 4,107 | hpp | C++ | src/lib/cli_cpp/cli/A_CLI_Manager_Configuration.hpp | marvins/cli-cpp | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | [
"MIT"
] | 4 | 2020-10-08T03:09:10.000Z | 2022-03-13T09:22:51.000Z | src/lib/cli_cpp/cli/A_CLI_Manager_Configuration.hpp | marvins/cli-cpp | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | [
"MIT"
] | 4 | 2015-05-30T17:40:46.000Z | 2015-07-01T01:10:16.000Z | src/lib/cli_cpp/cli/A_CLI_Manager_Configuration.hpp | marvins/cli-cpp | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | [
"MIT"
] | 2 | 2015-06-02T20:07:39.000Z | 2020-12-16T09:25:38.000Z | /**
* @file A_CLI_Manager_Configuration.hpp
* @author Marvin Smith
* @date 5/18/2015
*/
#ifndef CLI_A_CLI_MANAGER_CONFIGURATION_HPP
#define CLI_A_CLI_MANAGER_CONFIGURATION_HPP
// C++ Standard Libraries
#include <map>
#include <string>
#include <vector>
// CLI Libraries
#include "A_Connection_Manager_Base.hpp"
#include "A_Connection_Manager_Base_Config.hpp"
#include "../core/ConnectionType.hpp"
#include "../core/SessionType.hpp"
#include "../cmd/A_Command_Parser.hpp"
#include "../event/Event_Manager_Config.hpp"
#include "../render/A_Render_Driver_Context_Base.hpp"
#include "../render/A_Render_Manager_Base.hpp"
namespace CLI{
/**
* @class A_CLI_Manager_Configuration
*
* @brief Configuration parameters required for the CLI-Manager.
*/
class A_CLI_Manager_Configuration
{
public:
/**
* @brief Default Constructor
*
* Don't use unless as there are no setters in this method
*/
A_CLI_Manager_Configuration();
/**
* @brief Constructor
*/
A_CLI_Manager_Configuration( std::vector<A_Connection_Manager_Base_Config::ptr_t> connection_configs,
std::map<CORE::SessionType,
RENDER::Render_Driver_Config_Base::ptr_t> render_driver_configs,
CMD::A_Command_Parser::ptr_t command_parser,
CMD::A_Command_Queue_Config command_queue_config,
EVT::Event_Manager_Config event_manager_config );
/**
* @brief Get the Connection-Manager Configuration.
*
* @return Connection-Manager configuration object.
*/
inline std::vector<A_Connection_Manager_Base_Config::ptr_t> Get_Connection_Manager_Configs()const{
return m_connection_manager_configurations;
}
/**
* @brief Get the Render-Driver Configurations
* @return
*/
inline std::map<CORE::SessionType,RENDER::Render_Driver_Config_Base::ptr_t> Get_Render_Driver_Configs()const{
return m_render_driver_configs;
}
/**
* @brief Get the Command Parser
*
* @return Command Parser.
*/
inline CMD::A_Command_Parser::ptr_t Get_Command_Parser()const{
return m_command_parser;
}
/**
* @brief Get the CLI Command Queue Configuration.
*
* @return Command-Queue Configuration
*/
inline CMD::A_Command_Queue_Config Get_Command_Queue_Config()const{
return m_command_queue_config;
}
/**
* @brief Get the Event-Manager Configuration
*
* @return Event Manager config
*/
inline EVT::Event_Manager_Config Get_Event_Manager_Config()const{
return m_event_manager_config;
}
/**
* @brief Check if the configuration is valid.
*
* @return True if valid, false otherwise.
*/
bool Is_Valid()const;
/**
* @brief Print to Logging String
*/
std::string To_Log_String( int offset = 0 )const;
private:
/// Class Name
std::string m_class_name;
/// Connection Manager Configuration
std::vector<A_Connection_Manager_Base_Config::ptr_t> m_connection_manager_configurations;
/// Render Configurations
std::map<CORE::SessionType,RENDER::Render_Driver_Config_Base::ptr_t> m_render_driver_configs;
/// Command Parser
CMD::A_Command_Parser::ptr_t m_command_parser;
/// Event Manager Configuration
EVT::Event_Manager_Config m_event_manager_config;
/// Command Queue Configuration
CMD::A_Command_Queue_Config m_command_queue_config;
}; // End of A_CLI_Manager_Configuration Class
} // End of CLI Namespace
#endif
| 28.130137 | 117 | 0.601169 | [
"render",
"object",
"vector"
] |
aafebd8363a309930c7ba6332105304d54919c16 | 973 | hpp | C++ | src/json2cpp.hpp | jmarrec/json2cpp | 253111ce7d1154cb1d1d9ea022e304c5b21cfbc3 | [
"BSD-3-Clause"
] | null | null | null | src/json2cpp.hpp | jmarrec/json2cpp | 253111ce7d1154cb1d1d9ea022e304c5b21cfbc3 | [
"BSD-3-Clause"
] | null | null | null | src/json2cpp.hpp | jmarrec/json2cpp | 253111ce7d1154cb1d1d9ea022e304c5b21cfbc3 | [
"BSD-3-Clause"
] | null | null | null | #ifndef JSON2CPP_HPP
#define JSON2CPP_HPP
#include <filesystem>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
#include <string>
#include <vector>
struct compile_results
{
std::vector<std::string> hpp;
std::vector<std::string> impl;
};
std::string compile(const nlohmann::json &value, std::size_t &obj_count, std::vector<std::string> &lines);
compile_results compile(const std::string_view document_name, const nlohmann::json &json);
compile_results compile(const std::string_view document_name, const std::filesystem::path &filename);
void write_compilation(std::string_view document_name,
const compile_results &results,
const std::filesystem::path &base_output);
void compile_to(const std::string_view document_name,
const nlohmann::json &json,
const std::filesystem::path &base_output);
void compile_to(const std::string_view document_name,
const std::filesystem::path &filename,
const std::filesystem::path &base_output);
#endif
| 24.325 | 106 | 0.765673 | [
"vector"
] |
c903536f5decdb7b53504847fe2c27963b36c743 | 1,096 | cpp | C++ | TrainingWithBook/GRAPH/How to initialise graph.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/GRAPH/How to initialise graph.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/GRAPH/How to initialise graph.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
int n = 777;
vector <int> adj1[n]; //array of "adjacencies" - edges of our graph
adj1[1].push_back(2);
adj1[2].push_back(3);
adj1[2].push_back(4);
/*Ориентированный граф - то же самое, но надо определить, какая вершина - начало ребра, а какая - конец*/
/*Взвешенный граф:*/
vector <pair<int,int>> adj2[n]; //adj[i] - {x,y}, x - # of vertex, y - weight of edge i,x
adj2[2].push_back({4,4});// in our graph we can find edge (2;4) with weight 4
int s;//в цикле обходим все ребра, которые выходят из вершины с номером s
/*МАТРИЦА СМЕЖНОСТИ*/
int matrixOfAdj[n][n];
//If in our graph we can find an edge (i;j), matrixOfAdj[i][j] will be equal to the weight of that edge & if there is no edge (i;j), matrixOfAdj[i][j] = 0
/*LIST OF ALL EDGES*/
vector <pair<int,int>> edges;
//if there is an edge (i;j), we add it as a pair of vertexes to our list
//if edges in our graph have a weight, we can extend our list:
vector <tuple<int,int,int>> edges1;//{i,j,weight}
}
| 39.142857 | 158 | 0.632299 | [
"vector"
] |
c90645b186aa88e97e330f435ab62e0a01a313ea | 572 | cpp | C++ | LeetCode/Problems/Algorithms/#1696_JumpGameVI_sol3_dp_and_multiset_O(NlogK)_time_O(N)_extra_space_340ms_135.4MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#1696_JumpGameVI_sol3_dp_and_multiset_O(NlogK)_time_O(N)_extra_space_340ms_135.4MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#1696_JumpGameVI_sol3_dp_and_multiset_O(NlogK)_time_O(N)_extra_space_340ms_135.4MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
int maxResult(vector<int>& nums, int k) {
const int N = nums.size();
const int INF = 1e9;
vector<int> maxScore(N);
maxScore[0] = nums[0];
multiset<int> scores;
scores.insert(maxScore[0]);
for(int i = 1; i < N; ++i){
maxScore[i] = nums[i] + *scores.rbegin();
scores.insert(maxScore[i]);
if(scores.size() > k){
scores.erase(scores.find(maxScore[i - k]));
}
}
return maxScore[N - 1];
}
}; | 30.105263 | 60 | 0.466783 | [
"vector"
] |
c9110aa187e2898a8a6590a7207a52adbf834ee2 | 1,240 | hpp | C++ | include/astar.hpp | Dai-z/Robot2019 | 7e76fb5b72e725a15f02006b000665ec4393d761 | [
"MIT"
] | null | null | null | include/astar.hpp | Dai-z/Robot2019 | 7e76fb5b72e725a15f02006b000665ec4393d761 | [
"MIT"
] | null | null | null | include/astar.hpp | Dai-z/Robot2019 | 7e76fb5b72e725a15f02006b000665ec4393d761 | [
"MIT"
] | 1 | 2021-01-05T06:18:42.000Z | 2021-01-05T06:18:42.000Z | #include <geometry_msgs/Vector3.h>
#include <ros/ros.h>
#include <vector>
#include "imb/MCLInfo.h"
#include "imb/AStarInfo.h"
#include "imb/MarkInfo.h"
const int BOUND_X = 450;
const int BOUND_Y = 300;
struct DIR {
DIR(int dx, int dy, int dz, int cost = 1)
: dx(dx), dy(dy), dz(dz), cost(cost) {}
int dx, dy, dz;
int cost;
};
struct STATUS {
STATUS() {}
STATUS(int x, int y, int z, int cost) : x(x), y(y), z(z), cost(cost) {}
STATUS(geometry_msgs::Vector3 pos, int cost)
: x(pos.x), y(pos.y), z(pos.z), cost(cost) {}
int x, y, z;
int cost, heuristic;
STATUS* prev = NULL;
};
class AStar {
public:
AStar(ros::NodeHandle* nh);
~AStar();
void step();
private:
ros::NodeHandle* nh_;
ros::Subscriber sub_marks_;
ros::Subscriber sub_amcl_;
ros::Publisher pub_;
void marksCallback(const imb::MarkInfo::ConstPtr& msg);
void amclCallback(const imb::MCLInfo::ConstPtr& msg);
geometry_msgs::Vector3 robot_pos_;
geometry_msgs::Vector3 target_;
std::vector<geometry_msgs::Vector3> route_;
// For AMCL
// Moving steps
std::vector<DIR> dirs_;
// Heap for storing astar status
std::vector<STATUS*> heap_;
// Map
int map_[100][100][40];
int getHeuristic(const STATUS& a);
};
| 21.37931 | 73 | 0.650806 | [
"vector"
] |
c91db48804876a1c83d9b8cb325345f77448908a | 2,111 | cc | C++ | main_console.cc | GaryRay/mallie | 8588a98efff2d9c143cc361dedb1303e4452453c | [
"Zlib"
] | null | null | null | main_console.cc | GaryRay/mallie | 8588a98efff2d9c143cc361dedb1303e4452453c | [
"Zlib"
] | null | null | null | main_console.cc | GaryRay/mallie | 8588a98efff2d9c143cc361dedb1303e4452453c | [
"Zlib"
] | null | null | null | //
// Copyright 2013 Light Transport Entertainment Inc.
//
#ifdef _OPENMP
#include <omp.h>
#endif
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <vector>
#include "camera.h"
#include "timerutil.h"
#include "render.h"
#include "jpge.h"
#include "lodepng.h"
namespace mallie {
namespace {
inline unsigned char fclamp(float x) {
int i = x * 255.5;
if (i < 0)
return 0;
if (i > 255)
return 255;
return (unsigned char)i;
}
void HDRToLDR(std::vector<unsigned char> &out, const std::vector<float> &in,
int width, int height) {
out.resize(width * height * 3);
assert(in.size() == (width * height * 3));
// Simple [0, 1] -> [0, 255]
for (int i = 0; i < width * height * 3; i++) {
out[i] = fclamp(in[i]);
}
}
void SaveAsJPEG(const char *filename,
std::vector<unsigned char> &image, // RGB
int width, int height) {
jpge::params comp_params;
comp_params.m_quality = 100;
bool ret = jpge::compress_image_to_jpeg_file(filename, width, height, 3,
&image.at(0), comp_params);
assert(ret);
}
void SaveAsPNG(const char *filename,
std::vector<unsigned char> &image, // RGB
int width, int height) {
size_t out_size = 0;
std::vector<unsigned char> out;
unsigned int ret = lodepng::encode(filename, &image.at(0), width, height, LCT_RGB);
//assert(ret);
}
} // local
void DoMainConsole(Scene &scene, const RenderConfig &config) {
printf("[Mallie] Console mode\n");
std::vector<float> image;
std::vector<int> count;
int width = config.width;
int height = config.height;
image.resize(width * height * 3);
count.resize(width * height);
mallie::Render(scene, config, image, count, config.eye, config.lookat,
config.up, config.quat, 1);
std::string outfilename("output.png"); // fixme
std::vector<unsigned char> out;
HDRToLDR(out, image, width, height);
SaveAsPNG(outfilename.c_str(), out, width, height);
printf("[Mallie] Output %s\n", outfilename.c_str());
}
} // liina
| 23.197802 | 85 | 0.622928 | [
"render",
"vector"
] |
c9243b02971dd8d923633918e23ae5310a74a625 | 19,737 | cxx | C++ | fregl/fregl_coarse2fine_register.cxx | tostathaina/farsight | 7e9d6d15688735f34f7ca272e4e715acd11473ff | [
"Apache-2.0"
] | 8 | 2016-07-22T11:24:19.000Z | 2021-04-10T04:22:31.000Z | fregl/fregl_coarse2fine_register.cxx | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | null | null | null | fregl/fregl_coarse2fine_register.cxx | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | 7 | 2016-07-21T07:39:17.000Z | 2020-01-29T02:03:27.000Z | /*=========================================================================
Copyright 2009 Rensselaer Polytechnic Institute
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 "fregl_coarse2fine_register.h"
#include <rrl/rrl_convergence_on_weighted_nas.h>
#include <rrl/rrl_pair_reg_params.h>
#include <rrl/rrl_view_generator_sptr.h>
#include <rrl/rrl_model_selection_aicc.h>
#include <rrl/rrl_model_selection_criterion_sptr.h>
#include <rrl/rrl_view_gen_models.h>
#include <rrl/rrl_convergence_on_weighted_nas.h>
#include <rrl/rrl_view_based_reg_sym.h>
#include <rgrl/rgrl_feature_set_bins.h>
#include <rgrl/rgrl_matcher_k_nearest_pick_one.h>
#include <rgrl/rgrl_weighter_m_est.h>
#include <rgrl/rgrl_scale_est_closest.h>
#include <rgrl/rgrl_scale_est_all_weights.h>
#include <rgrl/rgrl_est_affine.h>
#include <rgrl/rgrl_data_manager.h>
#include <rgrl/rgrl_data_manager_sptr.h>
#include <rgrl/rgrl_scale.h>
#include <rgrl/rgrl_convergence_tester_sptr.h>
#include <rgrl/rgrl_feature_face_pt.h>
#include <rgrl/rgrl_feature_point.h>
#include <rgrl/rgrl_mask.h>
#include <rrel/rrel_m_est_obj.h>
#include <rrel/rrel_muset_obj.h>
#include <rrel/rrel_tukey_obj.h>
fregl_coarse2fine_register::
fregl_coarse2fine_register( rrl_pair_reg_params_sptr reg_params,
InternalImageType::Pointer from_image,
InternalImageType::Pointer to_image)
:params_(reg_params)
{
// Step0: Create features
const bool generate_at_all_scales = false; //don't generate at all scale
FeatureType::Pointer from_features_3d = new FeatureType( from_image, generate_at_all_scales );
from_features_3d->set_max_num_driving_faces(reg_params->max_driving_faces_);
from_features_3d->generate_at_all_scales();
FeatureType::Pointer to_features_3d = new FeatureType( to_image, generate_at_all_scales );
to_features_3d->set_max_num_driving_faces(reg_params->max_driving_faces_);
to_features_3d->generate_at_all_scales();
// Step1: Concatenate all features
//
make_vectors_of_feature_sets( from_features_3d,
concat_moving_matchable_corners_,
concat_moving_driving_corners_,
concat_moving_matchable_faces_,
concat_moving_driving_faces_,
params_->feature_min_scale_,
params_->feature_max_scale_,
params_->c2f_upper_min_feature_scale_);
make_vectors_of_feature_sets( to_features_3d,
concat_fixed_matchable_corners_,
concat_fixed_driving_corners_,
concat_fixed_matchable_faces_,
concat_fixed_driving_faces_,
params_->feature_min_scale_,
params_->feature_max_scale_,
params_->c2f_upper_min_feature_scale_ );
// if the size are not equivalent
if( concat_moving_driving_faces_.size() != concat_fixed_driving_faces_.size() ) {
const unsigned new_size = vnl_math_min( concat_moving_driving_faces_.size(),
concat_fixed_driving_faces_.size() );
concat_moving_matchable_corners_.resize( new_size);
concat_moving_driving_corners_.resize( new_size);
concat_moving_matchable_faces_.resize( new_size);
concat_moving_driving_faces_.resize( new_size);
concat_fixed_matchable_corners_.resize( new_size);
concat_fixed_driving_corners_.resize( new_size);
concat_fixed_matchable_faces_.resize( new_size);
concat_fixed_driving_faces_.resize( new_size);
}
// Feature sets should have already been created.
assert( concat_fixed_driving_faces_.size() > 0 );
}
bool
fregl_coarse2fine_register::
run( rgrl_transformation_sptr init_xform )
{
// step 1: Create a matcher
//
vcl_vector<rgrl_matcher_sptr> matchers;
const int num_nearest_to_test = 3;
const double distance_threshold_for_match = 30;
matchers.resize( 4 );
for( unsigned i=0; i<4; ++i ) {
matchers[i] = new rgrl_matcher_k_nearest_pick_one( num_nearest_to_test, distance_threshold_for_match );
}
// Step 2: Create a robust weighter
//
const double tukey_parameter = 4;
vcl_auto_ptr< rrel_m_est_obj > est_obj( new rrel_tukey_obj(tukey_parameter) );
// The parameter "use_precomputed_signature_wgt" is set to be
// true because the weight based on scale and (for face points)
// orientation will have been computed during the matching
// process.
const bool use_signature_error = false;
const bool use_precomputed_signature_wgt = true;
rgrl_weighter_sptr wgter = new rgrl_weighter_m_est( est_obj, use_signature_error, use_precomputed_signature_wgt ) ;
// Step 3: Create a scale estimator.
//
// muse and unwgted_scale_est are used in the first iteration. Do
// NOT use sk refinement
const bool max_lookup_table_size = 0; // Prevents costly and unnecessary preliminary generation of a table
const bool use_sk_refinement_in_muse = false;
vcl_auto_ptr<rrel_objective> obj( new rrel_muset_obj( max_lookup_table_size,
use_sk_refinement_in_muse ) );
const bool estimate_signature_covar = false;
rgrl_scale_estimator_unwgted_sptr unwgted_scale_est =
new rgrl_scale_est_closest( obj, estimate_signature_covar );
unwgted_scale_est->set_debug_flag(2);
unwgted_scale_est->set_warning( false ); // remove "unstable estimates" warning
rgrl_scale_estimator_wgted_sptr wgted_scale_est =
new rgrl_scale_est_all_weights( estimate_signature_covar );
wgted_scale_est->set_debug_flag(2);
// Step 4: Create the estimator. There is only one and it is affine.
//
rgrl_estimator_sptr estimator = new rgrl_est_affine(3);
// Step 5: Create a simple view generator that includes model
// selection but not region growing. Don't need an initializer,
// just an initial view. In fact, we don't even need model
// seletion, since there is only one model in our
// estimation. However, this seems like the least expensive model
// generator. Should switch to feature-based approach later.
bool use_rho_function = true; // in forming the error objective function
rrl_model_selection_criterion_sptr model_sel = new rrl_model_selection_aicc(use_rho_function);
rrl_view_generator_sptr c2f_view_generator = new rrl_view_gen_models( model_sel );
// Step 6: Create a data manager.
//
bool use_multi_stage = true;
rgrl_data_manager_sptr data_manager = new rgrl_data_manager( use_multi_stage );
// Step 7: Determine the max number of resolutions and set up the
// data manager. The problem is that two images could have different
// number of scales available. Take the minimum!
const unsigned num_resolutions
= vnl_math_min( concat_moving_driving_faces_.size(), concat_fixed_driving_faces_.size() );
for ( unsigned int res=0; res<num_resolutions; ++res ) {
if( !params_->use_faces_only_ ) {
data_manager->add_data( res, concat_moving_driving_corners_[res],
concat_fixed_matchable_corners_[res],
matchers[0], wgter, unwgted_scale_est, wgted_scale_est );
// backward matching
if( !params_->only_forward_matching_ )
data_manager->add_data( res, concat_moving_matchable_corners_[res],
concat_fixed_driving_corners_[res],
matchers[1], wgter, unwgted_scale_est, wgted_scale_est );
}
if( !params_->use_corners_only_ ) {
data_manager->add_data( res, concat_moving_driving_faces_[res],
concat_fixed_matchable_faces_[res],
matchers[2], wgter, unwgted_scale_est, wgted_scale_est );
// backward matching
if( !params_->only_forward_matching_ )
data_manager->add_data( res, concat_moving_matchable_faces_[res],
concat_fixed_driving_faces_[res],
matchers[3], wgter, unwgted_scale_est, wgted_scale_est );
}
data_manager->add_estimator( res, estimator );
data_manager->set_dimension_increase_for_next_stage( res, 1.0 ); // All features are in coords of original res
}
vcl_cout << "rrl_pair_reg::coarse_to_fine_registration: num_resolutions = "
<< num_resolutions << vcl_endl;
// Step 8: Set the initial scales based on what has been passed in.
// Need a scale for each feature type and direction.
rgrl_scale_sptr initial_scale = new rgrl_scale();
double initial_error_scale = 1.5*params_->c2f_upper_min_feature_scale_;
initial_scale->set_geometric_scale( initial_error_scale );
// Step 9. Create a convergence tester. Use Gary's. The only thing
// there we really don't need is the test on region growing, but as
// long as we ensure that the regions indeed do not change we're ok.
rgrl_convergence_tester_sptr conv_test ;
const bool force_check_all_init = false;
conv_test= new rrl_convergence_on_weighted_nas( force_check_all_init,
params_->error_threshold_upper_,
params_->error_threshold_lower_ );
conv_test->set_rel_tol( params_->relative_error_change_for_convergence_ );
// 2.10: Create a registration object and set limits on scale estimation.
rrl_view_based_reg_sptr c2f_registration_ptr;
if( !params_->only_forward_matching_ ) {
c2f_registration_ptr
= new rrl_view_based_reg_sym( data_manager,
c2f_view_generator,
conv_test );
} else {
c2f_registration_ptr
= new rrl_view_based_registration( data_manager,
c2f_view_generator,
conv_test );
}
c2f_registration_ptr->set_debug_flag( 2 );
c2f_registration_ptr->set_expected_min_geometric_scale(0.5);
c2f_registration_ptr->set_expected_max_geometric_scale(10.0);
c2f_registration_ptr->set_max_icp_iter( 8 );
// 2.11: Create the initial view
rgrl_mask_box moving_box = concat_moving_matchable_faces_[0]->bounding_box();
rgrl_mask_sptr moving_box_sptr = new rgrl_mask_box( moving_box );
rgrl_mask_box fixed_box = concat_fixed_matchable_faces_[0]->bounding_box();
rgrl_mask_sptr fixed_box_sptr = new rgrl_mask_box( fixed_box );
init_view_ = new rgrl_view( moving_box_sptr,
fixed_box_sptr,
moving_box,
moving_box,
estimator,
init_xform,
0,
init_xform->inverse_transform() );
// Final step: run the refinement!
// coarse-to-fine refinement is done with the reg engine.
// This for loop ensures that when reg fails at a coarse level,
// it can still try a finer level where there are more features.
for( unsigned res=num_resolutions-1; res>0&&!c2f_registration_ptr->has_best_view(); --res ) {
// make a copy of the view (the view may be rrl_view_sym type)
rgrl_view_sptr initial_view = init_view_->self_copy();
// set resolution to the coarsest one.
// No need to scale as everything is in image coordinate.
initial_view->set_resolution( res );
vcl_cout << "Coarse-to-fine registration is starting at level=(" << res << ")..." << vcl_endl;
c2f_registration_ptr->run( initial_view, initial_scale );
vcl_cout << "Finished coarse-to-fine registration..." << vcl_endl;
}
// If a best_view is available, an accurate alignment has been
// produced.
if ( !c2f_registration_ptr->has_best_view() ) {
vcl_cout << "Leaving rrl_pair_reg::coarse_to_fine_registration, without convergence."
<< vcl_endl;
return false;
}
else {
//final_view = reg_sptr->final_view();
//Store the result!
return true;
}
}
// This code is from rrl_gdbicp_info::rkpl_faces_to_rgrl_features. So,
// this code cannot be distriubted.
//
void
fregl_coarse2fine_register::
rkpl_faces_to_rgrl_features( vcl_vector< rkpl_keypoint<3> > const& rkpl_faces,
feature_vector & features )
{
vnl_vector<double> loc(3), dir(3);
for( unsigned int i=0; i<rkpl_faces.size(); ++i )
{
loc[0] = rkpl_faces[i].physical_location[0];
loc[1] = rkpl_faces[i].physical_location[1];
loc[2] = rkpl_faces[i].physical_location[2];
dir[0] = rkpl_faces[i].direction[0];
dir[1] = rkpl_faces[i].direction[1];
dir[2] = rkpl_faces[i].direction[2];
rgrl_feature_sptr fptr = new rgrl_feature_face_pt( loc, dir );
fptr->set_scale( rkpl_faces[i].smoothing_scale );
features.push_back( fptr );
}
}
// This code is from rrl_gdbicp_info::rkpl_corners_to_rgrl_features. So,
// this code cannot be distriubted.
//
void
fregl_coarse2fine_register::
rkpl_corners_to_rgrl_features( vcl_vector< rkpl_keypoint<3> > const& rkpl_corners,
feature_vector & features )
{
vnl_vector<double> loc(3);
for( unsigned int i=0; i<rkpl_corners.size(); ++i )
{
loc[0] = rkpl_corners[i].physical_location[0];
loc[1] = rkpl_corners[i].physical_location[1];
loc[2] = rkpl_corners[i].physical_location[2];
rgrl_feature_sptr fptr = new rgrl_feature_point( loc );
fptr->set_scale( rkpl_corners[i].smoothing_scale );
features.push_back( fptr );
}
}
// This code is from
// rrl_gdbicp_info::make_vectors_of_feature_sets. So, this code cannot
// be distriubted.
//
void
fregl_coarse2fine_register::
make_vectors_of_feature_sets(FeatureType::Pointer features,
feature_set_vector & concat_matchable_corners,
feature_set_vector & concat_driving_corners,
feature_set_vector & concat_matchable_faces,
feature_set_vector & concat_driving_faces,
double min_scale,
double max_scale,
double upper_min_feature_scale)
{
feature_vector as_rgrl_features;
// check on features available
if( !features->num_scales() ) {
vcl_cerr<<"Warning: Empty features set."<<vcl_endl;
return;
}
// Here we consider the entire set of features.
int min_index = 0;
int max_index = features->num_scales()-1;
int upper_min_index = min_index;
while ( upper_min_index < max_index &&
upper_min_feature_scale > 0 &&
features->scale(upper_min_index) <= upper_min_feature_scale )
++ upper_min_index;
if( upper_min_index > min_index )
--upper_min_index;
const int bin_size_for_matchable_faces = 10;
const int bin_size_for_driving_faces = 15;
const int bin_size_for_matchable_corners = 20;
const int bin_size_for_driving_corners = 25;
// Matchable corners
as_rgrl_features.reserve(5000);
concat_matchable_corners.resize( upper_min_index - min_index + 1 );
for ( int i=max_index; i>=min_index; --i ) {
rkpl_corners_to_rgrl_features( features->matchable_corners(i),
as_rgrl_features );
if ( i <= upper_min_index ) {
rgrl_feature_set_sptr fset
= new rgrl_feature_set_bins<3>( as_rgrl_features,
bin_size_for_matchable_corners,
vcl_string("MATCHABLE:CORNER") );
concat_matchable_corners[i-min_index] = fset;
vcl_cout<<"Created a matchable corner feature set at index " << i-min_index
<< ", and size " << as_rgrl_features.size() << vcl_endl;
DebugMacro( 3, "Created a matchable corner feature set at index " << i-min_index
<< ", and size " << as_rgrl_features.size() << vcl_endl );
}
}
// Driving corners
as_rgrl_features.clear();
as_rgrl_features.reserve(5000);
concat_driving_corners.resize( upper_min_index - min_index + 1 );
for ( int i=max_index; i>=min_index; --i ) {
rkpl_corners_to_rgrl_features( features->driving_corners(i),
as_rgrl_features );
if ( i <= upper_min_index ) {
rgrl_feature_set_sptr fset
= new rgrl_feature_set_bins<3>( as_rgrl_features,
bin_size_for_driving_corners,
vcl_string("DRIVING:CORNER") );
concat_driving_corners[i-min_index] = fset;
vcl_cout<<"Created a driving corner feature set at index " << i-min_index
<< ", and size " << as_rgrl_features.size() << vcl_endl;
DebugMacro(3, "Created a driving corner feature set at index " << i-min_index
<< ", and size " << as_rgrl_features.size() << vcl_endl );
}
}
// Matchable faces
as_rgrl_features.clear();
as_rgrl_features.reserve(5000);
concat_matchable_faces.resize( upper_min_index - min_index + 1 );
for ( int i=max_index; i>=min_index; --i ) {
rkpl_faces_to_rgrl_features( features->matchable_faces(i),
as_rgrl_features );
if ( i <= upper_min_index ) {
rgrl_feature_set_sptr fset
= new rgrl_feature_set_bins<3>( as_rgrl_features,
bin_size_for_matchable_faces,
vcl_string("MATCHABLE:FACE") );
concat_matchable_faces[i-min_index] = fset;
vcl_cout<< "Created a matchable faces feature set at index "
<< i-min_index
<< ", and size " << as_rgrl_features.size()
<< vcl_endl ;
DebugMacro( 3, "Created a matchable faces feature set at index "
<< i-min_index
<< ", and size " << as_rgrl_features.size()
<< vcl_endl );
}
}
// Driving faces
as_rgrl_features.clear();
as_rgrl_features.reserve(5000);
concat_driving_faces.resize( upper_min_index - min_index + 1 );
for ( int i=max_index; i>=min_index; --i ) {
rkpl_faces_to_rgrl_features( features->driving_faces(i),
as_rgrl_features );
if ( i <= upper_min_index ) {
rgrl_feature_set_sptr fset
= new rgrl_feature_set_bins<3>( as_rgrl_features,
bin_size_for_driving_faces,
vcl_string("DRIVING:FACE") );
concat_driving_faces[i-min_index] = fset;
vcl_cout<< "Created a driving faces feature set at index "
<< i-min_index
<< ", and size " << as_rgrl_features.size()
<< vcl_endl;
DebugMacro( 3, "Created a driving faces feature set at index "
<< i-min_index
<< ", and size " << as_rgrl_features.size()
<< vcl_endl );
}
}
}
| 42.083156 | 117 | 0.651923 | [
"object",
"model"
] |
c92aa04e316e2d31eac0fb5cf1ed465aaa5f4221 | 10,641 | hh | C++ | src/bbdep_sm.hh | poluyan/PepDockOpt | 4769a493080a28ed255b4c3d7b6c18fa44761a01 | [
"Apache-2.0"
] | null | null | null | src/bbdep_sm.hh | poluyan/PepDockOpt | 4769a493080a28ed255b4c3d7b6c18fa44761a01 | [
"Apache-2.0"
] | null | null | null | src/bbdep_sm.hh | poluyan/PepDockOpt | 4769a493080a28ed255b4c3d7b6c18fa44761a01 | [
"Apache-2.0"
] | null | null | null | /**************************************************************************
Copyright © 2019 Sergey Poluyan <svpoluyan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**************************************************************************/
#ifndef INCLUDED_bbdep_sm_hh
#define INCLUDED_bbdep_sm_hh
#include <bbutils.hh>
#include <dunbrackdata.hh>
#include <core/chemical/AtomType.hh>
#include <core/pose/Pose.hh>
#include <core/pose/util.hh>
#include <numeric/NumericTraits.hh>
namespace pepdockopt
{
namespace bbdep
{
struct sm_1d
{
std::vector<bbdep::Dunbrack_data> lib;
std::vector<std::vector<int>> libn;
std::vector<std::pair<double, double>> lib_grid;
std::vector<std::vector<double>> lib_states;
std::vector<bbutils::distribution_1d> lib_independent;
std::vector<std::vector<bbutils::distribution_1d>> lib_cdf_sum_all;
};
struct sm_2d
{
std::vector<bbdep::Dunbrack_data> lib;
std::vector<std::vector<int>> libn;
std::vector<std::pair<double, double>> lib_grid;
std::vector<std::vector<double>> lib_states_chi1;
std::vector<bbutils::distribution_1d> lib_independent;
std::vector<std::vector<bbutils::distribution_1d>> lib_cdf_sum_all;
std::vector<std::vector<bbutils::distribution_1d>> lib_chi2_depend_chi1;
};
struct sm_3d
{
std::vector<bbdep::Dunbrack_data> lib;
std::vector<std::vector<int>> libn;
std::vector<std::pair<double, double>> lib_grid;
std::vector<std::vector<double>> lib_states_chi1;
std::vector<std::vector<std::vector<double>>> lib_states_chi2;
std::vector<bbutils::distribution_1d> lib_independent;
std::vector<std::vector<bbutils::distribution_1d>> lib_cdf_sum_all;
std::vector<std::vector<bbutils::distribution_1d>> lib_chi2_depend_chi1;
std::vector<std::vector<std::vector<bbutils::distribution_1d>>> lib_chi3_depend_chi12;
};
struct sm_4d
{
std::vector<bbdep::Dunbrack_data> lib;
std::vector<std::vector<int>> libn;
std::vector<std::pair<double, double>> lib_grid;
std::vector<std::vector<double>> lib_states_chi1;
std::vector<std::vector<std::vector<double>>> lib_states_chi2;
std::vector<std::vector<std::vector<std::vector<double>>>> lib_states_chi3;
std::vector<bbutils::distribution_1d> lib_independent;
std::vector<std::vector<bbutils::distribution_1d>> lib_cdf_sum_all;
std::vector<std::vector<bbutils::distribution_1d>> lib_chi2_depend_chi1;
std::vector<std::vector<std::vector<bbutils::distribution_1d>>> lib_chi3_depend_chi12;
std::vector<std::vector<std::vector<std::vector<bbutils::distribution_1d>>>> lib_chi4_depend_chi123;
std::vector<std::vector<std::vector<size_t>>> lib_impossible_conformations;
};
class BBDEP_Dunbrack_sm
{
private:
std::string path;
size_t cdf_grid_step;
public:
std::vector<sm_1d> aa_sm_1d; // 0 ser, 1 val, 2 cys, 3 thr
std::vector<sm_2d> aa_sm_2d; // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu
std::vector<sm_3d> aa_sm_3d; // 0 met, 1 glu, 2 gln, 3 pro
std::vector<sm_4d> aa_sm_4d; // 0 arg, 1 lys
BBDEP_Dunbrack_sm();
void set_path(std::string path_to_files);
void set_step(size_t step);
void load_data_sm(std::string amino_acids);
void initialize_all(bool create_cdf_sum, std::string amino_acids, int threads_number);
void create_cdf_sums(core::chemical::AA amino_acid);
bbutils::distribution_1d get_chi1_all(std::vector<bbdep::Dunbrack_data> &data) const;
bbutils::distribution_1d get_chi2_all(std::vector<bbdep::Dunbrack_data> &data) const;
bbutils::distribution_1d get_chi3_all(std::vector<bbdep::Dunbrack_data> &data) const;
bbutils::distribution_1d get_chi4_all(std::vector<bbdep::Dunbrack_data> &data) const;
bbutils::distribution_1d fill_uniformly() const;
Dunbrack_data get_max(core::chemical::AA amino_acid, double Phi, double Psi);
size_t get_index_from_phi_psi(const std::vector<std::pair<double, double>> &data, double Phi, double Psi) const;
void fill_grid_and_states_and_create_cdf_chi1(const std::vector<bbdep::Dunbrack_data> &data,
std::vector<std::pair<double, double>> &all_chi1_index,
std::vector<bbutils::distribution_1d> &all_independent,
std::vector<std::vector<bbutils::distribution_1d>> &all_chi1_value,
std::vector<std::vector<double>> &states);
void fill_grid_and_states_and_create_cdf_chi2(const std::vector<bbdep::Dunbrack_data> &data,
std::vector<std::pair<double, double>> &all_chi1_index,
std::vector<bbutils::distribution_1d> &all_independent,
std::vector<std::vector<bbutils::distribution_1d>> &all_chi12_value,
std::vector<std::vector<bbutils::distribution_1d>> &chi2_depend_chi1,
std::vector<std::vector<double>> &states);
void fill_grid_and_states_and_create_cdf_chi3(const std::vector<bbdep::Dunbrack_data> &data,
std::vector<std::pair<double, double>> &all_chi1_index,
std::vector<bbutils::distribution_1d> &all_independent,
std::vector<std::vector<bbutils::distribution_1d>> &all_chi123_value,
std::vector<std::vector<bbutils::distribution_1d>> &chi2_depend_chi1,
std::vector<std::vector<std::vector<bbutils::distribution_1d>>> &chi3_depend_chi12,
std::vector<std::vector<double>> &chi1_states,
std::vector<std::vector<std::vector<double>>> &chi2_states);
void fill_grid_and_states_and_create_cdf_chi4(const std::vector<bbdep::Dunbrack_data> &data,
std::vector<std::pair<double, double>> &all_chi1_index,
std::vector<bbutils::distribution_1d> &all_independent,
std::vector<std::vector<bbutils::distribution_1d>> &all_chi1234_value,
std::vector<std::vector<bbutils::distribution_1d>> &chi2_depend_chi1,
std::vector<std::vector<std::vector<bbutils::distribution_1d>>> &chi3_depend_chi12,
std::vector<std::vector<std::vector<std::vector<bbutils::distribution_1d>>>> &chi4_depend_chi123,
std::vector<std::vector<double>> &chi1_states,
std::vector<std::vector<std::vector<double>>> &chi2_states,
std::vector<std::vector<std::vector<std::vector<double>>>> &chi3_states);
size_t determine_rotamer_state_0_2pi(double degree) const;
size_t determine_proline_rotamer_state_0_2pi(double degree) const;
size_t determine_rotamer_state_0_2pi_actual_chi1(size_t index, double degree, core::chemical::AA amino_acid) const;
size_t determine_rotamer_state_0_2pi_actual_chi2(size_t index, size_t chi1_state, double degree, core::chemical::AA amino_acid) const;
size_t determine_rotamer_state_0_2pi_actual_chi3(size_t index, size_t chi1_state, size_t chi2_state, double degree, core::chemical::AA amino_acid) const;
size_t find_index_for_cdf_chi234(core::chemical::AA amino_acid, double Phi, double Psi) const;
double get_degree_bbdep_from_phi_psi_x01_chi1_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const;
double get_degree_bbdep_from_phi_psi_x01_chi12_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const;
double get_degree_bbdep_from_phi_psi_x01_chi123_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const;
double get_degree_bbdep_from_phi_psi_x01_chi1_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const;
double get_degree_bbdep_from_phi_psi_x01_chi12_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const;
double get_degree_bbdep_from_phi_psi_x01_chi123_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const;
double get_inverse_degree_bbdep_from_phi_psi_x01_chi1_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const;
double get_inverse_degree_bbdep_from_phi_psi_x01_chi12_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const;
double get_inverse_degree_bbdep_from_phi_psi_x01_chi123_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const;
double get_inverse_degree_bbdep_from_phi_psi_x01_chi1_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const;
double get_inverse_degree_bbdep_from_phi_psi_x01_chi12_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const;
double get_inverse_degree_bbdep_from_phi_psi_x01_chi123_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const;
void fill_impossible_conformations(std::vector<bbdep::Dunbrack_data> &data,
std::vector<std::vector<std::vector<size_t>>> &imp_conf);
bool is_impossible_conformation(std::vector<size_t> conf,
double Phi,
double Psi,
std::vector<std::pair<double, double>> &lys_grid,
std::vector<std::vector<std::vector<size_t>>> &imp_conf);
bbdep::Dunbrack_data get_first_line(core::chemical::AA amino_acid) const;
double get_degree_bbind(core::chemical::AA amino_acid, double x01, size_t chinumber) const;
double get_degree_bbdep_from_phi_psi_x01_chinumber(size_t index, core::chemical::AA amino_acid, double x01, size_t chinumber) const;
};
double pdf_normal_dst(double x, double mu, double sigma);
void plot_chi1_all(pepdockopt::bbdep::BBDEP_Dunbrack_sm& bbdep_sm);
}
}
#endif
| 55.134715 | 228 | 0.732544 | [
"vector"
] |
c92d83f7ed3869b24f3cf543253a488b318feddf | 2,959 | cpp | C++ | private/shell/ext/mydocs/src/command.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/ext/mydocs/src/command.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/ext/mydocs/src/command.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | /*----------------------------------------------------------------------------
/ Title;
/ command.cpp
/
/ Authors;
/ Rick Turner (ricktu)
/
/ Notes;
/ Implements IOleCommandTarget for My Documents code.
/----------------------------------------------------------------------------*/
#include "precomp.hxx"
#pragma hdrstop
/*-----------------------------------------------------------------------------
/ CMyDocsCommand
/ This is the My Documents IOleCommandTarget implementation.
/----------------------------------------------------------------------------*/
CMyDocsCommand::CMyDocsCommand( )
{
TraceEnter(TRACE_COMMAND, "CMyDocsCommand::CMyDocsCommand");
TraceLeave();
}
CMyDocsCommand::~CMyDocsCommand()
{
TraceEnter(TRACE_COMMAND, "CMyDocsCommand::~CMyDocsCommand");
TraceLeave();
}
#undef CLASS_NAME
#define CLASS_NAME CMyDocsCommand
#include "unknown.inc"
STDMETHODIMP
CMyDocsCommand::QueryInterface(REFIID riid, LPVOID* ppvObject)
{
INTERFACES iface[] =
{
&IID_IOleCommandTarget, (IOleCommandTarget *)this,
};
return HandleQueryInterface(riid, ppvObject, iface, ARRAYSIZE(iface));
}
/*-----------------------------------------------------------------------------
/ IOleCommandTarget
/----------------------------------------------------------------------------*/
STDMETHODIMP
CMyDocsCommand::QueryStatus( const GUID *pguidCmdGroup,
ULONG cCmds,
OLECMD prgCmds[],
OLECMDTEXT *pCmdText
)
{
HRESULT hr = OLECMDERR_E_UNKNOWNGROUP;
TraceEnter(TRACE_COMMAND, "CMyDocsCommand::QueryStatus");
if (IsEqualGUID(*pguidCmdGroup, CGID_ShellServiceObject))
{
// We like Shell Service Object notifications...
hr = S_OK;
}
TraceLeaveResult(hr);
}
/*---------------------------------------------------------------------------*/
STDMETHODIMP
CMyDocsCommand::Exec( const GUID *pguidCmdGroup,
DWORD nCmdID,
DWORD nCmdexecopt,
VARIANTARG *pvaIn,
VARIANTARG *pvaOut
)
{
HRESULT hr = E_NOTIMPL;
TraceEnter(TRACE_COMMAND, "CMyDocsCommand::Exec");
if (IsEqualGUID(*pguidCmdGroup, CGID_ShellServiceObject))
{
// Handle Shell Service Object notifications here.
switch (nCmdID)
{
case SSOCMDID_OPEN:
Trace(TEXT("Called w/OPEN"));
hr = _CheckPerUserSettings();
break;
case SSOCMDID_CLOSE:
Trace(TEXT("Called w/CLOSE"));
hr = _RemovePerUserSettings();
break;
default:
hr = S_OK;
break;
}
}
TraceLeaveResult( hr );
}
| 26.419643 | 80 | 0.456573 | [
"object"
] |
c92ec9cefe05dc063223aec7ecf549323c9834d4 | 1,713 | cpp | C++ | lintcode/rehashing.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | lintcode/rehashing.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | lintcode/rehashing.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | /**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param hashTable: A list of The first node of linked list
* @return: A list of The first node of linked list which have twice size
*/
vector<ListNode*> rehashing(vector<ListNode*> hashTable) {
// write your code here
int m=hashTable.size();
int n=2*m;
vector<ListNode*> res(n,NULL);
for(int i=0; i<m; i++){
if(hashTable[i]!=NULL){
ListNode *cur=hashTable[i];
while(cur){
ListNode *next=cur->next;
int index;
if(cur->val<0){
index=((cur->val)%n+n)%n;
}else{
index=(cur->val)%n;
}
//insert it into new hash table
if(res[index]==NULL){
//set cur as head
res[index]=cur;
cur->next=NULL;
}else{
//insert it at tail
ListNode *p = res[index];
while(p->next){
p=p->next;
}
p->next=cur;
cur->next=NULL;
}
cur=next;
}
}
}
return res;
}
};
| 27.190476 | 77 | 0.350263 | [
"vector"
] |
c93042ebf43aa6773c25df81fd20121a8fd5a319 | 405 | hpp | C++ | source/kantan/System/System.hpp | Qu3tzal/sakura-no-hana | 7b3a5d4a5816a2a4bd82c30ef2328cbe7fe85b9d | [
"MIT"
] | null | null | null | source/kantan/System/System.hpp | Qu3tzal/sakura-no-hana | 7b3a5d4a5816a2a4bd82c30ef2328cbe7fe85b9d | [
"MIT"
] | null | null | null | source/kantan/System/System.hpp | Qu3tzal/sakura-no-hana | 7b3a5d4a5816a2a4bd82c30ef2328cbe7fe85b9d | [
"MIT"
] | null | null | null | #ifndef KANTAN_SYSTEM
#define KANTAN_SYSTEM
#include <SFML/System.hpp>
#include <vector>
#include <queue>
namespace kantan
{
class Entity;
class Event;
/**
System class.
**/
class System
{
public:
// Ctor.
System();
virtual void update(sf::Time elapsed, std::vector<Entity*>& entities, std::queue<Event*>& eventQueue) = 0;
};
} // namespace kantan.
#endif // KANTAN_SYSTEM
| 14.464286 | 109 | 0.659259 | [
"vector"
] |
c93b4ef11c7e264aac56d7f1ff8a520da55e7a00 | 22,663 | cpp | C++ | hackathon/LXF/soma_remove/svds.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/LXF/soma_remove/svds.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/LXF/soma_remove/svds.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#include <climits>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
#include "fun.h"
#include <algorithm>
#include "svds.h"
using namespace std;
const double EPS=1e-15;
void printt(vector<vector<double> > &X){
cout.precision(6);
cout.setf(ios::fixed);
for(int i=0;i<X.size();i++){
for(int j=0;j<X[i].size();j++)
cout<<X[i][j]<<' ';
cout<<endl;
}
cout<<endl;
}
void transpose(vector<vector<double> > &A, vector<vector<double> > &T){
if(A.empty()||A[0].empty()) return;
int m=A.size();
int n=A[0].size();
T.clear();
T.resize(n,vector<double>(m,0));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
T[j][i]=A[i][j];
}
void transpose(vector<vector<double> > &A){
int m=A.size();
for(int i=0;i<m;i++)
for(int j=i+1;j<m;j++)
swap(A[i][j],A[j][i]);
}
void randUnitVector(int n, vector<double> &v){
srand(time(NULL));
v.clear();v.resize(n);
while(true){
double r=0;
for(int i=0;i<n;i++){
v[i]=rand()*1.0/RAND_MAX-0.5;
r+=v[i]*v[i];
}
r=sqrt(r);
if(r>EPS){
for(int i=0;i<n;i++)
v[i]/=r;
break;
}
}
}
void multiply(vector<vector<double> > &A, vector<vector<double> > &B, vector<vector<double> > &C){
//C=A*B
C.clear();
if(A.empty() || A[0].empty() || B.empty() || B[0].empty()) return ;
C.resize(A.size(),vector<double>(B[0].size(),0));
for(int i=0;i<A.size();i++){
for(int j=0;j<B[0].size();j++){
C[i][j]=0;
for(int k=0;k<A[0].size();k++){
C[i][j]+=A[i][k]*B[k][j];
}
}
}
}
void multiply(const vector<vector<double> > &X, const vector<double> & v, vector<double> & res){
res.clear();
if(X.empty() || v.empty()) return;
int m=X[0].size();
res.resize(m,0);
for(int i=0;i<m;i++){
for(int j=0;X[i].size();j++){
res[i]+=X[i][j]*v[j];
}
}
}
double dotProduct(const vector<double> & a, const vector<double> & b){
double res=0;
for(int i=0;i<a.size();i++)
res+=a[i]*b[i];
return res;
}
void rightMultiply(SparseMatrix &A, const vector<double> & v, vector<double> & res){
//res= A*A'*v
int m=A.rows;
int n=A.cols;
res.clear();
res.resize(m,0);
vector<double> w(n,0);
A.moveFirst();
while(A.hasNext()){
Cell c=A.next();
w[c.col]+=c.value*v[c.row];
}
A.moveFirst();
while(A.hasNext()){
Cell c=A.next();
res[c.row]+=c.value*w[c.col];
}
}
void leftMultiply(SparseMatrix &A, const vector<double> & v, vector<double> & res){
//res= A'*A*v
int m=A.rows;
int n=A.cols;
res.clear();
res.resize(n,0);
vector<double> w(m,0);
A.moveFirst();
while(A.hasNext()){
Cell c=A.next();
w[c.row]+=c.value*v[c.col];
}
A.moveFirst();
while(A.hasNext()){
Cell c=A.next();
res[c.col]+=c.value*w[c.row];
}
}
void rightMultiply(const vector<vector<double> > & B,SparseMatrix &A, vector<vector<double> > & C){
//C= B'*A
int m=B[0].size();
int k=B.size();
int n=A.cols;
for(int i=0;i<C.size();i++) fill(C[i].begin(),C[i].end(),0);
A.moveFirst();
while(A.hasNext()){
Cell c=A.next();
for(int i=0;i<m;i++){
C[c.col][i]+=c.value*B[c.row][i];
}
}
}
void leftMultiply(const vector<vector<double> > & B,SparseMatrix &A, vector<vector<double> > & C){
//C <- A B
int r=B[0].size();
int n=B.size();
int m=A.rows;
C.clear();
C.resize(m,vector<double>(r,0));
A.moveFirst();
while(A.hasNext()){
Cell c=A.next();
for(int i=0;i<r;i++){
C[c.row][i]+=c.value*B[c.col][i];
}
}
}
double norm(const vector<double> &v){
double r=0;
for(int i=0;i<v.size();i++)
r+=v[i]*v[i];
return sqrt(r);
}
double normalize(vector<double> &v){
double r=0;
for(int i=0;i<v.size();i++)
r+=v[i]*v[i];
r=sqrt(r);
if(r>EPS){
for(int i=0;i<v.size();i++)
v[i]/=r;
}
return r;
}
void multiply(vector<double> &v, double d){
for(int i=0;i<v.size();i++)
v[i]*=d;
}
void hessenbergReduction(vector<vector<double> > &A, vector<vector<double> > &U){
//A: m*m matrix
//Reduction A to Hessenberg form: H=U'AU (A=UHU'), H overwrite A to save memory
int m=A.size();
vector<double> v(m);
U.clear();
U.resize(m,vector<double>(m,0));
for(int i=0;i<m;i++)
U[i][i]=1;
for(int i=1;i<m;i++){
fill(v.begin(),v.end(),0);
for(int j=i;j<m;j++)
v[j]=A[j][i-1];
v[i]-=norm(v);
normalize(v); //P=I-2*v*v'
//A=PAP
//1. PA
for(int j=i-1;j<m;j++){
double d=0;
for(int k=i;k<m;k++)
d+=A[k][j]*v[k];
for(int k=i;k<m;k++)
A[k][j]-=d*2*v[k];
}
//2. AP
for(int j=0;j<m;j++){//row j
double d=0;
for(int k=i;k<m;k++)
d+=A[j][k]*v[k];
for(int k=i;k<m;k++)
A[j][k]-=d*2*v[k];
}
//U=U*P
for(int j=0;j<m;j++){
double d=0;
for(int k=i;k<m;k++)
d+=U[j][k]*v[k];
for(int k=i;k<m;k++)
U[j][k]-=d*2*v[k];
}
}
}
void givensRotation(double a, double b, double &c, double &s){
if(fabs(b)<EPS){
c=1;s=0;
}else{
if(fabs(b)>fabs(a)){
double r=a/b;
s=1/sqrt(1+r*r);
c=s*r;
}else{
double r=b/a;
c=1/sqrt(1+r*r);
s=c*r;
}
}
}
void QRTridiagonal(vector<vector<double> > &A, vector<vector<double> > &Q){
//input: A m*m symmetry tridiagonal matrix
//output: Upper triangular R, and orthogonal Q, such that A=QRQ'
int n=A.size();
Q.clear();
Q.resize(n,vector<double>(n,0));
vector<double> cs(n-1,0);
vector<double> ss(n-1,0);
for(int i=0;i<n;i++) Q[i][i]=1;
for(int m=n;m>=2;m--){
while(1){
fill(cs.begin(),cs.end(),0);
fill(ss.begin(),ss.end(),0);
double delta=(A[m-2][m-2]-A[m-1][m-1])/2;
double sign=1;
if(delta<0) sign=-1;
//Wilkinson shift
double shift=A[m-1][m-1]-sign*A[m-1][m-2]*A[m-2][m-1]/(fabs(delta)+sqrt(delta*delta+A[m-1][m-2]*A[m-2][m-1]));
for(int i=0;i<m;i++)
A[i][i]-=shift;
for(int i=0;i<m-1;i++){
double a=A[i][i];
double b=A[i+1][i];
givensRotation(a,b,cs[i],ss[i]);
for(int j=i;j<=i+2 && j<m;j++){
a=A[i][j];
b=A[i+1][j];
A[i][j]=cs[i]*a+ss[i]*b;
A[i+1][j]=-ss[i]*a+cs[i]*b;
}
}
for(int j=1;j<m;j++){// cols j-1, j c -s
for(int i=max(0,j-2);i<=j;i++){// rows 0 ... j [a ,b] s c
double a=A[i][j-1];
double b=A[i][j];
A[i][j-1]=cs[j-1]*a+ss[j-1]*b;
A[i][j]=-ss[j-1]*a+cs[j-1]*b;
}
}
for(int i=0;i<m;i++)
A[i][i]+=shift;
//Q=Q*G1...Gm
for(int j=1;j<m;j++){
for(int i=0;i<n;i++){
double a=Q[i][j-1];
double b=Q[i][j];
Q[i][j-1]=cs[j-1]*a+ss[j-1]*b;
Q[i][j]=-ss[j-1]*a+cs[j-1]*b;
}
}
if(fabs(A[m-1][m-2])<1e-10)
break;
}
}
}
vector<double> secularEquationSolver(vector<double> &z, vector<double> &D, double sigma){
//solve equation
// 1 + \sigma \sum_j \frac{b^2_j}{d_j-\lambda} =0
int n=z.size();
vector<double> res(n);
//sort : d_0 < d_1 < ... < d_{n-1}
vector<int> index;
vector<double> d(n);
merge_sort(D,index);
if(sigma<0)
reverse(index.begin(),index.end());
vector<double> b(n);
for(int i=0;i<n;i++){
b[i]=z[index[i]];
d[i]=D[index[i]];
}
vector<double> lambda(n);
for(int i=0;i<n;i++){
vector<double> delta(d.size());
for(int j=0;j<delta.size();j++)
delta[j]=(d[j]-d[i])/sigma;
double gamma=0;
if(i+1<n){
//gamma>1/delta[i+1]
double A=b[i]*b[i];
double B=-A/delta[i+1]-1;
for(int j=0;j<delta.size();j++)
if(j!=i)
B-=b[j]*b[j]/delta[j];
double C=1;
for(int j=0;j<delta.size();j++)
if(j!=i)
C+=b[j]*b[j]/delta[j];
C/=delta[i+1];
C-=b[i+1]*b[i+1]/delta[i+1];
gamma=(-B+sqrt(B*B-4*A*C))/(2*A);
}
//start Newton
double diff=1;
while(diff*diff>EPS){
double g=0;
for(int j=0;j<n;j++){
g-=b[j]*b[j]/((delta[j]*gamma-1)*(delta[j]*gamma-1));
}
double f=1;
for(int j=0;j<n;j++){
f+=b[j]*b[j]/(delta[j]-1/gamma);
}
//f+g(newGamma-gamma)=0
double newGamma=-f/g+gamma;
diff=fabs(newGamma-gamma);
gamma=newGamma;
}
lambda[i]=1/gamma*sigma+d[i];
}
for(int i=0;i<n;i++)
res[index[i]]=lambda[i];
return res;
}
void DCSub(vector<double> &alpha, vector<double> &beta, vector<vector<double> > &Q, vector<double> &D, int start, int end){
if(start==end){
Q[start][start]=1;
D[start]=alpha[start];
return;
}else{
int mid=(start+end)/2;
// | mid mid+1
//---------------------------------------------
// mid | a(mid) b(mid+1)
// mid+1 | b(mid+1) a(mid+1)
alpha[mid]-=beta[mid+1];
alpha[mid+1]-=beta[mid+1];
DCSub(alpha,beta,Q,D,start,mid);
DCSub(alpha,beta,Q,D,mid+1,end);
//alpha[mid]+=beta[mid+1];
//alpha[mid+1]+=beta[mid+1];
int n=end-start+1;
vector<double> z(n,0);
for(int i=start;i<=mid;i++)
z[i-start]=Q[mid][i];
for(int i=mid+1;i<=end;i++)
z[i-start]=Q[mid+1][i];
//calculate eigen systems of matrix D+beta[mid+1]*z*z'
vector<double> d(n,0);
for(int i=0;i<n;i++)
d[i]=D[i+start];
//secular equation is:
// 1 + \sum_j \frac{z^2_j}{d_j-\lambda} =0
vector<double> lambda=secularEquationSolver(z, d, beta[mid+1]);
//eigen vector:
//P = (D-\lambda I)^{-1} z
vector<vector<double> > P(n,vector<double>(n));
for(int i=0;i<n;i++){//for each eigen value
vector<double> p(n);
for(int j=0;j<n;j++)
p[j]=1.0/(D[j+start]-lambda[i])*z[j];
normalize(p);
for(int j=0;j<n;j++)
P[j][i]=p[j];
}
vector<vector<double> > oldQ(n,vector<double>(n));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
oldQ[i][j]=Q[i+start][j+start];
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
Q[i+start][j+start]=0;
for(int k=0;k<n;k++){
Q[i+start][j+start]+=oldQ[i][k]*P[k][j];
}
}
}
//eigen value
for(int i=0;i<n;i++)
D[i+start]=lambda[i];
}
}
void DCTridiagonal(vector<double> alpha, vector<double> &beta, vector<vector<double> > &Q, vector<double> &D){
//input: A m*m symmetry tridiagonal matrix
//output: diagonal matrix D, and orthogonal D, such that A=QRQ'
int m=alpha.size();
Q.clear();
Q.resize(m,vector<double>(m,0));
D.clear();
D.resize(m,0);
DCSub(alpha, beta, Q, D, 0, m-1);
}
void QRHessenberg(vector<vector<double> > &A, vector<vector<double> > &Q){
//input: A m*m square Hessenberg Matrix
//output: Upper triangular R, and orthogonal Q, such that A=QRQ'
int n=A.size();
Q.clear();
Q.resize(n,vector<double>(n,0));
vector<double> cs(n-1,0);
vector<double> ss(n-1,0);
for(int i=0;i<n;i++) Q[i][i]=1;
for(int m=n;m>=2;m--){
while(1){
fill(cs.begin(),cs.end(),0);
fill(ss.begin(),ss.end(),0);
double delta=(A[m-2][m-2]-A[m-1][m-1])/2;
double sign=1;
if(delta<0) sign=-1;
//Wilkinson shift
double shift=A[m-1][m-1]-sign*A[m-1][m-2]*A[m-2][m-1]/(fabs(delta)+sqrt(delta*delta+A[m-1][m-2]*A[m-2][m-1]));
for(int i=0;i<m;i++)
A[i][i]-=shift;
for(int i=0;i<m-1;i++){
double a=A[i][i];
double b=A[i+1][i];
givensRotation(a,b,cs[i],ss[i]);
for(int j=i;j<m;j++){
a=A[i][j];
b=A[i+1][j];
A[i][j]=cs[i]*a+ss[i]*b;
A[i+1][j]=-ss[i]*a+cs[i]*b;
}
}
for(int j=1;j<m;j++){// cols j-1, j c -s
for(int i=0;i<=j;i++){// rows 0 ... j [a ,b] s c
double a=A[i][j-1];
double b=A[i][j];
A[i][j-1]=cs[j-1]*a+ss[j-1]*b;
A[i][j]=-ss[j-1]*a+cs[j-1]*b;
}
}
for(int i=0;i<m;i++)
A[i][i]+=shift;
//Q=Q*G1...Gm
for(int j=1;j<m;j++){
for(int i=0;i<n;i++){
double a=Q[i][j-1];
double b=Q[i][j];
Q[i][j-1]=cs[j-1]*a+ss[j-1]*b;
Q[i][j]=-ss[j-1]*a+cs[j-1]*b;
}
}
if(fabs(A[m-1][m-2])<1e-10)
break;
}
}
}
void QRHessenbergBasic(vector<vector<double> > &A, vector<vector<double> > &Q){
//input: A m*m square Hessenberg Matrix
//output: Upper triangular R such taht A=QRQ' for orthogonal matrix Q
int m=A.size();
vector<double> cs(m-1,0);
vector<double> ss(m-1,0);
double diff=1;
Q.clear();
Q.resize(m,vector<double>(m,0));
for(int i=0;i<m;i++) Q[i][i]=1;
while(1){
for(int i=0;i<m-1;i++){
double a=A[i][i];
double b=A[i+1][i];
givensRotation(a,b,cs[i],ss[i]);
for(int j=i;j<m;j++){
a=A[i][j];
b=A[i+1][j];
A[i][j]=cs[i]*a+ss[i]*b;
A[i+1][j]=-ss[i]*a+cs[i]*b;
}
}
for(int j=1;j<m;j++){// cols j-1, j c -s
for(int i=0;i<=j;i++){// rows 0 ... j [a ,b] s c
double a=A[i][j-1];
double b=A[i][j];
A[i][j-1]=cs[j-1]*a+ss[j-1]*b;
A[i][j]=-ss[j-1]*a+cs[j-1]*b;
}
}
//Q=Q*G1...Gm
for(int j=1;j<m;j++){
for(int i=0;i<m;i++){
double a=Q[i][j-1];
double b=Q[i][j];
Q[i][j-1]=cs[j-1]*a+ss[j-1]*b;
Q[i][j]=-ss[j-1]*a+cs[j-1]*b;
}
}
diff=0;
for(int i=0;i+1<m;i++){
diff+=A[i+1][i]*A[i+1][i];
}
diff=sqrt(diff);
if(diff<1e-10)
break;
}
}
void QRFactorization(vector<vector<double> > &A, vector<vector<double> > &Q, vector<vector<double> > &R){
//A=Q*R
//A: m*n matrix
//Q: m*m matrix
//R: m*n matrix
int m=A.size();
int n=A[0].size();
for(int i=0;i<Q.size();i++)
{
fill(Q[i].begin(),Q[i].end(),0);
}
for(int i=0;i<R.size();i++)
fill(R[i].begin(),R[i].end(),0);
vector<double> q(m);
vector<double> r(n);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
q[j]=A[j][i];
fill(r.begin(),r.end(),0);
for(int j=0;j<i && j<m;j++)
{
r[j]=0;
for(int k=0;k<q.size();k++)
r[j]+=Q[k][j]*q[k];
for(int k=0;k<q.size();k++)
q[k]-=Q[k][j]*r[j];
}
if(i<m)
{
r[i]=normalize(q);
for(int j=0;j<m;j++)
{
Q[j][i]=q[j];
}
}
for(int j=0;j<m;j++){
R[j][i]=r[j];
}
}
}
void lanczos(SparseMatrix &A, vector<vector<double> > &P, vector<double> &alpha, vector<double> &beta, unsigned int rank){
//P'*A*A'*P = T = diag(alpha) + diag(beta,1) + diag(beta, -1)
//P=[p1,p2, ... , pk]
rank=min(A.cols,min(A.rows,rank));
vector<double> p;
unsigned int m=A.rows;
unsigned int n=A.cols;
vector<double> prevP(m,0);
randUnitVector(m,p);
P.clear();
P.resize(m,vector<double>(rank,0));
vector<double> v;
alpha.clear();alpha.resize(rank);
beta.clear();beta.resize(rank);
beta[0]=0;
for(int i=0;i<rank;i++){
for(int j=0;j<p.size();j++){
P[j][i]=p[j];
}
rightMultiply(A, p, v);
alpha[i]=dotProduct(p,v);
if(i+1<rank){
for(int j=0;j<m;j++)
v[j]=v[j]-beta[i]*prevP[j]-alpha[i]*p[j];
beta[i+1]=norm(v);
prevP=p;
for(int j=0;j<m;j++)
p[j]=v[j]/beta[i+1];
}
}
}
void lanczosT(SparseMatrix &A, vector<vector<double> > &P, vector<double> &alpha, vector<double> &beta, unsigned int rank){
//P'*A'*A*P = T = diag(alpha) + diag(beta,1) + diag(beta, -1)
//P=[p1,p2, ... , pk]
rank=min(A.cols,min(A.rows,rank));
vector<double> p;
unsigned int m=A.rows;
unsigned int n=A.cols;
vector<double> prevP(n,0);
randUnitVector(n,p);
P.clear();
P.resize(n,vector<double>(rank,0));
vector<double> v;
alpha.clear();alpha.resize(rank);
beta.clear();beta.resize(rank);
beta[0]=0;
for(int i=0;i<rank;i++){
for(int j=0;j<p.size();j++){
P[j][i]=p[j];
}
leftMultiply(A, p, v);
alpha[i]=dotProduct(p,v);
if(i+1<rank){
for(int j=0;j<n;j++)
v[j]=v[j]-beta[i]*prevP[j]-alpha[i]*p[j];
beta[i+1]=norm(v);
prevP=p;
for(int j=0;j<n;j++)
p[j]=v[j]/beta[i+1];
}
}
}
void QRbasic(vector<vector<double> > &T, vector<vector<double> > &W){
int l=T.size();
W.clear();
W.resize(l,vector<double>(l,0));
vector<vector<double> > Q(l,vector<double>(l,0));
vector<vector<double> > R(l,vector<double>(l,0));
vector<vector<double> > nextW(l,vector<double>(l,0));
for(int i=0;i<l;i++)
W[i][i]=1;
while(true){
//T=Q*R
QRFactorization(T,Q,R);
//T=R*Q
multiply(R,Q,T);
//W=W*Q;
multiply(W,Q,nextW);
double diff=0;
for(int i=0;i<l;i++)
for(int j=0;j<l;j++)
diff+=(W[i][j]-nextW[i][j]) * (W[i][j]-nextW[i][j]);
W=nextW;
if(diff<EPS*EPS)
break;
}
}
void svds(SparseMatrix &A, int r, vector<vector<double> > &U, vector<double> &s, vector<vector<double> > &V, string algo){
//A=U*diag(s)*V'
//A:m*n matrix sparse matrix
//U:m*r matrix, U[i]=i th left singular vector
//s:r vector
//V:n*r matrix, V[i]=i th right singular vector
int m=A.rows;
int n=A.cols;
//lanczos: A*A'=P*T*P'
if(m<=n){
int l=m;
vector<vector<double> > P(m,vector<double>(l,0));
vector<double> alpha(l,0);
vector<double> beta(l,0);
lanczos(A,P,alpha,beta,l);
vector<vector<double> > W;
if(algo=="QR"){
vector<vector<double> > T(l,vector<double>(l,0));
for(int i=0;i<l;i++){
T[i][i]=alpha[i];
if(i)
T[i-1][i]=T[i][i-1]=beta[i];
}
QRTridiagonal(T,W);
}else if(algo=="DC"){
vector<double> D(l,0);
vector<vector<double> > Q;
DCTridiagonal(alpha,beta,Q,D);
//need sort
vector<int> index;
merge_sort(D,index);
reverse(index.begin(),index.end());
W.resize(l,vector<double>(l));
for(int i=0;i<l;i++)
for(int j=0;j<l;j++)
W[i][j]=Q[i][index[j]];
}
U.clear();U.resize(m,vector<double>(l));
multiply(P,W,U);
for(int i=0;i<U.size();i++)
U[i].resize(r);
V.clear();V.resize(n,vector<double>(r));
rightMultiply(U,A,V);
s.clear();s.resize(r,0);
for(int i=0;i<r;i++){
for(int j=0;j<n;j++)
s[i]+=V[j][i]*V[j][i];
s[i]=sqrt(s[i]);
if(s[i]>EPS){
for(int j=0;j<n;j++)
V[j][i]/=s[i];
}
}
}else{
int l=n;
vector<vector<double> > P(n,vector<double>(l,0));
vector<double> alpha(l,0);
vector<double> beta(l,0);
lanczosT(A,P,alpha,beta,l);
vector<vector<double> > W;
if(algo=="QR"){
vector<vector<double> > T(l,vector<double>(l,0));
for(int i=0;i<l;i++){
T[i][i]=alpha[i];
if(i)
T[i-1][i]=T[i][i-1]=beta[i];
}
QRTridiagonal(T,W);
}else if(algo=="DC"){
vector<double> D(l,0);
vector<vector<double> > Q;
DCTridiagonal(alpha,beta,Q,D);
//need sort
vector<int> index;
merge_sort(D,index);
reverse(index.begin(),index.end());
W.resize(l,vector<double>(l));
for(int i=0;i<l;i++)
for(int j=0;j<l;j++)
W[i][j]=Q[i][index[j]];
}
V.clear();V.resize(n,vector<double>(l,0));
U.clear();U.resize(m,vector<double>(r,0));
multiply(P,W,V);
for(int i=0;i<V.size();i++)
V[i].resize(r);
leftMultiply(V,A,U);
s.clear();s.resize(r,0);
for(int i=0;i<r;i++){
for(int j=0;j<m;j++)
s[i]+=U[j][i]*U[j][i];
s[i]=sqrt(s[i]);
if(s[i]>EPS){
for(int j=0;j<m;j++)
U[j][i]/=s[i];
}
}
}
}
| 28.542821 | 123 | 0.427437 | [
"vector"
] |
c948ae2dedeb02078008ef944230e107685150fe | 424 | hpp | C++ | shared/sdk/regenny/re7/via/render/OutputTargetStateDX11.hpp | fengjixuchui/REFramework | 131b25ef58064b1c36cdd15072c30f5fbd9a7ad8 | [
"MIT"
] | 583 | 2021-06-05T06:56:54.000Z | 2022-03-31T19:16:09.000Z | src/sdk/regenny/re7/via/render/OutputTargetStateDX11.hpp | drowhunter/REFramework | 49ef476d13439110cc0ae565cc323cd615d9b327 | [
"MIT"
] | 198 | 2021-07-13T02:54:19.000Z | 2022-03-29T20:28:53.000Z | src/sdk/regenny/re7/via/render/OutputTargetStateDX11.hpp | drowhunter/REFramework | 49ef476d13439110cc0ae565cc323cd615d9b327 | [
"MIT"
] | 73 | 2021-07-12T18:52:12.000Z | 2022-03-31T17:12:56.000Z | #pragma once
#include ".\TargetDescriptorDX11.hpp"
#include ".\OutputTargetState.hpp"
namespace regenny::via::render {
#pragma pack(push, 1)
struct OutputTargetStateDX11 : public OutputTargetState {
char pad_10[0x8];
regenny::via::render::TargetDescriptorDX11 desc; // 0x18
uint32_t hash; // 0x40
char pad_44[0x84];
void* swapchain; // 0xc8
void* device; // 0xd0
}; // Size: 0xd8
#pragma pack(pop)
}
| 26.5 | 60 | 0.698113 | [
"render"
] |
c949344873ccca3ba4a4cbd03008b49830dbb643 | 2,094 | hpp | C++ | third_party/CppADCodeGen/test/cppad/cg/patterns/pattern_test_model.hpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppADCodeGen/test/cppad/cg/patterns/pattern_test_model.hpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppADCodeGen/test/cppad/cg/patterns/pattern_test_model.hpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | #ifndef CPPAD_CG_TEST_PATTERN_TEST_MODEL_INCLUDED
#define CPPAD_CG_TEST_PATTERN_TEST_MODEL_INCLUDED
/* --------------------------------------------------------------------------
* CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation:
* Copyright (C) 2013 Ciengis
*
* CppADCodeGen is distributed under multiple licenses:
*
* - Eclipse Public License Version 1.0 (EPL1), and
* - GNU General Public License Version 3 (GPL3).
*
* EPL1 terms and conditions can be found in the file "epl-v10.txt", while
* terms and conditions for the GPL3 can be found in the file "gpl3.txt".
* ----------------------------------------------------------------------------
* Author: Joao Leal
*/
namespace CppAD {
template<class Base>
class PatternTestModel {
public:
virtual std::vector<AD<Base> > evaluateModel(const std::vector<AD<Base> >& x, size_t repeat) = 0;
inline virtual ~PatternTestModel() {
}
};
template<class Base>
class DefaultPatternTestModel : public PatternTestModel<Base> {
private:
std::vector<AD<Base> > (*model_)(const std::vector<AD<Base> >& x, size_t repeat);
public:
inline DefaultPatternTestModel(std::vector<AD<Base> > (*model)(const std::vector<AD<Base> >& x, size_t repeat)) :
model_(model) {
}
virtual std::vector<AD<Base> > evaluateModel(const std::vector<AD<Base> >& x, size_t repeat) {
return (*model_)(x, repeat);
}
};
template<class Base>
class PatternTestModelWithAtom : public PatternTestModel<Base> {
private:
std::vector<AD<Base> > (*model_)(const std::vector<AD<Base> >& x, size_t repeat, atomic_base<Base>& atom);
atomic_base<Base>& atom_;
public:
inline PatternTestModelWithAtom(std::vector<AD<Base> > (*model)(const std::vector<AD<Base> >& x, size_t repeat, atomic_base<Base>& atom),
atomic_base<Base>& atom) :
model_(model),
atom_(atom) {
}
virtual std::vector<AD<Base> > evaluateModel(const std::vector<AD<Base> >& x, size_t repeat) {
return (*model_)(x, repeat, atom_);
}
};
}
#endif | 32.71875 | 141 | 0.624642 | [
"vector",
"model"
] |
c94b6bb25ffa2d1aee1a3e8bcd3b63493d44f87d | 16,245 | cpp | C++ | Server/src/Services/Resource/ResourceOperationFactory.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Server/src/Services/Resource/ResourceOperationFactory.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Server/src/Services/Resource/ResourceOperationFactory.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "ResourceServiceDefs.h"
#include "ResourceOperationFactory.h"
// Repository Management APIs
#include "OpEnumerateRepositories.h"
#include "OpCreateRepository.h"
#include "OpDeleteRepository.h"
#include "OpUpdateRepository.h"
#include "OpGetRepositoryContent.h"
#include "OpGetRepositoryHeader.h"
#include "OpApplyResourcePackage.h"
// Resource Management APIs
#include "OpResourceExists.h"
#include "OpEnumerateResources.h"
#include "OpEnumerateResourceDocuments.h"
#include "OpSetResource.h"
#include "OpDeleteResource.h"
#include "OpMoveResource.h"
#include "OpCopyResource.h"
#include "OpGetResourceContent.h"
#include "OpGetResourceContents.h"
#include "OpGetResourceHeader.h"
#include "OpGetResourceModifiedDate.h"
#include "OpEnumerateResourceReferences.h"
#include "OpEnumerateParentMapDefinitions.h"
#include "OpEnumerateParentTileSetDefinitions.h"
#include "OpChangeResourceOwner.h"
#include "OpInheritPermissionsFrom.h"
// Resource Data Management APIs
#include "OpEnumerateResourceData.h"
#include "OpSetResourceData.h"
#include "OpDeleteResourceData.h"
#include "OpRenameResourceData.h"
#include "OpGetResourceData.h"
// Unmanaged Data APIs
#include "OpEnumerateUnmanagedData.h"
///----------------------------------------------------------------------------
/// <summary>
/// The default constructor for an MgResourceOperationFactory object. However,
/// since this function is protected, this object should never really be
/// constructed. Rather, it is merely a wrapper class for other static
/// functions.
/// </summary>
///----------------------------------------------------------------------------
MgResourceOperationFactory::MgResourceOperationFactory()
{
}
///----------------------------------------------------------------------------
/// <summary>
/// This static method returns the IMgOperationHandler object that corresponds
/// to the given ID and Version parameters.
/// </summary>
///
/// <param name="operationId">
/// The ID of the requested operation.
/// </param>
///
/// <param name="operationVersion">
/// The version of the requested operation.
/// </param>
///
/// <returns>
/// Returns an IMgOperationHandler object corresponding to the given parameters.
/// Returns NULL if one cannot be found.
/// </returns>
///
/// <exceptions>
/// MgException
/// </exceptions>
///
/// TODO: handle different versions
/// TODO: set up ids and whatnot in a hash or map instead of hardcoding the ids here
///----------------------------------------------------------------------------
IMgOperationHandler* MgResourceOperationFactory::GetOperation(
ACE_UINT32 operationId, ACE_UINT32 operationVersion)
{
auto_ptr<IMgOperationHandler> handler;
MG_RESOURCE_SERVICE_TRY()
switch (operationId)
{
case MgResourceService::opIdEnumerateRepositories:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateRepositories());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdCreateRepository:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpCreateRepository());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdDeleteRepository:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpDeleteRepository());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdUpdateRepository:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpUpdateRepository());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetRepositoryContent:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpGetRepositoryContent());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetRepositoryHeader:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpGetRepositoryHeader());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdApplyResourcePackage:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpApplyResourcePackage());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdResourceExists:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpResourceExists());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateResources:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateResources());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateResourceDocuments:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateResourceDocuments());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdSetResource:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpSetResource());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdDeleteResource:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpDeleteResource());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdMoveResource:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
case VERSION_SUPPORTED(2,2):
handler.reset(new MgOpMoveResource());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdCopyResource:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpCopyResource());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetResourceContent:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpGetResourceContent());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetResourceContents:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(2,2):
handler.reset(new MgOpGetResourceContents());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetResourceHeader:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpGetResourceHeader());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetResourceModifiedDate:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpGetResourceModifiedDate());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateReferences:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateResourceReferences());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateParentMapDefinitions:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateParentMapDefinitions());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateParentTileSetDefinitions:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(3,0):
handler.reset(new MgOpEnumerateParentTileSetDefinitions());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdChangeResourceOwner:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpChangeResourceOwner());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdInheritPermissionsFrom:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpInheritPermissionsFrom());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateResourceData:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateResourceData());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdSetResourceData:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpSetResourceData());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdDeleteResourceData:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpDeleteResourceData());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdRenameResourceData:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpRenameResourceData());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdGetResourceData:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpGetResourceData());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
case MgResourceService::opIdEnumerateUnmanagedData:
switch (VERSION_NO_PHASE(operationVersion))
{
case VERSION_SUPPORTED(1,0):
handler.reset(new MgOpEnumerateUnmanagedData());
break;
default:
throw new MgInvalidOperationVersionException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
break;
default:
throw new MgInvalidOperationException(
L"MgResourceOperationFactory.GetOperation", __LINE__, __WFILE__, NULL, L"", NULL);
}
MG_RESOURCE_SERVICE_CATCH_AND_THROW(L"MgResourceOperationFactory.GetOperation")
return handler.release();
}
| 35.238612 | 98 | 0.638966 | [
"object"
] |
c955acfa09914e419a8a3799c74c17224efe4a68 | 10,057 | cc | C++ | samples/cpu/convolution/convolution.cc | ncic-sugon/blitz | ea9a06dc78ef15d772e36d5d47ffac8d3f46034d | [
"BSD-2-Clause"
] | 149 | 2020-07-14T08:59:59.000Z | 2021-12-16T03:06:41.000Z | samples/cpu/convolution/convolution.cc | ten1123love/blitz | ea9a06dc78ef15d772e36d5d47ffac8d3f46034d | [
"BSD-2-Clause"
] | null | null | null | samples/cpu/convolution/convolution.cc | ten1123love/blitz | ea9a06dc78ef15d772e36d5d47ffac8d3f46034d | [
"BSD-2-Clause"
] | 130 | 2020-07-14T09:00:21.000Z | 2021-12-16T03:06:42.000Z | #include <omp.h>
#include <blitz.h>
using namespace blitz;
// N C H W
Shape input_shape(4);
Shape input_shape_algorithm(4);
// K C R S
Shape filter_shape(4);
Shape filter_shape_algorithm(4);
// N K P Q
Shape output_shape(4);
Shape output_shape_algorithm(4);
void compare(float* algo1, float* algo2, size_t size, float precision = 1e-3) {
for (size_t i = 0; i < size; ++i) {
if (algo1[i] > algo2[i] + precision || algo1[i] < algo2[i] - precision) {
LOG(INFO) << "Index: " << i << " algo1: " << algo1[i] << " algo2: " << algo2[i];
}
}
}
void set_shape_nchw(Shape& shape, size_t N, size_t C, size_t H, size_t W) {
shape[0] = N;
shape[1] = C;
shape[2] = H;
shape[3] = W;
shape.set_data_layout(BLITZ_BUFFER_NCHW);
}
void set_shape_nhwc(Shape& shape, size_t N, size_t C, size_t H, size_t W) {
shape[0] = N;
shape[1] = H;
shape[2] = W;
shape[3] = C;
shape.set_data_layout(BLITZ_BUFFER_NHWC);
}
void set_shape_kcrs(Shape& shape, size_t K, size_t C, size_t R, size_t S) {
shape[0] = K;
shape[1] = C;
shape[2] = R;
shape[3] = S;
shape.set_data_layout(BLITZ_FILTER_KCRS);
}
void set_shape_rsck(Shape& shape, size_t K, size_t C, size_t R, size_t S) {
shape[0] = R;
shape[1] = S;
shape[2] = C;
shape[3] = K;
shape.set_data_layout(BLITZ_FILTER_RSCK);
}
void convolution_forward(
const string& mode,
BLITZ_ALGORITHM algorithm,
size_t pad_h, size_t pad_w,
size_t str_h, size_t str_w,
size_t iter) {
// algorithm tensors
CPUTensor<float> input_cpu_algorithm(input_shape_algorithm);
CPUTensor<float> filter_cpu_algorithm(filter_shape_algorithm);
CPUTensor<float> output_cpu_algorithm(output_shape_algorithm);
ConvolutionContext<CPUTensor, float> context_algorithm(
input_shape_algorithm, filter_shape_algorithm,
pad_h, pad_w, str_h, str_w);
context_algorithm.InitAlgorithmForUser(algorithm);
// initial tensors
CPUTensor<float> input_cpu(input_shape);
CPUTensor<float> filter_cpu(filter_shape);
CPUTensor<float> output_cpu(output_shape);
ConvolutionContext<CPUTensor, float> context(
input_shape, filter_shape,
pad_h, pad_w, str_h, str_w);
context.InitAlgorithmForUser(BLITZ_CONVOLUTION_NAIVE_DIRECT);
// init values
Backend<CPUTensor, float>::UniformDistributionFunc(&input_cpu, 0.0, 1.0);
Backend<CPUTensor, float>::UniformDistributionFunc(&filter_cpu, 0.0, 1.0);
Backend<CPUTensor, float>::TransformCopyFunc(&input_cpu, &input_cpu_algorithm);
Backend<CPUTensor, float>::TransformCopyFunc(&filter_cpu, &filter_cpu_algorithm);
// direct convolution
if (mode != "performance") {
for (size_t i = 0; i < iter; ++i) {
Backend<CPUTensor, float>::Convolution2DForwardFunc(
&input_cpu,
&filter_cpu,
&output_cpu,
&context);
}
}
// algorithm convolution
for (size_t i = 0; i < iter; ++i) {
Backend<CPUTensor, float>::Convolution2DForwardFunc(
&input_cpu_algorithm,
&filter_cpu_algorithm,
&output_cpu_algorithm,
&context_algorithm);
}
if (mode != "performance") {
if (output_cpu_algorithm.data_layout() != input_cpu_algorithm.data_layout()) {
CPUTensor<float> output_cpu_transform(output_shape);
Backend<CPUTensor, float>::TransformCopyFunc(&output_cpu_algorithm, &output_cpu_transform);
compare(output_cpu.data(), output_cpu_transform.data(), output_cpu.size(), 1e-2);
} else {
compare(output_cpu.data(), output_cpu_algorithm.data(), output_cpu.size(), 1e-2);
}
}
}
void convolution_backward(
const string& mode,
BLITZ_ALGORITHM algorithm,
size_t pad_h, size_t pad_w,
size_t str_h, size_t str_w,
size_t iter) {
// algorithm tensors
CPUTensor<float> input_cpu_algorithm(input_shape_algorithm);
CPUTensor<float> filter_cpu_algorithm(filter_shape_algorithm);
CPUTensor<float> output_cpu_algorithm(output_shape_algorithm);
ConvolutionContext<CPUTensor, float> context_algorithm(
input_shape_algorithm, filter_shape_algorithm,
pad_h, pad_w, str_h, str_w);
context_algorithm.InitAlgorithmForUser(algorithm);
// initial tensors
CPUTensor<float> input_cpu(input_shape);
CPUTensor<float> filter_cpu(filter_shape);
CPUTensor<float> output_cpu(output_shape);
ConvolutionContext<CPUTensor, float> context(
input_shape, filter_shape,
pad_h, pad_w, str_h, str_w);
context.InitAlgorithmForUser(BLITZ_CONVOLUTION_NAIVE_DIRECT);
// init values
Backend<CPUTensor, float>::UniformDistributionFunc(&filter_cpu, 0.0, 1.0);
Backend<CPUTensor, float>::UniformDistributionFunc(&output_cpu, 0.0, 1.0);
Backend<CPUTensor, float>::TransformCopyFunc(&filter_cpu, &filter_cpu_algorithm);
Backend<CPUTensor, float>::TransformCopyFunc(&output_cpu, &output_cpu_algorithm);
// cpu convolution
if (mode != "performance") {
for (size_t i = 0; i < iter; ++i) {
Backend<CPUTensor, float>::Convolution2DBackwardFunc(
&output_cpu,
&filter_cpu,
&input_cpu,
&context);
}
}
// different algorithm
for (size_t i = 0; i < iter; ++i) {
Backend<CPUTensor, float>::Convolution2DBackwardFunc(
&output_cpu_algorithm,
&filter_cpu_algorithm,
&input_cpu_algorithm,
&context_algorithm);
}
if (mode != "performance") {
if (input_cpu_algorithm.data_layout() != output_cpu_algorithm.data_layout()) {
CPUTensor<float> input_cpu_transform(input_shape);
Backend<CPUTensor, float>::TransformCopyFunc(&input_cpu_algorithm, &input_cpu_transform);
compare(input_cpu.data(), input_cpu_transform.data(), input_cpu.size(), 1e-2);
} else {
compare(input_cpu.data(), input_cpu_algorithm.data(), input_cpu.size(), 1e-2);
}
}
}
void convolution_update(
const string& mode,
BLITZ_ALGORITHM algorithm,
size_t pad_h, size_t pad_w,
size_t str_h, size_t str_w,
size_t iter) {
// algorithm tensors
CPUTensor<float> input_cpu_algorithm(input_shape_algorithm);
CPUTensor<float> filter_cpu_algorithm(filter_shape_algorithm);
CPUTensor<float> output_cpu_algorithm(output_shape_algorithm);
ConvolutionContext<CPUTensor, float> context_algorithm(
input_shape_algorithm, filter_shape_algorithm,
pad_h, pad_w, str_h, str_w);
context_algorithm.InitAlgorithmForUser(algorithm);
// initial tensors
CPUTensor<float> input_cpu(input_shape);
CPUTensor<float> filter_cpu(filter_shape);
CPUTensor<float> output_cpu(output_shape);
ConvolutionContext<CPUTensor, float> context(
input_shape, filter_shape,
pad_h, pad_w, str_h, str_w);
context.InitAlgorithmForUser(BLITZ_CONVOLUTION_NAIVE_DIRECT);
// init values
Backend<CPUTensor, float>::UniformDistributionFunc(&output_cpu, 0.0, 1.0);
Backend<CPUTensor, float>::UniformDistributionFunc(&input_cpu, 0.0, 1.0);
Backend<CPUTensor, float>::TransformCopyFunc(&output_cpu, &output_cpu_algorithm);
Backend<CPUTensor, float>::TransformCopyFunc(&input_cpu, &input_cpu_algorithm);
// cpu convolution
if (mode != "performance") {
for (size_t i = 0; i < iter; ++i) {
Backend<CPUTensor, float>::Convolution2DUpdateFunc(
&input_cpu,
&output_cpu,
&filter_cpu,
&context);
}
}
// different algorithm
for (size_t i = 0; i < iter; ++i) {
Backend<CPUTensor, float>::Convolution2DUpdateFunc(
&input_cpu_algorithm,
&output_cpu_algorithm,
&filter_cpu_algorithm,
&context_algorithm);
}
if (mode != "performance") {
if (input_cpu_algorithm.data_layout() != output_cpu_algorithm.data_layout()) {
CPUTensor<float> filter_cpu_transform(filter_shape);
Backend<CPUTensor, float>::TransformCopyFunc(&filter_cpu_algorithm, &filter_cpu_transform);
memcpy(filter_cpu.data(), filter_cpu_transform.data(), sizeof(float) * filter_cpu.size());
} else {
compare(filter_cpu.data(), filter_cpu_algorithm.data(), filter_cpu.size(), 1);
}
}
}
int main(int argc, char** argv) {
const size_t NUM_ARGS = 19;
// phase kernel N C H W R S K P Q pad_h pad_w str_h str_w iter
if (argc != NUM_ARGS + 1) {
LOG(FATAL) << "Not matchable args!";
}
FLAGS_logtostderr = true;
google::InitGoogleLogging(argv[0]);
// get args
const std::string mode = std::string(argv[1]);
const std::string phase = std::string(argv[2]);
const std::string kernel = std::string(argv[3]);
const std::string input_layout = std::string(argv[4]);
const std::string output_layout = std::string(argv[5]);
const size_t N = atoi(argv[6]);
const size_t C = atoi(argv[7]);
const size_t H = atoi(argv[8]);
const size_t W = atoi(argv[9]);
const size_t R = atoi(argv[10]);
const size_t S = atoi(argv[11]);
const size_t K = atoi(argv[12]);
const size_t P = atoi(argv[13]);
const size_t Q = atoi(argv[14]);
const size_t pad_h = atoi(argv[15]);
const size_t pad_w = atoi(argv[16]);
const size_t str_h = atoi(argv[17]);
const size_t str_w = atoi(argv[18]);
const size_t iter = atoi(argv[19]);
// set shapes
if (input_layout == "nchw") {
set_shape_nchw(input_shape, N, C, H, W);
set_shape_kcrs(filter_shape, K, C, R, S);
set_shape_nchw(output_shape, N, K, P, Q);
set_shape_nchw(input_shape_algorithm, N, C, H, W);
set_shape_kcrs(filter_shape_algorithm, K, C, R, S);
} else {
set_shape_nhwc(input_shape, N, C, H, W);
set_shape_rsck(filter_shape, K, C, R, S);
set_shape_nhwc(output_shape, N, K, P, Q);
set_shape_nhwc(input_shape_algorithm, N, C, H, W);
set_shape_rsck(filter_shape_algorithm, K, C, R, S);
}
if (output_layout == "nchw") {
set_shape_nchw(output_shape_algorithm, N, K, P, Q);
} else {
set_shape_nhwc(output_shape_algorithm, N, K, P, Q);
}
// run convolution
if (phase == "forward") {
convolution_forward(mode, BlitzParseAlgorithm(kernel), pad_h, pad_w, str_h, str_w, iter);
} else if (phase == "backward") {
convolution_backward(mode, BlitzParseAlgorithm(kernel), pad_h, pad_w, str_h, str_w, iter);
} else if (phase == "update") {
convolution_update(mode, BlitzParseAlgorithm(kernel), pad_h, pad_w, str_h, str_w, iter);
}
return 0;
}
| 35.790036 | 97 | 0.700706 | [
"shape"
] |
c95d8ecc0563d11d923e5570d930ed47e96ba881 | 17,461 | cpp | C++ | odevice/app/src/main/jni/br_edu_ufsj_dcomp_ocr_Controller_copy.cpp | rcarvs/android-ocr | f8760afd378607ced0beca0b2c1beda14ea4ab49 | [
"MIT"
] | null | null | null | odevice/app/src/main/jni/br_edu_ufsj_dcomp_ocr_Controller_copy.cpp | rcarvs/android-ocr | f8760afd378607ced0beca0b2c1beda14ea4ab49 | [
"MIT"
] | null | null | null | odevice/app/src/main/jni/br_edu_ufsj_dcomp_ocr_Controller_copy.cpp | rcarvs/android-ocr | f8760afd378607ced0beca0b2c1beda14ea4ab49 | [
"MIT"
] | null | null | null | #include <jni.h>
#include <android/log.h>
#include <parallelme/ParallelME.hpp>
#include <parallelocr/ParallelOCR.hpp>
#include <stdio.h>
#include <android/bitmap.h>
#include <cstring>
#include <unistd.h>
#include <vector>
#include "br_edu_ufsj_dcomp_ocr_Controller.h"
using namespace parallelme;
using namespace parallelocr;
const static char gKernels[] =
"__kernel void blackandwhite(__global uchar4 *image) { \n"
" int gid = get_global_id(0); \n"
" uchar4 pixel = image[gid]; \n"
" if((pixel.x+pixel.y+pixel.z) > 645){ \n"
" pixel.x = pixel.y = pixel.z = 255; \n"
" }else{ \n"
" pixel.x = pixel.y = pixel.z = 0; \n"
" } \n"
" image[gid] = pixel; \n"
"} \n";
struct NativeData{
std::shared_ptr<Runtime> runtime;
std::shared_ptr<Program> program;
};
typedef struct{
uint8_t red, green, blue;
} RGB;
void convertIntToRgb(uint32_t pixel, RGB* rgb){
rgb->red = (int) ((pixel & 0x00FF0000) >> 16);
rgb->green = (int)((pixel & 0x0000FF00) >> 8);
rgb->blue = (int) (pixel & 0x00000FF);
}
typedef struct{
int left, top, right, bottom;
char letter;
} letter;
JNIEXPORT jlong JNICALL Java_br_edu_ufsj_dcomp_ocr_Controller_nativeInit(JNIEnv *env, jobject self) {
JavaVM *jvm; //cria um ponteiro para uma jvm
env->GetJavaVM(&jvm); //adiciona a jvm da execução para o ponteiro criado anteriormente
if(!jvm) return (jlong) nullptr; //se n encontrar a jvm retorna um nullptr
auto dataPointer = new NativeData(); //cria um ponteiro para os dados da struct NativeData
dataPointer->runtime = std::make_shared<Runtime>(jvm,std::make_shared<SchedulerFCFS>()); //preenche o objeto runtime da struct nativedata
dataPointer->program = std::make_shared<Program>(dataPointer->runtime, gKernels);
return (jlong) dataPointer;
}
JNIEXPORT void JNICALL Java_br_edu_ufsj_dcomp_ocr_Controller_nativeCreateImageLabels(JNIEnv *env,jobject self,jlong dataPointerLong,jobject bitmap){
parallelocr::Image image(bitmap);
//first pass will put image in black and white
nativeImageToBlackAndWhite(env,dataPointerLong,bitmap);
//secont pass is access image pixels
AndroidBitmapInfo info;
int ret;
void* pixels;
if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
return;
}
if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
LOGE("Bitmap format is not RGBA_8888 !");
return;
}
if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
}
uint32_t* line;
//now, the pixels are in var pixels, pass that for a unidimencional vector
int size = (info.height*info.width);
RGB rgbPixels[size];
int count = 0;
for(unsigned int yy = 0; yy < info.height; yy++){
line = (uint32_t*)pixels;
for(unsigned int xx =0; xx < info.width; xx++){
convertIntToRgb(line[xx],&rgbPixels[count]);
count++;
}
pixels = (char*)pixels + info.stride;
}
int *labels = (int*) malloc(sizeof(int)*count);
/*for(int i = 0;i<count;i++){
labels[i] = 0;
}*/
RGB rgbComp;
int label = 0;
for(int i=0;i<count;i++){
if((rgbPixels[i].red+rgbPixels[i].green+rgbPixels[i].blue) != (255*3)){
int top = (((int)(i-info.width) >= 0)?(i-info.width):-1);
int topLeft = (((int)(i-info.width-1)>=0 && ((i-info.width)/info.width) == ((i-info.width-1)/info.width))?(i-info.width-1):-1);
int topRight = (((int)(i-info.width+1)<size && ((i+info.width)/info.width) == ((i+info.width+1)/info.width))?(i-info.width+1):-1);
int left = (((int)(i-1) >= 0 && (i/info.width)==((i-1)/info.width))?(i-1):-1);
int right = (((int)(i+1) < size && (i/info.width)==((i+1)/info.width))?(i+1):-1);
int down = (((int)(i+info.width) < size)?(i+info.width):-1);
int downLeft = (((int)(i+info.width-1) < size && ((i+info.width-1)/info.width) == ((i+info.width)/info.width))?(i+info.width-1):-1);
int downRight = (((int)(i+info.width+1) < size && ((i+info.width+1)/info.width) == ((i+info.width)/info.width))?(i+info.width+1):-1);
unsigned int equals[8];
int contEquals = 0;
if(top != -1){
rgbComp = rgbPixels[top];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[top];
contEquals++;
}
}
if(topLeft != -1){
rgbComp = rgbPixels[topLeft];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[topLeft];
contEquals++;
}
}
if(topRight != -1){
rgbComp = rgbPixels[topRight];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[topRight];
contEquals++;
}
}
if(left != -1){
rgbComp = rgbPixels[left];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[left];
contEquals++;
}
}
if(right != -1){
rgbComp = rgbPixels[right];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[right];
contEquals++;
}
}
if(down != -1){
rgbComp = rgbPixels[down];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[down];
contEquals++;
}
}
if(downLeft != -1){
rgbComp = rgbPixels[downLeft];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[downLeft];
contEquals++;
}
}
if(downRight != -1){
rgbComp = rgbPixels[downRight];
if((rgbPixels[i].red==rgbComp.red) && (rgbPixels[i].green==rgbComp.green) && (rgbPixels[i].blue==rgbComp.blue)){
equals[contEquals] = labels[downRight];
contEquals++;
}
}
if(contEquals == 0){
label++;
labels[i] = label;
}else{
int downLabel = 0;
for(int j=0;j<contEquals;j++){
if(equals[j] != 0){
if(downLabel == 0){
downLabel = equals[j];
}else if(downLabel >(int) equals[j]){
downLabel = equals[j];
}
}
}
if(downLabel == 0){
label++;
labels[i] = label;
}else{
labels[i] = downLabel;
}
}
}
}
//now, lets create a list for resolve equivalences
int equivalences[(label+1)][label];
for(int i=0;i<label;i++){
for(int j=0;j<label;j++){
equivalences[i][j] = 0;
}
}
for(int i=0;i<=count;i++){
if(labels[i] != 0){
int top = (((int)(i-info.width) >= 0)?labels[(i-info.width)]:0);
int topLeft = (((int)(i-info.width-1)>=0 && ((i-info.width)/info.width) == ((i-info.width-1)/info.width))?labels[(i-info.width-1)]:0);
int topRight = (((int)(i-info.width+1)<size && ((i+info.width)/info.width) == ((i+info.width+1)/info.width))?labels[(i-info.width+1)]:0);
int left = (((int)(i-1) >= 0 && (i/info.width)==((i-1)/info.width))?labels[(i-1)]:0);
int right = (((int)(i+1) < size && (i/info.width)==((i+1)/info.width))?labels[(i+1)]:0);
int down = (((int)(i+info.width) < size)?labels[(i+info.width)]:0);
int downLeft = (((int)(i+info.width-1) < size && ((i+info.width-1)/info.width) == ((i+info.width)/info.width))?labels[(i+info.width-1)]:0);
int downRight = (((int)(i+info.width+1) < size && ((i+info.width+1)/info.width) == ((i+info.width)/info.width))?labels[(i+info.width+1)]:0);
int countEquivalences = 0;
bool insert;
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == labels[i]){
insert = false;
break;
}
}
if(insert){
equivalences[labels[i]][countEquivalences] = labels[i];
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == top){
insert = false;
break;
}
}
if(top != 0 && insert){
equivalences[labels[i]][countEquivalences] = top;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == topLeft){
insert = false;
break;
}
}
if(topLeft != 0 && insert){
equivalences[labels[i]][countEquivalences] = topLeft;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == topRight){
insert = false;
break;
}
}
if(topRight != 0 && insert){
equivalences[labels[i]][countEquivalences] = topRight;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == left){
insert = false;
break;
}
}
if(left != 0 && insert){
equivalences[labels[i]][countEquivalences] = left;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == right){
insert = false;
break;
}
}
if(right != 0 && insert){
equivalences[labels[i]][countEquivalences] = right;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == down){
insert = false;
break;
}
}
if(down != 0 && insert){
equivalences[labels[i]][countEquivalences] = down;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == downLeft){
insert = false;
break;
}
}
if(downLeft != 0 && insert){
equivalences[labels[i]][countEquivalences] = downLeft;
countEquivalences++;
}
insert = true;
for(int j=0;j<label;j++){
if(equivalences[labels[i]][j] == downRight){
insert = false;
break;
}
}
if(downRight != 0 && insert){
equivalences[labels[i]][countEquivalences] = downRight;
countEquivalences++;
}
}
}
for(int i=0;i<size;i++){
if(labels[i] != 0){
for(int j=0;j<label;j++){
if(labels[i] > equivalences[labels[i]][j] && equivalences[labels[i]][j] != 0){
labels[i] = equivalences[labels[i]][j];
}
}
}
}
int upLabel = 0;
for(int i=0; i<size;i++){
if(labels[i] > upLabel){
upLabel = labels[i];
}
}
//next step is identify the limits of label for each label
letter letters[upLabel];
for(int i=0;i<=upLabel;i++){
letters[i].top = letters[i].bottom = letters[i].left = letters[i].right = -1;
}
for(int i=0; i<size;i++){
if(labels[i] != 0){
int y = (int) (i+1)/info.width;
int x = i%info.width;
letters[labels[i]].top = ((y < letters[labels[i]].top || letters[labels[i]].top == -1) ? y : letters[labels[i]].top);
letters[labels[i]].bottom = ((y > letters[labels[i]].bottom || letters[labels[i]].bottom == -1) ? y : letters[labels[i]].bottom);
letters[labels[i]].left = ((x < letters[labels[i]].left || letters[labels[i]].left == -1) ? x : letters[labels[i]].left);
letters[labels[i]].right = ((x > letters[labels[i]].right || letters[labels[i]].right == -1) ? x : letters[labels[i]].right);
}
}
//identify the characters
//implementation of feature extraction
/*
1 - Crossing in each letter
In my crossing, I'm seeing the backgrounds amount (set of labels with rotule 0 for each set of labels with not zero rotule)
*/
for(int i = 1; i<=upLabel;i++){
//for each letter
//check if really have a letter on here
if(letters[i].top != 0 && letters[i].bottom != 0){
//calculate the size of letter inside the vector
std::string arquivo = "/sdcard/letter"+std::to_string(i)+".txt";
FILE * letterFile = fopen(arquivo.c_str(),"w+");
for(int y=letters[i].top;y<letters[i].bottom;y++){
int changes = 0;
for(int x=letters[i].left;x<letters[i].right;x++){
if(labels[info.width*y+x] != labels[info.width*y+x+1]){
changes++;
}
fprintf(letterFile,"%d",labels[info.width*y+x]);
}
fprintf(letterFile," - %d \n",changes);
}
fclose(letterFile);
}
}
//just for log
FILE * labelFile = fopen("/sdcard/labels.txt","w+");
for(int i=1;i<=upLabel;i++){
fprintf(labelFile, "Label: %d - TOP: %d | BOTTOM: %d | LEFT: %d | RIGHT: %d \n",i,letters[i].top,letters[i].bottom,letters[i].left,letters[i].right);
}
fclose(labelFile);
FILE * arquivo = fopen("/sdcard/out.txt","w+");
for(int i=0;i<(int) info.height;i++){
for(int j=0;j<(int)info.width;j++){
fprintf(arquivo, "%d ", labels[(info.width*i+j)]);
}
fprintf(arquivo, "\n");
}
fclose(arquivo);
}
void nativeImageToBlackAndWhite(JNIEnv *env,jlong dataPointerLong,jobject bitmap){
auto dataPointer = (NativeData *) dataPointerLong;
AndroidBitmapInfo info;
int ret;
if((ret = AndroidBitmap_getInfo(env,bitmap,&info)) < 0){
__android_log_print(ANDROID_LOG_VERBOSE, "LogCpp", "Image error: %d",ret);
return;
}
if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888){
__android_log_print(ANDROID_LOG_VERBOSE, "LogCpp", "Image Format Error");
return;
}
long imageSize = info.height*info.width;
auto bitmapBuffer = std::make_shared<Buffer>(Buffer::sizeGenerator(imageSize, Buffer::RGBA));
bitmapBuffer->setAndroidBitmapSource(env,bitmap);
auto task = std::make_unique<Task>(dataPointer->program);
task->addKernel("blackandwhite");
task->setConfigFunction([=] (DevicePtr &device, KernelHash &kernelHash) {
kernelHash["blackandwhite"]->setArg(0, bitmapBuffer)->setWorkSize(imageSize);
});
dataPointer->runtime->submitTask(std::move(task));
dataPointer->runtime->finish();
bitmapBuffer->copyToAndroidBitmap(env, bitmap);
} | 37.631466 | 157 | 0.478781 | [
"vector"
] |
c95fa2185a79f42bea3d7a5dd1608254b824c6ba | 1,230 | cpp | C++ | 134. Gas Station/Solution.cpp | Ainevsia/Leetcode-Rust | c4f16d72f3c0d0524478b6bb90fefae9607d88be | [
"BSD-2-Clause"
] | 15 | 2020-02-07T13:04:05.000Z | 2022-03-02T14:33:21.000Z | 134. Gas Station/Solution.cpp | Ainevsia/Leetcode-Rust | c4f16d72f3c0d0524478b6bb90fefae9607d88be | [
"BSD-2-Clause"
] | null | null | null | 134. Gas Station/Solution.cpp | Ainevsia/Leetcode-Rust | c4f16d72f3c0d0524478b6bb90fefae9607d88be | [
"BSD-2-Clause"
] | 3 | 2020-04-02T15:36:57.000Z | 2021-09-14T14:13:44.000Z | #include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <cmath>
#include <queue>
using namespace std;
class Solution {
public:
int n;
int next(int i) {
return i + 1 == n ? 0 : i + 1;
}
//If car starts at A and can not reach B. Any station between A and B can not reach B.(B is the first station that A can not reach.)
//If the total number of gas is bigger than the total number of cost. There must be a solution.
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
n = gas.size();
for (int i = 0; i < n; ) {
if (gas[i] < cost[i]) { i ++ ; continue; }
int dst = i, j = next(i), rg = gas[i] - cost[i];
while (j != dst) {
rg += gas[j] - cost[j];
if (rg < 0) break;
j = next(j);
}
if (j != dst) {
if (j < i) break;
else {
i = j;
continue;
}
}
else return i;
}
return -1;
}
};
int main() {
Solution a;
return 0;
}
| 23.653846 | 136 | 0.476423 | [
"vector"
] |
c96022afbcf2a5bfedf7317c3ace60daaa5a7298 | 10,368 | cc | C++ | tests/unit/Geometry/TestGeometry.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Geometry/tests/TestGeometry.cc | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Geometry/tests/TestGeometry.cc | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | #include <iostream>
#include "GeomVector.hh"
#include "GeomTensor.hh"
void main () {
// Test the GeomVector functions
cerr << "############################## Vector ##############################" << endl;
cerr << "GeomVector<3>(): " << GeomVector<3>() << endl;
cerr << "GeomVector<3>(1.0): " << GeomVector<3>(1.0) << endl;
GeomVector<3> r1(1.0, 2.0, 3.0);
GeomVector<3> r2(2.0, 2.0, 2.0);
// r1 = 1.0, 2.0, 3.0;
// r2 = 2.0, 2.0, 2.0;
cerr << "r1 = " << r1 << endl;
cerr << "r2 = " << r2 << endl;
GeomVector<3> r4(r1);
cerr << "r4(r1) = " << r4 << endl;
GeomVector<3> r3 = r2;
cerr << "r3 = r2 = " << r3 << endl;
double scalar = 5.0;
r3 = scalar;
cerr << "scalar = " << scalar << endl;
cerr << "r3 = scalar = " << r3 << endl;
cerr << "r1.x(), r1.y(), r1.z() = " << r1.x() << " "
<< r1.y() << " " << r1.z() << endl;
r3.Zero();
cerr << "r3.Zero(): " << r3 << endl;
cerr << "-r1 = " << -r1 << endl;
cerr << "r1 + r2 = " << r1 + r2 << endl;
cerr << "r1 - r2 = " << r1 - r2 << endl;
cerr << "r1*r2 = " << r1*r2 << endl;
cerr << "r1 + scalar = " << r1 + scalar << endl;
cerr << "r1 - scalar = " << r1 - scalar << endl;
cerr << "r1*scalar = " << r1*scalar << endl;
cerr << "r1/scalar = " << r1/scalar << endl;
r3 = r1;
r3 += r2;
cerr << "r1 += r2: " << r3 << endl;
r3 = r1;
r3 -= r2;
cerr << "r1 -= r2: " << r3 << endl;
r3 = r1;
r3 += scalar;
cerr << "r1 += scalar: " << r3 << endl;
r3 = r1;
r3 -= scalar;
cerr << "r1 -= scalar: " << r3 << endl;
r3 = r1;
r3 *= scalar;
cerr << "r1 *= scalar: " << r3 << endl;
r3 = r1;
r3 /= scalar;
cerr << "r1 /= scalar: " << r3 << endl;
cerr << "scalar + r1 = " << scalar + r1 << endl;
cerr << "scalar - r1 = " << scalar - r1 << endl;
cerr << "scalar*r1 = " << scalar*r1 << endl;
cerr << "r1 == r2: " << (r1 == r2) << endl;
cerr << "r1 != r2: " << (r1 != r2) << endl;
cerr << "r1 < r2: " << (r1 < r2) << endl;
cerr << "r1 > r2: " << (r1 > r2) << endl;
cerr << "r1 <= r2: " << (r1 <= r2) << endl;
cerr << "r1 >= r2: " << (r1 >= r2) << endl;
cerr << "r1 == r1: " << (r1 == r1) << endl;
cerr << "r1 != r1: " << (r1 != r1) << endl;
cerr << "r1 < r1: " << (r1 < r1) << endl;
cerr << "r1 > r1: " << (r1 > r1) << endl;
cerr << "r1 <= r1: " << (r1 <= r1) << endl;
cerr << "r1 >= r1: " << (r1 >= r1) << endl;
cerr << "r1.dot(r2) = " << r1.dot(r2) << endl;
cerr << "r1.cross(r2) = " << r1.cross(r2) << endl;
cerr << "r1.magnitude() = " << r1.magnitude() << endl;
cerr << "r1.magnitude2() = " << r1.magnitude2() << endl;
cerr << "r1.minElement() = " << r1.minElement() << endl;
cerr << "r1.maxElement() = " << r1.maxElement() << endl;
cerr << "r1.sumElements() = " << r1.sumElements() << endl;
// Create a 3d full tensor.
{
cerr << "############################ Full Tensor ############################"
<< endl;
cerr << "GeomTensor<3, FullTensor>(): " << endl
<< GeomTensor<3, FullTensor>() << endl;
cerr << "GeomTensor<3, FullTensor>(1.0): " << endl
<< GeomTensor<3, FullTensor>(1.0) << endl;
GeomTensor<3, FullTensor> T1(2.0, 1.0, 1.0,
2.0, 1.0, 0.0,
2.0, 0.0, 1.0);
cerr << "T1 = " << endl << T1 << endl;
GeomTensor<3, FullTensor> T2(1.0, 0.0, 0.0,
2.0, 2.0, 0.0,
3.0, 2.0, 3.0);
cerr << "T2 = " << endl << T2 << endl;
GeomTensor<3, FullTensor> T3;
T3 = T1;
cerr << "T3 = T1, T3 = " << endl << T3 << endl;
GeomTensor<3, FullTensor> T4(T1);
cerr << "T4(T1), T4 = " << endl << T4 << endl;
T3 = scalar;
cerr << "T3 = scalar, T3 = " << endl << T3 << endl;
cerr << "Accessing T1 individual elements: "
<< T1.xx() << " "
<< T1.xy() << " "
<< T1.xz() << " "
<< T1.yx() << " "
<< T1.yy() << " "
<< T1.yz() << " "
<< T1.zx() << " "
<< T1.zy() << " "
<< T1.zz() << endl;
T3 = T1;
T3.zz(5.0);
cerr << "T1.zz(5.0), T1 = " << endl << T3 << endl;
cerr << "T1.getRow(1) = " << T1.getRow(1) << endl;
cerr << "T1.getColumn(2) = " << T1.getColumn(2) << endl;
T3 = T1;
T3.setRow(1, GeomVector<3>(-1.0, -2.0, -3.0));
cerr << "T1.setRow(1, (-1, -2, -3)), T1 = " << endl << T3 << endl;
T3 = T1;
T3.setColumn(2, GeomVector<3>(-5.0, -4.0, -3.0));
cerr << "T1.setColumn(2, (-5, -4, -3)), T1 = " << endl << T3 << endl;
T3 = T1;
T3.Zero();
cerr << "T1.Zero(), T1 = " << endl << T3 << endl;
cerr << "-T1 = " << endl << -T1 << endl;
cerr << "T1 + T2 = " << endl << T1 + T2 << endl;
cerr << "T1 - T2 = " << endl << T1 - T2 << endl;
cerr << "T1*T2 = " << endl << T1*T2 << endl;
cerr << "T1*r1 = " << T1*r1 << endl;
cerr << "T1 + scalar = " << endl << T1 + scalar << endl;
cerr << "T1 - scalar = " << endl << T1 - scalar << endl;
cerr << "T1*scalar = " << endl << T1*scalar << endl;
cerr << "T1/scalar = " << endl << T1/scalar << endl;
T3 = T1;
T3 += T2;
cerr << "T1 += T2, T1 = " << endl << T3 << endl;
T3 = T1;
T3 -= T2;
cerr << "T1 -= T2, T1 = " << endl << T3 << endl;
T3 = T1;
T3 *= T2;
cerr << "T1 *= T2, T1 = " << endl << T3 << endl;
T3 = T1;
T3 += scalar;
cerr << "T1 += scalar, T1 = " << endl << T3 << endl;
T3 = T1;
T3 -= scalar;
cerr << "T1 -= scalar, T1 = " << endl << T3 << endl;
T3 = T1;
T3 *= scalar;
cerr << "T1 *= scalar, T1 = " << endl << T3 << endl;
T3 = T1;
T3 /= scalar;
cerr << "T1 /= scalar, T1 = " << endl << T3 << endl;
cerr << "T1 == T2: " << (T1 == T2) << endl;
cerr << "T1 == T1: " << (T1 == T1) << endl;
cerr << "T1 != T2: " << (T1 != T2) << endl;
cerr << "T1 != T1: " << (T1 != T1) << endl;
cerr << "T1.Symmetric() = " << endl << T1.Symmetric() << endl;
cerr << "T1.SkewSymmetric() = " << endl << T1.SkewSymmetric() << endl;
cerr << "T1.Transpose() = " << endl << T1.Transpose() << endl;
cerr << "T1.Trace() = " << T1.Trace() << endl;
cerr << "T1.Determinant() = " << T1.Determinant() << endl;
cerr << "T1.dot(T2) = " << endl << T1.dot(T2) << endl;
cerr << "T1.dot(r1) = " << T1.dot(r1) << endl;
cerr << "T1.doubledot(T2) = " << T1.doubledot(T2) << endl;
}
// Create a 3d symmetric tensor.
{
cerr << "############################ Symmetric Tensor ############################"
<< endl;
cerr << "GeomTensor<3, SymmetricTensor>(): " << endl
<< GeomTensor<3, SymmetricTensor>() << endl;
cerr << "GeomTensor<3, SymmetricTensor>(1.0): " << endl
<< GeomTensor<3, SymmetricTensor>(1.0) << endl;
GeomTensor<3, SymmetricTensor> T1(2.0, 0.0, 3.0,
0.0, 1.0, 0.0,
3.0, 0.0, 1.0);
cerr << "T1 = " << endl << T1 << endl;
GeomTensor<3, SymmetricTensor> T2(1.0, 3.0, 5.0,
3.0, 2.0, 0.0,
5.0, 0.0, 3.0);
cerr << "T2 = " << endl << T2 << endl;
GeomTensor<3, SymmetricTensor> T3;
T3 = T1;
cerr << "T3 = T1, T3 = " << endl << T3 << endl;
GeomTensor<3, SymmetricTensor> T4(T1);
cerr << "T4(T1), T4 = " << endl << T4 << endl;
T3 = scalar;
cerr << "T3 = scalar, T3 = " << endl << T3 << endl;
cerr << "Accessing T1 individual elements: "
<< T1.xx() << " "
<< T1.xy() << " "
<< T1.xz() << " "
<< T1.yx() << " "
<< T1.yy() << " "
<< T1.yz() << " "
<< T1.zx() << " "
<< T1.zy() << " "
<< T1.zz() << endl;
T3 = T1;
T3.zz(5.0);
cerr << "T1.zz(5.0), T1 = " << endl << T3 << endl;
cerr << "T1.getRow(1) = " << T1.getRow(1) << endl;
cerr << "T1.getColumn(2) = " << T1.getColumn(2) << endl;
T3 = T1;
T3.setRow(1, GeomVector<3>(-1.0, -2.0, -3.0));
cerr << "T1.setRow(1, (-1, -2, -3)), T1 = " << endl << T3 << endl;
T3 = T1;
T3.setColumn(2, GeomVector<3>(-5.0, -4.0, -3.0));
cerr << "T1.setColumn(2, (-5, -4, -3)), T1 = " << endl << T3 << endl;
T3 = T1;
T3.Zero();
cerr << "T1.Zero(), T1 = " << endl << T3 << endl;
cerr << "-T1 = " << endl << -T1 << endl;
cerr << "T1 + T2 = " << endl << T1 + T2 << endl;
cerr << "T1 - T2 = " << endl << T1 - T2 << endl;
cerr << "T1*T2 = " << endl << T1*T2 << endl;
cerr << "T1*r1 = " << T1*r1 << endl;
cerr << "T1 + scalar = " << endl << T1 + scalar << endl;
cerr << "T1 - scalar = " << endl << T1 - scalar << endl;
cerr << "T1*scalar = " << endl << T1*scalar << endl;
cerr << "T1/scalar = " << endl << T1/scalar << endl;
T3 = T1;
T3 += T2;
cerr << "T1 += T2, T1 = " << endl << T3 << endl;
T3 = T1;
T3 -= T2;
cerr << "T1 -= T2, T1 = " << endl << T3 << endl;
// T3 = T1;
// T3 *= T2;
// cerr << "T1 *= T2, T1 = " << endl << T3 << endl;
T3 = T1;
T3 += scalar;
cerr << "T1 += scalar, T1 = " << endl << T3 << endl;
T3 = T1;
T3 -= scalar;
cerr << "T1 -= scalar, T1 = " << endl << T3 << endl;
T3 = T1;
T3 *= scalar;
cerr << "T1 *= scalar, T1 = " << endl << T3 << endl;
T3 = T1;
T3 /= scalar;
cerr << "T1 /= scalar, T1 = " << endl << T3 << endl;
cerr << "T1 == T2: " << (T1 == T2) << endl;
cerr << "T1 == T1: " << (T1 == T1) << endl;
cerr << "T1 != T2: " << (T1 != T2) << endl;
cerr << "T1 != T1: " << (T1 != T1) << endl;
cerr << "T1.Symmetric() = " << endl << T1.Symmetric() << endl;
cerr << "T1.SkewSymmetric() = " << endl << T1.SkewSymmetric() << endl;
cerr << "T1.Transpose() = " << endl << T1.Transpose() << endl;
cerr << "T1.Trace() = " << T1.Trace() << endl;
cerr << "T1.Determinant() = " << T1.Determinant() << endl;
cerr << "T1.dot(T2) = " << endl << T1.dot(T2) << endl;
cerr << "T1.dot(r1) = " << T1.dot(r1) << endl;
cerr << "T1.doubledot(T2) = " << T1.doubledot(T2) << endl;
GeomTensor<3, FullTensor> T10(1, 2, 3,
4, 5, 6,
7, 8, 9);
cerr << "T10 = " << endl << T10 << endl;
cerr << "T1*T10 = " << endl << T1*T10 << endl;
cerr << "T10*T1 = " << endl << T10*T1 << endl;
}
cerr << "Done." << endl;
}
| 34.675585 | 89 | 0.410301 | [
"vector",
"3d"
] |
e923fc1cf275d07c6f7dd402594f2d4c725e7b9d | 1,596 | cpp | C++ | cpp/maxprofit3.cpp | fizzoo/kod | 79a4b415729e7cadbe9466fbdea9fe73a44485d8 | [
"MIT"
] | null | null | null | cpp/maxprofit3.cpp | fizzoo/kod | 79a4b415729e7cadbe9466fbdea9fe73a44485d8 | [
"MIT"
] | null | null | null | cpp/maxprofit3.cpp | fizzoo/kod | 79a4b415729e7cadbe9466fbdea9fe73a44485d8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<int> V;
void print_v(const V &v){
for (int i = 0; i < v.size(); ++i) {
cout << v[i] << " ";
}
cout << endl;
}
int maxprofit(V prices){
if (prices.size() < 2){
return 0;
}
auto res = V(prices.size(), 0);
auto max_from_right(res);
auto min_from_left(res);
// prof_left: if i sell on i, how much can i profit if i buy at [0, i-1]?
auto prof_left(res);
// prof_right: if i buy on i, how much can i profit if i sell at [i+1, end]?
auto prof_right(res);
int m = prices.back();
for (int i = max_from_right.size()-1; i >= 0; --i) {
m = max(m, prices[i]);
max_from_right[i] = m;
}
m = prices.front();
for (int i = 0; i < min_from_left.size(); ++i) {
m = min(m, prices[i]);
min_from_left[i] = m;
}
int maxprofit = 0;
for (int i = 1; i < prices.size(); ++i) {
prof_left[i] = max(prof_left[i-1], prices[i] - min_from_left[i]);
}
for (int i = prices.size()-2; i >= 0; --i) {
prof_right[i] = max(prof_right[i+1], max_from_right[i+1] - prices[i]);
}
// print_v(prices);
// cout << endl;
// print_v(max_from_right);
// print_v(prof_right);
// cout << endl;
// print_v(min_from_left);
// print_v(prof_left);
int maxprof = 0;
for (int i = 1; i < prices.size()-1; ++i) {
maxprof = max(maxprof, prof_left[i] + prof_right[i+1]);
}
return max(maxprof, prof_left.back());
}
int main(){
V t1 = {7,1,5,3,6,4};
V t2 = {7,6,3,2,1};
V t3 = {1,2,3,4,5};
V t4 = {3,3,5,0,0,3,1,4};
cout << maxprofit(t3);
}
| 22.478873 | 78 | 0.56391 | [
"vector"
] |
e927097f3a50c2fd90b22731816ff4aba51e208e | 8,562 | cpp | C++ | src/ngraph/op/fused/batch_to_space.cpp | nmostafa/ngraph | 1dbef5d30d58d9055ed9b843cf24b33553cbbc98 | [
"Apache-2.0"
] | null | null | null | src/ngraph/op/fused/batch_to_space.cpp | nmostafa/ngraph | 1dbef5d30d58d9055ed9b843cf24b33553cbbc98 | [
"Apache-2.0"
] | null | null | null | src/ngraph/op/fused/batch_to_space.cpp | nmostafa/ngraph | 1dbef5d30d58d9055ed9b843cf24b33553cbbc98 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <cmath>
#include <cstddef>
#include <memory>
#include <ops.hpp>
#include "ngraph/builder/make_constant.hpp"
#include "ngraph/builder/reshape.hpp"
#include "ngraph/node.hpp"
#include "ngraph/op/fused/batch_to_space.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/shape.hpp"
using namespace std;
using namespace ngraph;
constexpr NodeTypeInfo op::v1::BatchToSpace::type_info;
ngraph::op::v1::BatchToSpace::BatchToSpace(const ngraph::Output<ngraph::Node>& data,
const ngraph::Output<ngraph::Node>& block_shape,
const ngraph::Output<ngraph::Node>& crops_begin,
const ngraph::Output<ngraph::Node>& crops_end)
: FusedOp({data, block_shape, crops_begin, crops_end})
{
constructor_validate_and_infer_types();
}
NodeVector op::v1::BatchToSpace::decompose_op() const
{
auto data = input_value(0);
auto block = input_value(1);
auto crops_begin = input_value(2);
auto crops_end = input_value(3);
const auto& data_shape = data.get_shape();
NODE_VALIDATION_CHECK(this,
(data_shape.size() >= 2),
"The data tensor with rank lower than 2 is not supported (data rank: ",
data_shape.size(),
")");
const auto block_const = as_type_ptr<op::Constant>(block.get_node_shared_ptr());
const auto crops_begin_const = as_type_ptr<op::Constant>(crops_begin.get_node_shared_ptr());
const auto crops_end_const = as_type_ptr<op::Constant>(crops_end.get_node_shared_ptr());
vector<int64_t> block_values, crops_end_values;
block_values = block_const->cast_vector<int64_t>();
crops_end_values = crops_end_const->cast_vector<int64_t>();
// First we have to disperse the data from batch, then rearrange them
// so as appropriate chunks of data where close to their destination place.
// Finally squeeze data from respective dimensions.
vector<int64_t> dispersed_shape;
int64_t b_dim_divider = 1;
for (const auto& el : block_values)
{
NODE_VALIDATION_CHECK(this, el > 0, "block_shape values must be greater than 0");
b_dim_divider *= el;
}
NODE_VALIDATION_CHECK(this,
data_shape.at(0) % b_dim_divider == 0,
"BatchToSpace: The input data's 'batch' axis size: ",
data_shape.at(0),
" must be a multiple of ",
" product of block_shape values: ",
b_dim_divider);
// note: B_0 is expected to be 1.
// x' = reshape(`data`, [B_1, ..., B_{N - 1}, batch / (B_1 * ... B_{N - 1}), D_1, D_2, ...,
// D_{N - 1}]),
// where B_i = block_shape[i]
dispersed_shape.insert(dispersed_shape.begin(), block_values.begin() + 1, block_values.end());
dispersed_shape.push_back(data_shape.at(0) / b_dim_divider);
for (size_t i = 1; i < data_shape.size(); ++i)
{
dispersed_shape.push_back(data_shape.at(i));
}
const auto out_pattern_1 =
op::Constant::create(element::i64, Shape{dispersed_shape.size()}, dispersed_shape);
const bool special_zero = false;
auto flat_node = make_shared<ngraph::op::v1::Reshape>(data, out_pattern_1, special_zero)
->add_provenance_group_members_above({data});
// calculate axes to transpose
// x'' = transpose(x', [N, N + 1, 0, N + 2, 1, ..., N + N - 1, N - 1])
vector<size_t> axes_order{block_values.size() - 1};
for (size_t i = 0; i < block_values.size() - 1; ++i)
{
axes_order.push_back(i + block_values.size());
axes_order.push_back(i);
}
flat_node = builder::opset1::reorder_axes(flat_node, axes_order);
// x''' = reshape(x'', [batch / (B_1 * ... * B_{N - 1}), D_1 * B_1, D_2 * B_2, ... , D_{N - 1}
// * B_{N - 1}])
vector<int64_t> squeezed_shape;
squeezed_shape.push_back(data_shape.at(0) / b_dim_divider);
for (size_t i = 1; i < block_values.size(); ++i)
{
squeezed_shape.push_back(data_shape.at(i) * block_values.at(i));
}
const auto out_pattern_2 =
op::Constant::create(element::i64, Shape{squeezed_shape.size()}, squeezed_shape);
flat_node = make_shared<ngraph::op::v1::Reshape>(flat_node, out_pattern_2, special_zero)
->add_provenance_group_members_above({data});
// Crop the start and end of dimensions according to `crops_begin`, `crops_end` to produce
// the output of shape:
// note: `crops_begin[0], crops_end[0]` are expected to be 0.
// `y = [batch / (B_1 * ... * B_{N - 1}), crop(D_1 * B_1, crops_begin[1], crops_end[1]),
// crop(D_2 * B_2, crops_begin[2], crops_end[2]), ... ,
// crop(D_{N - 1} * B_{N - 1}, crops_begin[N - 1], crops_end[N - 1])]`
vector<int64_t> upperbounds_values;
auto flat_node_shape = flat_node->get_shape();
for (size_t i = 0; i < flat_node_shape.size(); ++i)
{
upperbounds_values.push_back(flat_node_shape.at(i) - crops_end_values.at(i));
}
const auto upperbounds = op::Constant::create(
crops_end.get_element_type(), Shape{upperbounds_values.size()}, upperbounds_values);
vector<int64_t> begin_mask(data_shape.size(), 0);
vector<int64_t> end_mask(data_shape.size(), 0);
flat_node = make_shared<op::v1::StridedSlice>(
flat_node, crops_begin_const, upperbounds, begin_mask, end_mask);
return NodeVector{flat_node};
}
void ngraph::op::v1::BatchToSpace::pre_validate_and_infer_types()
{
PartialShape data_pshape = get_input_partial_shape(0);
auto data = input_value(0);
auto block = input_value(1);
auto crops_begin = input_value(2);
auto crops_end = input_value(3);
NGRAPH_CHECK(block.get_node_shared_ptr()->is_constant(),
"block_shape input node is expected to be a static constant");
NGRAPH_CHECK(crops_begin.get_node_shared_ptr()->is_constant(),
"crops_begin input node is expected to be a static constant");
NGRAPH_CHECK(crops_end.get_node_shared_ptr()->is_constant(),
"crops_end input node is expected to be a static constant");
const auto& data_type = get_input_element_type(0);
const auto& block_shape_type = get_input_element_type(1);
const auto& crops_begin_type = get_input_element_type(2);
const auto& crops_end_type = get_input_element_type(3);
NODE_VALIDATION_CHECK(this,
block_shape_type.is_integral_number(),
"block_shape must be an integral number but got (",
block_shape_type,
").");
NODE_VALIDATION_CHECK(this,
crops_begin_type.is_integral_number(),
"crops_begin must be an integral number but got (",
crops_begin_type,
").");
NODE_VALIDATION_CHECK(this,
crops_end_type.is_integral_number(),
"crops_end must be an integral number but got (",
crops_end_type,
").");
if (data_pshape.is_dynamic())
{
set_output_type(0, data_type, PartialShape::dynamic());
}
}
std::shared_ptr<ngraph::Node>
ngraph::op::v1::BatchToSpace::copy_with_new_args(const ngraph::NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<BatchToSpace>(
new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3));
}
bool ngraph::op::v1::BatchToSpace::visit_attributes(ngraph::AttributeVisitor& visitor)
{
return true;
}
| 41.970588 | 100 | 0.614926 | [
"shape",
"vector"
] |
e92ade284ca0ae2b03718fe065fa6c15c0bb8f91 | 14,619 | cpp | C++ | dawn/src/dawn/CodeGen/Cuda-ico/ASTStencilBody.cpp | MeteoSwiss-APN/dawn | 92981ebce587eb71baa92e69a793f61572945f46 | [
"MIT"
] | 20 | 2017-09-28T14:23:54.000Z | 2021-08-23T09:58:26.000Z | dawn/src/dawn/CodeGen/Cuda-ico/ASTStencilBody.cpp | MeteoSwiss-APN/dawn | 92981ebce587eb71baa92e69a793f61572945f46 | [
"MIT"
] | 1,018 | 2017-10-09T13:55:47.000Z | 2022-03-14T13:16:38.000Z | dawn/src/dawn/CodeGen/Cuda-ico/ASTStencilBody.cpp | MeteoSwiss-APN/dawn | 92981ebce587eb71baa92e69a793f61572945f46 | [
"MIT"
] | 20 | 2017-09-21T10:35:24.000Z | 2021-01-18T09:24:58.000Z | //===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "ASTStencilBody.h"
#include "dawn/AST/ASTExpr.h"
#include "dawn/AST/LocationType.h"
#include "dawn/IIR/AST.h"
#include "dawn/IIR/ASTExpr.h"
#include <algorithm>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
namespace dawn {
namespace codegen {
namespace cudaico {
void ASTStencilBody::visit(const std::shared_ptr<ast::BlockStmt>& stmt) {
indent_ += DAWN_PRINT_INDENT;
auto indent = std::string(indent_, ' ');
for(const auto& s : stmt->getStatements()) {
ss_ << indent;
s->accept(*this);
}
indent_ -= DAWN_PRINT_INDENT;
}
std::string ASTStencilBody::nbhIterStr() const {
return "nbhIter" + std::to_string(recursiveIterNest_);
}
std::string ASTStencilBody::nbhIdxParentStr() const {
return "nbhIdx" + std::to_string(recursiveIterNest_ - 1);
}
std::string ASTStencilBody::nbhIdxStr() const {
return "nbhIdx" + std::to_string(recursiveIterNest_);
}
void ASTStencilBody::visit(const std::shared_ptr<ast::LoopStmt>& stmt) {
const auto maybeChainPtr =
dynamic_cast<const ast::ChainIterationDescr*>(stmt->getIterationDescrPtr());
DAWN_ASSERT_MSG(maybeChainPtr, "general loop concept not implemented yet!\n");
parentIsForLoop_ = true;
ss_ << "for (int " + nbhIterStr() + " = 0; " + nbhIterStr() + " < "
<< chainToSparseSizeString(maybeChainPtr->getIterSpace()) << "; " + nbhIterStr() + "++)";
ss_ << "{\n";
ss_ << "int " + nbhIdxStr() + " = " << chainToTableString(maybeChainPtr->getIterSpace()) << "["
<< "pidx + " << locToStrideString(maybeChainPtr->getIterSpace().Chain[0]) << " * " + nbhIterStr()
<< "];\n";
if(hasIrregularPentagons(maybeChainPtr->getChain()) || genAtlasCompatCode_) {
ss_ << "if (" + nbhIdxStr() + " == DEVICE_MISSING_VALUE) { continue; }";
}
stmt->getBlockStmt()->accept(*this);
ss_ << "}\n";
parentIsForLoop_ = false;
}
void ASTStencilBody::visit(const std::shared_ptr<ast::VerticalRegionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "VerticalRegionDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<ast::StencilCallDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "StencilCallDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<ast::BoundaryConditionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "BoundaryConditionDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<ast::StencilFunCallExpr>& expr) {
DAWN_ASSERT_MSG(0, "StencilFunCallExpr not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<ast::StencilFunArgExpr>& expr) {
DAWN_ASSERT_MSG(0, "StencilFunArgExpr not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<ast::ReturnStmt>& stmt) {
DAWN_ASSERT_MSG(0, "Return not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<ast::VarAccessExpr>& expr) {
std::string name = getName(expr);
int AccessID = iir::getAccessID(expr);
if(metadata_.isAccessType(iir::FieldAccessType::GlobalVariable, AccessID)) {
ss_ << "globals." << name;
} else {
ss_ << name;
if(expr->isArrayAccess()) {
ss_ << "[";
expr->getIndex()->accept(*this);
ss_ << "]";
}
}
}
void ASTStencilBody::visit(const std::shared_ptr<ast::LiteralAccessExpr>& expr) {
std::string type(ASTCodeGenCXX::builtinTypeIDToCXXType(expr->getBuiltinType(), false));
ss_ << (type.empty() ? "" : "(" + type + ") ") << expr->getValue();
}
void ASTStencilBody::visit(const std::shared_ptr<ast::UnaryOperator>& expr) {
ss_ << "(" << expr->getOp();
expr->getOperand()->accept(*this);
ss_ << ")";
}
void ASTStencilBody::visit(const std::shared_ptr<ast::BinaryOperator>& expr) {
ss_ << "(";
expr->getLeft()->accept(*this);
ss_ << " " << expr->getOp() << " ";
expr->getRight()->accept(*this);
ss_ << ")";
}
void ASTStencilBody::visit(const std::shared_ptr<ast::AssignmentExpr>& expr) {
expr->getLeft()->accept(*this);
ss_ << " " << expr->getOp() << " ";
expr->getRight()->accept(*this);
}
std::string ASTStencilBody::makeIndexString(const std::shared_ptr<ast::FieldAccessExpr>& expr,
std::string kiterStr) const {
bool isVertical = metadata_.getFieldDimensions(iir::getAccessID(expr)).isVertical();
if(isVertical) {
return kiterStr;
}
bool isHorizontal = !metadata_.getFieldDimensions(iir::getAccessID(expr)).K();
bool isFullField = !isHorizontal && !isVertical;
auto unstrDims = ast::dimension_cast<const ast::UnstructuredFieldDimension&>(
metadata_.getFieldDimensions(iir::getAccessID(expr)).getHorizontalFieldDimension());
bool isDense = unstrDims.isDense();
bool isSparse = unstrDims.isSparse();
std::string denseSize = locToStrideString(unstrDims.getDenseLocationType());
// 3D
if(isFullField && isDense) {
if((parentIsReduction_ || parentIsForLoop_) &&
ast::offset_cast<const ast::UnstructuredOffset&>(expr->getOffset().horizontalOffset())
.hasOffset()) {
// if the field access has an horizontal offset we use the neighbour reduction index
return kiterStr + "*" + denseSize + "+ " + nbhIdxStr();
} else {
// otherwise the main pidx grid point index
return kiterStr + "*" + denseSize + "+ " + pidxStr();
}
}
if(isFullField && isSparse) {
DAWN_ASSERT_MSG(parentIsForLoop_ || parentIsReduction_,
"Sparse Field Access not allowed in this context");
return nbhIterStr() + " * kSize * " + denseSize + " + " + kiterStr + "*" + denseSize + " + " +
pidxStr();
}
// 2D
if(isHorizontal && isDense) {
if((parentIsReduction_ || parentIsForLoop_) &&
ast::offset_cast<const ast::UnstructuredOffset&>(expr->getOffset().horizontalOffset())
.hasOffset()) {
return nbhIdxStr();
} else {
return "pidx";
}
}
if(isHorizontal && isSparse) {
DAWN_ASSERT_MSG(parentIsForLoop_ || parentIsReduction_,
"Sparse Field Access not allowed in this context");
std::string sparseSize = chainToSparseSizeString(unstrDims.getIterSpace());
return nbhIterStr() + " * " + denseSize + " + " + pidxStr();
}
DAWN_ASSERT_MSG(false, "Bad Field configuration found in code gen!");
return "BAD_FIELD_CONFIG";
}
void ASTStencilBody::visit(const std::shared_ptr<ast::FieldAccessExpr>& expr) {
if(!expr->getOffset().hasVerticalIndirection()) {
ss_ << expr->getName() + "[" +
makeIndexString(expr, "(kIter + " +
std::to_string(expr->getOffset().verticalShift()) + ")") +
"]";
} else {
auto vertOffset = makeIndexString(std::static_pointer_cast<ast::FieldAccessExpr>(
expr->getOffset().getVerticalIndirectionFieldAsExpr()),
"kIter");
ss_ << expr->getName() + "[" +
makeIndexString(expr, "(int)(" +
expr->getOffset().getVerticalIndirectionFieldName() + "[" +
vertOffset + "] " + " + " +
std::to_string(expr->getOffset().verticalShift()) + ")") +
"]";
}
}
void ASTStencilBody::visit(const std::shared_ptr<ast::FunCallExpr>& expr) {
std::string callee = expr->getCallee();
// TODO: temporary hack to remove namespace prefixes
std::size_t lastcolon = callee.find_last_of(":");
ss_ << callee.substr(lastcolon + 1) << "(";
std::size_t numArgs = expr->getArguments().size();
for(std::size_t i = 0; i < numArgs; ++i) {
expr->getArguments()[i]->accept(*this);
ss_ << (i == numArgs - 1 ? "" : ", ");
}
ss_ << ")";
}
void ASTStencilBody::visit(const std::shared_ptr<ast::IfStmt>& stmt) {
ss_ << "if(";
stmt->getCondExpr()->accept(*this);
ss_ << ")\n";
ss_ << "{";
stmt->getThenStmt()->accept(*this);
ss_ << "}";
if(stmt->hasElse()) {
ss_ << std::string(indent_, ' ') << "else\n";
ss_ << "{";
stmt->getElseStmt()->accept(*this);
ss_ << "}";
}
}
void ASTStencilBody::generateNeighbourRedLoop(std::stringstream& ss) const {
for(auto& it : reductionParser_) {
const std::unique_ptr<ASTStencilBody>& tt = it.second;
ss << (*tt).ss_.rdbuf();
}
}
void ASTStencilBody::visit(const std::shared_ptr<ast::ExprStmt>& stmt) {
FindReduceOverNeighborExpr findReduceOverNeighborExpr;
stmt->getExpr()->accept(findReduceOverNeighborExpr);
// if there are neighbour reductions, we preprocess them in advance in order to be able to code
// generate the loop over neighbour reduction before the expression stmt
if(findReduceOverNeighborExpr.hasReduceOverNeighborExpr()) {
// instantiate a new ast stencil body to parse exclusively the neighbour reductions
ASTStencilBody astParser(metadata_, genAtlasCompatCode_, recursiveIterNest_);
astParser.parentIsForLoop_ = parentIsForLoop_;
astParser.parentIsReduction_ = parentIsReduction_;
stmt->getExpr()->accept(astParser);
// code generate the loop over neighbours reduction
astParser.generateNeighbourRedLoop(ss_);
reductionParser_ = std::move(astParser.reductionParser_);
}
stmt->getExpr()->accept(*this);
ss_ << ";\n";
}
void ASTStencilBody::visit(const std::shared_ptr<ast::VarDeclStmt>& stmt) {
FindReduceOverNeighborExpr findReduceOverNeighborExpr;
stmt->accept(findReduceOverNeighborExpr);
if(findReduceOverNeighborExpr.hasReduceOverNeighborExpr()) {
ASTStencilBody astParser(metadata_, genAtlasCompatCode_, recursiveIterNest_);
astParser.parentIsForLoop_ = parentIsForLoop_;
astParser.parentIsReduction_ = parentIsReduction_;
for(auto& expr : stmt->getInitList()) {
expr->accept(astParser);
}
astParser.generateNeighbourRedLoop(ss_);
reductionParser_ = std::move(astParser.reductionParser_);
}
ASTCodeGenCXX::visit(stmt);
}
bool ASTStencilBody::hasIrregularPentagons(const std::vector<ast::LocationType>& chain) const {
DAWN_ASSERT(chain.size() > 1);
return (std::count(chain.begin(), chain.end() - 1, ast::LocationType::Vertices) != 0);
}
std::string ASTStencilBody::nbhLhsName(const std::shared_ptr<ast::Expr>& expr) const {
return "lhs_" + std::to_string(expr->getID());
}
std::string ASTStencilBody::pidxStr() const {
// the pidx within a nested neighbour reduction is the parent neighbor reduction loop index
if(recursiveIterNest_ > 0)
return nbhIdxParentStr();
else
return "pidx";
}
void ASTStencilBody::evalNeighbourReduction(
const std::shared_ptr<ast::ReductionOverNeighborExpr>& expr) {
auto lhs_name = nbhLhsName(expr);
std::string weights_name = "weights_" + std::to_string(expr->getID());
ss_ << "::dawn::float_type " << lhs_name << " = ";
expr->getInit()->accept(*this);
ss_ << ";\n";
auto weights = expr->getWeights();
if(weights.has_value()) {
ss_ << "::dawn::float_type " << weights_name << "[" << weights->size() << "] = {";
bool first = true;
for(auto weight : *weights) {
if(!first) {
ss_ << ", ";
}
weight->accept(*this);
first = false;
}
ss_ << "};\n";
}
ss_ << "for (int " + nbhIterStr() + " = 0; " + nbhIterStr() + " < "
<< chainToSparseSizeString(expr->getIterSpace()) << "; " + nbhIterStr() + "++)";
ss_ << "{\n";
ss_ << "int " + nbhIdxStr() + " = " << chainToTableString(expr->getIterSpace()) << "["
<< pidxStr() << " + " << locToStrideString(expr->getIterSpace().Chain[0]) << " * " + nbhIterStr()
<< "];\n";
if(hasIrregularPentagons(expr->getNbhChain()) || genAtlasCompatCode_) {
ss_ << "if (" + nbhIdxStr() + " == DEVICE_MISSING_VALUE) { continue; }";
}
FindReduceOverNeighborExpr findReduceOverNeighborExpr;
expr->getRhs()->accept(findReduceOverNeighborExpr);
// here we have finished generating the loop over neighbours structure
// before we generate the expression, we check if (and generate) nested neighbour reductions
if(findReduceOverNeighborExpr.hasReduceOverNeighborExpr()) {
ASTStencilBody astParser(metadata_, genAtlasCompatCode_, recursiveIterNest_ + 1);
astParser.parentIsForLoop_ = parentIsForLoop_;
astParser.parentIsReduction_ = parentIsReduction_;
expr->getRhs()->accept(astParser);
for(auto& redParser : astParser.reductionParser_) {
ss_ << (redParser.second)->ss_.str();
}
}
if(!expr->isArithmetic()) {
ss_ << lhs_name << " = " << expr->getOp() << "(" << lhs_name << ", ";
} else {
ss_ << lhs_name << " " << expr->getOp() << "= ";
}
if(expr->getWeights().has_value()) {
std::string weights_name = "weights_" + std::to_string(expr->getID());
ss_ << weights_name << "[" + nbhIterStr() + "] * ";
}
expr->getRhs()->accept(*this);
if(!expr->isArithmetic()) {
ss_ << ");\n";
} else {
ss_ << ";\n";
}
ss_ << "}\n";
}
void ASTStencilBody::visit(const std::shared_ptr<ast::ReductionOverNeighborExpr>& expr) {
std::string lhs_name = nbhLhsName(expr);
reductionParser_.emplace(expr->getID(), std::make_unique<ASTStencilBody>(
metadata_, genAtlasCompatCode_, recursiveIterNest_));
reductionParser_.at(expr->getID())->parentIsReduction_ = true;
reductionParser_.at(expr->getID())->evalNeighbourReduction(expr);
ss_ << lhs_name;
}
std::string ASTStencilBody::getName(const std::shared_ptr<ast::VarDeclStmt>& stmt) const {
return metadata_.getFieldNameFromAccessID(iir::getAccessID(stmt));
}
std::string ASTStencilBody::getName(const std::shared_ptr<ast::Expr>& expr) const {
return metadata_.getFieldNameFromAccessID(iir::getAccessID(expr));
}
ASTStencilBody::ASTStencilBody(const iir::StencilMetaInformation& metadata, bool genAtlasCompatCode,
int recursiveIterNest)
: metadata_(metadata), genAtlasCompatCode_(genAtlasCompatCode),
recursiveIterNest_(recursiveIterNest) {}
ASTStencilBody::~ASTStencilBody() {}
} // namespace cudaico
} // namespace codegen
} // namespace dawn
| 35.918919 | 103 | 0.635201 | [
"vector",
"3d"
] |
e92d187a3cef215fbaecd2b64d6a0681f71534f8 | 3,895 | cxx | C++ | ZDC/ZDCbase/AliZDCEnCalib.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | ZDC/ZDCbase/AliZDCEnCalib.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 2 | 2016-11-25T08:40:56.000Z | 2019-10-11T12:29:29.000Z | ZDC/ZDCbase/AliZDCEnCalib.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1 | 2019-12-27T08:43:06.000Z | 2019-12-27T08:43:06.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// class for ZDC ENERGY calibration //
// -> values for energy calibration //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliZDCEnCalib.h"
ClassImp(AliZDCEnCalib)
//________________________________________________________________
AliZDCEnCalib::AliZDCEnCalib():
TNamed()
{
Reset();
for(Int_t i=0; i<6; i++) fEnCalibration[i] = 0.;
}
//________________________________________________________________
AliZDCEnCalib::AliZDCEnCalib(const char* name):
TNamed()
{
// Constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
Reset();
for(Int_t i=0; i<6; i++){
fEnCalibration[i] = 0.;
}
}
//________________________________________________________________
AliZDCEnCalib::AliZDCEnCalib(const AliZDCEnCalib& calibda) :
TNamed(calibda)
{
// Copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
Reset();
for(int i=0; i<6; i++){
fEnCalibration[i] = calibda.GetEnCalib(i);
}
}
//________________________________________________________________
AliZDCEnCalib &AliZDCEnCalib::operator =(const AliZDCEnCalib& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
Reset();
for(int i=0; i<6; i++){
fEnCalibration[i] = calibda.GetEnCalib(i);
}
return *this;
}
//________________________________________________________________
AliZDCEnCalib::~AliZDCEnCalib()
{
}
//________________________________________________________________
void AliZDCEnCalib::Reset()
{
// Reset
}
//________________________________________________________________
void AliZDCEnCalib::Print(Option_t *) const
{
// Printing of calibration object
printf("\n\n ####### Energy calibration coefficients ####### \n");
printf(" ZNC = %.4f (E[TeV]/ADCch.) \n",fEnCalibration[0]);
printf(" ZPC = %.4f (E[TeV]/ADCch.) \n",fEnCalibration[1]);
printf(" ZNA = %.4f (E[TeV]/ADCch.) \n",fEnCalibration[2]);
printf(" ZPA = %.4f (E[TeV]/ADCch.) \n",fEnCalibration[3]);
printf(" ZEM1 = %.2f (E[TeV]/ADCch.) \n",fEnCalibration[4]);
printf(" ZEM2 = %.2f (E[TeV]/ADCch.) \n",fEnCalibration[5]);
}
//________________________________________________________________
void AliZDCEnCalib::SetEnCalib(Float_t* EnCalib)
{
// Set energy calibration coefficients
if(EnCalib) for(int t=0; t<6; t++) fEnCalibration[t] = EnCalib[t];
else for(int t=0; t<6; t++) fEnCalibration[t] = 0.;
}
| 35.409091 | 88 | 0.56611 | [
"object"
] |
e92d1d1c82e5e4e9a898a0ba443393243f5ad005 | 73 | hpp | C++ | src/boost_geometry_strategies_cartesian_point_in_poly_winding.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_geometry_strategies_cartesian_point_in_poly_winding.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_geometry_strategies_cartesian_point_in_poly_winding.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/geometry/strategies/cartesian/point_in_poly_winding.hpp>
| 36.5 | 72 | 0.863014 | [
"geometry"
] |
e93736fc13c85ffe4687782e5598fa8c4917c123 | 4,830 | hpp | C++ | include/silver_bullets/task_engine/ParallelTaskScheduler.hpp | kairzhanable/silver_bullets | 3c45732088b9640c3fd575ba0f081d3cff95ed58 | [
"MIT"
] | null | null | null | include/silver_bullets/task_engine/ParallelTaskScheduler.hpp | kairzhanable/silver_bullets | 3c45732088b9640c3fd575ba0f081d3cff95ed58 | [
"MIT"
] | 3 | 2020-05-02T07:17:04.000Z | 2021-11-19T13:18:30.000Z | include/silver_bullets/task_engine/ParallelTaskScheduler.hpp | kairzhanable/silver_bullets | 3c45732088b9640c3fd575ba0f081d3cff95ed58 | [
"MIT"
] | 3 | 2020-11-13T17:10:48.000Z | 2021-11-19T11:23:18.000Z | #pragma once
#include "TaskExecutor.hpp"
#include "silver_bullets/sync/ThreadNotifier.hpp"
#include <memory>
#include <vector>
#include <deque>
namespace silver_bullets {
namespace task_engine {
template<class TaskFunc>
class ParallelTaskScheduler
{
public:
template<class ... Args>
explicit ParallelTaskScheduler(Args&& ... args) :
m_cancelParam(std::forward<Args>(args)...)
{
}
ParallelTaskScheduler& addTaskExecutor(const std::shared_ptr<TaskExecutor<TaskFunc>>& taskExecutor)
{
m_resourceInfo[taskExecutor->resourceType()].executors.push_back(taskExecutor);
taskExecutor->setTaskCompletionNotifier(&m_taskCompletionNotifier);
return *this;
}
ParallelTaskScheduler& addTask(const TaskExecutorStartParam& startParam)
{
auto& ri = m_resourceInfo.at(startParam.task.resourceType);
ri.tasks.push_back(startParam);
maybeStartNextTask(startParam.task.resourceType);
return *this;
}
bool isRunning() const {
return m_running;
}
ParallelTaskScheduler& wait()
{
while(m_running) {
m_taskCompletionNotifier.wait();
propagateCb();
}
return *this;
}
template< class Rep, class Period >
bool maybeWait(const std::chrono::duration<Rep, Period>& timeout)
{
auto endTime = std::chrono::system_clock::now() + timeout;
auto remainingTimeout = timeout;
while(m_running) {
if (!m_taskCompletionNotifier.wait_for(remainingTimeout))
return false;
auto currentTime = std::chrono::system_clock::now();
if (currentTime >= endTime)
return false;
remainingTimeout = std::chrono::duration_cast<decltype (remainingTimeout)>(endTime - currentTime);
propagateCb();
}
return true;
}
bool propagateCb()
{
auto cancelled = TaskExecutorCancelParam<TaskFunc>::isCancelled(m_cancelParam);
if (m_running) {
// Track finished tasks
std::size_t totalRunningExecutorCount = 0;
for (auto& resourceInfoItem : m_resourceInfo) {
auto& ri = resourceInfoItem.second;
if (cancelled)
ri.tasks.clear();
for (std::size_t i=0; i<ri.runningExecutorCount; ++i) {
auto& x = ri.executors[i];
if (x->propagateCb()) {
// Executor has finished task
// Put the executor after the last currently executing one
BOOST_ASSERT(ri.runningExecutorCount > 0);
--ri.runningExecutorCount;
if (i != ri.runningExecutorCount) {
BOOST_ASSERT(i < ri.runningExecutorCount);
std::swap(x, ri.executors[ri.runningExecutorCount]);
--i;
}
// Start next task, if any
if (!cancelled)
maybeStartNextTask(resourceInfoItem.first);
}
}
totalRunningExecutorCount += ri.runningExecutorCount;
}
if (totalRunningExecutorCount == 0)
m_running = false;
}
return !m_running;
}
TaskExecutorCancelParam_t<TaskFunc>& cancelParam() {
return m_cancelParam;
}
private:
struct ResourceInfo
{
std::vector<std::shared_ptr<TaskExecutor<TaskFunc>>> executors;
std::size_t runningExecutorCount = 0; // Running are all at the beginning of executors
std::deque <TaskExecutorStartParam> tasks;
};
TaskExecutorCancelParam_t<TaskFunc> m_cancelParam;
sync::ThreadNotifier m_taskCompletionNotifier;
std::map<int, ResourceInfo> m_resourceInfo;
bool m_running = false;
bool maybeStartNextTask(int resourceType)
{
auto& ri = m_resourceInfo.at(resourceType);
if (ri.tasks.empty())
return false;
if (ri.executors.empty())
throw std::runtime_error("ParallelTaskScheduler: No suitable resources are supplied");
if (ri.runningExecutorCount < ri.executors.size()) {
// Start next task
auto& x = ri.executors[ri.runningExecutorCount];
auto startParam = ri.tasks.front();
ri.tasks.pop_front();
x->start(std::move(startParam));
++ri.runningExecutorCount;
m_running = true;
return true;
}
else {
// All executors are busy
BOOST_ASSERT(m_running);
return false;
}
}
};
} // namespace task_engine
} // namespace silver_bullets
| 31.363636 | 110 | 0.579089 | [
"vector"
] |
e93bd7d228468b2f8592d22b3fe9f4288d0e179d | 3,301 | cpp | C++ | tests/Unit/Time/Triggers/Test_Times.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | tests/Unit/Time/Triggers/Test_Times.cpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | tests/Unit/Time/Triggers/Test_Times.cpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <cmath>
#include <initializer_list>
#include <limits>
#include <memory>
#include <pup.h>
#include <pup_stl.h>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "Framework/TestCreation.hpp"
#include "Framework/TestHelpers.hpp"
#include "Options/Protocols/FactoryCreation.hpp"
#include "Parallel/RegisterDerivedClassesWithCharm.hpp"
#include "Parallel/Tags/Metavariables.hpp"
#include "ParallelAlgorithms/EventsAndTriggers/Trigger.hpp"
#include "Time/Slab.hpp"
#include "Time/Tags.hpp"
#include "Time/Time.hpp"
#include "Time/TimeSequence.hpp"
#include "Time/TimeStepId.hpp"
#include "Time/Triggers/Times.hpp"
#include "Utilities/ProtocolHelpers.hpp"
#include "Utilities/TMPL.hpp"
namespace {
struct Metavariables {
using component_list = tmpl::list<>;
struct factory_creation
: tt::ConformsTo<Options::protocols::FactoryCreation> {
using factory_classes =
tmpl::map<tmpl::pair<TimeSequence<double>,
TimeSequences::all_time_sequences<double>>,
tmpl::pair<Trigger, tmpl::list<Triggers::Times>>>;
};
};
} // namespace
SPECTRE_TEST_CASE("Unit.Time.Triggers.Times", "[Unit][Time]") {
Parallel::register_factory_classes_with_charm<Metavariables>();
const auto check = [](const double time, const double slab_size,
const std::vector<double>& trigger_times,
const bool expected) {
CAPTURE(time);
CAPTURE(slab_size);
CAPTURE(trigger_times);
const auto slab = Slab::with_duration_from_start(0.8 * time, slab_size);
// None of the arguments here should matter, except that they are
// based on the correct slab.
const TimeStepId time_id(false, 12, slab.start() + slab.duration() / 13);
const std::unique_ptr<Trigger> trigger = std::make_unique<Triggers::Times>(
std::make_unique<TimeSequences::Specified<double>>(trigger_times));
const auto sent_trigger = serialize_and_deserialize(trigger);
const auto box = db::create<
db::AddSimpleTags<Parallel::Tags::MetavariablesImpl<Metavariables>,
Tags::TimeStepId, Tags::Time>>(
Metavariables{}, time_id, time);
CHECK(trigger->is_triggered(box) == expected);
CHECK(sent_trigger->is_triggered(box) == expected);
};
static constexpr double infinity = std::numeric_limits<double>::infinity();
check(1.0, 1.0, {}, false);
check(1.0, 1.0, {1.0}, true);
check(1.0, 1.0, {2.0}, false);
check(1.0, 1.0, {0.0, 1.0, 2.0}, true);
check(1.0, 1.0, {2.0, 1.0, 0.0}, true);
check(std::nextafter(1.0, +infinity), 1.0, {0.0, 1.0, 2.0}, true);
check(std::nextafter(1.0, -infinity), 1.0, {0.0, 1.0, 2.0}, true);
check(1.0e5, 1.0, {1.0e5}, true);
check(std::nextafter(1.0e5, +infinity), 1.0, {1.0e5}, true);
check(std::nextafter(1.0e5, -infinity), 1.0, {1.0e5}, true);
const double inaccurate_1 = 1.0 + 1.0e5 - std::nextafter(1.0e5, -infinity);
check(inaccurate_1, 1.0, {1.0}, false);
check(inaccurate_1, 1.0e5, {1.0}, true);
TestHelpers::test_creation<std::unique_ptr<Trigger>, Metavariables>(
"Times:\n"
" Specified:\n"
" Values: [2.0, 1.0, 3.0, 2.0]");
}
| 35.880435 | 79 | 0.669494 | [
"vector"
] |
e9496f02ba2d65444b43814cbac7a35674dafe57 | 231 | hh | C++ | test/ruby/cxx_import_tests/nested_type.hh | maltewi/tools-typelib | c0a28415b6cea4d5500a00d6e7003554d684748e | [
"CECILL-B"
] | 7 | 2015-05-29T09:59:27.000Z | 2020-05-15T13:41:18.000Z | test/ruby/cxx_import_tests/nested_type.hh | jmachowinski/typelib | 9f04e8d842dd489f95c35e63568ef30b29d5df5a | [
"CECILL-B"
] | 68 | 2015-01-06T17:02:27.000Z | 2021-01-27T23:54:05.000Z | test/ruby/cxx_import_tests/nested_type.hh | rock-core/tools-typelib | b15a6c8500db4add544a8ffd6d1d795c65c5283b | [
"CECILL-B"
] | 18 | 2015-03-20T10:57:52.000Z | 2021-01-27T18:53:14.000Z | #include <vector>
namespace nested_types {
struct Outside
{
struct Inside
{
int a;
};
int b;
};
struct User
{
std::vector<Outside::Inside> vector;
};
}
| 12.157895 | 44 | 0.454545 | [
"vector"
] |
e94c47e8faefba50d92c86781111fbe89e3e1ad1 | 30,720 | cc | C++ | services/ui/ws/test_utils.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | services/ui/ws/test_utils.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | services/ui/ws/test_utils.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // 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.
#include "services/ui/ws/test_utils.h"
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop_current.h"
#include "base/strings/string_number_conversions.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "services/service_manager/public/mojom/connector.mojom.h"
#include "services/ui/common/image_cursors_set.h"
#include "services/ui/public/interfaces/cursor/cursor.mojom.h"
#include "services/ui/ws/cursor_location_manager.h"
#include "services/ui/ws/display_binding.h"
#include "services/ui/ws/display_creation_config.h"
#include "services/ui/ws/display_manager.h"
#include "services/ui/ws/test_gpu_host.h"
#include "services/ui/ws/threaded_image_cursors.h"
#include "services/ui/ws/threaded_image_cursors_factory.h"
#include "services/ui/ws/window_manager_access_policy.h"
#include "services/ui/ws/window_manager_window_tree_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/cursor/cursor.h"
#include "ui/gfx/geometry/dip_util.h"
namespace ui {
namespace ws {
namespace test {
namespace {
ClientWindowId NextUnusedClientWindowId(WindowTree* tree) {
for (ClientSpecificId id = kEmbedTreeWindowId;; ++id) {
// Used the id of the client in the upper bits to simplify things.
const ClientWindowId client_id = ClientWindowId(tree->id(), id);
if (!tree->GetWindowByClientId(client_id))
return client_id;
}
}
display::ViewportMetrics MakeViewportMetrics(const display::Display& display) {
gfx::Size pixel_size = gfx::ConvertSizeToPixel(display.device_scale_factor(),
display.bounds().size());
display::ViewportMetrics metrics;
metrics.bounds_in_pixels.set_size(pixel_size);
metrics.device_scale_factor = display.device_scale_factor();
metrics.ui_scale_factor = 1;
return metrics;
}
class TestThreadedImageCursorsFactory : public ThreadedImageCursorsFactory {
public:
TestThreadedImageCursorsFactory() {}
~TestThreadedImageCursorsFactory() override {}
// ThreadedImageCursorsFactory:
std::unique_ptr<ThreadedImageCursors> CreateCursors() override {
if (!resource_runner_) {
resource_runner_ = base::ThreadTaskRunnerHandle::Get();
image_cursors_set_ = std::make_unique<ui::ImageCursorsSet>();
}
return std::make_unique<ws::ThreadedImageCursors>(
resource_runner_, image_cursors_set_->GetWeakPtr());
}
private:
scoped_refptr<base::SingleThreadTaskRunner> resource_runner_;
std::unique_ptr<ui::ImageCursorsSet> image_cursors_set_;
DISALLOW_COPY_AND_ASSIGN(TestThreadedImageCursorsFactory);
};
} // namespace
// TestScreenManager -------------------------------------------------
TestScreenManager::TestScreenManager() {}
TestScreenManager::~TestScreenManager() {
display::Screen::SetScreenInstance(nullptr);
}
int64_t TestScreenManager::AddDisplay() {
return AddDisplay(
display::Display(display::kInvalidDisplayId, gfx::Rect(100, 100)));
}
int64_t TestScreenManager::AddDisplay(const display::Display& input_display) {
// Generate a unique display id.
int64_t display_id = display_ids_.empty() ? 1 : *display_ids_.rbegin() + 1;
display_ids_.insert(display_id);
display::Display display = input_display;
display.set_id(display_id);
// First display added will be the primary display.
display::DisplayList::Type type = display::DisplayList::Type::NOT_PRIMARY;
if (display_ids_.size() == 1)
type = display::DisplayList::Type::PRIMARY;
screen_->display_list().AddDisplay(display, type);
delegate_->OnDisplayAdded(display, MakeViewportMetrics(display));
if (type == display::DisplayList::Type::PRIMARY)
delegate_->OnPrimaryDisplayChanged(display_id);
return display_id;
}
void TestScreenManager::ModifyDisplay(
const display::Display& display,
const base::Optional<display::ViewportMetrics>& metrics) {
DCHECK(display_ids_.count(display.id()) == 1);
screen_->display_list().UpdateDisplay(display);
if (metrics)
delegate_->OnDisplayModified(display, *metrics);
else
delegate_->OnDisplayModified(display, MakeViewportMetrics(display));
}
void TestScreenManager::RemoveDisplay(int64_t display_id) {
DCHECK(display_ids_.count(display_id) == 1);
screen_->display_list().RemoveDisplay(display_id);
delegate_->OnDisplayRemoved(display_id);
display_ids_.erase(display_id);
}
void TestScreenManager::Init(display::ScreenManagerDelegate* delegate) {
delegate_ = delegate;
// Reset everything.
display_ids_.clear();
display::Screen::SetScreenInstance(nullptr);
screen_ = std::make_unique<display::ScreenBase>();
display::Screen::SetScreenInstance(screen_.get());
}
display::ScreenBase* TestScreenManager::GetScreen() {
return screen_.get();
}
// TestPlatformDisplayFactory -------------------------------------------------
TestPlatformDisplayFactory::TestPlatformDisplayFactory(
ui::CursorData* cursor_storage)
: cursor_storage_(cursor_storage) {}
TestPlatformDisplayFactory::~TestPlatformDisplayFactory() {}
std::unique_ptr<PlatformDisplay>
TestPlatformDisplayFactory::CreatePlatformDisplay(
ServerWindow* root_window,
const display::ViewportMetrics& metrics) {
return std::make_unique<TestPlatformDisplay>(metrics, cursor_storage_);
}
// WindowTreeTestApi ---------------------------------------------------------
WindowTreeTestApi::WindowTreeTestApi(WindowTree* tree) : tree_(tree) {}
WindowTreeTestApi::~WindowTreeTestApi() {}
void WindowTreeTestApi::StartPointerWatcher(bool want_moves) {
tree_->StartPointerWatcher(want_moves);
}
void WindowTreeTestApi::StopPointerWatcher() {
tree_->StopPointerWatcher();
}
// EventProcessorTestApi ----------------------------------------------------
bool EventProcessorTestApi::IsWindowPointerTarget(
const ServerWindow* window) const {
for (const auto& pair : ep_->pointer_targets_) {
if (pair.second.window == window)
return true;
}
return false;
}
int EventProcessorTestApi::NumberPointerTargetsForWindow(ServerWindow* window) {
int count = 0;
for (const auto& pair : ep_->pointer_targets_)
if (pair.second.window == window)
count++;
return count;
}
bool EventProcessorTestApi::IsObservingWindow(ServerWindow* window) {
return ep_->observed_windows_.count(window) > 0;
}
// TestDisplayBinding ---------------------------------------------------------
WindowTree* TestDisplayBinding::CreateWindowTree(ServerWindow* root) {
const uint32_t embed_flags = 0;
WindowTree* tree = window_server_->EmbedAtWindow(
root, ui::mojom::WindowTreeClientPtr(), embed_flags,
base::WrapUnique(new WindowManagerAccessPolicy));
WindowTreeTestApi(tree).set_is_for_embedding(false);
tree->ConfigureWindowManager(automatically_create_display_roots_);
return tree;
}
// TestWindowManager ----------------------------------------------------------
TestWindowManager::TestWindowManager() {}
TestWindowManager::~TestWindowManager() {}
void TestWindowManager::OnConnect() {
connect_count_++;
}
void TestWindowManager::WmOnAcceleratedWidgetForDisplay(
int64_t display,
gpu::SurfaceHandle surface_handle) {}
void TestWindowManager::WmNewDisplayAdded(
const display::Display& display,
ui::mojom::WindowDataPtr root,
bool drawn,
const base::Optional<viz::LocalSurfaceId>& local_surface_id) {
display_added_count_++;
}
void TestWindowManager::WmDisplayRemoved(int64_t display_id) {
got_display_removed_ = true;
display_removed_id_ = display_id;
}
void TestWindowManager::WmSetModalType(Id window_id, ui::ModalType type) {
on_set_modal_type_called_ = true;
}
void TestWindowManager::WmCreateTopLevelWindow(
uint32_t change_id,
const viz::FrameSinkId& frame_sink_id,
const base::flat_map<std::string, std::vector<uint8_t>>& properties) {
got_create_top_level_window_ = true;
change_id_ = change_id;
}
void TestWindowManager::WmClientJankinessChanged(ClientSpecificId client_id,
bool janky) {}
void TestWindowManager::WmBuildDragImage(const gfx::Point& screen_location,
const SkBitmap& drag_image,
const gfx::Vector2d& drag_image_offset,
ui::mojom::PointerKind source) {}
void TestWindowManager::WmMoveDragImage(const gfx::Point& screen_location,
WmMoveDragImageCallback callback) {
std::move(callback).Run();
}
void TestWindowManager::WmDestroyDragImage() {}
void TestWindowManager::WmPerformMoveLoop(uint32_t change_id,
Id window_id,
mojom::MoveLoopSource source,
const gfx::Point& cursor_location) {
on_perform_move_loop_called_ = true;
}
void TestWindowManager::WmCancelMoveLoop(uint32_t change_id) {}
void TestWindowManager::WmDeactivateWindow(Id window_id) {}
void TestWindowManager::WmStackAbove(uint32_t change_id,
Id above_id,
Id below_id) {}
void TestWindowManager::WmStackAtTop(uint32_t change_id, Id window_id) {}
void TestWindowManager::WmPerformWmAction(Id window_id,
const std::string& action) {
last_wm_action_ = action;
}
void TestWindowManager::OnAccelerator(uint32_t ack_id,
uint32_t accelerator_id,
std::unique_ptr<ui::Event> event) {
on_accelerator_called_ = true;
on_accelerator_id_ = accelerator_id;
}
void TestWindowManager::OnCursorTouchVisibleChanged(bool enabled) {}
void TestWindowManager::OnEventBlockedByModalWindow(Id window_id) {}
// TestWindowTreeClient -------------------------------------------------------
TestWindowTreeClient::TestWindowTreeClient()
: binding_(this), record_on_change_completed_(false) {}
TestWindowTreeClient::~TestWindowTreeClient() {}
void TestWindowTreeClient::Bind(
mojo::InterfaceRequest<mojom::WindowTreeClient> request) {
binding_.Bind(std::move(request));
}
void TestWindowTreeClient::OnEmbed(
mojom::WindowDataPtr root,
ui::mojom::WindowTreePtr tree,
int64_t display_id,
Id focused_window_id,
bool drawn,
const base::Optional<viz::LocalSurfaceId>& local_surface_id) {
// TODO(sky): add test coverage of |focused_window_id|.
tracker_.OnEmbed(std::move(root), drawn);
}
void TestWindowTreeClient::OnEmbedFromToken(
const base::UnguessableToken& token,
::ui::mojom::WindowDataPtr root,
int64_t display_id,
const base::Optional<viz::LocalSurfaceId>& local_surface_id) {}
void TestWindowTreeClient::OnEmbeddedAppDisconnected(Id window) {
tracker_.OnEmbeddedAppDisconnected(window);
}
void TestWindowTreeClient::OnUnembed(Id window_id) {
tracker_.OnUnembed(window_id);
}
void TestWindowTreeClient::OnCaptureChanged(Id new_capture_window_id,
Id old_capture_window_id) {
tracker_.OnCaptureChanged(new_capture_window_id, old_capture_window_id);
}
void TestWindowTreeClient::OnFrameSinkIdAllocated(
Id window_id,
const viz::FrameSinkId& frame_sink_id) {
tracker_.OnFrameSinkIdAllocated(window_id, frame_sink_id);
}
void TestWindowTreeClient::OnTopLevelCreated(
uint32_t change_id,
mojom::WindowDataPtr data,
int64_t display_id,
bool drawn,
const base::Optional<viz::LocalSurfaceId>& local_surface_id) {
tracker_.OnTopLevelCreated(change_id, std::move(data), drawn);
}
void TestWindowTreeClient::OnWindowBoundsChanged(
Id window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
const base::Optional<viz::LocalSurfaceId>& local_surface_id) {
tracker_.OnWindowBoundsChanged(window, std::move(old_bounds),
std::move(new_bounds), local_surface_id);
}
void TestWindowTreeClient::OnWindowTransformChanged(
Id window,
const gfx::Transform& old_transform,
const gfx::Transform& new_transform) {}
void TestWindowTreeClient::OnClientAreaChanged(
Id window_id,
const gfx::Insets& new_client_area,
const std::vector<gfx::Rect>& new_additional_client_areas) {}
void TestWindowTreeClient::OnTransientWindowAdded(Id window_id,
Id transient_window_id) {}
void TestWindowTreeClient::OnTransientWindowRemoved(Id window_id,
Id transient_window_id) {}
void TestWindowTreeClient::OnWindowHierarchyChanged(
Id window,
Id old_parent,
Id new_parent,
std::vector<mojom::WindowDataPtr> windows) {
tracker_.OnWindowHierarchyChanged(window, old_parent, new_parent,
std::move(windows));
}
void TestWindowTreeClient::OnWindowReordered(Id window_id,
Id relative_window_id,
mojom::OrderDirection direction) {
tracker_.OnWindowReordered(window_id, relative_window_id, direction);
}
void TestWindowTreeClient::OnWindowDeleted(Id window) {
tracker_.OnWindowDeleted(window);
}
void TestWindowTreeClient::OnWindowVisibilityChanged(Id window, bool visible) {
tracker_.OnWindowVisibilityChanged(window, visible);
}
void TestWindowTreeClient::OnWindowOpacityChanged(Id window,
float old_opacity,
float new_opacity) {
tracker_.OnWindowOpacityChanged(window, new_opacity);
}
void TestWindowTreeClient::OnWindowParentDrawnStateChanged(Id window,
bool drawn) {
tracker_.OnWindowParentDrawnStateChanged(window, drawn);
}
void TestWindowTreeClient::OnWindowSharedPropertyChanged(
Id window,
const std::string& name,
const base::Optional<std::vector<uint8_t>>& new_data) {
tracker_.OnWindowSharedPropertyChanged(window, name, new_data);
}
void TestWindowTreeClient::OnWindowInputEvent(
uint32_t event_id,
Id window,
int64_t display_id,
Id display_root_window,
const gfx::PointF& event_location_in_screen_pixel_layout,
std::unique_ptr<ui::Event> event,
bool matches_pointer_watcher) {
tracker_.OnWindowInputEvent(window, *event.get(), display_id,
event_location_in_screen_pixel_layout,
matches_pointer_watcher);
}
void TestWindowTreeClient::OnPointerEventObserved(
std::unique_ptr<ui::Event> event,
Id window_id,
int64_t display_id) {
tracker_.OnPointerEventObserved(*event.get(), window_id);
}
void TestWindowTreeClient::OnWindowFocused(Id focused_window_id) {
tracker_.OnWindowFocused(focused_window_id);
}
void TestWindowTreeClient::OnWindowCursorChanged(Id window_id,
ui::CursorData cursor) {
tracker_.OnWindowCursorChanged(window_id, cursor);
}
void TestWindowTreeClient::OnWindowSurfaceChanged(
Id window_id,
const viz::SurfaceInfo& surface_info) {}
void TestWindowTreeClient::OnDragDropStart(
const base::flat_map<std::string, std::vector<uint8_t>>& mime_data) {}
void TestWindowTreeClient::OnDragEnter(Id window,
uint32_t key_state,
const gfx::Point& position,
uint32_t effect_bitmask,
OnDragEnterCallback callback) {}
void TestWindowTreeClient::OnDragOver(Id window,
uint32_t key_state,
const gfx::Point& position,
uint32_t effect_bitmask,
OnDragOverCallback callback) {}
void TestWindowTreeClient::OnDragLeave(Id window) {}
void TestWindowTreeClient::OnCompleteDrop(Id window,
uint32_t key_state,
const gfx::Point& position,
uint32_t effect_bitmask,
OnCompleteDropCallback callback) {}
void TestWindowTreeClient::OnPerformDragDropCompleted(uint32_t change_id,
bool success,
uint32_t action_taken) {}
void TestWindowTreeClient::OnDragDropDone() {}
void TestWindowTreeClient::OnChangeCompleted(uint32_t change_id, bool success) {
if (record_on_change_completed_)
tracker_.OnChangeCompleted(change_id, success);
}
void TestWindowTreeClient::RequestClose(Id window_id) {}
void TestWindowTreeClient::GetWindowManager(
mojo::AssociatedInterfaceRequest<mojom::WindowManager> internal) {}
// TestWindowTreeBinding ------------------------------------------------------
TestWindowTreeBinding::TestWindowTreeBinding(
WindowTree* tree,
std::unique_ptr<TestWindowTreeClient> client)
: WindowTreeBinding(client.get()),
tree_(tree),
client_(std::move(client)) {}
TestWindowTreeBinding::~TestWindowTreeBinding() {}
mojom::WindowManager* TestWindowTreeBinding::GetWindowManager() {
if (!window_manager_.get())
window_manager_ = std::make_unique<TestWindowManager>();
return window_manager_.get();
}
void TestWindowTreeBinding::SetIncomingMethodCallProcessingPaused(bool paused) {
is_paused_ = paused;
}
mojom::WindowTreeClient* TestWindowTreeBinding::CreateClientForShutdown() {
DCHECK(!client_after_reset_);
client_after_reset_ = std::make_unique<TestWindowTreeClient>();
return client_after_reset_.get();
}
// TestWindowServerDelegate ----------------------------------------------
TestWindowServerDelegate::TestWindowServerDelegate()
: threaded_image_cursors_factory_(
std::make_unique<TestThreadedImageCursorsFactory>()) {}
TestWindowServerDelegate::~TestWindowServerDelegate() {}
TestWindowTreeBinding* TestWindowServerDelegate::Embed(WindowTree* tree,
ServerWindow* window,
int flags) {
mojom::WindowTreeClientPtr client;
mojom::WindowTreeClientRequest client_request = mojo::MakeRequest(&client);
ClientWindowId client_window_id;
if (!tree->IsWindowKnown(window, &client_window_id))
return nullptr;
tree->Embed(client_window_id, std::move(client), flags);
last_client()->Bind(std::move(client_request));
return last_binding();
}
void TestWindowServerDelegate::StartDisplayInit() {}
void TestWindowServerDelegate::OnNoMoreDisplays() {
got_on_no_more_displays_ = true;
}
std::unique_ptr<WindowTreeBinding>
TestWindowServerDelegate::CreateWindowTreeBinding(
BindingType type,
ws::WindowServer* window_server,
ws::WindowTree* tree,
mojom::WindowTreeRequest* tree_request,
mojom::WindowTreeClientPtr* client) {
std::unique_ptr<TestWindowTreeBinding> binding =
std::make_unique<TestWindowTreeBinding>(tree);
bindings_.push_back(binding.get());
return std::move(binding);
}
bool TestWindowServerDelegate::IsTestConfig() const {
return true;
}
void TestWindowServerDelegate::OnWillCreateTreeForWindowManager(
bool automatically_create_display_roots) {
if (window_server_->display_creation_config() !=
DisplayCreationConfig::UNKNOWN) {
return;
}
window_server_->SetDisplayCreationConfig(
automatically_create_display_roots ? DisplayCreationConfig::AUTOMATIC
: DisplayCreationConfig::MANUAL);
}
ThreadedImageCursorsFactory*
TestWindowServerDelegate::GetThreadedImageCursorsFactory() {
return threaded_image_cursors_factory_.get();
}
// WindowServerTestHelper ---------------------------------------------------
WindowServerTestHelper::WindowServerTestHelper()
: cursor_(ui::CursorType::kNull), platform_display_factory_(&cursor_) {
// Some tests create their own message loop, for example to add a task runner.
if (!base::MessageLoopCurrent::Get())
message_loop_ = std::make_unique<base::MessageLoop>();
PlatformDisplay::set_factory_for_testing(&platform_display_factory_);
window_server_ = std::make_unique<WindowServer>(&window_server_delegate_,
true /* should_host_viz */);
std::unique_ptr<GpuHost> gpu_host = std::make_unique<TestGpuHost>();
window_server_->SetGpuHost(std::move(gpu_host));
window_server_delegate_.set_window_server(window_server_.get());
}
WindowServerTestHelper::~WindowServerTestHelper() {
// Destroy |window_server_| while the message-loop is still alive.
window_server_.reset();
}
// WindowEventTargetingHelper ------------------------------------------------
WindowEventTargetingHelper::WindowEventTargetingHelper(
bool automatically_create_display_roots) {
display_ = new Display(window_server());
display_binding_ = new TestDisplayBinding(window_server(),
automatically_create_display_roots);
display_->Init(display::ViewportMetrics(),
base::WrapUnique(display_binding_));
wm_client_ = ws_test_helper_.window_server_delegate()->last_client();
wm_client_->tracker()->changes()->clear();
}
WindowEventTargetingHelper::~WindowEventTargetingHelper() {}
ServerWindow* WindowEventTargetingHelper::CreatePrimaryTree(
const gfx::Rect& root_window_bounds,
const gfx::Rect& window_bounds) {
WindowTree* wm_tree = window_server()->GetTreeWithId(kWindowManagerClientId);
const ClientWindowId embed_window_id(wm_tree->id(),
next_primary_tree_window_id_++);
EXPECT_TRUE(wm_tree->NewWindow(embed_window_id, ServerWindow::Properties()));
EXPECT_TRUE(wm_tree->SetWindowVisibility(embed_window_id, true));
EXPECT_TRUE(wm_tree->AddWindow(FirstRootId(wm_tree), embed_window_id));
display_->root_window()->SetBounds(root_window_bounds, base::nullopt);
mojom::WindowTreeClientPtr client;
ws_test_helper_.window_server_delegate()->last_client()->Bind(
mojo::MakeRequest(&client));
const uint32_t embed_flags = 0;
wm_tree->Embed(embed_window_id, std::move(client), embed_flags);
ServerWindow* embed_window = wm_tree->GetWindowByClientId(embed_window_id);
embed_window->set_event_targeting_policy(
mojom::EventTargetingPolicy::DESCENDANTS_ONLY);
WindowTree* tree1 = window_server()->GetTreeWithRoot(embed_window);
WindowTreeTestApi(tree1).set_is_for_embedding(false);
EXPECT_NE(nullptr, tree1);
EXPECT_NE(tree1, wm_tree);
embed_window->SetBounds(window_bounds, base::nullopt);
return embed_window;
}
void WindowEventTargetingHelper::CreateSecondaryTree(
ServerWindow* embed_window,
const gfx::Rect& window_bounds,
TestWindowTreeClient** out_client,
WindowTree** window_tree,
ServerWindow** window) {
WindowTree* tree1 = window_server()->GetTreeWithRoot(embed_window);
ASSERT_TRUE(tree1 != nullptr);
const ClientWindowId child1_id(tree1->id(), kEmbedTreeWindowId);
ASSERT_TRUE(tree1->NewWindow(child1_id, ServerWindow::Properties()));
ServerWindow* child1 = tree1->GetWindowByClientId(child1_id);
ASSERT_TRUE(child1);
EXPECT_TRUE(tree1->AddWindow(ClientWindowIdForWindow(tree1, embed_window),
child1_id));
embed_window->set_is_activation_parent(true);
child1->SetVisible(true);
child1->SetBounds(window_bounds, base::nullopt);
TestWindowTreeClient* embed_client =
ws_test_helper_.window_server_delegate()->last_client();
embed_client->tracker()->changes()->clear();
wm_client_->tracker()->changes()->clear();
*out_client = embed_client;
*window_tree = tree1;
*window = child1;
}
void WindowEventTargetingHelper::SetTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
base::MessageLoopCurrent::Get()->SetTaskRunner(task_runner);
}
// ----------------------------------------------------------------------------
TestScreenProviderObserver::TestScreenProviderObserver() : binding_(this) {}
TestScreenProviderObserver::~TestScreenProviderObserver() = default;
mojom::ScreenProviderObserverPtr TestScreenProviderObserver::GetPtr() {
mojom::ScreenProviderObserverPtr ptr;
binding_.Bind(mojo::MakeRequest(&ptr));
return ptr;
}
std::string TestScreenProviderObserver::GetAndClearObserverCalls() {
std::string result;
std::swap(observer_calls_, result);
return result;
}
std::string TestScreenProviderObserver::DisplayIdsToString(
const std::vector<mojom::WsDisplayPtr>& wm_displays) {
std::string display_ids;
for (const auto& wm_display : wm_displays) {
if (!display_ids.empty())
display_ids += " ";
display_ids += base::Int64ToString(wm_display->display.id());
}
return display_ids;
}
void TestScreenProviderObserver::OnDisplaysChanged(
std::vector<mojom::WsDisplayPtr> displays,
int64_t primary_display_id,
int64_t internal_display_id) {
if (!observer_calls_.empty())
observer_calls_ += "\n";
observer_calls_ += "OnDisplaysChanged " + DisplayIdsToString(displays);
observer_calls_ += " " + base::Int64ToString(internal_display_id);
}
// -----------------------------------------------------------------------------
TestPlatformDisplay::TestPlatformDisplay(
const display::ViewportMetrics& metrics,
ui::CursorData* cursor_storage)
: metrics_(metrics), cursor_storage_(cursor_storage) {}
TestPlatformDisplay::~TestPlatformDisplay() = default;
// PlatformDisplay:
void TestPlatformDisplay::Init(PlatformDisplayDelegate* delegate) {
delegate->OnAcceleratedWidgetAvailable();
}
void TestPlatformDisplay::SetViewportSize(const gfx::Size& size) {}
void TestPlatformDisplay::SetTitle(const base::string16& title) {}
void TestPlatformDisplay::SetCapture() {
has_capture_ = true;
}
void TestPlatformDisplay::ReleaseCapture() {
has_capture_ = false;
}
void TestPlatformDisplay::SetCursor(const ui::CursorData& cursor) {
*cursor_storage_ = cursor;
}
void TestPlatformDisplay::SetCursorSize(const ui::CursorSize& cursor_size) {}
void TestPlatformDisplay::ConfineCursorToBounds(const gfx::Rect& pixel_bounds) {
confine_cursor_bounds_ = pixel_bounds;
}
void TestPlatformDisplay::MoveCursorTo(
const gfx::Point& window_pixel_location) {}
void TestPlatformDisplay::UpdateTextInputState(
const ui::TextInputState& state) {}
void TestPlatformDisplay::SetImeVisibility(bool visible) {}
void TestPlatformDisplay::UpdateViewportMetrics(
const display::ViewportMetrics& metrics) {
metrics_ = metrics;
}
const display::ViewportMetrics& TestPlatformDisplay::GetViewportMetrics() {
return metrics_;
}
gfx::AcceleratedWidget TestPlatformDisplay::GetAcceleratedWidget() const {
return gfx::kNullAcceleratedWidget;
}
FrameGenerator* TestPlatformDisplay::GetFrameGenerator() {
return nullptr;
}
EventSink* TestPlatformDisplay::GetEventSink() {
return nullptr;
}
void TestPlatformDisplay::SetCursorConfig(display::Display::Rotation rotation,
float scale) {
cursor_scale_ = scale;
}
// -----------------------------------------------------------------------------
CursorLocationManagerTestApi::CursorLocationManagerTestApi(
CursorLocationManager* cursor_location_manager)
: cursor_location_manager_(cursor_location_manager) {}
CursorLocationManagerTestApi::~CursorLocationManagerTestApi() = default;
base::subtle::Atomic32 CursorLocationManagerTestApi::current_cursor_location() {
return cursor_location_manager_->current_cursor_location_;
}
// -----------------------------------------------------------------------------
void AddWindowManager(WindowServer* window_server,
bool automatically_create_display_roots) {
window_server->window_manager_window_tree_factory()->CreateWindowTree(
nullptr, nullptr, automatically_create_display_roots);
}
display::Display MakeDisplay(int origin_x,
int origin_y,
int width_pixels,
int height_pixels,
float scale_factor) {
gfx::Size scaled_size = gfx::ConvertSizeToDIP(
scale_factor, gfx::Size(width_pixels, height_pixels));
gfx::Rect bounds(gfx::Point(origin_x, origin_y), scaled_size);
display::Display display;
display.set_bounds(bounds);
display.set_work_area(bounds);
display.set_device_scale_factor(scale_factor);
return display;
}
ServerWindow* FirstRoot(WindowTree* tree) {
return tree->roots().size() == 1u
? const_cast<ServerWindow*>(*(tree->roots().begin()))
: nullptr;
}
ClientWindowId FirstRootId(WindowTree* tree) {
ServerWindow* first_root = FirstRoot(tree);
return first_root ? ClientWindowIdForWindow(tree, first_root)
: ClientWindowId();
}
ClientWindowId ClientWindowIdForWindow(WindowTree* tree,
const ServerWindow* window) {
ClientWindowId client_window_id;
// If window isn't known we'll return 0, which should then error out.
tree->IsWindowKnown(window, &client_window_id);
return client_window_id;
}
ServerWindow* NewWindowInTree(WindowTree* tree, ClientWindowId* client_id) {
return NewWindowInTreeWithParent(tree, FirstRoot(tree), client_id);
}
ServerWindow* NewWindowInTreeWithParent(WindowTree* tree,
ServerWindow* parent,
ClientWindowId* client_id,
const gfx::Rect& bounds) {
if (!parent)
return nullptr;
ClientWindowId parent_client_id;
if (!tree->IsWindowKnown(parent, &parent_client_id))
return nullptr;
ClientWindowId client_window_id = NextUnusedClientWindowId(tree);
if (!tree->NewWindow(client_window_id, ServerWindow::Properties()))
return nullptr;
if (!tree->SetWindowVisibility(client_window_id, true))
return nullptr;
if (!tree->AddWindow(parent_client_id, client_window_id))
return nullptr;
ServerWindow* window = tree->GetWindowByClientId(client_window_id);
window->SetBounds(bounds);
if (client_id)
*client_id = client_window_id;
return window;
}
gfx::Point Atomic32ToPoint(base::subtle::Atomic32 atomic) {
return gfx::Point(static_cast<int16_t>(atomic >> 16),
static_cast<int16_t>(atomic & 0xFFFF));
}
} // namespace test
} // namespace ws
} // namespace ui
| 35.88785 | 80 | 0.693815 | [
"geometry",
"vector",
"transform"
] |
e950aad62b28f33cd8b214f75412932d6bf62419 | 5,964 | cc | C++ | src/fuzzers/rw/t2t.cc | stnfc/android-system-nfc | ee659f69beed15b31bc08a7283fb9a403430c1a9 | [
"Apache-2.0"
] | null | null | null | src/fuzzers/rw/t2t.cc | stnfc/android-system-nfc | ee659f69beed15b31bc08a7283fb9a403430c1a9 | [
"Apache-2.0"
] | null | null | null | src/fuzzers/rw/t2t.cc | stnfc/android-system-nfc | ee659f69beed15b31bc08a7283fb9a403430c1a9 | [
"Apache-2.0"
] | null | null | null | #include "fuzz.h"
#define MODULE_NAME "Type2 Read/Write"
enum {
SUB_TYPE_PRESENCE_CHECK,
SUB_TYPE_READ,
SUB_TYPE_WRITE,
SUB_TYPE_SECTOR_SELECT,
SUB_TYPE_SET_TAG_READONLY,
SUB_TYPE_WRITE_NDEF,
SUB_TYPE_READ_NDEF,
SUB_TYPE_DETECT_NDEF,
SUB_TYPE_LOCATE_TLV,
SUB_TYPE_FORMAT_NDEF,
SUB_TYPE_MAX
};
static void rw_cback(tRW_EVENT event, tRW_DATA* p_rw_data) {
FUZZLOG(MODULE_NAME ": rw_cback: event=0x%02x, p_rw_data=%p", event,
p_rw_data);
if (event == RW_T2T_READ_CPLT_EVT || event == RW_T2T_RAW_FRAME_EVT) {
if (p_rw_data->data.p_data) {
GKI_freebuf(p_rw_data->data.p_data);
p_rw_data->data.p_data = nullptr;
}
}
}
#define TEST_NFCID_VALUE \
{ 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }
static bool Init(Fuzz_Context& /*ctx*/) {
tNFC_ACTIVATE_DEVT activate_params = {
.protocol = NFC_PROTOCOL_T2T,
.rf_tech_param = {.mode = NFC_DISCOVERY_TYPE_POLL_A,
.param = {.pa = {
.sel_rsp = NFC_SEL_RES_NFC_FORUM_T2T,
}}}};
rw_init();
if (NFC_STATUS_OK != RW_SetActivatedTagType(&activate_params, rw_cback)) {
FUZZLOG(MODULE_NAME ": RW_SetActivatedTagType failed");
return false;
}
return true;
}
static bool Init_PresenceCheck(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tPresenceCheck();
}
static bool Init_Read(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tRead(0);
}
static bool Init_Write(Fuzz_Context& ctx) {
const uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04,
0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04};
auto scratch = ctx.GetBuffer(sizeof(data), data);
return NFC_STATUS_OK == RW_T2tWrite(0, scratch);
}
static bool Init_SectorSelect(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tSectorSelect(0);
}
static bool Init_SetTagReadOnly(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tSetTagReadOnly(true);
}
static bool Init_WriteNDef(Fuzz_Context& ctx) {
const uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04,
0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04};
auto scratch = ctx.GetBuffer(sizeof(data), data);
tRW_T2T_CB* p_t2t = &rw_cb.tcb.t2t;
p_t2t->ndef_status = T2T_NDEF_DETECTED;
return NFC_STATUS_OK == RW_T2tWriteNDef(sizeof(data), scratch);
}
static bool Init_ReadNDef(Fuzz_Context& ctx) {
auto scratch = ctx.GetBuffer(256);
tRW_T2T_CB* p_t2t = &rw_cb.tcb.t2t;
p_t2t->ndef_status = T2T_NDEF_DETECTED;
p_t2t->ndef_msg_len = 128;
p_t2t->bytes_count = 128;
return NFC_STATUS_OK == RW_T2tReadNDef(scratch, 256);
}
static bool Init_DetectNDef(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tDetectNDef(true);
}
static bool Init_LocateTlv(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tLocateTlv(TAG_LOCK_CTRL_TLV);
}
static bool Init_FormatNDef(Fuzz_Context& /*ctx*/) {
return NFC_STATUS_OK == RW_T2tFormatNDef();
}
static bool Fuzz_Init(Fuzz_Context& ctx) {
if (!Init(ctx)) {
FUZZLOG(MODULE_NAME ": initialization failed");
return false;
}
bool result = false;
switch (ctx.SubType) {
case SUB_TYPE_PRESENCE_CHECK:
result = Init_PresenceCheck(ctx);
break;
case SUB_TYPE_READ:
result = Init_Read(ctx);
break;
case SUB_TYPE_WRITE:
result = Init_Write(ctx);
break;
case SUB_TYPE_SECTOR_SELECT:
result = Init_SectorSelect(ctx);
break;
case SUB_TYPE_SET_TAG_READONLY:
result = Init_SetTagReadOnly(ctx);
break;
case SUB_TYPE_WRITE_NDEF:
result = Init_WriteNDef(ctx);
break;
case SUB_TYPE_READ_NDEF:
result = Init_ReadNDef(ctx);
break;
case SUB_TYPE_DETECT_NDEF:
result = Init_DetectNDef(ctx);
break;
case SUB_TYPE_LOCATE_TLV:
result = Init_LocateTlv(ctx);
break;
case SUB_TYPE_FORMAT_NDEF:
result = Init_FormatNDef(ctx);
break;
default:
FUZZLOG(MODULE_NAME ": Unknown command %d", ctx.SubType);
result = false;
break;
}
if (!result) {
FUZZLOG(MODULE_NAME ": Initializing command %02X failed", ctx.SubType);
}
return result;
}
static void Fuzz_Deinit(Fuzz_Context& /*ctx*/) {
if (rf_cback) {
tNFC_CONN conn = {
.deactivate = {.status = NFC_STATUS_OK,
.type = NFC_DEACTIVATE_TYPE_IDLE,
.is_ntf = true,
.reason = NFC_DEACTIVATE_REASON_DH_REQ_FAILED}};
rf_cback(NFC_RF_CONN_ID, NFC_DEACTIVATE_CEVT, &conn);
}
}
static void Fuzz_Run(Fuzz_Context& ctx) {
for (auto it = ctx.Data.cbegin() + 1; it != ctx.Data.cend(); ++it) {
NFC_HDR* p_msg;
p_msg = (NFC_HDR*)GKI_getbuf(sizeof(NFC_HDR) + it->size());
if (p_msg == nullptr) {
FUZZLOG(MODULE_NAME ": GKI_getbuf returns null, size=%zu", it->size());
return;
}
/* Initialize NFC_HDR */
p_msg->len = it->size();
p_msg->offset = 0;
uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
memcpy(p, it->data(), it->size());
tNFC_CONN conn = {.data = {
.status = NFC_STATUS_OK,
.p_data = p_msg,
}};
FUZZLOG(MODULE_NAME ": SubType=%02X, Response[%zd/%zd]=%s", ctx.SubType,
it - ctx.Data.cbegin(), ctx.Data.size() - 1,
BytesToHex(*it).c_str());
rf_cback(NFC_RF_CONN_ID, NFC_DATA_CEVT, &conn);
}
}
void Type2_FixPackets(uint8_t /*SubType*/, std::vector<bytes_t>& /*Data*/) {}
void Type2_Fuzz(uint8_t SubType, const std::vector<bytes_t>& Data) {
Fuzz_Context ctx(SubType % SUB_TYPE_MAX, Data);
if (Fuzz_Init(ctx)) {
Fuzz_Run(ctx);
}
Fuzz_Deinit(ctx);
}
| 28.4 | 78 | 0.622066 | [
"vector"
] |
e950e2c25140347a4a73d7f4d0001aa0ecf50fb5 | 29,113 | cpp | C++ | master/autotools-book-files/autotools/book/flaim-ch8-10/flaim/src/fssearch.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | master/autotools-book-files/autotools/book/flaim-ch8-10/flaim/src/fssearch.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | master/autotools-book-files/autotools/book/flaim-ch8-10/flaim/src/fssearch.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | //-------------------------------------------------------------------------
// Desc: B-tree searching.
// Tabs: 3
//
// Copyright (c) 1990-2007 Novell, Inc. All Rights Reserved.
//
// 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; version 2.1
// 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
// Library 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, contact Novell, Inc.
//
// To contact Novell about this file by physical or electronic mail,
// you may find current contact information at www.novell.com.
//
// $Id$
//------------------------------------------------------------------------------
#include "flaimsys.h"
FSTATIC FLMUINT FSKeyCmp(
BTSK * pStack,
FLMBYTE * key,
FLMUINT uiKeyLen,
FLMUINT drnDomain);
/****************************************************************************
Desc: Search the b-tree for a matching key.
****************************************************************************/
RCODE FSBtSearch(
FDB * pDb,
LFILE * pLFile,
BTSK ** pStackRV,
FLMBYTE * key,
FLMUINT keyLen,
FLMUINT dinDomain)
{
RCODE rc = FERR_OK;
BTSK * pStack = *pStackRV;
FLMBYTE * pKeyBuf = pStack->pKeyBuf;
FLMUINT uiBlkAddr;
FLMUINT uiKeyBufSize;
LFILE TmpLFile;
uiKeyBufSize = (pLFile->uiLfType == LF_INDEX) ? MAX_KEY_SIZ : DIN_KEY_SIZ;
// Get the correct root block specified in the LFILE.
if (RC_BAD( rc = FSGetRootBlock( pDb, &pLFile, &TmpLFile, pStack)))
{
if (rc == FERR_NO_ROOT_BLOCK)
{
flmAssert( pLFile->uiRootBlk == BT_END);
rc = FERR_OK;
}
goto Exit;
}
// MAIN LOOP Read each block going down the b-tree. Save state
// information in the pStack[].
for (;;)
{
pStack->uiFlags = FULL_STACK;
pStack->uiKeyBufSize = uiKeyBufSize;
if (pStack->uiBlkType != BHT_NON_LEAF_DATA)
{
rc = FSBtScan( pStack, key, keyLen, dinDomain);
}
else
{
rc = FSBtScanNonLeafData( pStack,
keyLen == 1
? (FLMUINT) *key
: (FLMUINT) f_bigEndianToUINT32( key));
}
if (RC_BAD( rc))
{
goto Exit;
}
if (!pStack->uiLevel)
{
// Leaf level - we are done.
break;
}
uiBlkAddr = FSChildBlkAddr( pStack);
pStack++;
pStack->pKeyBuf = pKeyBuf;
if (RC_BAD( rc = FSGetBlock( pDb, pLFile, uiBlkAddr, pStack)))
{
goto Exit;
}
}
*pStackRV = pStack;
Exit:
return (rc);
}
/****************************************************************************
Desc: Search the right-most end of the b-tree.
****************************************************************************/
RCODE FSBtSearchEnd(
FDB * pDb,
LFILE * pLFile, // Logical file definition
BTSK ** pStackRV, // Stack of variables for each level
FLMUINT uiDrn) // Used to position and setup for update
{
RCODE rc = FERR_OK;
BTSK * pStack = *pStackRV;
FLMBYTE * pKeyBuf = pStack->pKeyBuf;
FLMBYTE key[ DIN_KEY_SIZ + 4];
FLMUINT uiBlkAddr;
LFILE TmpLFile;
// Get the correct root block specified in the LFILE.
if (RC_BAD( rc = FSGetRootBlock( pDb, &pLFile, &TmpLFile, pStack)))
{
if (rc == FERR_NO_ROOT_BLOCK)
{
flmAssert( pLFile->uiRootBlk == BT_END);
rc = FERR_OK;
}
goto Exit;
}
f_UINT32ToBigEndian( (FLMUINT32)uiDrn, key);
for (;;)
{
pStack->uiFlags = FULL_STACK;
pStack->uiKeyBufSize = DIN_KEY_SIZ;
// Remove all scanning from non-leaf data blocks (both formats).
if (pStack->uiLevel)
{
pStack->uiCurElm = pStack->uiBlkEnd; // Position past last element
FSBtPrevElm( pDb, pLFile, pStack); // Build full key in pKeyBuf[]
}
else
{
if (pStack->uiBlkType != BHT_NON_LEAF_DATA)
{
rc = FSBtScan( pStack, key, DIN_KEY_SIZ, 0);
}
else
{
rc = FSBtScanNonLeafData( pStack, uiDrn);
}
if (RC_BAD( rc))
{
goto Exit;
}
}
if (!pStack->uiLevel)
{
// Leaf level - we are done.
break;
}
uiBlkAddr = FSChildBlkAddr( pStack);
pStack++;
pStack->pKeyBuf = pKeyBuf;
if (RC_BAD( rc = FSGetBlock( pDb, pLFile, uiBlkAddr, pStack)))
{
goto Exit;
}
}
*pStackRV = pStack;
Exit:
return (rc);
}
/****************************************************************************
Desc: Returns the root block of a passed-in LFILE
****************************************************************************/
RCODE FSGetRootBlock(
FDB * pDb,
LFILE ** ppLFile,
LFILE * pTmpLFile,
BTSK * pStack)
{
RCODE rc = FERR_OK;
LFILE * pLFile = *ppLFile;
FLMUINT uiBlkAddr;
FLMBOOL bRereadLFH = FALSE;
// Make Sure this is the correct root block in the LFILE area. If not
// then read in the LFH structure and try again. It would be nice to
// have a routine that reads only root blocks. DSS: Added check for
// uiBlkAddr >= pDb->Loghdr.uiLogicalEOF because the pLFile could have
// a root block address of an aborted update transaction where the root
// block has not yet been fixed up by the aborting transaction (in a
// shared environment).
if (((uiBlkAddr = pLFile->uiRootBlk) == BT_END) ||
(uiBlkAddr >= pDb->LogHdr.uiLogicalEOF))
{
bRereadLFH = TRUE;
}
else if (RC_BAD( rc = FSGetBlock( pDb, pLFile, uiBlkAddr, pStack)))
{
if (rc == FERR_DATA_ERROR || (rc == FERR_OLD_VIEW && !pDb->uiKilledTime))
{
bRereadLFH = TRUE;
pStack->uiBlkAddr = BT_END;
}
else
{
goto Exit;
}
}
else
{
// Check for valid root block - Root Flag and Logical file number
FLMBYTE * pBlk = pStack->pBlk;
if (!(BH_IS_ROOT_BLK( pBlk)) ||
(pLFile->uiLfNum != FB2UW( &pBlk[BH_LOG_FILE_NUM])))
{
bRereadLFH = TRUE;
FSReleaseBlock( pStack, FALSE);
pStack->uiBlkAddr = BT_END;
}
}
// Reread the LFH from disk if we do not have the root block
if (bRereadLFH)
{
// If we are in a read transaction, copy the LFILE structure so
// that we don't mess up a thread that may be doing an update.
if (flmGetDbTransType( pDb) == FLM_READ_TRANS)
{
f_memcpy( pTmpLFile, pLFile, sizeof(LFILE));
pLFile = pTmpLFile;
}
if (RC_BAD( rc = flmLFileRead( pDb, pLFile)))
{
goto Exit;
}
// If there is no root block, return right away
if ((uiBlkAddr = pLFile->uiRootBlk) == BT_END)
{
// The caller of FSGetRootBlock is expected to check for and
// handle FERR_NO_ROOT_BLOCK. It should NEVER be returned to the
// application. NOTE: Checking for BT_END_OF_DATA will not work
// in every case to check for no root block because it is not
// always initialized before calling FSGetRootBlock, so it could
// have garbage in it if we don't end up going through this code
// path.
rc = RC_SET( FERR_NO_ROOT_BLOCK);
pStack->uiCmpStatus = BT_END_OF_DATA;
pStack->uiBlkAddr = BT_END;
goto Exit;
}
if (RC_BAD( rc = FSGetBlock( pDb, pLFile, uiBlkAddr, pStack)))
{
goto Exit;
}
}
Exit:
*ppLFile = pLFile;
return (rc);
}
/****************************************************************************
Desc: Scan a b-tree block for a matching key at any b-tree block level.
****************************************************************************/
RCODE FSBtScan(
BTSK * pStack, // [in/out] Stack of variables for each level
FLMBYTE * pSearchKey, // The input key to search for
FLMUINT uiSearchKeyLen, // Length of the key (not null terminated)
FLMUINT dinDomain) // INDEXES ONLY - lower bounds of din
{
RCODE rc = FERR_OK;
FLMBYTE * pCurElm; // Points to the current element.
FLMBYTE * pBlk; // Points to the cache block.
FLMBYTE * pKeyBuf; // Points to pStack->pKeyBuf (optimization).
FLMBYTE * pElmKey; // Points to the key within the element.
FLMUINT uiRecLen = 0; // Length of the record portion.
FLMUINT uiPrevKeyCnt; // Number left end bytes compressed
FLMUINT uiElmKeyLen; // Length of the current element's key portion
FLMUINT uiBlkType; // B-tree block type - Leaf or non-leaf.
FLMUINT uiElmOvhd; // Number bytes overhead for element.
FLMUINT uiBytesMatched; // Number of bytes matched with pSearchKey
uiBlkType = pStack->uiBlkType;
flmAssert( uiBlkType != BHT_NON_LEAF_DATA);
// Initialize stack variables for possibly better performance.
pKeyBuf = pStack->pKeyBuf;
pBlk = pStack->pBlk;
uiElmOvhd = pStack->uiElmOvhd;
pStack->uiCurElm = BH_OVHD;
pStack->uiKeyLen = pStack->uiPKC = pStack->uiPrevElmPKC = 0;
uiBytesMatched = 0;
for (;;)
{
pCurElm = &pBlk[pStack->uiCurElm];
uiElmKeyLen = BBE_GETR_KL( pCurElm);
// Read in RAW mode - doesn't do all bit checking
if ((uiPrevKeyCnt = (BBE_GETR_PKC( pCurElm))) > BBE_PKC_MAX)
{
uiElmKeyLen += (uiPrevKeyCnt & BBE_KL_HBITS) << BBE_KL_SHIFT_BITS;
uiPrevKeyCnt &= BBE_PKC_MAX;
}
// Should not have a non-zero PKC if we are on the first element of
// a block
if (uiPrevKeyCnt && pStack->uiCurElm == BH_OVHD)
{
rc = RC_SET( FERR_DATA_ERROR);
goto Exit;
}
// Get the record portion length when on the leaf blocks.
if (uiBlkType == BHT_LEAF)
{
uiRecLen = BBE_GET_RL( pCurElm);
}
pStack->uiPrevElmPKC = pStack->uiPKC;
// The zero length key is the terminating element in a right-most
// block.
if ((pStack->uiKeyLen = uiPrevKeyCnt + uiElmKeyLen) == 0)
{
pStack->uiPrevElmPKC = f_min( uiBytesMatched, BBE_PKC_MAX);
pStack->uiPKC = 0;
pStack->uiCmpStatus = BT_END_OF_DATA;
goto Exit;
}
// Handle special case of left-end compression maxing out.
if (uiPrevKeyCnt == BBE_PKC_MAX && BBE_PKC_MAX < uiBytesMatched)
{
uiBytesMatched = BBE_PKC_MAX;
}
// Check out this element to see if the key matches.
if (uiPrevKeyCnt == uiBytesMatched)
{
pElmKey = &pCurElm[uiElmOvhd];
for (;;)
{
// All bytes of the search key are matched?
if (uiBytesMatched == uiSearchKeyLen)
{
pStack->uiPKC = f_min( uiBytesMatched, BBE_PKC_MAX);
// Build pKeyBuf with the search key because it matches.
// Current key is either equal or greater than search key.
if (uiSearchKeyLen < pStack->uiKeyLen)
{
f_memcpy( &pKeyBuf[uiSearchKeyLen], pElmKey,
pStack->uiKeyLen - uiSearchKeyLen);
pStack->uiCmpStatus = BT_GT_KEY;
}
else
{
if (dinDomain)
{
FLMBYTE* pCurRef = pCurElm;
if ((dinDomain - 1) <
FSGetDomain( &pCurRef, (FLMBYTE) uiElmOvhd))
{
// Keep going...
goto Next_Element;
}
}
pStack->uiCmpStatus = BT_EQ_KEY;
}
f_memcpy( pKeyBuf, pSearchKey, uiSearchKeyLen);
goto Exit;
}
// .. else matches all the bytes in the element key.
if (uiBytesMatched == pStack->uiKeyLen)
{
pStack->uiPKC = f_min( uiBytesMatched, BBE_PKC_MAX);
// Need an outer break call here - forced to do a goto.
goto Next_Element;
}
// Compare the next byte in the search key and element
if (pSearchKey[uiBytesMatched] != *pElmKey)
{
break;
}
uiBytesMatched++;
pElmKey++;
}
pStack->uiPKC = f_min( uiBytesMatched, BBE_PKC_MAX);
// Check if we are done comparing, if so build pKeyBuf[].
if (pSearchKey[uiBytesMatched] < *pElmKey)
{
if (uiBytesMatched)
{
f_memcpy( pKeyBuf, pSearchKey, uiBytesMatched);
}
f_memcpy( &pKeyBuf[uiBytesMatched], pElmKey,
pStack->uiKeyLen - uiBytesMatched);
pStack->uiCmpStatus = BT_GT_KEY;
goto Exit;
}
}
else if (uiPrevKeyCnt < uiBytesMatched)
{
// Current key > search key. Set pKeyBuf and break out.
pStack->uiPKC = uiPrevKeyCnt;
if (uiPrevKeyCnt)
{
f_memcpy( pKeyBuf, pSearchKey, uiPrevKeyCnt);
}
f_memcpy( &pKeyBuf[uiPrevKeyCnt], &pCurElm[uiElmOvhd], uiElmKeyLen);
pStack->uiCmpStatus = BT_GT_KEY;
goto Exit;
}
// else the key is less than the search key (uiPrevKeyCnt >
// uiBytesMatched).
Next_Element:
// Position to the next element
pStack->uiCurElm += uiElmKeyLen +
((uiBlkType == BHT_LEAF)
? (BBE_KEY + uiRecLen)
: (BNE_IS_DOMAIN( pCurElm)
? (BNE_DOMAIN_LEN + uiElmOvhd)
: uiElmOvhd));
// Most common check first.
if (pStack->uiCurElm < pStack->uiBlkEnd)
{
continue;
}
if (pStack->uiCurElm == pStack->uiBlkEnd)
{
// On the equals conditition it may be OK in some very special
// cases.
pStack->uiCmpStatus = BT_END_OF_DATA;
goto Exit;
}
// Marched off the end of the block - something is corrupt.
rc = RC_SET( FERR_CACHE_ERROR);
goto Exit;
}
Exit:
return (rc);
}
/****************************************************************************
Desc: Binary search into a non-leaf data record block.
****************************************************************************/
RCODE FSBtScanNonLeafData(
BTSK * pStack,
FLMUINT uiDrn)
{
RCODE rc = FERR_OK;
FLMBYTE * pBlk = pStack->pBlk;
FLMUINT uiLow = 0;
FLMUINT uiMid;
FLMUINT uiHigh = ((pStack->uiBlkEnd - BH_OVHD) >> 3) - 1;
FLMUINT uiTblSize = uiHigh;
FLMUINT uiCurDrn;
pStack->uiCmpStatus = BT_GT_KEY;
for (;;)
{
uiMid = (uiLow + uiHigh) >> 1;
uiCurDrn = f_bigEndianToUINT32( &pBlk[ BH_OVHD + (uiMid << 3)]);
if (uiCurDrn == 0)
{
// Special case - at the end of a rightmost block.
pStack->uiCmpStatus = BT_EQ_KEY;
break;
}
if (uiDrn == uiCurDrn)
{
// Remember a data record can span multiple blocks (same DRN).
while (uiMid)
{
uiCurDrn = f_bigEndianToUINT32(
&pBlk[ BH_OVHD + ((uiMid - 1) << 3)]);
if (uiDrn != uiCurDrn)
{
break;
}
uiMid--;
}
pStack->uiCmpStatus = BT_EQ_KEY;
break;
}
// Down to one item if too high then position to next item.
if (uiLow >= uiHigh)
{
if ((uiDrn > uiCurDrn) && uiMid < uiTblSize)
{
uiMid++;
}
break;
}
// If too high then try lower section
if (uiDrn < uiCurDrn)
{
// First item too high?
if (uiMid == 0)
{
break;
}
uiHigh = uiMid - 1;
}
else
{
// Try upper section because mid value is too low.
if (uiMid == uiTblSize)
{
uiMid++;
pStack->uiCmpStatus = BT_END_OF_DATA;
break;
}
uiLow = uiMid + 1;
}
}
// Set curElm and the key buffer.
pStack->uiCurElm = BH_OVHD + (uiMid << 3);
f_UINT32ToBigEndian( (FLMUINT32)uiCurDrn, pStack->pKeyBuf);
return (rc);
}
/****************************************************************************
Desc: Read the block information and initialize all needed pStack
elements.
****************************************************************************/
void FSBlkToStack(
BTSK * pStack)
{
FLMBYTE * pBlk = pStack->pBlk;
FLMUINT uiBlkType;
pStack->uiBlkType = uiBlkType = (FLMUINT) (BH_GET_TYPE( pBlk));
// The standard overhead is used in the pStack Compares are made to
// determine if the element is extended.
if (uiBlkType == BHT_LEAF)
{
pStack->uiElmOvhd = BBE_KEY;
}
else if (uiBlkType == BHT_NON_LEAF_DATA)
{
pStack->uiElmOvhd = BNE_DATA_OVHD;
}
else if (uiBlkType == BHT_NON_LEAF)
{
pStack->uiElmOvhd = BNE_KEY_START;
}
else if (uiBlkType == BHT_NON_LEAF_COUNTS)
{
pStack->uiElmOvhd = BNE_KEY_COUNTS_START;
}
else
{
flmAssert( 0);
pStack->uiElmOvhd = BNE_KEY_START;
}
pStack->uiKeyLen = pStack->uiPKC = pStack->uiPrevElmPKC = 0;
pStack->uiCurElm = BH_OVHD;
pStack->uiBlkEnd = (FLMUINT) FB2UW( &pBlk[BH_ELM_END]);
pStack->uiLevel = (FLMUINT) pBlk[BH_LEVEL];
}
/****************************************************************************
Desc: Scan to a specific element (pStack->uiCurElm) in a b-tree block.
****************************************************************************/
RCODE FSBtScanTo(
BTSK * pStack,
FLMBYTE * pSearchKey,
FLMUINT uiSearchKeyLen,
FLMUINT dinDomain)
{
RCODE rc = FERR_OK;
FLMBYTE * pCurElm;
FLMBYTE * pBlk;
FLMBYTE * pKeyBuf = pStack->pKeyBuf;
FLMBYTE * pPrevElm;
FLMUINT uiPrevKeyCnt = 0;
FLMUINT uiElmKeyLen = 0;
FLMUINT uiTargetCurElm = pStack->uiCurElm;
FLMUINT uiElmOvhd;
FLMUINT uiKeyBufLen;
FSBlkToStack( pStack);
pBlk = pStack->pBlk;
uiElmOvhd = pStack->uiElmOvhd;
if (uiTargetCurElm > pStack->uiBlkEnd)
{
uiTargetCurElm = pStack->uiBlkEnd;
}
// The code is easy for non-leaf data blocks.
if (pStack->uiBlkType == BHT_NON_LEAF_DATA)
{
// Target may be any byte offset in the block.
while (pStack->uiCurElm < uiTargetCurElm)
{
pStack->uiCurElm += BNE_DATA_OVHD;
}
if (uiTargetCurElm < pStack->uiBlkEnd)
{
flmCopyDrnKey( pKeyBuf, &pBlk[pStack->uiCurElm]);
pStack->uiCmpStatus = BT_EQ_KEY;
}
else
{
pStack->uiCmpStatus = BT_END_OF_DATA;
}
goto Exit;
}
// Note: There is no way pPrevElm can be accessed and point to NULL
// unless the block is corrupt and starts with a PKC value.
pCurElm = NULL;
uiKeyBufLen = 0;
while (pStack->uiCurElm < uiTargetCurElm)
{
pPrevElm = pCurElm;
pCurElm = &pBlk[pStack->uiCurElm];
uiPrevKeyCnt = BBE_GET_PKC( pCurElm);
uiElmKeyLen = BBE_GET_KL( pCurElm);
if ((pStack->uiKeyLen = uiPrevKeyCnt + uiElmKeyLen) > pStack->uiKeyBufSize)
{
rc = RC_SET( FERR_CACHE_ERROR);
goto Exit;
}
// Copy the minimum number of bytes from the previous element.
if (uiPrevKeyCnt > uiKeyBufLen)
{
FLMUINT uiCopyLength = uiPrevKeyCnt - uiKeyBufLen;
FLMBYTE * pSrcPtr = &pPrevElm[uiElmOvhd];
flmAssert( pCurElm != NULL);
while (uiCopyLength--)
{
pKeyBuf[uiKeyBufLen++] = *pSrcPtr++;
}
}
else
{
uiKeyBufLen = uiPrevKeyCnt;
}
// Position to the next element
if (pStack->uiBlkType == BHT_LEAF)
{
pStack->uiCurElm += (FLMUINT) (BBE_LEN( pCurElm));
if (pStack->uiCurElm + BBE_LEM_LEN >= pStack->uiBlkEnd)
{
f_memcpy( &pKeyBuf[uiKeyBufLen], &pCurElm[uiElmOvhd], uiElmKeyLen);
if (uiSearchKeyLen && (pStack->uiCurElm < pStack->uiBlkEnd))
{
// This is a rare and unsure case where caller needs to
// have pStack->uiPrevElmPKC set correctly.
FSKeyCmp( pStack, pSearchKey, uiSearchKeyLen, dinDomain);
}
goto Hit_End;
}
}
else
{
pStack->uiCurElm += (FLMUINT) (BNE_LEN( pStack, pCurElm));
if (pStack->uiCurElm >= pStack->uiBlkEnd)
{
// Make sure that pKeyBuf has the last element's key.
f_memcpy( &pKeyBuf[uiKeyBufLen], &pCurElm[uiElmOvhd], uiElmKeyLen);
Hit_End:
pStack->uiKeyLen = 0;
pStack->uiPrevElmPKC = pStack->uiPKC;
pStack->uiPKC = 0;
pStack->uiCmpStatus = BT_END_OF_DATA;
goto Exit;
}
}
}
// Check to see if the scan hit where you wanted, if so setup stack &
// pKeyBuf.
if (pStack->uiCurElm == uiTargetCurElm)
{
// BE CAREFUL. Names with "target" point to this element. All other
// references include pCurElm point to the previous element.
FLMBYTE * pTargetCurElm = CURRENT_ELM( pStack);
FLMUINT uiTargetPrevKeyCnt = BBE_GET_PKC( pTargetCurElm);
FLMUINT uiTargetElmKeyLen = BBE_GET_KL( pTargetCurElm);
// Compare the current key so that prevPKC and PKC are set.
pStack->uiCmpStatus = BT_EQ_KEY;
if (pCurElm)
{
if (uiSearchKeyLen)
{
// Copy the entire key into keyBuf to compare
f_memcpy( &pKeyBuf[uiPrevKeyCnt], &pCurElm[uiElmOvhd], uiElmKeyLen);
pStack->uiCmpStatus = FSKeyCmp( pStack, pSearchKey, uiSearchKeyLen,
dinDomain);
}
else if (uiTargetPrevKeyCnt > uiKeyBufLen)
{
// Copy what is necessary. uiPrevKeyCnt is equal to
// uiKeyBufLen.
FLMUINT uiCopyLength = uiTargetPrevKeyCnt - uiKeyBufLen;
FLMBYTE * pSrcPtr = &pCurElm[uiElmOvhd];
while (uiCopyLength--)
{
pKeyBuf[uiKeyBufLen++] = *pSrcPtr++;
}
}
}
if ((pStack->uiKeyLen = uiTargetPrevKeyCnt + uiTargetElmKeyLen) >
pStack->uiKeyBufSize)
{
rc = RC_SET( FERR_CACHE_ERROR);
goto Exit;
}
if (uiTargetElmKeyLen)
{
f_memcpy( &pKeyBuf[uiTargetPrevKeyCnt], &pTargetCurElm[uiElmOvhd],
uiTargetElmKeyLen);
if (uiSearchKeyLen)
{
pStack->uiCmpStatus = FSKeyCmp( pStack, pSearchKey, uiSearchKeyLen,
dinDomain);
}
}
else
{
// This will be hit on a condition where we want to insert "ABCD
// (10)" into ABCD (15) ABCD (5) between the two keys. (10) is
// the DIN value. Because the keys are equal we don't have to
// call compare again. The uiPKC is the uiPrevKeyCnt value.
pStack->uiPrevElmPKC = pStack->uiPKC;
pStack->uiPKC = uiTargetPrevKeyCnt;
}
}
else
{
// Copy the remaining bytes of the current key into the buffer.
if (pCurElm)
{
f_memcpy( &pKeyBuf[uiPrevKeyCnt], &pCurElm[uiElmOvhd], uiElmKeyLen);
}
pStack->uiCmpStatus = BT_GT_KEY;
}
Exit:
return (rc);
}
/****************************************************************************
Desc: Standard key compare routine for a key and a b-tree element
****************************************************************************/
FSTATIC FLMUINT FSKeyCmp(
BTSK * pStack,
FLMBYTE * key,
FLMUINT uiKeyLen,
FLMUINT dinDomain)
{
FLMBYTE * pCurElm;
FLMBYTE * pKeyBuf; // Current element's key
FLMUINT uiCmp; // Return value
FLMUINT uiCompareLen; // Length to compare
FLMUINT uiOrigCompareLen; // Original compare length
FLMUINT uiCurElmKeyLen; // Current element's length
FLMUINT uiPKCTemp;
// Get again the current element's key length & compute compare length
uiCurElmKeyLen = pStack->uiKeyLen;
uiOrigCompareLen = uiCompareLen = f_min( uiKeyLen, uiCurElmKeyLen);
pKeyBuf = pStack->pKeyBuf; // Point to the local key buffer
pStack->uiPrevElmPKC = pStack->uiPKC; // Change previous element
pStack->uiPKC = 0;
while (uiCompareLen--)
{
if (*key++ == *pKeyBuf++)
{
continue;
}
uiPKCTemp = uiOrigCompareLen - (uiCompareLen + 1);
pStack->uiPKC = (uiPKCTemp > BBE_PKC_MAX) ? BBE_PKC_MAX : uiPKCTemp;
// Not equal so return
return ((*(--key) < *(--pKeyBuf)) ? BT_GT_KEY : BT_LT_KEY);
}
// Set the prev key count value
pStack->uiPKC = (uiOrigCompareLen <= BBE_PKC_MAX)
? uiOrigCompareLen
: BBE_PKC_MAX;
// Set return status, If equal then compare the dinDomain if needed.
uiCmp = uiKeyLen > uiCurElmKeyLen
? BT_LT_KEY
: (uiKeyLen < uiCurElmKeyLen
? BT_GT_KEY
: BT_EQ_KEY);
if ((uiCmp == BT_EQ_KEY) && dinDomain)
{
pCurElm = CURRENT_ELM( pStack);
if ((dinDomain - 1) < FSGetDomain( &pCurElm, (FLMBYTE) pStack->uiElmOvhd))
{
uiCmp = BT_LT_KEY;
}
}
return (uiCmp);
}
/****************************************************************************
Desc: Go to the next element within the block
****************************************************************************/
RCODE FSBlkNextElm(
BTSK * pStack)
{
RCODE rc = FERR_BT_END_OF_DATA;
FLMBYTE * elmPtr;
FLMUINT uiElmSize;
elmPtr = &pStack->pBlk[pStack->uiCurElm];
if (pStack->uiBlkType == BHT_LEAF)
{
uiElmSize = BBE_LEN( elmPtr);
if (pStack->uiCurElm + BBE_LEM_LEN < pStack->uiBlkEnd)
{
if ((pStack->uiCurElm += uiElmSize) + BBE_LEM_LEN < pStack->uiBlkEnd)
{
rc = FERR_OK;
}
}
}
else
{
if (pStack->uiBlkType == BHT_NON_LEAF_DATA)
{
uiElmSize = BNE_DATA_OVHD;
}
else
{
uiElmSize = (FLMUINT) BNE_LEN( pStack, elmPtr);
}
if (pStack->uiCurElm < pStack->uiBlkEnd)
{
// Check if this is not the last element within the block
if ((pStack->uiCurElm += uiElmSize) < pStack->uiBlkEnd)
{
rc = FERR_OK;
}
}
}
return (rc);
}
/****************************************************************************
Desc: Go to the next element in the logical b-tree while building the key
****************************************************************************/
RCODE FSBtNextElm(
FDB * pDb,
LFILE * pLFile,
BTSK * pStack)
{
RCODE rc = FERR_OK;
if (pStack->uiCurElm < BH_OVHD)
{
pStack->uiCurElm = BH_OVHD;
}
else if ((rc = FSBlkNextElm( pStack)) == FERR_BT_END_OF_DATA)
{
FLMBYTE * pBlk = BLK_ELM_ADDR( pStack, BH_NEXT_BLK);
FLMUINT blkNum = FB2UD( pBlk);
if (blkNum != BT_END)
{
// Current element was last element in the block - go to next
// block
if (RC_OK( rc = FSGetBlock( pDb, pLFile, blkNum, pStack)))
{
// Set blk end and adjust parent block to next element
pBlk = pStack->pBlk;
pStack->uiBlkEnd = (FLMUINT) FB2UW( &pBlk[BH_ELM_END]);
pStack->uiCurElm = BH_OVHD;
pStack->uiPKC = 0;
pStack->uiPrevElmPKC = 0;
if (pStack->uiFlags & FULL_STACK)
{
rc = FSAdjustStack( pDb, pLFile, pStack, TRUE);
}
}
}
}
if (RC_OK( rc))
{
FLMBYTE * pCurElm = CURRENT_ELM( pStack);
FLMUINT uiKeyLen;
if (pStack->uiBlkType == BHT_NON_LEAF_DATA)
{
flmCopyDrnKey( pStack->pKeyBuf, pCurElm);
goto Exit;
}
// Copy key to the stack->pKeyBuf & check for end key
if ((uiKeyLen = BBE_GET_KL( pCurElm)) != 0)
{
FLMUINT uiPKC = (FLMUINT) (BBE_GET_PKC( pCurElm));
if (uiKeyLen + uiPKC <= pStack->uiKeyBufSize)
{
pStack->uiKeyLen = (uiKeyLen + uiPKC);
f_memcpy( &pStack->pKeyBuf[ uiPKC], &pCurElm[ pStack->uiElmOvhd],
uiKeyLen);
}
else
{
rc = RC_SET( FERR_CACHE_ERROR);
goto Exit;
}
}
}
Exit:
return (rc);
}
/****************************************************************************
Desc: Adjust a full stack
****************************************************************************/
RCODE FSAdjustStack(
FDB * pDb,
LFILE * pLFile,
BTSK * pStack,
FLMBOOL bMovedNext)
{
RCODE rc = FERR_OK;
pStack->uiFlags = FULL_STACK;
// Pop the stack and go to the next element This is a recursive call
// back to FSBtNextElm() or FSBtPrevElm() Watch out, this will not work
// if the concurrency model changes to a b-tree locking method like
// other products use.
//
// Pop the pStack going to the parents block
pStack--;
// It is very rare that block will need to be read. Maybe some sort of
// split case. The block should have already have been read.
if (RC_OK( rc = FSGetBlock( pDb, pLFile, pStack->uiBlkAddr, pStack)))
{
rc = bMovedNext
? FSBtNextElm( pDb, pLFile, pStack)
: FSBtPrevElm( pDb, pLFile, pStack);
}
// Push the pStack and unpin the current block
pStack++;
return (rc);
}
/****************************************************************************
Desc: Read in a block from the cache and set most stack elements.
****************************************************************************/
RCODE FSGetBlock(
FDB * pDb,
LFILE * pLFile,
FLMUINT uiBlkAddr,
BTSK * pStack)
{
RCODE rc = FERR_OK;
FLMBYTE * pBlk;
// Release whatever block might be there first. If no block is there
// (pStack->pSCache == NULL), FSReleaseBlock does nothing. Stacks are
// ALWAYS initialized to set pSCache to NULL, so this is OK to call
// even if stack has never been used to read a block yet.
if (pStack->pSCache)
{
// If we already have the block we want, keep it!
if (pStack->pSCache->uiBlkAddress != uiBlkAddr)
{
FSReleaseBlock( pStack, FALSE);
}
}
if (!pStack->pSCache)
{
flmAssert( !pStack->pBlk);
if (RC_BAD( rc = ScaGetBlock( pDb, pLFile, BHT_LEAF, uiBlkAddr, NULL,
&pStack->pSCache)))
{
goto Exit;
}
}
pStack->pBlk = pBlk = pStack->pSCache->pucBlk;
if (pStack->uiBlkAddr != uiBlkAddr)
{
FLMUINT uiBlkType;
pStack->uiBlkAddr = uiBlkAddr;
// Set other pStack elements.
pStack->uiBlkType = uiBlkType = (FLMUINT) (BH_GET_TYPE( pBlk));
// The standard overhead is used in the stack Compares are made to
// determine if the element is extended.
if (uiBlkType == BHT_LEAF)
{
pStack->uiElmOvhd = BBE_KEY;
}
else if (uiBlkType == BHT_NON_LEAF_DATA)
{
pStack->uiElmOvhd = BNE_DATA_OVHD;
}
else if (uiBlkType == BHT_NON_LEAF)
{
pStack->uiElmOvhd = BNE_KEY_START;
}
else if (uiBlkType == BHT_NON_LEAF_COUNTS)
{
pStack->uiElmOvhd = BNE_KEY_COUNTS_START;
}
else
{
rc = RC_SET( FERR_DATA_ERROR);
FSReleaseBlock( pStack, FALSE);
goto Exit;
}
pStack->uiKeyLen = pStack->uiPKC = pStack->uiPrevElmPKC = 0;
pStack->uiLevel = (FLMUINT) pBlk[BH_LEVEL];
pStack->uiCurElm = BH_OVHD;
}
pStack->uiBlkEnd = (FLMUINT) FB2UW( &pBlk[BH_ELM_END]);
Exit:
return (rc);
}
/****************************************************************************
Desc: Release all of the cache associated with a stack.
****************************************************************************/
void FSReleaseStackCache(
BTSK * pStack,
FLMUINT uiNumLevels,
FLMBOOL bMutexAlreadyLocked)
{
FLMBOOL bMutexLocked = FALSE;
while (uiNumLevels)
{
if (pStack->pSCache)
{
if (!bMutexLocked && !bMutexAlreadyLocked)
{
f_mutexLock( gv_FlmSysData.hShareMutex);
bMutexLocked = TRUE;
}
ScaReleaseCache( pStack->pSCache, TRUE);
pStack->pSCache = NULL;
pStack->pBlk = NULL;
}
uiNumLevels--;
pStack++;
}
if (bMutexLocked)
{
f_mutexUnlock( gv_FlmSysData.hShareMutex);
}
}
| 23.2904 | 80 | 0.607289 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.