text
stringlengths 500
20k
| source
stringclasses 27
values | lang
stringclasses 3
values | char_count
int64 500
20k
| word_count
int64 4
19.8k
|
---|---|---|---|---|
// Copyright 2011 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Features shared by parsing and pre-parsing scanners.
#include "scanner.h"
#include "../include/v8stdint.h"
#include "char-predicates-inl.h"
namespace v8 {
namespace internal {
// ----------------------------------------------------------------------------
// Scanner
Scanner::Scanner(UnicodeCache* unicode_cache)
: unicode_cache_(unicode_cache),
octal_pos_(Location::invalid()),
harmony_scoping_(false),
harmony_modules_(false) { }
void Scanner::Initialize(Utf16CharacterStream* source) {
source_ = source;
// Need to capture identifiers in order to recognize "get" and "set"
// in object literals.
Init();
// Skip initial whitespace allowing HTML comment ends just like
// after a newline and scan first token.
has_line_terminator_before_next_ = true;
SkipWhiteSpace();
Scan();
}
uc32 Scanner::ScanHexNumber(int expected_length) {
ASSERT(expected_length <= 4); // prevent overflow
uc32 digits[4] = { 0, 0, 0, 0 };
uc32 x = 0;
for (int i = 0; i < expected_length; i++) {
digits[i] = c0_;
int d = HexValue(c0_);
if (d < 0) {
// According to ECMA-262, 3rd, 7.8.4, page 18, these hex escapes
// should be illegal, but other JS VMs just return the
// non-escaped version of the original character.
// Push back digits that we have advanced past.
for (int j = i-1; j >= 0; j--) {
PushBack(digits[j]);
}
return -1;
}
x = x * 16 + d;
Advance();
}
return x;
}
// Ensure that tokens can be stored in a byte.
STATIC_ASSERT(Token::NUM_TOKENS <= 0x100);
// Table of one-character tokens, by character (0x00..0x7f only).
static const byte one_char_tokens[] = {
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::LPAREN, // 0x28
Token::RPAREN, // 0x29
Token::ILLEGAL,
Token::ILLEGAL,
Token::COMMA, // 0x2c
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::COLON, // 0x3a
Token::SEMICOLON, // 0x3b
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::CONDITIONAL, // 0x3f
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::LBRACK, // 0x5b
Token::ILLEGAL,
Token::RBRACK, // 0x5d
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::ILLEGAL,
Token::LBRACE, // 0x7b
Token::ILLEGAL,
Token::RBRACE, // 0x7d
Token::BIT_NOT, // 0x7e
Token::ILLEGAL
};
Token::Value Scanner::Next() {
current_ = next_;
has_line_terminator_before_next_ = false;
has_multiline_comment_before_next_ = false;
if (static_cast<unsigned>(c0_) <= 0x7f) {
Token::Value token = static_cast<Token::Value>(one_char_tokens[c0_]);
if (token != Token::ILLEGAL) {
int pos = source_pos();
next_.token = token;
next_.location.beg_pos = pos;
next_.location.end_pos = pos + 1;
Advance();
return current_.token;
}
}
Scan();
return current_.token;
}
static inline bool IsByteOrderMark(uc32 c) {
// The Unicode value U+FFFE is guaranteed never to be assigned as a
// Unicode character; this implies that in a Unicode context the
// 0xFF, 0xFE byte pattern can only be interpreted as the U+FEFF
// character expressed in little-endian byte order (since it could
// not be a U+FFFE character expressed in big-endian byte
// order). Nevertheless, we check for it to be compatible with
// Spidermonkey.
return c == 0xFEFF || c == 0xFFFE;
}
bool Scanner::SkipWhiteSpace() {
int start_position = source_pos();
while (true) {
// We treat byte-order marks (BOMs) as whitespace for better
// compatibility with Spidermonkey and other JavaScript engines.
while (unicode_cache_->IsWhiteSpace(c0_) || IsByteOrderMark(c0_)) {
// IsWhiteSpace() includes line terminators!
if (unicode_cache_->IsLineTerminator(c0_)) {
// Ignore line terminators, but remember them. This is necessary
// for automatic semicolon insertion.
has_line_terminator_before_next_ = true;
}
Advance();
}
// If there is an HTML comment end '-->' at the beginning of a
// line (with only whitespace in front of it), we treat the rest
// of the line as a comment. This is in line with the way
// SpiderMonkey handles it.
if (c0_ == '-' && has_line_terminator_before_next_) {
Advance();
if (c0_ == '-') {
Advance();
if (c0_ == '>') {
// Treat the rest of the line as a comment.
SkipSingleLineComment();
// Continue skipping white space after the comment.
continue;
}
PushBack('-'); // undo Advance()
}
PushBack('-'); // undo Advance()
}
// Return whether or not we skipped any characters.
return source_pos() != start_position;
}
}
Token::Value Scanner::SkipSingleLineComment() {
Advance();
// The line terminator at the end of the line is not considered
// to be part of the single-line comment; it is recognized
// separately by the lexical grammar and becomes part of the
// stream of input elements for the syntactic grammar (see
// ECMA-262, section 7.4).
while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
Advance();
}
return Token::WHITESPACE;
}
Token::Value Scanner::SkipMultiLineComment() {
ASSERT(c0_ == '*');
Advance();
while (c0_ >= 0) {
uc32 ch = c0_;
Advance();
if (unicode_cache_->IsLineTerminator(ch)) {
// Following ECMA-262, section 7.4, a comment containing
// a newline will make the comment count as a line-terminator.
has_multiline_comment_before_next_ = true;
}
// If we have reached the end of the multi-line comment, we
// consume the '/' and insert a whitespace. This way all
// multi-line comments are treated as whitespace.
if (ch == '*' && c0_ == '/') {
c0_ = ' ';
return Token::WHITESPACE;
}
}
// Unterminated multi-line comment.
return Token::ILLEGAL;
}
Token::Value Scanner::ScanHtmlComment() {
// Check for <!-- comments.
ASSERT(c0_ == '!');
Advance();
if (c0_ == '-') {
Advance();
if (c0_ == '-') return SkipSingleLineComment();
PushBack('-'); // undo Advance()
}
PushBack('!'); // undo Advance()
ASSERT(c0_ == '!');
return Token::LT;
}
void Scanner::Scan() {
next_.literal_chars = NULL;
Token::Value token;
do {
// Remember the position of the next token
next_.location.beg_pos = source_pos();
switch (c0_) {
case ' ':
case '\t':
Advance();
token = Token::WHITESPACE;
break;
case '\n':
Advance();
has_line_terminator_before_next_ = true;
token = Token::WHITESPACE;
break;
case '"': case '\'':
token = ScanString();
break;
case '<':
// < <= << <<= <!--
Advance();
if (c0_ == '=') {
token = Select(Token::LTE);
} else if (c0_ == '<') {
token = Select('=', Token::ASSIGN_SHL, Token::SHL);
} else if (c0_ == '!') {
token = ScanHtmlComment();
} else {
token = Token::LT;
}
break;
case '>':
// > >= >> >>= >>> >>>=
Advance();
if (c0_ == '=') {
token = Select(Token::GTE);
} else if (c0_ == '>') {
// >> >>= >>> >>>=
Advance();
if (c0_ == '=') {
token = Select(Token::ASSIGN_SAR);
} else if (c0_ == '>') {
token = Select('=', Token::ASSIGN_SHR, Token::SHR);
} else {
token = Token::SAR;
}
} else {
token = Token::GT;
}
break;
case '=':
// = == ===
Advance();
if (c0_ == '=') {
token = Select('=', Token::EQ_STRICT, Token::EQ);
} else {
token = Token::ASSIGN;
}
break;
case '!':
// ! != !==
Advance();
if (c0_ == '=') {
token = Select('=', Token::NE_STRICT, Token::NE);
} else {
token = Token::NOT;
}
break;
case '+':
// + ++ +=
Advance();
if (c0_ == '+') {
token = Select(Token::INC);
} else if (c0_ == '=') {
token = Select(Token::ASSIGN_ADD);
} else {
token = Token::ADD;
}
break;
case '-':
// - -- --> -=
Advance();
if (c0_ == '-') {
Advance();
if (c0_ == '>' && has_line_terminator_before_next_) {
// For compatibility with SpiderMonkey, we skip lines that
// start with an HTML comment end '-->'.
token = SkipSingleLineComment();
} else {
token = Token::DEC;
}
} else if (c0_ == '=') {
token = Select(Token::ASSIGN_SUB);
} else {
token = Token::SUB;
}
break;
case '*':
// * *=
token = Select('=', Token::ASSIGN_MUL, Token::MUL);
break;
case '%':
// % %=
token = Select('=', Token::ASSIGN_MOD, Token::MOD);
break;
case '/':
// / // /* /=
Advance();
if (c0_ == '/') {
token = SkipSingleLineComment();
} else if (c0_ == '*') {
token = SkipMultiLineComment();
} else if (c0_ == '=') {
token = Select(Token::ASSIGN_DIV);
} else {
token = Token::DIV;
}
break;
case '&':
// & && &=
Advance();
if (c0_ == '&') {
token = Select(Token::AND);
} else if (c0_ == '=') {
token = Select(Token::ASSIGN_BIT_AND);
} else {
token = Token::BIT_AND;
}
break;
case '|':
// | || |=
Advance();
if (c0_ == '|') {
token = Select(Token::OR);
} else if (c0_ == '=') {
token = Select(Token::ASSIGN_BIT_OR);
} else {
token = Token::BIT_OR;
}
break;
case '^':
// ^ ^=
token = Select('=', Token::ASSIGN_BIT_XOR, Token::BIT_XOR);
break;
case '.':
// . Number
Advance();
if (IsDecimalDigit(c0_)) {
token = ScanNumber(true);
} else {
token = Token::PERIOD;
}
break;
case ':':
token = Select(Token::COLON);
break;
case ';':
token = Select(Token::SEMICOLON);
break;
case ',':
token = Select(Token::COMMA);
break;
case '(':
token = Select(Token::LPAREN);
break;
case ')':
token = Select(Token::RPAREN);
break;
case '[':
token = Select(Token::LBRACK);
break;
case ']':
token = Select(Token::RBRACK);
break;
case '{':
token = Select(Token::LBRACE);
break;
case '}':
token = Select(Token::RBRACE);
break;
case '?':
token = Select(Token::CONDITIONAL);
break;
case '~':
token = Select(Token::BIT_NOT);
break;
default:
if (unicode_cache_->IsIdentifierStart(c0_)) {
token = ScanIdentifierOrKeyword();
} else if (IsDecimalDigit(c0_)) {
token = ScanNumber(false);
} else if (SkipWhiteSpace()) {
token = Token::WHITESPACE;
} else if (c0_ < 0) {
token = Token::EOS;
} else {
token = Select(Token::ILLEGAL);
}
break;
}
// Continue scanning for tokens as long as we're just skipping
// whitespace.
} while (token == Token::WHITESPACE);
next_.location.end_pos = source_pos();
next_.token = token;
}
void Scanner::SeekForward(int pos) {
// After this call, we will have the token at the given position as
// the "next" token. The "current" token will be invalid.
if (pos == next_.location.beg_pos) return;
int current_pos = source_pos();
ASSERT_EQ(next_.location.end_pos, current_pos);
// Positions inside the lookahead token aren't supported.
ASSERT(pos >= current_pos);
if (pos != current_pos) {
source_->SeekForward(pos - source_->pos());
Advance();
// This function is only called to seek to the location
// of the end of a function (at the "}" token). It doesn't matter
// whether there was a line terminator in the part we skip.
has_line_terminator_before_next_ = false;
has_multiline_comment_before_next_ = false;
}
Scan();
}
void Scanner::ScanEscape() {
uc32 c = c0_;
Advance();
// Skip escaped newlines.
if (unicode_cache_->IsLineTerminator(c)) {
// Allow CR+LF newlines in multiline string literals.
if (IsCarriageReturn(c) && IsLineFeed(c0_)) Advance();
// Allow LF+CR newlines in multiline string literals.
if (IsLineFeed(c) && IsCarriageReturn(c0_)) Advance();
return;
}
switch (c) {
case '\'': // fall through
case '"' : // fall through
case '\\': break;
case 'b' : c = '\b'; break;
case 'f' : c = '\f'; break;
case 'n' : c = '\n'; break;
case 'r' : c = '\r'; break;
case 't' : c = '\t'; break;
case 'u' : {
c = ScanHexNumber(4);
if (c < 0) c = 'u';
break;
}
case 'v' : c = '\v'; break;
case 'x' : {
c = ScanHexNumber(2);
if (c < 0) c = 'x';
break;
}
case '0' : // fall through
case '1' : // fall through
case '2' : // fall through
case '3' : // fall through
case '4' : // fall through
case '5' : // fall through
case '6' : // fall through
case '7' : c = ScanOctalEscape(c, 2); break;
}
// According to ECMA-262, 3rd, 7.8.4 (p 18ff) these
// should be illegal, but they are commonly handled
// as non-escaped characters by JS VMs.
AddLiteralChar(c);
}
// Octal escapes of the forms '\0xx' and '\xxx' are not a part of
// ECMA-262. Other JS VMs support them.
uc32 Scanner::ScanOctalEscape(uc32 c, int length) {
uc32 x = c - '0';
int i = 0;
for (; i < length; i++) {
int d = c0_ - '0';
if (d < 0 || d > 7) break;
int nx = x * 8 + d;
if (nx >= 256) break;
x = nx;
Advance();
}
// Anything except '\0' is an octal escape sequence, illegal in strict mode.
// Remember the position of octal escape sequences so that an error
// can be reported later (in strict mode).
// We don't report the error immediately, because the octal escape can
// occur before the "use strict" directive.
if (c != '0' || i > 0) {
octal_pos_ = Location(source_pos() - i - 1, source_pos() - 1);
}
return x;
}
Token::Value Scanner::ScanString() {
uc32 quote = c0_;
Advance(); // consume quote
LiteralScope literal(this);
while (c0_ != quote && c0_ >= 0
&& !unicode_cache_->IsLineTerminator(c0_)) {
uc32 c = c0_;
Advance();
if (c == '\\') {
if (c0_ < 0) return Token::ILLEGAL;
ScanEscape();
} else {
AddLiteralChar(c);
}
}
if (c0_ != quote) return Token::ILLEGAL;
literal.Complete();
Advance(); // consume quote
return Token::STRING;
}
void Scanner::ScanDecimalDigits() {
while (IsDecimalDigit(c0_))
AddLiteralCharAdvance();
}
Token::Value Scanner::ScanNumber(bool seen_period) {
ASSERT(IsDecimalDigit(c0_)); // the first digit of the number or the fraction
enum { DECIMAL, HEX, OCTAL } kind = DECIMAL;
LiteralScope literal(this);
if (seen_period) {
// we have already seen a decimal point of the float
AddLiteralChar('.');
ScanDecimalDigits(); // we know we have at least one digit
} else {
// if the first character is '0' we must check for octals and hex
if (c0_ == '0') {
int start_pos = source_pos(); // For reporting octal positions.
AddLiteralCharAdvance();
// either 0, 0exxx, 0Exxx, 0.xxx, an octal number, or a hex number
if (c0_ == 'x' || c0_ == 'X') {
// hex number
kind = HEX;
AddLiteralCharAdvance();
if (!IsHexDigit(c0_)) {
// we must have at least one hex digit after 'x'/'X'
return Token::ILLEGAL;
}
while (IsHexDigit(c0_)) {
AddLiteralCharAdvance();
}
} else if ('0' <= c0_ && c0_ <= '7') {
// (possible) octal number
kind = OCTAL;
while (true) {
if (c0_ == '8' || c0_ == '9') {
kind = DECIMAL;
break;
}
if (c0_ < '0' || '7' < c0_) {
// Octal literal finished.
octal_pos_ = Location(start_pos, source_pos());
break;
}
AddLiteralCharAdvance();
}
} | c++ | code | 19,998 | 4,708 |
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "tools/ToolUtils.h"
#include <string>
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkFontMgr.h"
#include "include/core/SkGraphics.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPoint.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTextBlob.h"
#include "include/core/SkTypeface.h"
#include "include/gpu/GrDirectContext.h"
#include "src/core/SkGlyphRun.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "tools/fonts/RandomScalerContext.h"
#ifdef SK_BUILD_FOR_WIN
#include "include/ports/SkTypeface_win.h"
#endif
#include "tests/Test.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "src/gpu/text/GrAtlasManager.h"
#include "src/gpu/text/GrTextBlobCache.h"
static void draw(SkCanvas* canvas, int redraw, const SkTArray<sk_sp<SkTextBlob>>& blobs) {
int yOffset = 0;
for (int r = 0; r < redraw; r++) {
for (int i = 0; i < blobs.count(); i++) {
const auto& blob = blobs[i];
const SkRect& bounds = blob->bounds();
yOffset += SkScalarCeilToInt(bounds.height());
SkPaint paint;
canvas->drawTextBlob(blob, 0, SkIntToScalar(yOffset), paint);
}
}
}
static const int kWidth = 1024;
static const int kHeight = 768;
static void setup_always_evict_atlas(GrDirectContext* dContext) {
dContext->priv().getAtlasManager()->setAtlasDimensionsToMinimum_ForTesting();
}
class GrTextBlobTestingPeer {
public:
static void SetBudget(GrTextBlobCache* cache, size_t budget) {
SkAutoSpinlock lock{cache->fSpinLock};
cache->fSizeBudget = budget;
cache->internalCheckPurge();
}
};
// This test hammers the GPU textblobcache and font atlas
static void text_blob_cache_inner(skiatest::Reporter* reporter, GrDirectContext* dContext,
int maxTotalText, int maxGlyphID, int maxFamilies, bool normal,
bool stressTest) {
// setup surface
uint32_t flags = 0;
SkSurfaceProps props(flags, kRGB_H_SkPixelGeometry);
// configure our context for maximum stressing of cache and atlas
if (stressTest) {
setup_always_evict_atlas(dContext);
GrTextBlobTestingPeer::SetBudget(dContext->priv().getTextBlobCache(), 0);
}
SkImageInfo info = SkImageInfo::Make(kWidth, kHeight, kRGBA_8888_SkColorType,
kPremul_SkAlphaType);
auto surface(SkSurface::MakeRenderTarget(dContext, SkBudgeted::kNo, info, 0, &props));
REPORTER_ASSERT(reporter, surface);
if (!surface) {
return;
}
SkCanvas* canvas = surface->getCanvas();
sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault());
int count = std::min(fm->countFamilies(), maxFamilies);
// make a ton of text
SkAutoTArray<uint16_t> text(maxTotalText);
for (int i = 0; i < maxTotalText; i++) {
text[i] = i % maxGlyphID;
}
// generate textblobs
SkTArray<sk_sp<SkTextBlob>> blobs;
for (int i = 0; i < count; i++) {
SkFont font;
font.setSize(48); // draw big glyphs to really stress the atlas
SkString familyName;
fm->getFamilyName(i, &familyName);
sk_sp<SkFontStyleSet> set(fm->createStyleSet(i));
for (int j = 0; j < set->count(); ++j) {
SkFontStyle fs;
set->getStyle(j, &fs, nullptr);
// We use a typeface which randomy returns unexpected mask formats to fuzz
sk_sp<SkTypeface> orig(set->createTypeface(j));
if (normal) {
font.setTypeface(orig);
} else {
font.setTypeface(sk_make_sp<SkRandomTypeface>(orig, SkPaint(), true));
}
SkTextBlobBuilder builder;
for (int aa = 0; aa < 2; aa++) {
for (int subpixel = 0; subpixel < 2; subpixel++) {
for (int lcd = 0; lcd < 2; lcd++) {
font.setEdging(SkFont::Edging::kAlias);
if (aa) {
font.setEdging(SkFont::Edging::kAntiAlias);
if (lcd) {
font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
}
}
font.setSubpixel(SkToBool(subpixel));
if (!SkToBool(lcd)) {
font.setSize(160);
}
const SkTextBlobBuilder::RunBuffer& run = builder.allocRun(font,
maxTotalText,
0, 0,
nullptr);
memcpy(run.glyphs, text.get(), maxTotalText * sizeof(uint16_t));
}
}
}
blobs.emplace_back(builder.make());
}
}
// create surface where LCD is impossible
info = SkImageInfo::Make(kWidth, kHeight, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
SkSurfaceProps propsNoLCD(0, kUnknown_SkPixelGeometry);
auto surfaceNoLCD(canvas->makeSurface(info, &propsNoLCD));
REPORTER_ASSERT(reporter, surface);
if (!surface) {
return;
}
SkCanvas* canvasNoLCD = surfaceNoLCD->getCanvas();
// test redraw
draw(canvas, 2, blobs);
draw(canvasNoLCD, 2, blobs);
// test draw after free
dContext->freeGpuResources();
draw(canvas, 1, blobs);
dContext->freeGpuResources();
draw(canvasNoLCD, 1, blobs);
// test draw after abandon
dContext->abandonContext();
draw(canvas, 1, blobs);
}
DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobCache, reporter, ctxInfo) {
text_blob_cache_inner(reporter, ctxInfo.directContext(), 1024, 256, 30, true, false);
}
DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobStressCache, reporter, ctxInfo) {
text_blob_cache_inner(reporter, ctxInfo.directContext(), 256, 256, 10, true, true);
}
DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobAbnormal, reporter, ctxInfo) {
text_blob_cache_inner(reporter, ctxInfo.directContext(), 256, 256, 10, false, false);
}
DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobStressAbnormal, reporter, ctxInfo) {
text_blob_cache_inner(reporter, ctxInfo.directContext(), 256, 256, 10, false, true);
}
static const int kScreenDim = 160;
static SkBitmap draw_blob(SkTextBlob* blob, SkSurface* surface, SkPoint offset) {
SkPaint paint;
SkCanvas* canvas = surface->getCanvas();
canvas->save();
canvas->drawColor(SK_ColorWHITE, SkBlendMode::kSrc);
canvas->translate(offset.fX, offset.fY);
canvas->drawTextBlob(blob, 0, 0, paint);
SkBitmap bitmap;
bitmap.allocN32Pixels(kScreenDim, kScreenDim);
surface->readPixels(bitmap, 0, 0);
canvas->restore();
return bitmap;
}
static bool compare_bitmaps(const SkBitmap& expected, const SkBitmap& actual) {
SkASSERT(expected.width() == actual.width());
SkASSERT(expected.height() == actual.height());
for (int i = 0; i < expected.width(); ++i) {
for (int j = 0; j < expected.height(); ++j) {
SkColor expectedColor = expected.getColor(i, j);
SkColor actualColor = actual.getColor(i, j);
if (expectedColor != actualColor) {
return false;
}
}
}
return true;
}
static sk_sp<SkTextBlob> make_blob() {
auto tf = SkTypeface::MakeFromName("Roboto2-Regular", SkFontStyle());
SkFont font;
font.setTypeface(tf);
font.setSubpixel(false);
font.setEdging(SkFont::Edging::kAlias);
font.setSize(24);
static char text[] = "HekpqB";
static const int maxGlyphLen = sizeof(text) * 4;
SkGlyphID glyphs[maxGlyphLen];
int glyphCount =
font.textToGlyphs(text, sizeof(text), SkTextEncoding::kUTF8, glyphs, maxGlyphLen);
SkTextBlobBuilder builder;
const auto& runBuffer = builder.allocRun(font, glyphCount, 0, 0);
for (int i = 0; i < glyphCount; i++) {
runBuffer.glyphs[i] = glyphs[i];
}
return builder.make();
}
// Turned off to pass on android and ios devices, which were running out of memory..
#if 0
static sk_sp<SkTextBlob> make_large_blob() {
auto tf = SkTypeface::MakeFromName("Roboto2-Regular", SkFontStyle());
SkFont font;
font.setTypeface(tf);
font.setSubpixel(false);
font.setEdging(SkFont::Edging::kAlias);
font.setSize(24);
const int mallocSize = 0x3c3c3bd; // x86 size
std::unique_ptr<char[]> text{new char[mallocSize + 1]};
if (text == nullptr) {
return nullptr;
}
for (int i = 0; i < mallocSize; i++) {
text[i] = 'x';
}
text[mallocSize] = 0;
static const int maxGlyphLen = mallocSize;
std::unique_ptr<SkGlyphID[]> glyphs{new SkGlyphID[maxGlyphLen]};
int glyphCount =
font.textToGlyphs(
text.get(), mallocSize, SkTextEncoding::kUTF8, glyphs.get(), maxGlyphLen);
SkTextBlobBuilder builder;
const auto& runBuffer = builder.allocRun(font, glyphCount, 0, 0);
for (int i = 0; i < glyphCount; i++) {
runBuffer.glyphs[i] = glyphs[i];
}
return builder.make();
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(TextBlobIntegerOverflowTest, reporter, ctxInfo) {
auto dContext = ctxInfo.directContext();
const SkImageInfo info =
SkImageInfo::Make(kScreenDim, kScreenDim, kN32_SkColorType, kPremul_SkAlphaType);
auto surface = SkSurface::MakeRenderTarget(dContext, SkBudgeted::kNo, info);
auto blob = make_large_blob();
int y = 40;
SkBitmap base = draw_blob(blob.get(), surface.get(), {40, y + 0.0f});
}
#endif
static const bool kDumpPngs = true;
// dump pngs needs a "good" and a "bad" directory to put the results in. This allows the use of the
// skdiff tool to visualize the differences.
void write_png(const std::string& filename, const SkBitmap& bitmap) {
auto data = SkEncodeBitmap(bitmap, SkEncodedImageFormat::kPNG, 0);
SkFILEWStream w{filename.c_str()};
w.write(data->data(), data->size());
w.fsync();
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(TextBlobJaggedGlyph, reporter, ctxInfo) {
auto direct = ctxInfo.directContext();
const SkImageInfo info =
SkImageInfo::Make(kScreenDim, kScreenDim, kN32_SkColorType, kPremul_SkAlphaType);
auto surface = SkSurface::MakeRenderTarget(direct, SkBudgeted::kNo, info);
auto blob = make_blob();
for (int y = 40; y < kScreenDim - 40; y++) {
SkBitmap base = draw_blob(blob.get(), surface.get(), {40, y + 0.0f});
SkBitmap half = draw_blob(blob.get(), surface.get(), {40, y + 0.5f});
SkBitmap unit = draw_blob(blob.get(), surface.get(), {40, y + 1.0f});
bool isOk = compare_bitmaps(base, half) || compare_bitmaps(unit, half);
REPORTER_ASSERT(reporter, isOk);
if (!isOk) {
if (kDumpPngs) {
{
std::string filename = "bad/half-y" + std::to_string(y) + ".png";
write_png(filename, half);
}
{
std::string filename = "good/half-y" + std::to_string(y) + ".png";
write_png(filename, base);
}
}
break;
}
}
// Testing the x direction across all platforms does not workout, because letter spacing can
// change based on non-integer advance widths, but this has been useful for diagnosing problems.
#if 0
blob = make_blob();
for (int x = 40; x < kScreenDim - 40; x++) {
SkBitmap base = draw_blob(blob.get(), surface.get(), {x + 0.0f, 40});
SkBitmap half = draw_blob(blob.get(), surface.get(), {x + 0.5f, 40});
SkBitmap unit = draw_blob(blob.get(), surface.get(), {x + 1.0f, 40});
bool isOk = compare_bitmaps(base, half) || compare_bitmaps(unit, half);
REPORTER_ASSERT(reporter, isOk);
if (!isOk) {
if (kDumpPngs) {
{
std::string filename = "bad/half-x" + std::to_string(x) + ".png";
write_png(filename, half);
}
{
std::string filename = "good/half-x" + std::to_string(x) + ".png";
write_png(filename, base);
}
}
break;
}
}
#endif
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(TextBlobSmoothScroll, reporter, ctxInfo) {
auto direct = ctxInfo.directContext();
const SkImageInfo info =
SkImageInfo::Make(kScreenDim, kScreenDim, kN32_SkColorType, kPremul_SkAlphaType);
auto surface = SkSurface::MakeRenderTarget(direct, SkBudgeted::kNo, info);
auto movingBlob = make_blob();
for (SkScalar y = 40; y < 50; y += 1.0/8.0) {
auto expectedBlob = make_blob();
auto expectedBitMap = draw_blob(expectedBlob.get(), surface.get(), {40, y});
auto movingBitmap = draw_blob(movingBlob.get(), surface.get(), {40, y});
bool isOk = compare_bitmaps(expectedBitMap, movingBitmap);
REPORTER_ASSERT(reporter, isOk);
if (!isOk) {
if (kDumpPngs) {
{
std::string filename = "bad/scroll-y" + std::to_string(y) + ".png";
write_png(filename, movingBitmap);
}
{
std::string filename = "good/scroll-y" + std::to_string(y) + ".png";
write_png(filename, expectedBitMap);
}
}
break;
}
}
} | c++ | code | 13,774 | 2,793 |
// Copyright (c) 2011-2018 The ton Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/receiverequestdialog.h>
#include <qt/forms/ui_receiverequestdialog.h>
#include <qt/tonunits.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <QClipboard>
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include <config/ton-config.h> /* for USE_QRCODE */
#endif
ReceiveRequestDialog::ReceiveRequestDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveRequestDialog),
model(nullptr)
{
ui->setupUi(this);
#ifndef USE_QRCODE
ui->btnSaveAs->setVisible(false);
ui->lblQRCode->setVisible(false);
#endif
connect(ui->btnSaveAs, &QPushButton::clicked, ui->lblQRCode, &QRImageWidget::saveImage);
}
ReceiveRequestDialog::~ReceiveRequestDialog()
{
delete ui;
}
void ReceiveRequestDialog::setModel(WalletModel *_model)
{
this->model = _model;
if (_model)
connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &ReceiveRequestDialog::update);
// update the display unit if necessary
update();
}
void ReceiveRequestDialog::setInfo(const SendCoinsRecipient &_info)
{
this->info = _info;
update();
}
void ReceiveRequestDialog::update()
{
if(!model)
return;
QString target = info.label;
if(target.isEmpty())
target = info.address;
setWindowTitle(tr("Request payment to %1").arg(target));
QString uri = GUIUtil::formattonURI(info);
ui->btnSaveAs->setEnabled(false);
QString html;
html += "<html><font face='verdana, arial, helvetica, sans-serif'>";
html += "<b>"+tr("Payment information")+"</b><br>";
html += "<b>"+tr("URI")+"</b>: ";
html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>";
html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>";
if(info.amount)
html += "<b>"+tr("Amount")+"</b>: " + tonUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), info.amount) + "<br>";
if(!info.label.isEmpty())
html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>";
if(!info.message.isEmpty())
html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>";
if(model->isMultiwallet()) {
html += "<b>"+tr("Wallet")+"</b>: " + GUIUtil::HtmlEscape(model->getWalletName()) + "<br>";
}
ui->outUri->setText(html);
if (ui->lblQRCode->setQR(uri, info.address)) {
ui->btnSaveAs->setEnabled(true);
}
}
void ReceiveRequestDialog::on_btnCopyURI_clicked()
{
GUIUtil::setClipboard(GUIUtil::formattonURI(info));
}
void ReceiveRequestDialog::on_btnCopyAddress_clicked()
{
GUIUtil::setClipboard(info.address);
} | c++ | code | 2,843 | 785 |
/*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>
#include <OSL/oslcomp.h>
#include <OSL/oslexec.h>
using namespace OSL;
static void
usage ()
{
std::cout <<
"oslc -- Open Shading Language compiler " OSL_LIBRARY_VERSION_STRING "\n"
OSL_COPYRIGHT_STRING "\n"
"Usage: oslc [options] file\n"
" Options:\n"
"\t--help Print this usage message\n"
"\t-o filename Specify output filename\n"
"\t-v Verbose mode\n"
"\t-q Quiet mode\n"
"\t-Ipath Add path to the #include search path\n"
"\t-Dsym[=val] Define preprocessor symbol\n"
"\t-Usym Undefine preprocessor symbol\n"
"\t-O0, -O1, -O2 Set optimization level (default=1)\n"
"\t-d Debug mode\n"
"\t-E Only preprocess the input and output to stdout\n"
"\t-Werror Treat all warnings as errors\n"
;
}
namespace { // anonymous
// Subclass ErrorHandler because we want our messages to appear somewhat
// differant than the default ErrorHandler base class, in order to match
// typical compiler command line messages.
class OSLC_ErrorHandler : public ErrorHandler {
public:
virtual void operator () (int errcode, const std::string &msg) {
static OIIO::mutex err_mutex;
OIIO::lock_guard guard (err_mutex);
switch (errcode & 0xffff0000) {
case EH_INFO :
if (verbosity() >= VERBOSE)
std::cout << msg << std::endl;
break;
case EH_WARNING :
if (verbosity() >= NORMAL)
std::cerr << msg << std::endl;
break;
case EH_ERROR :
std::cerr << msg << std::endl;
break;
case EH_SEVERE :
std::cerr << msg << std::endl;
break;
case EH_DEBUG :
#ifdef NDEBUG
break;
#endif
default :
if (verbosity() > QUIET)
std::cout << msg;
break;
}
}
};
static OSLC_ErrorHandler default_oslc_error_handler;
} // anonymous namespace
int
main (int argc, const char *argv[])
{
// Globally force classic "C" locale, and turn off all formatting
// internationalization, for the entire oslc application.
std::locale::global (std::locale::classic());
OIIO::Filesystem::convert_native_arguments (argc, (const char **)argv);
if (argc <= 1) {
usage ();
return EXIT_SUCCESS;
}
std::vector<std::string> args;
bool quiet = false;
std::string shader_path;
// Parse arguments from command line
for (int a = 1; a < argc; ++a) {
if (! strcmp (argv[a], "--help") | ! strcmp (argv[a], "-h")) {
usage ();
return EXIT_SUCCESS;
}
else if (! strcmp (argv[a], "-v") ||
! strcmp (argv[a], "-q") ||
! strcmp (argv[a], "-d") ||
! strcmp (argv[a], "-E") ||
! strcmp (argv[a], "-O") || ! strcmp (argv[a], "-O0") ||
! strcmp (argv[a], "-O1") || ! strcmp (argv[a], "-O2") ||
! strcmp (argv[a], "-Werror")
) {
// Valid command-line argument
args.emplace_back(argv[a]);
quiet |= (strcmp (argv[a], "-q") == 0);
}
else if (! strcmp (argv[a], "-o") && a < argc-1) {
// Output filepath
args.emplace_back(argv[a]);
++a;
args.emplace_back(argv[a]);
}
else if (argv[a][0] == '-' &&
(argv[a][1] == 'D' || argv[a][1] == 'U' || argv[a][1] == 'I')) {
args.emplace_back(argv[a]);
}
else {
// Shader to compile
shader_path = argv[a];
}
}
if (shader_path.empty ()) {
std::cout << "ERROR: Missing shader path" << "\n\n";
usage ();
return EXIT_FAILURE;
}
OSLCompiler compiler (&default_oslc_error_handler);
bool ok = compiler.compile (shader_path, args);
if (ok) {
if (!quiet)
std::cout << "Compiled " << shader_path << " -> " << compiler.output_filename() << "\n";
}
else {
std::cout << "FAILED " << shader_path << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | c++ | code | 6,022 | 1,302 |
//
// @author [email protected]
//
#include <op_boilerplate.h>
#if NOT_EXCLUDED(OP_cumsum)
#include <ops/declarable/helpers/prefix.h>
#include <ops/declarable/CustomOperations.h>
namespace nd4j {
namespace ops {
CONFIGURABLE_OP_IMPL(cumsum, 1, 1, true, 0, 2) {
auto input = INPUT_VARIABLE(0);
auto output = OUTPUT_VARIABLE(0);
const bool exclusive = INT_ARG(0) == 1;
const bool reverse = INT_ARG(1) == 1;
if (block.getIArguments()->size() == 2 && block.width() == 1) {
// all at once case
nd4j::ops::helpers::_prefix<T, simdOps::Add<T>>(input->buffer(), input->shapeInfo(), output->buffer(), output->shapeInfo(), exclusive, reverse);
}
else {
std::vector<int> dims(block.numI() - 2);
if (block.width() == 1) {
for (int e = 0; e < block.numI() - 2; e++)
dims[e] = INT_ARG(e + 2);
}
else {
auto ax = INPUT_VARIABLE(1);
dims = ax->template asVectorT<int>();
}
for (int e = 0; e < dims.size(); e++)
if (dims[e] < 0)
dims[e] += input->rankOf();
nd4j::ops::helpers::_prefix<T, simdOps::Add<T>>(input, output, dims, exclusive, reverse);
}
return ND4J_STATUS_OK;
}
}
}
#endif | c++ | code | 1,279 | 351 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gtest/gtest.h"
#include "mozilla/DataStorage.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsNetUtil.h"
#include "nsPrintfCString.h"
#include "nsStreamUtils.h"
#include "prtime.h"
using namespace mozilla;
class psm_DataStorageTest : public ::testing::Test {
protected:
void SetUp() override {
const ::testing::TestInfo* const testInfo =
::testing::UnitTest::GetInstance()->current_test_info();
NS_ConvertUTF8toUTF16 testName(testInfo->name());
storage = DataStorage::GetFromRawFileName(testName);
storage->Init(nullptr);
}
RefPtr<DataStorage> storage;
};
constexpr auto testKey = "test"_ns;
constexpr auto testValue = "value"_ns;
constexpr auto privateTestValue = "private"_ns;
TEST_F(psm_DataStorageTest, GetPutRemove) {
// Test Put/Get on Persistent data
EXPECT_EQ(NS_OK, storage->Put(testKey, testValue, DataStorage_Persistent));
// Don't re-use testKey / testValue here, to make sure that this works as
// expected with objects that have the same semantic value but are not
// literally the same object.
nsCString result = storage->Get("test"_ns, DataStorage_Persistent);
EXPECT_STREQ("value", result.get());
// Get on Temporary/Private data with the same key should give nothing
result = storage->Get(testKey, DataStorage_Temporary);
EXPECT_TRUE(result.IsEmpty());
result = storage->Get(testKey, DataStorage_Private);
EXPECT_TRUE(result.IsEmpty());
// Put with Temporary/Private data shouldn't affect Persistent data
constexpr auto temporaryTestValue = "temporary"_ns;
EXPECT_EQ(NS_OK,
storage->Put(testKey, temporaryTestValue, DataStorage_Temporary));
EXPECT_EQ(NS_OK,
storage->Put(testKey, privateTestValue, DataStorage_Private));
result = storage->Get(testKey, DataStorage_Temporary);
EXPECT_STREQ("temporary", result.get());
result = storage->Get(testKey, DataStorage_Private);
EXPECT_STREQ("private", result.get());
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ("value", result.get());
// Put of a previously-present key overwrites it (if of the same type)
constexpr auto newValue = "new"_ns;
EXPECT_EQ(NS_OK, storage->Put(testKey, newValue, DataStorage_Persistent));
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ("new", result.get());
// Removal should work
storage->Remove(testKey, DataStorage_Temporary);
result = storage->Get(testKey, DataStorage_Temporary);
EXPECT_TRUE(result.IsEmpty());
// But removing one type shouldn't affect the others
result = storage->Get(testKey, DataStorage_Private);
EXPECT_STREQ("private", result.get());
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ("new", result.get());
// Test removing the other types as well
storage->Remove(testKey, DataStorage_Private);
result = storage->Get(testKey, DataStorage_Private);
EXPECT_TRUE(result.IsEmpty());
storage->Remove(testKey, DataStorage_Persistent);
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_TRUE(result.IsEmpty());
}
TEST_F(psm_DataStorageTest, InputValidation) {
// Keys may not have tabs or newlines
EXPECT_EQ(NS_ERROR_INVALID_ARG,
storage->Put("key\thas tab"_ns, testValue, DataStorage_Persistent));
nsCString result = storage->Get("key\thas tab"_ns, DataStorage_Persistent);
EXPECT_TRUE(result.IsEmpty());
EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put("key has\nnewline"_ns, testValue,
DataStorage_Persistent));
result = storage->Get("keyhas\nnewline"_ns, DataStorage_Persistent);
EXPECT_TRUE(result.IsEmpty());
// Values may not have newlines
EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put(testKey, "value\nhas newline"_ns,
DataStorage_Persistent));
result = storage->Get(testKey, DataStorage_Persistent);
// Values may have tabs
EXPECT_TRUE(result.IsEmpty());
EXPECT_EQ(NS_OK, storage->Put(testKey, "val\thas tab; this is ok"_ns,
DataStorage_Persistent));
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ("val\thas tab; this is ok", result.get());
nsCString longKey("a");
for (int i = 0; i < 8; i++) {
longKey.Append(longKey);
}
// A key of length 256 will work
EXPECT_EQ(NS_OK, storage->Put(longKey, testValue, DataStorage_Persistent));
result = storage->Get(longKey, DataStorage_Persistent);
EXPECT_STREQ("value", result.get());
longKey.AppendLiteral("a");
// A key longer than that will not work
EXPECT_EQ(NS_ERROR_INVALID_ARG,
storage->Put(longKey, testValue, DataStorage_Persistent));
result = storage->Get(longKey, DataStorage_Persistent);
EXPECT_TRUE(result.IsEmpty());
nsCString longValue("a");
for (int i = 0; i < 10; i++) {
longValue.Append(longValue);
}
// A value of length 1024 will work
EXPECT_EQ(NS_OK, storage->Put(testKey, longValue, DataStorage_Persistent));
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ(longValue.get(), result.get());
longValue.AppendLiteral("a");
// A value longer than that will not work
storage->Remove(testKey, DataStorage_Persistent);
EXPECT_EQ(NS_ERROR_INVALID_ARG,
storage->Put(testKey, longValue, DataStorage_Persistent));
result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_TRUE(result.IsEmpty());
}
TEST_F(psm_DataStorageTest, Eviction) {
// Eviction is on a per-table basis. Tables shouldn't affect each other.
EXPECT_EQ(NS_OK, storage->Put(testKey, testValue, DataStorage_Persistent));
for (int i = 0; i < 1025; i++) {
EXPECT_EQ(NS_OK,
storage->Put(nsPrintfCString("%d", i), nsPrintfCString("%d", i),
DataStorage_Temporary));
nsCString result =
storage->Get(nsPrintfCString("%d", i), DataStorage_Temporary);
EXPECT_STREQ(nsPrintfCString("%d", i).get(), result.get());
}
// We don't know which entry got evicted, but we can count them.
int entries = 0;
for (int i = 0; i < 1025; i++) {
nsCString result =
storage->Get(nsPrintfCString("%d", i), DataStorage_Temporary);
if (!result.IsEmpty()) {
entries++;
}
}
EXPECT_EQ(entries, 1024);
nsCString result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ("value", result.get());
}
TEST_F(psm_DataStorageTest, ClearPrivateData) {
EXPECT_EQ(NS_OK,
storage->Put(testKey, privateTestValue, DataStorage_Private));
nsCString result = storage->Get(testKey, DataStorage_Private);
EXPECT_STREQ("private", result.get());
storage->Observe(nullptr, "last-pb-context-exited", nullptr);
result = storage->Get(testKey, DataStorage_Private);
EXPECT_TRUE(result.IsEmpty());
}
TEST_F(psm_DataStorageTest, Shutdown) {
EXPECT_EQ(NS_OK, storage->Put(testKey, testValue, DataStorage_Persistent));
nsCString result = storage->Get(testKey, DataStorage_Persistent);
EXPECT_STREQ("value", result.get());
// Get "now" (in days) close to when the data was last touched, so we won't
// get intermittent failures with the day not matching.
int64_t microsecondsPerDay = 24 * 60 * 60 * int64_t(PR_USEC_PER_SEC);
int32_t nowInDays = int32_t(PR_Now() / microsecondsPerDay);
// Simulate shutdown.
storage->Observe(nullptr, "profile-before-change", nullptr);
nsCOMPtr<nsIFile> backingFile;
EXPECT_EQ(NS_OK, NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
getter_AddRefs(backingFile)));
const ::testing::TestInfo* const testInfo =
::testing::UnitTest::GetInstance()->current_test_info();
NS_ConvertUTF8toUTF16 testName(testInfo->name());
EXPECT_EQ(NS_OK, backingFile->Append(testName));
nsCOMPtr<nsIInputStream> fileInputStream;
EXPECT_EQ(NS_OK, NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream),
backingFile));
nsCString data;
EXPECT_EQ(NS_OK, NS_ConsumeStream(fileInputStream, UINT32_MAX, data));
// The data will be of the form 'test\t0\t<days since the epoch>\tvalue'
EXPECT_STREQ(nsPrintfCString("test\t0\t%d\tvalue\n", nowInDays).get(),
data.get());
} | c++ | code | 8,544 | 1,878 |
#include <dirent.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <vector>
#include <math.h>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// Done: An example of how to read data from the filesystem
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == kPreNamKey) {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
filestream.close();
return value;
}
// Done: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os;
string kernel;
string version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
stream.close();
return kernel;
}
// BONUS: Update this to use std::filesystem
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
closedir(directory);
return pids;
}
// Done: Read and return the system memory utilization
float LinuxParser::MemoryUtilization() {
string line;
string key;
string value;
string trash;
float memtotal;
float memfree;
std::ifstream filestream(kProcDirectory + kMeminfoFilename);
if (filestream.is_open()){
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value >> trash){
if (key == kMemTotKey){
memtotal = std::stof(value);
}
if (key == kMemFreeKey){
memfree = std::stof(value);
break;
}
}
}
}
filestream.close();
return (memtotal - memfree)/memtotal;
}
// Done: Read and return the system uptime
long int LinuxParser::UpTime() {
string uptime;
long int uptimel;
string line;
std::ifstream stream(kProcDirectory + kUptimeFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> uptime;
uptimel = std::stol(uptime);
}
stream.close();
return uptimel;
}
//Added manually: CPU utilization of process ID
float LinuxParser::CpuUtilization(int pid) {
string value;
string line;
long int utime;
long int stime;
long int cutime;
long int cstime;
long int uptime;
int pos = 0;
int utime_pos = 13;
int stime_pos = 14;
int cutime_pos =15;
int cstime_pos = 16;
float cpu_util = 0;
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> value && pos < 22) {
if (pos == utime_pos) {utime = (std::stol(value));}
if (pos == stime_pos) {stime = (std::stol(value));}
if (pos == cutime_pos) {cutime = (std::stol(value));}
if (pos == cstime_pos) {cstime = (std::stol(value));}
pos++;
}
break;
}
//Problem is that sys uptime is in secs
uptime = LinuxParser::UpTime(pid);
// I used the given Stackoverflow-Link for this calculation
// total = utime + stime
long total_time = utime + stime;
//total with wait = total + cu +cs
long total_time_with_wait = total_time + cutime + cstime;
long total_tww_secs = total_time_with_wait / sysconf(_SC_CLK_TCK);
//Utilization = total with wait / uptime
cpu_util = static_cast<float>(total_tww_secs) / static_cast<float>(uptime);
}
filestream.close();
return cpu_util;
}
int LinuxParser::TotalProcesses() {
string line;
string key;
string value;
int tot_process;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()){
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value){
if (key == kProcKey){
tot_process = std::stoi(value);
break;
}
}
}
}
filestream.close();
return tot_process;
}
// Done: Read and return the number of running processes
int LinuxParser::RunningProcesses() {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()){
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value){
if (key == kProRunKey){
return std::stoi(value);
}
}
}
}
filestream.close();
return std::stoi(value);
}
// Done: Read and return the command associated with a process
string LinuxParser::Command(int pid) {
string pidpath = kProcDirectory + to_string(pid) + kCmdlineFilename;
string line;
std::ifstream stream(pidpath);
if (stream.is_open()) {
std::getline(stream, line);
return line;
}
stream.close();
return line;
}
// Done: Read and return the memory used by a process
string LinuxParser::Ram(int pid) {
string pidpath = kProcDirectory + to_string(pid) + kStatusFilename;
string line;
string key;
string value;
string value_MB_str;
int value_kB;
std::ifstream filestream(pidpath);
if (filestream.is_open()){
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value){
if (key == kVmKey){
value_kB = std::stoi(value);
value_MB_str = to_string(value_kB / 1000);
return value_MB_str;
}
}
}
}
filestream.close();
return value_MB_str;
}
// Done: Read and return the user ID associated with a process
string LinuxParser::Uid(int pid) {
string pidpath = kProcDirectory + to_string(pid) + kStatusFilename;
string line;
string key;
string value;
std::ifstream filestream(pidpath);
if (filestream.is_open()){
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value){
if (key == kUidKey){
return value;
}
}
}
}
filestream.close();
return value;
}
// Done: Read and return the user associated with a process
string LinuxParser::User(int pid) {
string uid = Uid(pid);
string line;
string key;
string value;
std::ifstream filestream(kPasswordPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), 'x', ' ');
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
while (linestream >> value >> key) {
if (key == uid ) {
return value;
}
}
}
}
filestream.close();
return value;
}
// Done: Read and return the uptime of a process
long LinuxParser::UpTime(int pid) {
string pidpath = kProcDirectory + to_string(pid) + kStatFilename;
string line, value;
vector<string> values;
std::ifstream stream(pidpath);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
while (linestream >> value) {
values.push_back(value);
}
}
stream.close();
return UpTime() - stol(values[21])/sysconf(_SC_CLK_TCK);
} | c++ | code | 8,054 | 1,931 |
#include <gtest/gtest.h>
#include <platform.h>
#include <stdio.h>
#include <ast/ast.h>
#include <ast/id_internal.h>
#include <ast/id.h>
#include "util.h"
static void test_id(const char* id, bool expect_pass, int spec)
{
ast_t* node = ast_blank(TK_ID);
ast_set_name(node, id);
pass_opt_t opt;
pass_opt_init(&opt);
bool r = check_id(&opt, node, "test", spec);
pass_opt_done(&opt);
ast_free(node);
if(r != expect_pass)
{
printf("Expected [0x%x] \"%s\" to %s but it %s\n", spec, id,
expect_pass ? "pass" : "fail",
r ? "passed" : "failed");
ASSERT_TRUE(false);
}
}
class IdTest : public testing::Test
{};
TEST_F(IdTest, LeadingUnderscore)
{
DO(test_id("foo", true, 0));
DO(test_id("_foo", false, 0));
DO(test_id("foo", true, ALLOW_LEADING_UNDERSCORE));
DO(test_id("_foo", true, ALLOW_LEADING_UNDERSCORE));
}
TEST_F(IdTest, StartUpperCase)
{
DO(test_id("foo", false, START_UPPER));
DO(test_id("Foo", true, START_UPPER));
DO(test_id("_foo", false, START_UPPER));
DO(test_id("_Foo", false, START_UPPER));
DO(test_id("foo", false, START_UPPER | ALLOW_LEADING_UNDERSCORE));
DO(test_id("Foo", true, START_UPPER | ALLOW_LEADING_UNDERSCORE));
DO(test_id("_foo", false, START_UPPER | ALLOW_LEADING_UNDERSCORE));
DO(test_id("_Foo", true, START_UPPER | ALLOW_LEADING_UNDERSCORE));
}
TEST_F(IdTest, StartLowerCase)
{
DO(test_id("foo", true, START_LOWER));
DO(test_id("Foo", false, START_LOWER));
DO(test_id("_foo", false, START_LOWER));
DO(test_id("_Foo", false, START_LOWER));
DO(test_id("foo", true, START_LOWER | ALLOW_LEADING_UNDERSCORE));
DO(test_id("Foo", false, START_LOWER | ALLOW_LEADING_UNDERSCORE));
DO(test_id("_foo", true, START_LOWER | ALLOW_LEADING_UNDERSCORE));
DO(test_id("_Foo", false, START_LOWER | ALLOW_LEADING_UNDERSCORE));
}
TEST_F(IdTest, StartAnyCase)
{
DO(test_id("foo", true, 0));
DO(test_id("Foo", true, 0));
DO(test_id("_foo", false, 0));
DO(test_id("_Foo", false, 0));
DO(test_id("foo", true, ALLOW_LEADING_UNDERSCORE));
DO(test_id("Foo", true, ALLOW_LEADING_UNDERSCORE));
DO(test_id("_foo", true, ALLOW_LEADING_UNDERSCORE));
DO(test_id("_Foo", true, ALLOW_LEADING_UNDERSCORE));
}
TEST_F(IdTest, ContainUnderscore)
{
DO(test_id("foo_bar", false, 0));
DO(test_id("_foo_bar", false, 0));
DO(test_id("foo_bar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("_foo_bar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("foo_bar", true, ALLOW_UNDERSCORE));
DO(test_id("_foo_bar", false, ALLOW_UNDERSCORE));
DO(test_id("foo_bar", true, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
DO(test_id("_foo_bar", true, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
}
TEST_F(IdTest, DoubleUnderscore)
{
DO(test_id("foo__bar", false, 0));
DO(test_id("__foobar", false, 0));
DO(test_id("__foo__bar", false, 0));
DO(test_id("foo__bar", false, ALLOW_UNDERSCORE));
DO(test_id("__foobar", false, ALLOW_UNDERSCORE));
DO(test_id("__foo__bar", false, ALLOW_UNDERSCORE));
DO(test_id("foo__bar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("__foobar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("__foo__bar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("foo__bar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
DO(test_id("__foobar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
DO(test_id("__foo__bar", false,
ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
}
TEST_F(IdTest, TripleUnderscore)
{
DO(test_id("foo___bar", false, 0));
DO(test_id("___foobar", false, 0));
DO(test_id("___foo___bar", false, 0));
DO(test_id("foo___bar", false, ALLOW_UNDERSCORE));
DO(test_id("___foobar", false, ALLOW_UNDERSCORE));
DO(test_id("___foo___bar", false, ALLOW_UNDERSCORE));
DO(test_id("foo___bar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("___foobar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("___foo___bar", false, ALLOW_LEADING_UNDERSCORE));
DO(test_id("foo___bar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
DO(test_id("___foobar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
DO(test_id("___foo___bar", false,
ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE));
}
TEST_F(IdTest, TrailingUnderscore)
{
DO(test_id("foo_bar", false, 0));
DO(test_id("foobar_", false, 0));
DO(test_id("foo_bar_", false, 0));
DO(test_id("foobar_'", false, 0));
DO(test_id("foo_bar", true, ALLOW_UNDERSCORE));
DO(test_id("foobar_", false, ALLOW_UNDERSCORE));
DO(test_id("foo_bar_", false, ALLOW_UNDERSCORE));
DO(test_id("foobar_'", false, ALLOW_UNDERSCORE));
DO(test_id("foo_bar", true, ALLOW_UNDERSCORE | ALLOW_TICK));
DO(test_id("foobar_", false, ALLOW_UNDERSCORE | ALLOW_TICK));
DO(test_id("foo_bar_", false, ALLOW_UNDERSCORE | ALLOW_TICK));
DO(test_id("foobar_'", false, ALLOW_UNDERSCORE | ALLOW_TICK));
}
TEST_F(IdTest, Prime)
{
DO(test_id("foo", true, 0));
DO(test_id("fo'o", false, 0));
DO(test_id("fo''o", false, 0));
DO(test_id("foo'", false, 0));
DO(test_id("foo''", false, 0));
DO(test_id("foo'''", false, 0));
DO(test_id("foo", true, ALLOW_TICK));
DO(test_id("fo'o", false, ALLOW_TICK));
DO(test_id("fo''o", false, ALLOW_TICK));
DO(test_id("foo'", true, ALLOW_TICK));
DO(test_id("foo''", true, ALLOW_TICK));
DO(test_id("foo'''", true, ALLOW_TICK));
}
TEST_F(IdTest, PrivateName)
{
ASSERT_TRUE(is_name_private("_foo"));
ASSERT_TRUE(is_name_private("_Foo"));
ASSERT_TRUE(is_name_private("$_foo"));
ASSERT_TRUE(is_name_private("$_Foo"));
ASSERT_FALSE(is_name_private("foo"));
ASSERT_FALSE(is_name_private("Foo"));
ASSERT_FALSE(is_name_private("$foo"));
ASSERT_FALSE(is_name_private("$Foo"));
}
TEST_F(IdTest, TypeName)
{
ASSERT_TRUE(is_name_type("Foo"));
ASSERT_TRUE(is_name_type("_Foo"));
ASSERT_TRUE(is_name_type("$Foo"));
ASSERT_TRUE(is_name_type("$_Foo"));
ASSERT_FALSE(is_name_type("foo"));
ASSERT_FALSE(is_name_type("_foo"));
ASSERT_FALSE(is_name_type("$foo"));
ASSERT_FALSE(is_name_type("$_foo"));
}
TEST_F(IdTest, FFIType)
{
ASSERT_TRUE(is_name_ffi("@foo"));
ASSERT_FALSE(is_name_ffi("foo"));
}
TEST_F(IdTest, InternalTypeName)
{
ASSERT_TRUE(is_name_internal_test("$foo"));
ASSERT_TRUE(is_name_internal_test("$_foo"));
ASSERT_TRUE(is_name_internal_test("$Foo"));
ASSERT_TRUE(is_name_internal_test("$_Foo"));
ASSERT_FALSE(is_name_internal_test("foo"));
ASSERT_FALSE(is_name_internal_test("_foo"));
ASSERT_FALSE(is_name_internal_test("Foo"));
ASSERT_FALSE(is_name_internal_test("_Foo"));
} | c++ | code | 6,513 | 1,792 |
#include "graphics/impl/bitmap_loader/stb_bitmap_loader.h"
#ifdef ARK_USE_STB_IMAGE
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include "core/inf/array.h"
#include "core/inf/readable.h"
#include "core/util/log.h"
#include "graphics/base/bitmap.h"
namespace ark {
namespace {
struct STBUserCallback {
sp<Readable> _readable;
bool _eof;
STBUserCallback(const sp<Readable>& readable)
: _readable(readable), _eof(false) {
}
};
static int _stb_read_callback(void* user, char *data,int size)
{
STBUserCallback* u = reinterpret_cast<STBUserCallback*>(user);
return static_cast<int>(u->_readable->read(data, static_cast<uint32_t>(size)));
}
static void _stb_skip_callback(void* user, int n)
{
STBUserCallback* u = reinterpret_cast<STBUserCallback*>(user);
u->_readable->seek(n, SEEK_CUR);
}
static int _stb_eof_callback(void *user)
{
STBUserCallback* u = reinterpret_cast<STBUserCallback*>(user);
return static_cast<int>(u->_eof);
}
class STBImageByteArray : public Array<uint8_t> {
public:
STBImageByteArray(void* array, size_t length)
: _array(array), _length(length) {
}
~STBImageByteArray() {
stbi_image_free(_array);
}
virtual uint8_t* buf() override {
return reinterpret_cast<uint8_t*>(_array);
}
virtual size_t length() override {
return _length;
}
private:
void* _array;
size_t _length;
};
}
STBBitmapLoader::STBBitmapLoader(bool justDecodeBounds)
: _just_decode_bounds(justDecodeBounds)
{
}
bitmap STBBitmapLoader::load(const sp<Readable>& readable)
{
stbi_io_callbacks callback;
callback.read = _stb_read_callback;
callback.skip = _stb_skip_callback;
callback.eof = _stb_eof_callback;
STBUserCallback user(readable);
int width, height, channels;
if(_just_decode_bounds)
{
int ret = stbi_info_from_callbacks(&callback, &user, &width, &height, &channels);
DCHECK(ret, "stbi_info_from_callbacks failure: %s", stbi_failure_reason());
return bitmap::make(width, height, 0, channels, false);
}
uint32_t componentSize = stbi_is_hdr_from_callbacks(&callback, &user) ? 4 : 1;
readable->seek(0, SEEK_SET);
void* bytes = componentSize == 1 ? reinterpret_cast<void*>(stbi_load_from_callbacks(&callback, &user, &width, &height, &channels, 0))
: reinterpret_cast<void*>(stbi_loadf_from_callbacks(&callback, &user, &width, &height, &channels, 0));
DCHECK(bytes, "stbi_load_from_callbacks failure: %s", stbi_failure_reason());
uint32_t stride = width * channels * componentSize;
return bitmap::make(width, height, stride, static_cast<uint8_t>(channels), sp<STBImageByteArray>::make(bytes, stride * height));
}
}
#endif | c++ | code | 2,786 | 572 |
/****************************************************************************
*
* This is a part of CTPPS offline software.
* Authors:
* Jan Kašpar ([email protected])
* Nicola Minafra
* Laurent Forthomme
*
****************************************************************************/
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "FWCore/Framework/interface/Run.h"
#include "DQMServices/Core/interface/DQMOneEDAnalyzer.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "DataFormats/Provenance/interface/EventRange.h"
#include "DataFormats/CTPPSDigi/interface/TotemVFATStatus.h"
#include "DataFormats/CTPPSDigi/interface/TotemFEDInfo.h"
#include "DataFormats/Common/interface/DetSetVector.h"
#include "DataFormats/CTPPSDetId/interface/CTPPSDiamondDetId.h"
#include "DataFormats/CTPPSDigi/interface/CTPPSDiamondDigi.h"
#include "DataFormats/CTPPSReco/interface/CTPPSPixelLocalTrack.h"
#include "DataFormats/CTPPSDetId/interface/CTPPSPixelDetId.h"
#include "DataFormats/CTPPSReco/interface/CTPPSDiamondRecHit.h"
#include "DataFormats/CTPPSReco/interface/CTPPSDiamondLocalTrack.h"
#include "Geometry/VeryForwardGeometryBuilder/interface/CTPPSGeometry.h"
#include "Geometry/Records/interface/VeryForwardRealGeometryRecord.h"
#include <string>
//----------------------------------------------------------------------------------------------------
// Utility for efficiency computations
bool channelAlignedWithTrack(const CTPPSGeometry* geom,
const CTPPSDiamondDetId& detid,
const CTPPSDiamondLocalTrack& localTrack,
const float tolerance = 1) {
const DetGeomDesc* det = geom->getSensor(detid);
const float x_pos = det->translation().x(),
x_width = 2.0 * det->params().at(0); // parameters stand for half the size
return ((x_pos + 0.5 * x_width > localTrack.getX0() - localTrack.getX0Sigma() - tolerance &&
x_pos + 0.5 * x_width < localTrack.getX0() + localTrack.getX0Sigma() + tolerance) ||
(x_pos - 0.5 * x_width > localTrack.getX0() - localTrack.getX0Sigma() - tolerance &&
x_pos - 0.5 * x_width < localTrack.getX0() + localTrack.getX0Sigma() + tolerance) ||
(x_pos - 0.5 * x_width < localTrack.getX0() - localTrack.getX0Sigma() - tolerance &&
x_pos + 0.5 * x_width > localTrack.getX0() + localTrack.getX0Sigma() + tolerance));
}
namespace dds {
struct Cache {
std::unordered_map<unsigned int, std::unique_ptr<TH2F>> hitDistribution2dMap;
std::unordered_map<unsigned int, unsigned long> hitsCounterMap;
};
} // namespace dds
class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer<edm::LuminosityBlockCache<dds::Cache>> {
public:
CTPPSDiamondDQMSource(const edm::ParameterSet&);
~CTPPSDiamondDQMSource() override;
protected:
void dqmBeginRun(const edm::Run&, const edm::EventSetup&) override;
void bookHistograms(DQMStore::IBooker&, const edm::Run&, const edm::EventSetup&) override;
void analyze(const edm::Event&, const edm::EventSetup&) override;
std::shared_ptr<dds::Cache> globalBeginLuminosityBlock(const edm::LuminosityBlock&,
const edm::EventSetup&) const override;
void globalEndLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) override;
void dqmEndRun(const edm::Run&, const edm::EventSetup&) override;
private:
// Constants
static const double SEC_PER_LUMI_SECTION; // Number of seconds per lumisection: used to compute hit rates in Hz
static const int CHANNEL_OF_VFAT_CLOCK; // Channel ID of the VFAT that contains clock data
static const double DISPLAY_RESOLUTION_FOR_HITS_MM; // Bin width of histograms showing hits and tracks (in mm)
static const double INV_DISPLAY_RESOLUTION_FOR_HITS_MM;
static const double HPTDC_BIN_WIDTH_NS; // ns per HPTDC bin
static const int CTPPS_NUM_OF_ARMS;
static const int CTPPS_DIAMOND_STATION_ID;
static const int CTPPS_DIAMOND_RP_ID;
static const int CTPPS_PIXEL_STATION_ID;
static const int CTPPS_NEAR_RP_ID;
static const int CTPPS_FAR_RP_ID;
static const int CTPPS_DIAMOND_NUM_OF_PLANES;
static const int CTPPS_DIAMOND_NUM_OF_CHANNELS;
static const int CTPPS_FED_ID_45;
static const int CTPPS_FED_ID_56;
edm::EDGetTokenT<edm::DetSetVector<TotemVFATStatus>> tokenStatus_;
edm::EDGetTokenT<edm::DetSetVector<CTPPSPixelLocalTrack>> tokenPixelTrack_;
edm::EDGetTokenT<edm::DetSetVector<CTPPSDiamondDigi>> tokenDigi_;
edm::EDGetTokenT<edm::DetSetVector<CTPPSDiamondRecHit>> tokenDiamondHit_;
edm::EDGetTokenT<edm::DetSetVector<CTPPSDiamondLocalTrack>> tokenDiamondTrack_;
edm::EDGetTokenT<std::vector<TotemFEDInfo>> tokenFEDInfo_;
bool excludeMultipleHits_;
double horizontalShiftBwDiamondPixels_;
double horizontalShiftOfDiamond_;
std::vector<std::pair<edm::EventRange, int>> runParameters_;
int centralOOT_;
unsigned int verbosity_;
/// plots related to the whole system
struct GlobalPlots {
GlobalPlots() {}
GlobalPlots(DQMStore::IBooker& ibooker);
};
GlobalPlots globalPlot_;
/// plots related to one Diamond detector package
struct PotPlots {
std::unordered_map<unsigned int, MonitorElement*> activity_per_bx;
MonitorElement* hitDistribution2d = nullptr;
MonitorElement* hitDistribution2d_lumisection = nullptr;
MonitorElement* hitDistribution2dOOT = nullptr;
MonitorElement* hitDistribution2dOOT_le = nullptr;
MonitorElement *activePlanes = nullptr, *activePlanesInclusive = nullptr;
MonitorElement* trackDistribution = nullptr;
MonitorElement* trackDistributionOOT = nullptr;
std::unordered_map<unsigned int, MonitorElement*> pixelTomographyAll;
MonitorElement *leadingEdgeCumulative_both = nullptr, *leadingEdgeCumulative_all = nullptr,
*leadingEdgeCumulative_le = nullptr, *trailingEdgeCumulative_te = nullptr;
MonitorElement *timeOverThresholdCumulativePot = nullptr, *leadingTrailingCorrelationPot = nullptr;
MonitorElement* leadingWithoutTrailingCumulativePot = nullptr;
MonitorElement* ECCheck = nullptr;
MonitorElement* HPTDCErrorFlags_2D = nullptr;
MonitorElement* MHComprensive = nullptr;
// MonitorElement* clock_Digi1_le = nullptr;
// MonitorElement* clock_Digi1_te = nullptr;
// MonitorElement* clock_Digi3_le = nullptr;
// MonitorElement* clock_Digi3_te = nullptr;
unsigned int HitCounter, MHCounter, LeadingOnlyCounter, TrailingOnlyCounter, CompleteCounter;
std::map<int, int> effTriplecountingChMap;
std::map<int, int> effDoublecountingChMap;
MonitorElement* EfficiencyOfChannelsInPot = nullptr;
TH2F pixelTracksMap;
PotPlots() {}
PotPlots(DQMStore::IBooker& ibooker, unsigned int id);
};
std::unordered_map<unsigned int, PotPlots> potPlots_;
int EC_difference_56_, EC_difference_45_;
/// plots related to one Diamond plane
struct PlanePlots {
MonitorElement* digiProfileCumulativePerPlane = nullptr;
MonitorElement* hitProfile = nullptr;
MonitorElement* hit_multiplicity = nullptr;
MonitorElement* pixelTomography_far = nullptr;
MonitorElement* EfficiencyWRTPixelsInPlane = nullptr;
TH2F pixelTracksMapWithDiamonds;
PlanePlots() {}
PlanePlots(DQMStore::IBooker& ibooker, unsigned int id);
};
std::unordered_map<unsigned int, PlanePlots> planePlots_;
/// plots related to one Diamond channel
struct ChannelPlots {
std::unordered_map<unsigned int, MonitorElement*> activity_per_bx;
MonitorElement* HPTDCErrorFlags = nullptr;
MonitorElement *leadingEdgeCumulative_both = nullptr, *leadingEdgeCumulative_le = nullptr,
*trailingEdgeCumulative_te = nullptr;
MonitorElement* TimeOverThresholdCumulativePerChannel = nullptr;
MonitorElement* LeadingTrailingCorrelationPerChannel = nullptr;
MonitorElement* leadingWithoutTrailing = nullptr;
MonitorElement* pixelTomography_far = nullptr;
MonitorElement* hit_rate = nullptr;
unsigned int HitCounter, MHCounter, LeadingOnlyCounter, TrailingOnlyCounter, CompleteCounter;
ChannelPlots() {}
ChannelPlots(DQMStore::IBooker& ibooker, unsigned int id);
};
std::unordered_map<unsigned int, ChannelPlots> channelPlots_;
};
//----------------------------------------------------------------------------------------------------
// Values for all constants
const double CTPPSDiamondDQMSource::SEC_PER_LUMI_SECTION = 23.31;
const int CTPPSDiamondDQMSource::CHANNEL_OF_VFAT_CLOCK = 30;
const double CTPPSDiamondDQMSource::DISPLAY_RESOLUTION_FOR_HITS_MM = 0.1;
const double CTPPSDiamondDQMSource::INV_DISPLAY_RESOLUTION_FOR_HITS_MM = 1. / DISPLAY_RESOLUTION_FOR_HITS_MM;
const double CTPPSDiamondDQMSource::HPTDC_BIN_WIDTH_NS = 25. / 1024;
const int CTPPSDiamondDQMSource::CTPPS_NUM_OF_ARMS = 2;
const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_STATION_ID = 1;
const int CTPPSDiamondDQMSource::CTPPS_PIXEL_STATION_ID = 2;
const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_RP_ID = 6;
const int CTPPSDiamondDQMSource::CTPPS_NEAR_RP_ID = 2;
const int CTPPSDiamondDQMSource::CTPPS_FAR_RP_ID = 3;
const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_PLANES = 4;
const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_CHANNELS = 12;
const int CTPPSDiamondDQMSource::CTPPS_FED_ID_56 = 582;
const int CTPPSDiamondDQMSource::CTPPS_FED_ID_45 = 583;
//----------------------------------------------------------------------------------------------------
CTPPSDiamondDQMSource::GlobalPlots::GlobalPlots(DQMStore::IBooker& ibooker) { ibooker.setCurrentFolder("CTPPS"); }
//----------------------------------------------------------------------------------------------------
CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned int id)
: HitCounter(0),
MHCounter(0),
LeadingOnlyCounter(0),
TrailingOnlyCounter(0),
CompleteCounter(0),
pixelTracksMap("Pixel track maps for efficiency", "Pixel track maps for efficiency", 25, 0, 25, 12, -2, 10) {
std::string path, title;
CTPPSDiamondDetId(id).rpName(path, CTPPSDiamondDetId::nPath);
ibooker.setCurrentFolder(path);
CTPPSDiamondDetId(id).rpName(title, CTPPSDiamondDetId::nFull);
activity_per_bx[0] =
ibooker.book1D("activity per BX 0 25", title + " Activity per BX 0 - 25 ns;Event.BX", 3600, -1.5, 3598. + 0.5);
activity_per_bx[1] =
ibooker.book1D("activity per BX 25 50", title + " Activity per BX 25 - 50 ns;Event.BX", 3600, -1.5, 3598. + 0.5);
activity_per_bx[2] =
ibooker.book1D("activity per BX 50 75", title + " Activity per BX 50 - 75 ns;Event.BX", 3600, -1.5, 3598. + 0.5);
hitDistribution2d = ibooker.book2D("hits in planes",
title + " hits in planes;plane number;x (mm)",
10,
-0.5,
4.5,
19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM,
-0.5,
18.5);
hitDistribution2d_lumisection = ibooker.book2D("hits in planes lumisection",
title + " hits in planes in the last lumisection;plane number;x (mm)",
10,
-0.5,
4.5,
19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM,
-0.5,
18.5);
hitDistribution2dOOT = ibooker.book2D("hits with OOT in planes",
title + " hits with OOT in planes;plane number + 0.25 OOT;x (mm)",
17,
-0.25,
4,
19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM,
-0.5,
18.5);
hitDistribution2dOOT_le = ibooker.book2D("hits with OOT in planes (le only)",
title + " hits with OOT in planes (le only);plane number + 0.25 OOT;x (mm)",
17,
-0.25,
4,
19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM,
-0.5,
18.5);
activePlanes =
ibooker.book1D("active planes", title + " active planes (per event);number of active planes", 6, -0.5, 5.5);
activePlanesInclusive =
ibooker.book1D("active planes inclusive",
title + " active planes, MH and le only included (per event);number of active planes",
6,
-0.5,
5.5);
trackDistribution =
ibooker.book1D("tracks", title + " tracks;x (mm)", 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5);
trackDistributionOOT = ibooker.book2D("tracks with OOT",
title + " tracks with OOT;plane number;x (mm)",
9,
-0.5,
4,
19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM,
-0.5,
18.5);
pixelTomographyAll[0] =
ibooker.book2D("tomography pixel 0 25",
title + " tomography with pixel 0 - 25 ns (all planes);x + 25*plane(mm);y (mm)",
100,
0,
100,
8,
0,
8);
pixelTomographyAll[1] =
ibooker.book2D("tomography pixel 25 50",
title + " tomography with pixel 25 - 50 ns (all planes);x + 25*plane(mm);y (mm)",
100,
0,
100,
8,
0,
8);
pixelTomographyAll[2] =
ibooker.book2D("tomography pixel 50 75",
title + " tomography with pixel 50 - 75 ns (all planes);x + 25*plane(mm);y (mm)",
100,
0,
100,
8,
0,
8);
leadingEdgeCumulative_both = ibooker.book1D(
"leading edge (le and te)", title + " leading edge (le and te) (recHits); leading edge (ns)", 75, 0, 75);
leadingEdgeCumulative_all = ibooker.book1D(
"leading edge (all)", title + " leading edge (with or without te) (DIGIs); leading edge (ns)", 75, 0, 75);
leadingEdgeCumulative_le =
ibooker.book1D("leading edge (le only)", title + " leading edge (le only) (DIGIs); leading edge (ns)", 75, 0, 75);
trailingEdgeCumulative_te = ibooker.book1D(
"trailing edge (te only)", title + " trailing edge (te only) (DIGIs); trailing edge (ns)", 75, 0, 75);
timeOverThresholdCumulativePot =
ibooker.book1D("time over threshold", title + " time over threshold;time over threshold (ns)", 250, -25, 100);
leadingTrailingCorrelationPot =
ibooker.book2D("leading trailing correlation",
title + " leading trailing correlation;leading edge (ns);trailing edge (ns)",
75,
0,
75,
75,
0,
75);
leadingWithoutTrailingCumulativePot =
ibooker.book1D("event category", title + " leading edges without trailing;;%", 3, 0.5, 3.5);
leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel(1, "Leading only");
leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel(2, "Trailing only");
leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel(3, "Both");
ECCheck = ibooker.book1D("optorxEC(8bit) - vfatEC", title + " EC Error;optorxEC-vfatEC", 50, -25, 25);
HPTDCErrorFlags_2D = ibooker.book2D("HPTDC Errors", title + " HPTDC Errors", 16, -0.5, 16.5, 9, -0.5, 8.5);
for (unsigned short error_index = 1; error_index < 16; ++error_index)
HPTDCErrorFlags_2D->getTH2F()->GetXaxis()->SetBinLabel(error_index,
HPTDCErrorFlags::getHPTDCErrorName(error_index - 1).c_str());
HPTDCErrorFlags_2D->getTH2F()->GetXaxis()->SetBinLabel(16, "Wrong EC");
int tmpIndex = 0;
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 18");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 17");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 16");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 15");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 18");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 17");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 16");
HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 15");
MHComprensive =
ibooker.book2D("MH in channels", title + " MH (%) in channels;plane number;ch number", 10, -0.5, 4.5, 14, -1, 13);
EfficiencyOfChannelsInPot =
ibooker.book2D("Efficiency in channels",
title + " Efficiency (%) in channels (diamonds only);plane number;ch number",
10,
-0.5,
4.5,
14,
-1,
13);
// ibooker.setCurrentFolder( path+"/clock/" );
// clock_Digi1_le = ibooker.book1D( "clock1 leading edge", title+" clock1;leading edge (ns)", 250, 0, 25 );
// clock_Digi1_te = ibooker.book1D( "clock1 trailing edge", title+" clock1;trailing edge (ns)", 75, 0, 75 );
// clock_Digi3_le = ibooker.book1D( "clock3 leading edge", title+" clock3;leading edge (ns)", 250, 0, 25 );
// clock_Digi3_te = ibooker.book1D( "clock3 trailing edge", title+" clock3;trailing edge (ns)", 75, 0, 75 );
}
//----------------------------------------------------------------------------------------------------
CTPPSDiamondDQMSource::PlanePlots::PlanePlots(DQMStore::IBooker& ibooker, unsigned int id)
: pixelTracksMapWithDiamonds("Pixel track maps for efficiency with coincidence",
"Pixel track maps for efficiency with coincidence",
25,
0,
25,
12,
-2,
10) {
std::string path, title;
CTPPSDiamondDetId(id).planeName(path, CTPPSDiamondDetId::nPath);
ibooker.setCurrentFolder(path);
CTPPSDiamondDetId(id).planeName(title, CTPPSDiamondDetId::nFull);
digiProfileCumulativePerPlane = ibooker.book1D("digi profile", title + " digi profile; ch number", 12, -0.5, 11.5);
hitProfile = ibooker.book1D(
"hit profile", title + " hit profile;x (mm)", 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5);
hit_multiplicity = ibooker.book1D("channels per plane", title + " channels per plane; ch per plane", 13, -0.5, 12.5);
pixelTomography_far =
ibooker.book2D("tomography pixel", title + " tomography with pixel;x + 25 OOT (mm);y (mm)", 75, 0, 75, 8, 0, 8);
EfficiencyWRTPixelsInPlane =
ibooker.book2D("Efficiency wrt pixels | c++ | code | 20,000 | 3,796 |
/**
* @file ac_controller_software.cpp
* @author Vinicius Pimenta Bernardo ([email protected])
* @brief Host PC software.
* @version 0.1
* @date 2021-04-18
*
* @copyright Copyright (c) 2021
*
*/
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <string.h>
#include "Serial.h"
#include "cJSON.h"
#define COM_PORT "COM3"
// #define TERMINAL_DEBUG
using namespace std;
int main()
{
bool leave = false;
// Serial buffer and params
char incomingData[256] = "";
int dataLength = 255;
int readResult = 0;
// Terminal command issued by user
int userInput = 0;
// Flag to wait for serial comms to end current transaction
int serialWaitingResponse = 0;
// File class and file name
ofstream logFile;
char fileName[9] = "";
// Start and connect to serial port
Serial *SP = new Serial(COM_PORT);
if (SP->IsConnected())
{
cout << "Serial connected" << endl;
}
// User menu on terminal
cout << "--- Host PC (Windows) ---" << endl;
cout << "--- Possible actions:" << endl;
cout << "--- 0. Leave" << endl;
cout << "--- 1. Download events from device" << endl;
cout << "--- 2. List all events" << endl;
cout << "--- 3. Start AC (Remote start button)" << endl;
// Main loop
while (!leave)
{
if (!serialWaitingResponse)
{
// Prompt for user command
cout << "Action: ";
cin >> userInput;
switch (userInput)
{
case 0:
leave = true;
case 1:
// Upload log from board event queue
if (SP->IsConnected())
{
SP->WriteData("u", strlen("u"));
serialWaitingResponse = 1;
cout << "Upload started" << endl;
}
break;
case 2:
cout << "--- 1. Last connected device" << endl;
cout << "--- 2. Enter device id" << endl;
cout << "Option: ";
cin >> userInput;
if (userInput == 1)
{
// See if any device recently uploaded (if fileName already exists)
if (strstr(fileName, ".txt") != NULL)
{
string line;
ifstream myfile;
myfile.open(fileName);
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else
{
cout << "Unable to open file" << endl;
}
}
else
{
cout << "No device found" << endl;
}
}
else if (userInput == 2)
{
int id = 0;
cout << "Type device id (xxxx): ";
cin >> id;
sprintf_s(fileName, "%d.txt", id);
string line;
ifstream myfile;
myfile.open(fileName);
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else
{
cout << "Unable to open file" << endl;
}
}
break;
case 3:
// Simulate button via serial
if (SP->IsConnected())
{
SP->WriteData("b", strlen("b"));
}
break;
default:
break;
}
}
else if (serialWaitingResponse)
{
if (SP->IsConnected())
{
// Read from serial if waiting for response
readResult = SP->ReadData(incomingData, dataLength);
#ifdef TERMINAL_DEBUG
cout << "Bytes read: " << readResult << endl;
#endif
incomingData[readResult] = 0;
// Process response
if (readResult > 0)
{
#ifdef TERMINAL_DEBUG
cout << incomingData << endl;
#endif
if (strstr(incomingData, "isEmpty") != NULL)
{
serialWaitingResponse = 0;
cout << "Upload ended" << endl;
}
else if (strstr(incomingData, "\"id\"") != NULL)
{
// Parse incoming json string
cJSON *dataJSON = cJSON_Parse(incomingData);
cJSON *idJSON = cJSON_GetObjectItem(dataJSON, "id");
cJSON *eventJSON = cJSON_GetObjectItem(dataJSON, "event");
cJSON *stateJSON = cJSON_GetObjectItem(dataJSON, "state");
cJSON *timestampJSON = cJSON_GetObjectItem(dataJSON, "timestamp");
#ifdef TERMINAL_DEBUG
cout << cJSON_Print(dataJSON) << endl;
#endif
// Print in one line
cout << "{";
cout << "\"id\": \"" << idJSON->valuestring << "\"";
cout << ", \"event\": \"" << eventJSON->valuestring << "\"";
cout << ", \"state\": \"" << stateJSON->valuestring << "\"";
cout << ", \"timestamp\": " << timestampJSON->valueint;
cout << "}" << endl;
// Generate file name with device id (xxxx.txt)
sprintf_s(fileName, "%s.txt", idJSON->valuestring);
#ifdef TERMINAL_DEBUG
cout << fileName << endl;
#endif
// Write to file (http://www.cplusplus.com/reference/fstream/ofstream/open/)
logFile.open(fileName, ios_base::app);
if (logFile.is_open())
{
logFile << "{";
logFile << "\"id\": \"" << idJSON->valuestring << "\"";
logFile << ", \"event\": \"" << eventJSON->valuestring << "\"";
logFile << ", \"state\": \"" << stateJSON->valuestring << "\"";
logFile << ", \"timestamp\": " << timestampJSON->valueint;
logFile << "}\n";
logFile.close();
}
else
{
cout << "Failed to open log file" << endl;
}
// Keep uploading until queue is empty
SP->WriteData("u", strlen("u"));
}
}
}
}
Sleep(100);
}
return 0;
} | c++ | code | 7,389 | 1,324 |
/*
==============================================================================
This file is part of the juce_core module of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission to use, copy, modify, and/or distribute this software for any purpose with
or without fee is hereby granted, provided that the above copyright notice and this
permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
All other JUCE modules are covered by a dual GPL/commercial license, so if you are
using any other modules, be sure to check that you also comply with their license.
For more details, visit www.juce.com
==============================================================================
*/
StringPairArray::StringPairArray (const bool ignoreCase_)
: ignoreCase (ignoreCase_)
{
}
StringPairArray::StringPairArray (const StringPairArray& other)
: keys (other.keys),
values (other.values),
ignoreCase (other.ignoreCase)
{
}
StringPairArray::~StringPairArray()
{
}
StringPairArray& StringPairArray::operator= (const StringPairArray& other)
{
keys = other.keys;
values = other.values;
return *this;
}
bool StringPairArray::operator== (const StringPairArray& other) const
{
for (int i = keys.size(); --i >= 0;)
if (other [keys[i]] != values[i])
return false;
return true;
}
bool StringPairArray::operator!= (const StringPairArray& other) const
{
return ! operator== (other);
}
const String& StringPairArray::operator[] (StringRef key) const
{
return values [keys.indexOf (key, ignoreCase)];
}
String StringPairArray::getValue (StringRef key, const String& defaultReturnValue) const
{
const int i = keys.indexOf (key, ignoreCase);
if (i >= 0)
return values[i];
return defaultReturnValue;
}
void StringPairArray::set (const String& key, const String& value)
{
const int i = keys.indexOf (key, ignoreCase);
if (i >= 0)
{
values.set (i, value);
}
else
{
keys.add (key);
values.add (value);
}
}
void StringPairArray::addArray (const StringPairArray& other)
{
for (int i = 0; i < other.size(); ++i)
set (other.keys[i], other.values[i]);
}
void StringPairArray::clear()
{
keys.clear();
values.clear();
}
void StringPairArray::remove (StringRef key)
{
remove (keys.indexOf (key, ignoreCase));
}
void StringPairArray::remove (const int index)
{
keys.remove (index);
values.remove (index);
}
void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
{
ignoreCase = shouldIgnoreCase;
}
String StringPairArray::getDescription() const
{
String s;
for (int i = 0; i < keys.size(); ++i)
{
s << keys[i] << " = " << values[i];
if (i < keys.size())
s << ", ";
}
return s;
}
void StringPairArray::minimiseStorageOverheads()
{
keys.minimiseStorageOverheads();
values.minimiseStorageOverheads();
} | c++ | code | 3,781 | 791 |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
///
///@file Pstreams.cc
///@brief Reading/writing persistent objects
///
///@authors
/// Steven G. Parker,
/// Modified by:
/// Michelle Miller
/// Department of Computer Science
/// University of Utah
///@date April 1994 Modified:
/// Thu Feb 19 17:04:59 MST 1998
///
#include <Core/Persistent/Pstreams.h>
#include <Core/Logging/LoggerInterface.h>
#include <Core/Utils/Legacy/StringUtil.h>
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
#include <teem/air.h>
#include <teem/nrrd.h>
#include <zlib.h>
#endif
#include <string.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef _WIN32
# include <io.h>
#endif
using namespace SCIRun::Core::Logging;
namespace SCIRun {
// BinaryPiostream -- portable
BinaryPiostream::BinaryPiostream(const std::string& filename, Direction dir,
const int& v, LoggerHandle pr)
: Piostream(dir, v, filename, pr),
fp_(nullptr)
{
if (v == -1) // no version given so use PERSISTENT_VERSION
version_ = PERSISTENT_VERSION;
else
version_ = v;
if (dir==Read)
{
fp_ = fopen (filename.c_str(), "rb");
if (!fp_)
{
reporter_->error("Error opening file: " + filename + " for reading.");
err = true;
return;
}
// Old versions had headers of size 12.
if (version() == 1)
{
char hdr[12];
if (!fread(hdr, 1, 12, fp_))
{
reporter_->error("Header read failed.");
err = true;
return;
}
}
else
{
// Versions > 1 have size of 16 to account for endianness in
// header (LIT | BIG).
char hdr[16];
if (!fread(hdr, 1, 16, fp_))
{
reporter_->error("Header read failed.");
err = true;
return;
}
}
}
else
{
fp_ = fopen(filename.c_str(), "wb");
if (!fp_)
{
reporter_->error("Error opening file '" + filename + "' for writing.");
err = true;
return;
}
if (version() > 1)
{
// write out 16 bytes, but we need 17 for \0
char hdr[17];
sprintf(hdr, "SCI\nBIN\n%03d\n%s", version_, endianness());
if (!fwrite(hdr, 1, 16, fp_))
{
reporter_->error("Header write failed.");
err = true;
return;
}
}
else
{
// write out 12 bytes, but we need 13 for \0
char hdr[13];
sprintf(hdr, "SCI\nBIN\n%03d\n", version_);
if (!fwrite(hdr, 1, 13, fp_))
{
reporter_->error("Header write failed.");
err = true;
return;
}
}
}
}
BinaryPiostream::BinaryPiostream(int fd, Direction dir, const int& v,
LoggerHandle pr)
: Piostream(dir, v, "", pr),
fp_(nullptr)
{
if (v == -1) // No version given so use PERSISTENT_VERSION.
version_ = PERSISTENT_VERSION;
else
version_ = v;
if (dir == Read)
{
fp_ = fdopen (fd, "rb");
if (!fp_)
{
reporter_->error("Error opening socket " + to_string(fd) +
" for reading.");
err = true;
return;
}
// Old versions had headers of size 12.
if (version() == 1)
{
char hdr[12];
// read header
if (!fread(hdr, 1, 12, fp_))
{
reporter_->error("Header read failed.");
err = true;
return;
}
}
else
{
// Versions > 1 have size of 16 to account for endianness in
// header (LIT | BIG).
char hdr[16];
if (!fread(hdr, 1, 16, fp_))
{
reporter_->error("Header read failed.");
err = true;
return;
}
}
}
else
{
fp_ = fdopen(fd, "wb");
if (!fp_)
{
reporter_->error("Error opening socket " + to_string(fd) +
" for writing.");
err = true;
return;
}
if (version() > 1)
{
char hdr[16];
sprintf(hdr, "SCI\nBIN\n%03d\n%s", version_, endianness());
if (!fwrite(hdr, 1, 16, fp_))
{
reporter_->error("Header write failed.");
err = true;
return;
}
}
else
{
char hdr[12];
sprintf(hdr, "SCI\nBIN\n%03d\n", version_);
if (!fwrite(hdr, 1, 12, fp_))
{
reporter_->error("Header write failed.");
err = true;
return;
}
}
}
}
BinaryPiostream::~BinaryPiostream()
{
if (fp_) fclose(fp_);
}
void
BinaryPiostream::reset_post_header()
{
if (! reading()) return;
fseek(fp_, 0, SEEK_SET);
if (version() == 1)
{
// Old versions had headers of size 12.
char hdr[12];
// read header
fread(hdr, 1, 12, fp_);
}
else
{
// Versions > 1 have size of 16 to account for endianness in
// header (LIT | BIG).
char hdr[16];
// read header
fread(hdr, 1, 16, fp_);
}
}
const char *
BinaryPiostream::endianness()
{
/// @todo SCIRUN4_CODE_TO_BE_ENABLED_LATER
//if (airMyEndian == airEndianLittle)
return "LIT\n";
//else
//return "BIG\n";
}
template <class T>
inline void
BinaryPiostream::gen_io(T& data, const char *iotype)
{
if (err) return;
if (dir==Read)
{
if (!fread(&data, sizeof(data), 1, fp_))
{
err = true;
reporter_->error(std::string("BinaryPiostream error reading ") +
iotype + ".");
}
}
else
{
if (!fwrite(&data, sizeof(data), 1, fp_))
{
err = true;
reporter_->error(std::string("BinaryPiostream error writing ") +
iotype + ".");
}
}
}
void
BinaryPiostream::io(char& data)
{
if (version() == 1)
{
// xdr_char
int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "char");
}
}
void
BinaryPiostream::io(signed char& data)
{
if (version() == 1)
{
// Wrote as short, still xdr int eventually.
short tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "signed char");
}
}
void
BinaryPiostream::io(unsigned char& data)
{
if (version() == 1)
{
// xdr_u_char
unsigned int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "unsigned char");
}
}
void
BinaryPiostream::io(short& data)
{
if (version() == 1)
{
// xdr_short
int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "short");
}
}
void
BinaryPiostream::io(unsigned short& data)
{
if (version() == 1)
{
// xdr_u_short
unsigned int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "unsigned short");
}
}
void
BinaryPiostream::io(int& data)
{
gen_io(data, "int"); // xdr_int
}
void
BinaryPiostream::io(unsigned int& data)
{
gen_io(data, "unsigned int"); // xdr_u_int
}
void
BinaryPiostream::io(long& data)
{
if (version() == 1)
{
// xdr_long
// Note that xdr treats longs as 4 byte numbers.
int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
// For 32bits for now (we need to update this later in the next
// version of Pio)
int tmp = data;
gen_io(tmp, "long");
data = tmp;
}
}
void
BinaryPiostream::io(unsigned long& data)
{
if (version() == 1)
{
// xdr_u_long
// Note that xdr treats longs as 4 byte numbers.
unsigned int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
// For 32bits for now (we need to update this later in the next
// version of Pio)
unsigned int tmp = data;
gen_io(tmp, "unsigned long");
data = tmp;
}
}
void
BinaryPiostream::io(long long& data)
{
gen_io(data, "long long"); // xdr_longlong_t
}
void
BinaryPiostream::io(unsigned long long& data)
{
gen_io(data, "unsigned long long"); //xdr_u_longlong_t
}
void
BinaryPiostream::io(double& data)
{
gen_io(data, "double"); // xdr_double
}
void
BinaryPiostream::io(float& data)
{
gen_io(data, "float"); // xdr_float
}
void
BinaryPiostream::io(std::string& data)
{
// xdr_wrapstring
if (err) return;
unsigned int chars = 0;
if (dir == Write)
{
if (version() == 1)
{
// An xdr string is 4 byte int for string size, followed by the
// characters without the null termination, then padded back out
// to the 4 byte boundary with zeros.
chars = data.size();
io(chars);
if (!fwrite(data.c_str(), sizeof(char), chars, fp_)) err = true;
// Pad data out to 4 bytes.
int extra = chars % 4;
if (extra)
{
static const char pad[4] = {0, 0, 0, 0};
if (!fwrite(pad, sizeof(char), 4 - extra, fp_)) err = true;
}
}
else
{
const char* p = data.c_str();
chars = static_cast<int>(strlen(p)) + 1;
io(chars);
if (!fwrite(p, sizeof(char), chars, fp_)) err = true;
}
}
if (dir == Read)
{
// Read in size.
io(chars);
if (version() == 1)
{
// Create buffer which is multiple of 4.
int extra = 4 - (chars%4);
if (extra == 4)
extra = 0;
unsigned int buf_size = chars + extra;
data = "";
if (buf_size)
{
char* buf = new char[buf_size];
// Read in data plus padding.
if (!fread(buf, sizeof(char), buf_size, fp_))
{
err = true;
delete [] buf;
return;
}
// Only use actual size of string.
for (unsigned int i=0; i<chars; i++)
data += buf[i];
delete [] buf;
}
}
else
{
char* buf = new char[chars];
fread(buf, sizeof(char), chars, fp_);
data = std::string(buf);
delete[] buf;
}
}
}
bool
BinaryPiostream::block_io(void *data, size_t s, size_t nmemb)
{
if (err || version() == 1) { return false; }
if (dir == Read)
{
const size_t did = fread(data, s, nmemb, fp_);
if (did != nmemb)
{
err = true;
reporter_->error("BinaryPiostream error reading block io.");
}
}
else
{
const size_t did = fwrite(data, s, nmemb, fp_);
if (did != nmemb)
{
err = true;
reporter_->error("BinaryPiostream error writing block io.");
}
}
return true;
}
////
// BinarySwapPiostream -- portable
// Piostream used when endianness of machine and file don't match
BinarySwapPiostream::BinarySwapPiostream(const std::string& filename, Direction dir,
const int& v, LoggerHandle pr)
: BinaryPiostream(filename, dir, v, pr)
{
}
BinarySwapPiostream::BinarySwapPiostream(int fd, Direction dir, const int& v,
LoggerHandle pr)
: BinaryPiostream(fd, dir, v, pr)
{
}
BinarySwapPiostream::~BinarySwapPiostream()
{
}
const char *
BinarySwapPiostream::endianness()
{
/// @todo SCIRUN4_CODE_TO_BE_ENABLED_LATER
//if (airMyEndian == airEndianLittle)
return "LIT\n";
//else
//return "BIG\n";
}
template <class T>
inline void
BinarySwapPiostream::gen_io(T& data, const char *iotype)
{
if (err) return;
if (dir==Read)
{
unsigned char tmp[sizeof(data)];
if (!fread(tmp, sizeof(data), 1, fp_))
{
err = true;
reporter_->error(std::string("BinaryPiostream error reading ") +
iotype + ".");
return;
}
unsigned char *cdata = reinterpret_cast<unsigned char *>(&data);
for (unsigned int i = 0; i < sizeof(data); i++)
{
cdata[i] = tmp[sizeof(data)-i-1];
}
}
else
{
#if 0
unsigned char tmp[sizeof(data)];
unsigned char *cdata = reinterpret_cast<unsigned char *>(&data);
for (unsigned int i = 0; i < sizeof(data); i++)
{
tmp[i] = cdata[sizeof(data)-i-1];
}
if (!fwrite(tmp, sizeof(data), 1, fp_))
{
err = true;
reporter_->error(std::string("BinaryPiostream error writing ") +
iotype + ".");
}
#else
if (!fwrite(&data, sizeof(data), 1, fp_))
{
err = true;
reporter_->error(std::string("BinaryPiostream error writing ") +
iotype + ".");
}
#endif
}
}
void
BinarySwapPiostream::io(short& data)
{
if (version() == 1)
{
// xdr_short
int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "short");
}
}
void
BinarySwapPiostream::io(unsigned short& data)
{
if (version() == 1)
{
// xdr_u_short
unsigned int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "unsigned short");
}
}
void
BinarySwapPiostream::io(int& data)
{
gen_io(data, "int");
}
void
BinarySwapPiostream::io(unsigned int& data)
{
gen_io(data, "unsigned int");
}
void
BinarySwapPiostream::io(long& data)
{
if (version() == 1)
{
// xdr_long
// Note that xdr treats longs as 4 byte numbers.
int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "long");
}
}
void
BinarySwapPiostream::io(unsigned long& data)
{
if (version() == 1)
{
// xdr_u_long
// Note that xdr treats longs as 4 byte numbers.
unsigned int tmp;
tmp = data;
io(tmp);
data = tmp;
}
else
{
gen_io(data, "unsigned long");
}
}
void
BinarySwapPiostream::io(long long& data)
{
gen_io(data, "long long");
}
void
BinarySwapPiostream::io(unsigned long long& data)
{
gen_io(data, "unsigned long long");
}
void
BinarySwapPiostream::io(double& data)
{
gen_io(data, "double");
}
void
BinarySwapPiostream::io(float& data)
{
gen_io(data, "float");
}
TextPiostream::TextPiostream(const std::string& filename, Direction dir,
LoggerHandle pr)
: Piostream(dir, -1, filename, pr),
ownstreams_p_(true)
{
if (dir==Read)
{
ostr=nullptr;
istr=new std::ifstream(filename.c_str());
if (!istr)
{
reporter_->error("Error opening file: " + filename + " for reading.");
err = true;
return;
}
char hdr[12];
istr->read(hdr, 8);
if (!*istr)
{
reporter_->error("Error reading header of file: " + filename);
err = true;
return;
}
int c=8;
while (*istr && c < 12)
{
hdr[c]=istr->get();
if (hdr[c] == '\n')
break;
c++;
}
if (!readHeader(reporter_, filename, hdr, "ASC", version_, file_endian))
{
reporter_->error("Error parsing header of file: " + filename);
err = true;
return;
}
}
else
{
istr=nullptr;
ostr = new std::ofstream(filename.c_str(), std::ios_base::binary | std::ios_base::out);
std::ostream& out=*ostr;
if (!out)
{
reporter_->error("Error opening file: " + filename + " for writing.");
err = true;
return;
}
out << "SCI\nASC\n" << PERSISTENT_VERSION << "\n";
version_ = PERSISTENT_VERSION;
}
}
TextPiostream::TextPiostream(std::istream *strm, LoggerHandle pr)
: Piostream(Read, -1, "", pr),
istr(strm),
ostr(nullptr),
ownstreams_p_(false)
{
char hdr[12];
istr->read(hdr, 8);
if (!*istr)
{
reporter_->error("Error reading header of istream.");
err = true;
return;
}
int c=8;
while (*istr && c < 12)
{
hdr[c]=istr->get();
if (hdr[c] == '\n')
break;
c++;
}
if (!readHeader(reporter_, "istream", hdr, "ASC", version_, file_endian))
{
reporter_->error("Error parsing header of istream.");
err = true;
return;
}
}
TextPiostream::TextPiostream(std::ostream *strm, LoggerHandle pr)
: Piostream(Write, -1, "", pr),
istr(nullptr),
ostr(strm),
ownstreams_p_(false)
{
std::ostream& out=*ostr;
out << "SCI\nASC\n" << PERSISTENT_VERSION << "\n";
version_ = PERSISTENT_VERSION;
}
TextPiostream::~TextPiostream()
{
if (ownstreams_p_)
{
delete istr;
delete ostr;
}
}
void
TextPiostream::reset_post_header()
{
if (! reading()) return;
istr->seekg(0, std::ios::beg);
char hdr[12];
istr->read(hdr, 8);
int c=8;
while (*istr && c < 12)
{
hdr[c]=istr->get();
if (hdr[c] == '\n')
break;
c++;
}
}
void
TextPiostream::ioString(bool do_quotes, std::string& str)
{
if (do_quotes)
{
io(str);
}
else
{
if (dir==Read)
{
char buf[1000];
char* p=buf;
int n=0;
std::istream& in=*istr;
for(;;)
{
char c;
in.get(c);
if (!in)
{
reporter_->error("String input failed.");
char buf[100];
in.clear();
in.getline(buf, 100);
reporter_->error(std::string("Rest of line is: ") + buf);
err = true;
break;
}
if (c == ' ')
break;
else
*p++=c;
if (n++ > 998)
{
reporter_->error("String too long.");
char buf[100];
in.clear();
in.getline(buf, 100);
reporter_->error(std::string("Rest of line is: ") + buf);
err = true;
break;
}
}
*p=0;
str = std::string(buf);
}
else
{
*ostr << str << " ";
}
}
}
std::string
TextPiostream::peek_class()
{
// if we have the name already do nothing
if (have_peekname_)
{
return peekname_;
}
else
{
expect('{');
ioString(false, peekname_);
have_peekname_ = true;
return peekname_;
}
}
int
TextPiostream::begin_class(const std::string& classname, int current_version)
{
if (err) return -1;
int version = current_version;
std::string gname;
if (dir==Write)
{
gname=classname;
*ostr << '{';
ioString(false, gname);
}
else if (dir==Read && have_peekname_)
{
gname = peekname_;
}
else
{
expect('{');
ioString(false, gname);
}
have_peekname_ = false;
if (dir==Read)
{
}
io(version);
if (dir == Read && version > current_version)
{
err = true;
reporter_->error("File too new. " + classname + " has version " +
to_string(version) +
", but this scirun build is at version " +
to_string(current_version) + ".");
}
return version;
}
void
TextPiostream::end_class()
{
if (err) return;
if (dir==Read)
{
expect('}');
expect('\n');
}
else
{
*ostr << "}\n";
}
}
void
TextPiostream::begin_cheap_delim()
{
if (err) return;
if (dir==Read)
{
expect('{');
}
else
{
*ostr << "{";
}
}
void
TextPiostream::end_cheap_delim()
{
if (err) return;
if (dir==Read)
{
expect('}');
}
else
{
*ostr << "}";
}
}
void
TextPiostream::io(bool& data)
{
if (err) return;
if (dir==Read)
{
std::istream& in=*istr;
in >> data;
if (!in)
{
reporter_->error("Error reading bool.");
char buf[100];
in.clear();
in.getline(buf, 100);
reporter_->error(std::string("Rest of line is: ") + buf);
err = true;
return;
}
next_entry();
}
else
{ | c++ | code | 19,995 | 5,051 |
#pragma once
#include <graphene/chain/protocol/operations.hpp>
#include <graphene/chain/protocol/lua_types.hpp>
#include <graphene/db/generic_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/database.hpp>
#include <lua_extern.hpp>
#include <graphene/chain/protocol/lua_scheduler.hpp>
#include <graphene/chain/protocol/memo.hpp>
#include <graphene/utilities/words.hpp>
#include <fc/crypto/aes.hpp>
#include <graphene/process_encryption/process_encryption_helper.hpp>
namespace graphene
{
namespace chain
{
using namespace process_encryption;
struct register_scheduler;
//nico lua Key_Special
static const std::string Key_Special[] = {"table", "_G", "_VERSION", "coroutine", "debug", "math", "io",
"utf8", "bit", "package", "string", "os", "cjson","baseENV"
#if !defined(LUA_COMPAT_GRAPHENE)
,
"require"
#endif
};
struct contract_base_info;
class contract_object : public graphene::db::abstract_object<contract_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = contract_object_type;
time_point_sec creation_date;
account_id_type owner;
string name;
uint32_t user_invoke_share_percent;
bool is_release=false;
tx_hash_type current_version;
bool check_contract_authority = false;
public_key_type contract_authority;
lua_map contract_data;
lua_map contract_ABI;
contract_bin_code_id_type lua_code_b_id;
public:
contract_object(){};
contract_object(string name):name(name){id=contract_id_type(1);}
void compiling_contract(lua_State *bL, string lua_code,bool is_baseENV=false);
contract_id_type get_id() const { return id; }
optional<lua_types> parse_function_summary(lua_scheduler &context, int index);
lua_table do_contract(string lua_code,lua_State *L=nullptr);
void do_contract_function(account_id_type caller, string function_name, vector<lua_types> value_list,
lua_map &account_data, graphene::chain::database &db, const flat_set<public_key_type> &sigkeys, contract_result &apply_result);
void do_contract_function(account_id_type caller, string function_name, vector<lua_types> value_list,
lua_map &account_data, graphene::chain::database &db, const flat_set<public_key_type> &sigkeys, contract_result &apply_result,contract_id_type contract_id);
void do_actual_contract_function(account_id_type caller, string function_name, vector<lua_types> value_list,
lua_map &account_data, graphene::chain::database &db, const flat_set<public_key_type> &sigkeys, contract_result &apply_result,contract_id_type contract_id);
void set_mode(const transaction_evaluation_state * tx_mode) { trx_state = tx_mode; }
contract_result get_result() { return this->result; }
struct process_variable &get_process_variable() { return _process_value; }
void set_process_value(vector<char> process_value);
vector<char> set_result_process_value();
bool check_contract_authority_falg() { return check_contract_authority; }
void set_process_encryption_helper(const process_encryption_helper helper) {encryption_helper=helper; }
void register_function(lua_scheduler &context, register_scheduler *fc_register,graphene::chain::contract_base_info*base_info)const;
optional<lua_types> get_lua_data(lua_scheduler &context, int index, bool check_fc = false);
void push_global_parameters(lua_scheduler &context, lua_map &global_variable_list, string tablename = "");
void push_table_parameters(lua_scheduler &context, lua_map &table_variable, string tablename);
void push_function_actual_parameters(lua_State *L, vector<lua_types> &value_list);
void get_code(vector<char>&target){target=lua_code_b;lua_code_b.clear();}
void set_code(vector<char>source){FC_ASSERT(source.size()>0); lua_code_b=source;}
private:
process_encryption_helper encryption_helper;
vector<char> lua_code_b;
contract_result result;
const transaction_evaluation_state * trx_state;
struct process_variable _process_value;
};
struct boost_lua_variant_visitor : public boost::static_visitor<lua_types>
{
template <typename T>
lua_types operator()(T t) const { return t; }
};
class account_contract_data : public graphene::db::abstract_object<account_contract_data>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = contract_data_type;
account_id_type owner;
contract_id_type contract_id;
lua_map contract_data;
account_contract_data(){};
contract_data_id_type get_id() const { return id; }
};
struct contract_base_info
{
string name;
string id;
string owner;
string caller;
string creation_date;
string contract_authority;
string invoker_contract_id;
contract_base_info(const contract_object &co, account_id_type caller,object_id_type contract_id)
{
this->name = co.name;
this->id = string(co.id);
object_id_type temp=co.owner;
this->owner =string(temp);
temp=caller;
this->caller = string(temp);
this->creation_date = string(co.creation_date);
this->contract_authority = string(co.contract_authority);
this->invoker_contract_id = string(contract_id);
}
};
/*
class contract_runing_stata : public graphene::db::abstract_object<contract_runing_stata>
{
contract_id_type contract_id;
bool isruning;
fc::time_point_sec last_call_time;
};
*/
#ifdef INCREASE_CONTRACT
/*********************************************合约索引�?**********************************************/
struct by_name;
struct by_owner;
typedef multi_index_container<
contract_object,
indexed_by<
ordered_unique<
tag<by_id>,
member<object, object_id_type, &object::id>>,
ordered_unique<
tag<by_name>,
member<contract_object, string, &contract_object::name>>,
ordered_non_unique<
tag<by_owner>,member<contract_object,account_id_type,&contract_object::owner>>
>
> contract_multi_index_type;
/**
* @ingroup object_index
*/
typedef generic_index<contract_object, contract_multi_index_type> contract_index;
/*********************************************合约数据索引�?**********************************************/
struct by_account_contract
{
};
typedef multi_index_container<
account_contract_data,
indexed_by<
ordered_unique<
tag<by_id>, member<object, object_id_type, &object::id>>,
ordered_unique<
tag<by_account_contract>,
composite_key<
account_contract_data,
member<account_contract_data, account_id_type, &account_contract_data ::owner>,
member<account_contract_data, contract_id_type, &account_contract_data ::contract_id>>>>>
account_contract_data_multi_index_type;
/**
* @ingroup object_index
*/
typedef generic_index<account_contract_data, account_contract_data_multi_index_type> account_contract_data_index;
class contract_bin_code_object: public graphene::db::abstract_object<contract_bin_code_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_contract_bin_code_type;
contract_id_type contract_id;
vector<char> lua_code_b;
};
struct by_contract_id{};
typedef multi_index_container<
contract_bin_code_object,
indexed_by<
ordered_unique<
tag<by_id>, member<object, object_id_type, &object::id>>,
ordered_unique<
tag<by_contract_id>,member<contract_bin_code_object,contract_id_type,&contract_bin_code_object::contract_id>>
>
>
contract_bin_code_multi_index_type;
typedef generic_index<contract_bin_code_object, contract_bin_code_multi_index_type> contract_bin_code_index;
#endif
} // namespace chain
} // namespace graphene
FC_REFLECT_DERIVED(graphene::chain::contract_object,
(graphene::db::object),
(creation_date)(owner)(name)(user_invoke_share_percent)(current_version)(contract_authority)(is_release)(check_contract_authority)(contract_data)(contract_ABI)(lua_code_b_id))
FC_REFLECT_DERIVED(graphene::chain::account_contract_data,
(graphene::db::object),
(owner)(contract_id)(contract_data))
FC_REFLECT_DERIVED(graphene::chain::contract_bin_code_object,(graphene::db::object),(contract_id)(lua_code_b)) | c++ | code | 8,671 | 1,543 |
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#ifndef _RGB2GRAY_OBSERVER_INTERFACE_HH
#define _RGB2GRAY_OBSERVER_INTERFACE_HH
// forward declaration
class Rgb2gray;
class Rgb2grayObserverInterface {
public:
virtual ~Rgb2grayObserverInterface() { }
virtual void on_update_from(const Rgb2gray *subject) = 0;
};
#endif | c++ | code | 844 | 188 |
/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/collective/recv_v2_op.h"
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#include "paddle/fluid/platform/collective_helper.h"
#include "paddle/fluid/platform/nccl_helper.h"
#endif
namespace paddle {
namespace operators {
template <typename T>
class RecvOpV2CUDAKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext &ctx) const override {
#if (defined(PADDLE_WITH_RCCL) || defined(PADDLE_WITH_NCCL)) && \
NCCL_VERSION_CODE >= 2703
int rid = ctx.Attr<int>("ring_id");
PADDLE_ENFORCE_GE(
rid, 0,
platform::errors::InvalidArgument(
"The ring_id (%d) for recv_v2 op must be non-negative.", rid));
int peer = ctx.Attr<int>("peer");
PADDLE_ENFORCE_GE(
peer, 0,
platform::errors::InvalidArgument(
"The peer (%d) for recv_v2 op must be non-negative.", peer));
auto out = ctx.Output<framework::LoDTensor>("Out");
auto out_dims = out->dims();
auto numel = out->numel();
int data_type = ctx.Attr<int>("dtype");
framework::proto::VarType::Type type =
framework::proto::VarType::Type(data_type);
gpuStream_t stream = nullptr;
auto place = ctx.GetPlace();
auto comm = platform::NCCLCommContext::Instance().Get(rid, place);
if (ctx.Attr<bool>("use_calc_stream")) {
auto dev_ctx = platform::DeviceContextPool::Instance().Get(place);
stream = static_cast<platform::CUDADeviceContext *>(dev_ctx)->stream();
} else {
stream = comm->stream();
}
PADDLE_ENFORCE_LT(
peer, comm->nranks(),
platform::errors::InvalidArgument("The value of peer (%d) you set must "
"be less than comm->nranks (%d).",
peer, comm->nranks()));
out->mutable_data<T>(out_dims, place);
ncclDataType_t dtype = platform::ToNCCLDataType(type);
PADDLE_ENFORCE_CUDA_SUCCESS(platform::dynload::ncclRecv(
out->data<T>(), numel, dtype, peer, comm->comm(), stream));
VLOG(3) << "rank " << comm->rank() << " recv "
<< framework::product(out->dims()) << " from " << peer;
#else
PADDLE_THROW(platform::errors::Unavailable(
"PaddlePaddle should be compiled with NCCL and "
"NCCL version >= 2.7.3 is needed."));
#endif
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_CUDA_KERNEL(recv_v2, ops::RecvOpV2CUDAKernel<float>,
ops::RecvOpV2CUDAKernel<double>,
ops::RecvOpV2CUDAKernel<int>,
ops::RecvOpV2CUDAKernel<int64_t>,
ops::RecvOpV2CUDAKernel<plat::float16>); | c++ | code | 3,378 | 747 |
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "async.h"
#include "debug.h"
#include "vector.h"
#include "threadlocal.h"
#include <exception>
#include <map>
#if KJ_USE_FUTEX
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#endif
#if !KJ_NO_RTTI
#include <typeinfo>
#if __GNUC__
#include <cxxabi.h>
#include <stdlib.h>
#endif
#endif
namespace kj {
namespace {
KJ_THREADLOCAL_PTR(EventLoop) threadLocalEventLoop = nullptr;
#define _kJ_ALREADY_READY reinterpret_cast< ::kj::_::Event*>(1)
EventLoop& currentEventLoop() {
EventLoop* loop = threadLocalEventLoop;
KJ_REQUIRE(loop != nullptr, "No event loop is running on this thread.");
return *loop;
}
class BoolEvent: public _::Event {
public:
bool fired = false;
Maybe<Own<_::Event>> fire() override {
fired = true;
return nullptr;
}
};
class YieldPromiseNode final: public _::PromiseNode {
public:
void onReady(_::Event& event) noexcept override {
event.armBreadthFirst();
}
void get(_::ExceptionOrValue& output) noexcept override {
output.as<_::Void>() = _::Void();
}
};
class NeverDonePromiseNode final: public _::PromiseNode {
public:
void onReady(_::Event& event) noexcept override {
// ignore
}
void get(_::ExceptionOrValue& output) noexcept override {
KJ_FAIL_REQUIRE("Not ready.");
}
};
} // namespace
namespace _ { // private
class TaskSetImpl {
public:
inline TaskSetImpl(TaskSet::ErrorHandler& errorHandler)
: errorHandler(errorHandler) {}
~TaskSetImpl() noexcept(false) {
// std::map doesn't like it when elements' destructors throw, so carefully disassemble it.
if (!tasks.empty()) {
Vector<Own<Task>> deleteMe(tasks.size());
for (auto& entry: tasks) {
deleteMe.add(kj::mv(entry.second));
}
}
}
class Task final: public Event {
public:
Task(TaskSetImpl& taskSet, Own<_::PromiseNode>&& nodeParam)
: taskSet(taskSet), node(kj::mv(nodeParam)) {
node->setSelfPointer(&node);
node->onReady(*this);
}
protected:
Maybe<Own<Event>> fire() override {
// Get the result.
_::ExceptionOr<_::Void> result;
node->get(result);
// Delete the node, catching any exceptions.
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
node = nullptr;
})) {
result.addException(kj::mv(*exception));
}
// Call the error handler if there was an exception.
KJ_IF_MAYBE(e, result.exception) {
taskSet.errorHandler.taskFailed(kj::mv(*e));
}
// Remove from the task map.
auto iter = taskSet.tasks.find(this);
KJ_ASSERT(iter != taskSet.tasks.end());
Own<Event> self = kj::mv(iter->second);
taskSet.tasks.erase(iter);
return mv(self);
}
_::PromiseNode* getInnerForTrace() override {
return node;
}
private:
TaskSetImpl& taskSet;
kj::Own<_::PromiseNode> node;
};
void add(Promise<void>&& promise) {
auto task = heap<Task>(*this, kj::mv(promise.node));
Task* ptr = task;
tasks.insert(std::make_pair(ptr, kj::mv(task)));
}
kj::String trace() {
kj::Vector<kj::String> traces;
for (auto& entry: tasks) {
traces.add(entry.second->trace());
}
return kj::strArray(traces, "\n============================================\n");
}
private:
TaskSet::ErrorHandler& errorHandler;
// TODO(perf): Use a linked list instead.
std::map<Task*, Own<Task>> tasks;
};
class LoggingErrorHandler: public TaskSet::ErrorHandler {
public:
static LoggingErrorHandler instance;
void taskFailed(kj::Exception&& exception) override {
KJ_LOG(ERROR, "Uncaught exception in daemonized task.", exception);
}
};
LoggingErrorHandler LoggingErrorHandler::instance = LoggingErrorHandler();
class NullEventPort: public EventPort {
public:
bool wait() override {
KJ_FAIL_REQUIRE("Nothing to wait for; this thread would hang forever.");
}
bool poll() override { return false; }
void wake() const override {
// TODO(someday): Implement using condvar.
kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED,
"Cross-thread events are not yet implemented for EventLoops with no EventPort."));
}
static NullEventPort instance;
};
NullEventPort NullEventPort::instance = NullEventPort();
} // namespace _ (private)
// =======================================================================================
void EventPort::setRunnable(bool runnable) {}
void EventPort::wake() const {
kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED,
"cross-thread wake() not implemented by this EventPort implementation"));
}
EventLoop::EventLoop()
: port(_::NullEventPort::instance),
daemons(kj::heap<_::TaskSetImpl>(_::LoggingErrorHandler::instance)) {}
EventLoop::EventLoop(EventPort& port)
: port(port),
daemons(kj::heap<_::TaskSetImpl>(_::LoggingErrorHandler::instance)) {}
EventLoop::~EventLoop() noexcept(false) {
// Destroy all "daemon" tasks, noting that their destructors might try to access the EventLoop
// some more.
daemons = nullptr;
// The application _should_ destroy everything using the EventLoop before destroying the
// EventLoop itself, so if there are events on the loop, this indicates a memory leak.
KJ_REQUIRE(head == nullptr, "EventLoop destroyed with events still in the queue. Memory leak?",
head->trace()) {
// Unlink all the events and hope that no one ever fires them...
_::Event* event = head;
while (event != nullptr) {
_::Event* next = event->next;
event->next = nullptr;
event->prev = nullptr;
event = next;
}
break;
}
KJ_REQUIRE(threadLocalEventLoop != this,
"EventLoop destroyed while still current for the thread.") {
threadLocalEventLoop = nullptr;
break;
}
}
void EventLoop::run(uint maxTurnCount) {
running = true;
KJ_DEFER(running = false);
for (uint i = 0; i < maxTurnCount; i++) {
if (!turn()) {
break;
}
}
setRunnable(isRunnable());
}
bool EventLoop::turn() {
_::Event* event = head;
if (event == nullptr) {
// No events in the queue.
return false;
} else {
head = event->next;
if (head != nullptr) {
head->prev = &head;
}
depthFirstInsertPoint = &head;
if (tail == &event->next) {
tail = &head;
}
event->next = nullptr;
event->prev = nullptr;
Maybe<Own<_::Event>> eventToDestroy;
{
event->firing = true;
KJ_DEFER(event->firing = false);
eventToDestroy = event->fire();
}
depthFirstInsertPoint = &head;
return true;
}
}
bool EventLoop::isRunnable() {
return head != nullptr;
}
void EventLoop::setRunnable(bool runnable) {
if (runnable != lastRunnableState) {
port.setRunnable(runnable);
lastRunnableState = runnable;
}
}
void EventLoop::enterScope() {
KJ_REQUIRE(threadLocalEventLoop == nullptr, "This thread already has an EventLoop.");
threadLocalEventLoop = this;
}
void EventLoop::leaveScope() {
KJ_REQUIRE(threadLocalEventLoop == this,
"WaitScope destroyed in a different thread than it was created in.") {
break;
}
threadLocalEventLoop = nullptr;
}
namespace _ { // private
void waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, WaitScope& waitScope) {
EventLoop& loop = waitScope.loop;
KJ_REQUIRE(&loop == threadLocalEventLoop, "WaitScope not valid for this thread.");
KJ_REQUIRE(!loop.running, "wait() is not allowed from within event callbacks.");
BoolEvent doneEvent;
node->setSelfPointer(&node);
node->onReady(doneEvent);
loop.running = true;
KJ_DEFER(loop.running = false);
while (!doneEvent.fired) {
if (!loop.turn()) {
// No events in the queue. Wait for callback.
loop.port.wait();
}
}
loop.setRunnable(loop.isRunnable());
node->get(result);
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
node = nullptr;
})) {
result.addException(kj::mv(*exception));
}
}
Promise<void> yield() {
return Promise<void>(false, kj::heap<YieldPromiseNode>());
}
Own<PromiseNode> neverDone() {
return kj::heap<NeverDonePromiseNode>();
}
void NeverDone::wait(WaitScope& waitScope) const {
ExceptionOr<Void> dummy;
waitImpl(neverDone(), dummy, waitScope);
KJ_UNREACHABLE;
}
void detach(kj::Promise<void>&& promise) {
EventLoop& loop = currentEventLoop();
KJ_REQUIRE(loop.daemons.get() != nullptr, "EventLoop is shutting down.") { return; }
loop.daemons->add(kj::mv(promise));
}
Event::Event()
: loop(currentEventLoop()), next(nullptr), prev(nullptr) {}
Event::~Event() noexcept(false) {
if (prev != nullptr) {
if (loop.tail == &next) {
loop.tail = prev;
}
if (loop.depthFirstInsertPoint == &next) {
loop.depthFirstInsertPoint = prev;
}
*prev = next;
if (next != nullptr) {
next->prev = prev;
}
}
KJ_REQUIRE(!firing, "Promise callback destroyed itself.");
KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
"Promise destroyed from a different thread than it was created in.");
}
void Event::armDepthFirst() {
KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
"Event armed from different thread than it was created in. You must use "
"the thread-safe work queue to queue events cross-thread.");
if (prev == nullptr) {
next = *loop.depthFirstInsertPoint;
prev = loop.depthFirstInsertPoint;
*prev = this;
if (next != nullptr) {
next->prev = &next;
}
loop.depthFirstInsertPoint = &next;
if (loop.tail == prev) {
loop.tail = &next;
}
loop.setRunnable(true);
}
}
void Event::armBreadthFirst() {
KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
"Event armed from different thread than it was created in. You must use "
"the thread-safe work queue to queue events cross-thread.");
if (prev == nullptr) {
next = *loop.tail;
prev = loop.tail;
*prev = this;
if (next != nullptr) {
next->prev = &next;
}
loop.tail = &next;
loop.setRunnable(true);
}
}
_::PromiseNode* Event::getInnerForTrace() {
return nullptr;
}
#if !KJ_NO_RTTI
#if __GNUC__
static kj::String demangleTypeName(const char* name) {
int status;
char* buf = abi::__cxa_demangle(name, nullptr, nullptr, &status);
kj::String result = kj::heapString(buf == nullptr ? name : buf);
free(buf);
return kj::mv(result);
}
#else
static kj::String demangleTypeName(const char* name) {
return kj::heapString(name);
}
#endif
#endif
static kj::String traceImpl(Event* event, _::PromiseNode* node) {
#if KJ_NO_RTTI
return heapString("Trace not available because RTTI is disabled.");
#else
kj::Vector<kj::String> trace;
if (event != nullptr) {
trace.add(demangleTypeName(typeid(*event).name()));
}
while (node != nullptr) {
trace.add(demangleTypeName(typeid(*node).name()));
node = node->getInnerForTrace();
}
return strArray(trace, "\n");
#endif
}
kj::String Event::trace() {
return traceImpl(this, getInnerForTrace());
}
} // namespace _ (private)
// =======================================================================================
TaskSet::TaskSet(ErrorHandler& errorHandler)
: impl(heap<_::TaskSetImpl>(errorHandler)) {}
TaskSet::~TaskSet() noexcept(false) {}
void TaskSet::add(Promise<void>&& promise) {
impl->add(kj::mv(promise));
}
kj::String TaskSet::trace() {
return impl->trace();
}
namespace _ { // private
kj::String PromiseBase::trace() {
return traceImpl(nullptr, node);
}
void PromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {}
PromiseNode* PromiseNode::getInnerForTrace() { return nullptr; }
void PromiseNode::OnReadyEvent::init(Event& newEvent) {
if (event == _kJ_ALREADY_READY) {
// A new continuation was added to a promise that was already ready. In this case, we schedule
// breadth-first, to make it difficult for applications to accidentally starve the event loop
// by repeatedly waiting on immediate promises.
newEvent.armBreadthFirst();
} else {
event = &newEvent;
}
}
void PromiseNode::OnReadyEvent::arm() {
if (event == nullptr) {
event = _kJ_ALREADY_READY;
} else {
// A promise resolved and an event is already waiting on it. In this case, arm in depth-first
// order so that the event runs immediately after the current one. This way, chained promises
// execute together for better cache locality and lower latency.
event->armDepthFirst();
}
}
// -------------------------------------------------------------------
ImmediatePromiseNodeBase::ImmediatePromiseNodeBase() {}
ImmediatePromiseNodeBase::~ImmediatePromiseNodeBase() noexcept(false) {}
void ImmediatePromiseNodeBase::onReady(Event& event) noexcept {
event.armBreadthFirst();
}
ImmediateBrokenPromiseNode::ImmediateBrokenPromiseNode(Exception&& exception)
: exception(kj::mv(exception)) {}
void ImmediateBrokenPromiseNode::get(ExceptionOrValue& output) noexcept {
output.exception = kj::mv(exception);
}
// -------------------------------------------------------------------
AttachmentPromiseNodeBase::AttachmentPromiseNodeBase(Own<PromiseNode>&& dependencyParam)
: dependency(kj::mv(dependencyParam)) {
dependency->setSelfPointer(&dependency);
}
void AttachmentPromiseNodeBase::onReady(Event& event) noexcept {
dependency->onReady(event);
}
void AttachmentPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
dependency->get(output);
}
PromiseNode* AttachmentPromiseNodeBase::getInnerForTrace() {
return dependency;
}
void AttachmentPromiseNodeBase::dropDependency() {
dependency = nullptr;
}
// -------------------------------------------------------------------
TransformPromiseNodeBase::TransformPromiseNodeBase(
Own<PromiseNode>&& dependencyParam, void* continuationTracePtr)
: dependency(kj::mv(dependencyParam)), continuationTracePtr(continuationTracePtr) {
dependency->setSelfPointer(&dependency);
}
void TransformPromiseNodeBase::onReady(Event& event) noexcept {
dependency->onReady(event);
}
void TransformPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
getImpl(output);
dropDependency();
})) {
output.addException(kj::mv(*exception));
}
}
PromiseNode* TransformPromiseNodeBase::getInnerForTrace() {
return dependency;
}
void TransformPromiseNodeBase::dropDependency() {
dependency = nullptr;
}
void TransformPromiseNodeBase::getDepResult(ExceptionOrValue& output) {
dependency->get(output);
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
dependency = nullptr;
})) {
output.addException(kj::mv(*exception));
}
KJ_IF_MAYBE(e, output.exception) {
e->addTrace(continuationTracePtr);
}
}
// -------------------------------------------------------------------
ForkBranchBase::ForkBranchBase(Own<ForkHubBase>&& hubParam): hub(kj::mv(hubParam)) {
if (hub->tailBranch == nullptr) {
onReadyEvent.arm();
} else {
// Insert into hub's linked list of branches.
prevPtr = hub->tailBranch;
*prevPtr = this;
next = nullptr;
hub->tailBranch = &next;
}
}
ForkBranchBase::~ForkBranchBase() noexcept(false) {
if (prevPtr != nullptr) {
// Remove from hub's linked list of branches.
*prevPtr = next;
(next == nullptr ? hub->tailBranch : next->prevPtr) = prevPtr;
}
}
void ForkBranchBase::hubReady() noexcept {
onReadyEvent.arm();
}
void ForkBranchBase::releaseHub(ExceptionOrValue& output) {
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
hub = nullptr;
})) {
output.addException(kj::mv(*exception));
}
}
void ForkBranchBase::onReady(Event& event) noexcept {
onReadyEvent.init(event);
}
PromiseNode* ForkBranchBase::getInnerForTrace() {
return hub->getInnerForTrace();
}
// -------------------------------------------------------------------
ForkHubBase::ForkHubBase(Own<PromiseNode>&& innerParam, ExceptionOrValue& resultRef)
: inner(kj::mv(innerParam)), resultRef(resultRef) {
inner->setSelfPointer(&inner);
inner->onReady(*this);
}
Maybe<Own<Event>> ForkHubBase::fire() {
// Dependency is ready. Fetch its result and then delete the node.
inner->get(resultRef);
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
inner = nullptr;
})) {
resultRef.addException(kj::mv(*exception));
}
for (auto branch = headBranch; branch != nullptr; branch = branch->next) {
branch->hubReady();
*branch->prevPtr = nullptr;
branch->prevPtr = nullptr;
}
*tailBranch = nullptr;
// Indicate that the list is no longer active.
tailBranch = nullptr;
return nullptr;
}
_::PromiseNode* ForkHubBase::getInnerForTrace() {
return inner;
}
// -------------------------------------------------------------------
ChainPromiseNode::ChainPromiseNode(Own<PromiseNode> innerParam)
: state(STEP1), inner(kj::mv(innerParam)) {
inner->setSelfPointer(&inner);
inner->onReady(*this);
}
ChainPromiseNode::~ChainPromiseNode() noexcept(false) {}
void ChainPromiseNode::onReady(Event& event) noexcept {
switch (state) {
case STEP1:
KJ_REQUIRE(onReadyEvent == nullptr, "onReady() can only be called once.");
onReadyEvent = &event;
return;
case STEP2:
inner->onReady(event);
return;
}
KJ_UNREACHABLE;
}
void ChainPromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {
if (state == STEP2) {
*selfPtr = kj::mv(inner); // deletes this!
selfPtr->get()->setSelfPointer(selfPtr);
} else {
this->selfPtr = selfPtr;
}
}
void ChainPromiseNode::get(ExceptionOrValue& output) noexcept {
KJ_REQUIRE(state == STEP2);
return inner->get(output);
}
PromiseNode* ChainPromiseNode::getInnerForTrace() {
return inner;
}
Maybe<Own<Event>> ChainPromiseNode::fire() {
KJ_REQUIRE(state != STEP2);
static_assert(sizeof(Promise<int>) == sizeof(PromiseBase),
"This code assumes Promise<T> does not add any new members to PromiseBase.");
ExceptionOr<PromiseBase> intermediate;
inner->get(intermediate);
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
inner = nullptr;
})) {
intermediate.addException(kj::mv(*exception));
}
KJ_IF_MAYBE(exception, intermediate.exception) {
// There is an exception. If there is also a value, delete it.
kj::runCatchingExceptions([&]() { intermediate.value = nullptr; });
// Now set step2 to a rejected promise.
inner = heap<ImmediateBrokenPromiseNode>(kj::mv(*exception));
} else KJ_IF_MAYBE(value, intermediate.value) {
// There is a value and no exception. The value is itself a promise. Adopt it as our
// step2.
inner = kj:: | c++ | code | 20,000 | 4,733 |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdb/v20170320/model/SellConfig.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
SellConfig::SellConfig() :
m_deviceHasBeenSet(false),
m_typeHasBeenSet(false),
m_cdbTypeHasBeenSet(false),
m_memoryHasBeenSet(false),
m_cpuHasBeenSet(false),
m_volumeMinHasBeenSet(false),
m_volumeMaxHasBeenSet(false),
m_volumeStepHasBeenSet(false),
m_connectionHasBeenSet(false),
m_qpsHasBeenSet(false),
m_iopsHasBeenSet(false),
m_infoHasBeenSet(false),
m_statusHasBeenSet(false),
m_tagHasBeenSet(false),
m_deviceTypeHasBeenSet(false),
m_deviceTypeNameHasBeenSet(false),
m_engineTypeHasBeenSet(false)
{
}
CoreInternalOutcome SellConfig::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Device") && !value["Device"].IsNull())
{
if (!value["Device"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Device` IsString=false incorrectly").SetRequestId(requestId));
}
m_device = string(value["Device"].GetString());
m_deviceHasBeenSet = true;
}
if (value.HasMember("Type") && !value["Type"].IsNull())
{
if (!value["Type"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Type` IsString=false incorrectly").SetRequestId(requestId));
}
m_type = string(value["Type"].GetString());
m_typeHasBeenSet = true;
}
if (value.HasMember("CdbType") && !value["CdbType"].IsNull())
{
if (!value["CdbType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.CdbType` IsString=false incorrectly").SetRequestId(requestId));
}
m_cdbType = string(value["CdbType"].GetString());
m_cdbTypeHasBeenSet = true;
}
if (value.HasMember("Memory") && !value["Memory"].IsNull())
{
if (!value["Memory"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Memory` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_memory = value["Memory"].GetInt64();
m_memoryHasBeenSet = true;
}
if (value.HasMember("Cpu") && !value["Cpu"].IsNull())
{
if (!value["Cpu"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Cpu` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_cpu = value["Cpu"].GetInt64();
m_cpuHasBeenSet = true;
}
if (value.HasMember("VolumeMin") && !value["VolumeMin"].IsNull())
{
if (!value["VolumeMin"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.VolumeMin` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_volumeMin = value["VolumeMin"].GetInt64();
m_volumeMinHasBeenSet = true;
}
if (value.HasMember("VolumeMax") && !value["VolumeMax"].IsNull())
{
if (!value["VolumeMax"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.VolumeMax` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_volumeMax = value["VolumeMax"].GetInt64();
m_volumeMaxHasBeenSet = true;
}
if (value.HasMember("VolumeStep") && !value["VolumeStep"].IsNull())
{
if (!value["VolumeStep"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.VolumeStep` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_volumeStep = value["VolumeStep"].GetInt64();
m_volumeStepHasBeenSet = true;
}
if (value.HasMember("Connection") && !value["Connection"].IsNull())
{
if (!value["Connection"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Connection` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_connection = value["Connection"].GetInt64();
m_connectionHasBeenSet = true;
}
if (value.HasMember("Qps") && !value["Qps"].IsNull())
{
if (!value["Qps"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Qps` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_qps = value["Qps"].GetInt64();
m_qpsHasBeenSet = true;
}
if (value.HasMember("Iops") && !value["Iops"].IsNull())
{
if (!value["Iops"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Iops` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_iops = value["Iops"].GetInt64();
m_iopsHasBeenSet = true;
}
if (value.HasMember("Info") && !value["Info"].IsNull())
{
if (!value["Info"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Info` IsString=false incorrectly").SetRequestId(requestId));
}
m_info = string(value["Info"].GetString());
m_infoHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Status` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_status = value["Status"].GetInt64();
m_statusHasBeenSet = true;
}
if (value.HasMember("Tag") && !value["Tag"].IsNull())
{
if (!value["Tag"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.Tag` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_tag = value["Tag"].GetInt64();
m_tagHasBeenSet = true;
}
if (value.HasMember("DeviceType") && !value["DeviceType"].IsNull())
{
if (!value["DeviceType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.DeviceType` IsString=false incorrectly").SetRequestId(requestId));
}
m_deviceType = string(value["DeviceType"].GetString());
m_deviceTypeHasBeenSet = true;
}
if (value.HasMember("DeviceTypeName") && !value["DeviceTypeName"].IsNull())
{
if (!value["DeviceTypeName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.DeviceTypeName` IsString=false incorrectly").SetRequestId(requestId));
}
m_deviceTypeName = string(value["DeviceTypeName"].GetString());
m_deviceTypeNameHasBeenSet = true;
}
if (value.HasMember("EngineType") && !value["EngineType"].IsNull())
{
if (!value["EngineType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `SellConfig.EngineType` IsString=false incorrectly").SetRequestId(requestId));
}
m_engineType = string(value["EngineType"].GetString());
m_engineTypeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void SellConfig::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_deviceHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Device";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_device.c_str(), allocator).Move(), allocator);
}
if (m_typeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Type";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator);
}
if (m_cdbTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CdbType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_cdbType.c_str(), allocator).Move(), allocator);
}
if (m_memoryHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Memory";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_memory, allocator);
}
if (m_cpuHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Cpu";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_cpu, allocator);
}
if (m_volumeMinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VolumeMin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_volumeMin, allocator);
}
if (m_volumeMaxHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VolumeMax";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_volumeMax, allocator);
}
if (m_volumeStepHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VolumeStep";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_volumeStep, allocator);
}
if (m_connectionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Connection";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_connection, allocator);
}
if (m_qpsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Qps";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_qps, allocator);
}
if (m_iopsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Iops";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_iops, allocator);
}
if (m_infoHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Info";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_info.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_status, allocator);
}
if (m_tagHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tag";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_tag, allocator);
}
if (m_deviceTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeviceType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_deviceType.c_str(), allocator).Move(), allocator);
}
if (m_deviceTypeNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeviceTypeName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_deviceTypeName.c_str(), allocator).Move(), allocator);
}
if (m_engineTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EngineType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_engineType.c_str(), allocator).Move(), allocator);
}
}
string SellConfig::GetDevice() const
{
return m_device;
}
void SellConfig::SetDevice(const string& _device)
{
m_device = _device;
m_deviceHasBeenSet = true;
}
bool SellConfig::DeviceHasBeenSet() const
{
return m_deviceHasBeenSet;
}
string SellConfig::GetType() const
{
return m_type;
}
void SellConfig::SetType(const string& _type)
{
m_type = _type;
m_typeHasBeenSet = true;
}
bool SellConfig::TypeHasBeenSet() const
{
return m_typeHasBeenSet;
}
string SellConfig::GetCdbType() const
{
return m_cdbType;
}
void SellConfig::SetCdbType(const string& _cdbType)
{
m_cdbType = _cdbType;
m_cdbTypeHasBeenSet = true;
}
bool SellConfig::CdbTypeHasBeenSet() const
{
return m_cdbTypeHasBeenSet;
}
int64_t SellConfig::GetMemory() const
{
return m_memory;
}
void SellConfig::SetMemory(const int64_t& _memory)
{
m_memory = _memory;
m_memoryHasBeenSet = true;
}
bool SellConfig::MemoryHasBeenSet() const
{
return m_memoryHasBeenSet;
}
int64_t SellConfig::GetCpu() const
{
return m_cpu;
}
void SellConfig::SetCpu(const int64_t& _cpu)
{
m_cpu = _cpu;
m_cpuHasBeenSet = true;
}
bool SellConfig::CpuHasBeenSet() const
{
return m_cpuHasBeenSet;
}
int64_t SellConfig::GetVolumeMin() const
{
return m_volumeMin;
}
void SellConfig::SetVolumeMin(const int64_t& _volumeMin)
{
m_volumeMin = _volumeMin;
m_volumeMinHasBeenSet = true;
}
bool SellConfig::VolumeMinHasBeenSet() const
{
return m_volumeMinHasBeenSet;
}
int64_t SellConfig::GetVolumeMax() const
{
return m_volumeMax;
}
void SellConfig::SetVolumeMax(const int64_t& _volumeMax)
{
m_volumeMax = _volumeMax;
m_volumeMaxHasBeenSet = true;
}
bool SellConfig::VolumeMaxHasBeenSet() const
{
return m_volumeMaxHasBeenSet;
}
int64_t SellConfig::GetVolumeStep() const
{
return m_volumeStep;
}
void SellConfig::SetVolumeStep(const int64_t& _volumeStep)
{
m_volumeStep = _volumeStep;
m_volumeStepHasBeenSet = true;
}
bool SellConfig::VolumeStepHasBeenSet() const
{
return m_volumeStepHasBeenSet;
}
int64_t SellConfig::GetConnection() const
{
return m_connection;
}
void SellConfig::SetConnection(const int64_t& _connection)
{
m_connection = _connection;
m_connectionHasBeenSet = true;
}
bool SellConfig::ConnectionHasBeenSet() const
{
return m_connectionHasBeenSet;
}
int64_t SellConfig::GetQps() const
{
return m_qps;
}
void SellConfig::SetQps(const int64_t& _qps)
{
m_qps = _qps;
m_qpsHasBeenSet = true;
}
bool SellConfig::QpsHasBeenSet() const
{
return m_qpsHasBeenSet;
}
int64_t SellConfig::GetIops() const
{
return m_iops;
}
void SellConfig::SetIops(const int64_t& _iops)
{
m_iops = _iops;
m_iopsHasBeenSet = true;
}
bool SellConfig::IopsHasBeenSet() const
{
return m_iopsHasBeenSet;
}
string SellConfig::GetInfo() const
{
return m_info;
}
void SellConfig::SetInfo(const string& _info)
{
m_info = _info;
m_infoHasBeenSet = true;
}
bool SellConfig::InfoHasBeenSet() const
{
return m_infoHasBeenSet;
}
int64_t SellConfig::GetStatus() const
{
return m_status;
}
void SellConfig::SetStatus(const int64_t& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool SellConfig::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
int64_t SellConfig::GetTag() const
{
return m_tag;
}
void SellConfig::SetTag(const int64_t& _tag)
{
m_tag = _tag;
m_tagHasBeenSet = true;
}
bool SellConfig::TagHasBeenSet() const
{
return m_tagHasBeenSet;
}
string SellConfig::GetDeviceType() const
{
return m_deviceType;
}
void SellConfig::SetDeviceType(const string& _deviceType)
{
m_deviceType = _deviceType;
m_deviceTypeHasBeenSet = true;
}
bool SellConfig::DeviceTypeHasBeenSet() const
{
return m_deviceTypeHasBeenSet;
}
string SellConfig::GetDeviceTypeName() const
{
return m_deviceTypeName;
}
void SellConfig::SetDeviceTypeName(const string& _deviceTypeName)
{
m_deviceTypeName = _deviceTypeName;
m_deviceTypeNameHasBeenSet = true;
}
bool SellConfig::DeviceTypeNameHasBeenSet() const
{
return m_deviceTypeNameHasBeenSet;
}
string SellConfig::GetEngineType() const
{
return m_engineType;
}
void SellConfig::SetEngineType(const string& _engineType)
{
m_engineType = _engineType;
m_engineTypeHasBeenSet = true;
}
bool SellConfig::EngineTypeHasBeenSet() const
{
return m_engineTypeHasBeenSet;
} | c++ | code | 16,511 | 3,479 |
#include "datastore.h"
#include "datastore_p.h"
#include "defaults_p.h"
#include <QtJsonSerializer/QJsonSerializer>
#include "signal_private_connect_p.h"
using namespace QtDataSync;
using std::function;
DataStore::DataStore(QObject *parent) :
DataStore{DefaultSetup, parent}
{}
DataStore::DataStore(const QString &setupName, QObject *parent) :
QObject{parent},
d{nullptr}
{
initStore(setupName);
}
DataStore::DataStore(QObject *parent, void *) :
QObject{parent},
d{nullptr}
{}
void DataStore::initStore(const QString &setupName)
{
d.reset(new DataStorePrivate(this, setupName));
connect(d->store, &LocalStore::dataChanged,
this, [this](const ObjectKey &key, bool deleted) {
emit dataChanged(QMetaType::type(key.typeName), key.id, deleted, {});
});
connect(d->store, &LocalStore::dataResetted,
this, PSIG(&DataStore::dataResetted));
}
DataStore::~DataStore() = default;
qint64 DataStore::count(int metaTypeId) const //MAJOR change to uint
{
return static_cast<qint64>(d->store->count(d->typeName(metaTypeId)));
}
QStringList DataStore::keys(int metaTypeId) const
{
return d->store->keys(d->typeName(metaTypeId));
}
QVariantList DataStore::loadAll(int metaTypeId) const
{
const auto allData = d->store->loadAll(d->typeName(metaTypeId));
QVariantList resList;
resList.reserve(allData.size());
for(const auto &val : allData)
resList.append(d->serializer->deserialize(val, metaTypeId));
return resList;
}
QVariant DataStore::load(int metaTypeId, const QString &key) const
{
auto data = d->store->load({d->typeName(metaTypeId), key});
return d->serializer->deserialize(data, metaTypeId);
}
void DataStore::save(int metaTypeId, QVariant value)
{
auto typeName = d->typeName(metaTypeId);
if(!value.convert(metaTypeId))
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Failed to convert passed variant to the target type"));
auto meta = QMetaType::metaObjectForType(metaTypeId);
if(!meta)
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a meta object"));
auto userProp = meta->userProperty();
if(!userProp.isValid())
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a user property"));
QString key;
auto flags = QMetaType::typeFlags(metaTypeId);
if(flags.testFlag(QMetaType::IsGadget))
key = userProp.readOnGadget(value.data()).toString();
else if(flags.testFlag(QMetaType::PointerToQObject))
key = userProp.read(value.value<QObject*>()).toString();
else if(flags.testFlag(QMetaType::SharedPointerToQObject))
key = userProp.read(value.value<QSharedPointer<QObject>>().data()).toString();
else if(flags.testFlag(QMetaType::WeakPointerToQObject))
key = userProp.read(value.value<QWeakPointer<QObject>>().data()).toString();
else if(flags.testFlag(QMetaType::TrackingPointerToQObject))
key = userProp.read(value.value<QPointer<QObject>>().data()).toString();
else
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type is neither a gadget nor a pointer to an object"));
if(key.isEmpty())
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Failed to convert USER property to a string"));
auto json = d->serializer->serialize(value);
if(!json.isObject())
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Serialization converted to invalid json type. Only json objects are allowed"));
d->store->save({typeName, key}, json.toObject());
}
bool DataStore::remove(int metaTypeId, const QString &key)
{
return d->store->remove({d->typeName(metaTypeId), key});
}
void DataStore::update(int metaTypeId, QObject *object) const
{
auto typeName = d->typeName(metaTypeId);
auto meta = QMetaType::metaObjectForType(metaTypeId);
if(!meta)
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a meta object"));
auto userProp = meta->userProperty();
if(!userProp.isValid())
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a user property"));
auto key = userProp.read(object).toString();
if(key.isEmpty())
throw InvalidDataException(d->defaults, typeName, QStringLiteral("Failed to convert user property value to a string"));
if(!object->metaObject()->inherits(meta)) {
throw InvalidDataException(d->defaults,
typeName,
QStringLiteral("Passed object of type %1 does not inherit the given meta type")
.arg(QString::fromUtf8(object->metaObject()->className())));
}
auto nObj = load(metaTypeId, key).value<QObject*>();
for(auto i = 0; i < meta->propertyCount(); i++) {
auto prop = meta->property(i);
prop.write(object, prop.read(nObj));
}
nObj->deleteLater();
}
QVariantList DataStore::search(int metaTypeId, const QString &query, SearchMode mode) const
{
const auto dataList= d->store->find(d->typeName(metaTypeId), query, mode);
QVariantList resList;
resList.reserve(dataList.size());
for(const auto &val : dataList)
resList.append(d->serializer->deserialize(val, metaTypeId));
return resList;
}
void DataStore::iterate(int metaTypeId, const function<bool (QVariant)> &iterator) const
{
for(const auto &key : keys(metaTypeId)) {
if(!iterator(load(metaTypeId, key)))
break;
}
}
void DataStore::clear(int metaTypeId)
{
d->store->clear(d->typeName(metaTypeId));
}
// ------------- PRIVATE IMPLEMENTATION -------------
DataStorePrivate::DataStorePrivate(DataStore *q, const QString &setupName) :
defaults{DefaultsPrivate::obtainDefaults(setupName)},
logger{defaults.createLogger("datastore", q)},
serializer{defaults.serializer()},
store{new LocalStore(defaults, q)}
{}
QByteArray DataStorePrivate::typeName(int metaTypeId) const
{
auto name = QMetaType::typeName(metaTypeId);
if(name)
return name;
else
throw InvalidDataException(defaults, "type_" + QByteArray::number(metaTypeId), QStringLiteral("Not a valid metatype id"));
}
// ------------- Exceptions -------------
DataStoreException::DataStoreException(const Defaults &defaults, const QString &message) :
Exception(defaults, message)
{}
DataStoreException::DataStoreException(const DataStoreException * const other) :
Exception(other)
{}
LocalStoreException::LocalStoreException(const Defaults &defaults, const ObjectKey &key, const QString &context, const QString &message) :
DataStoreException(defaults, message),
_key(key),
_context(context)
{}
LocalStoreException::LocalStoreException(const LocalStoreException * const other) :
DataStoreException(other),
_key(other->_key),
_context(other->_context)
{}
ObjectKey LocalStoreException::key() const
{
return _key;
}
QString LocalStoreException::context() const
{
return _context;
}
QByteArray LocalStoreException::className() const noexcept
{
return QTDATASYNC_EXCEPTION_NAME(LocalStoreException);
}
QString LocalStoreException::qWhat() const
{
QString msg = Exception::qWhat() +
QStringLiteral("\n\tContext: %1"
"\n\tTypeName: %2")
.arg(_context, QString::fromUtf8(_key.typeName));
if(!_key.id.isNull())
msg += QStringLiteral("\n\tKey: %1").arg(_key.id);
return msg;
}
void LocalStoreException::raise() const
{
throw (*this);
}
QException *LocalStoreException::clone() const
{
return new LocalStoreException(this);
}
NoDataException::NoDataException(const Defaults &defaults, const ObjectKey &key) :
DataStoreException(defaults, QStringLiteral("The requested data does not exist")),
_key(key)
{}
NoDataException::NoDataException(const NoDataException * const other) :
DataStoreException(other),
_key(other->_key)
{}
ObjectKey NoDataException::key() const
{
return _key;
}
QByteArray NoDataException::className() const noexcept
{
return QTDATASYNC_EXCEPTION_NAME(NoDataException);
}
QString NoDataException::qWhat() const
{
return Exception::qWhat() +
QStringLiteral("\n\tTypeName: %1"
"\n\tKey: %2")
.arg(QString::fromUtf8(_key.typeName), _key.id);
}
void NoDataException::raise() const
{
throw (*this);
}
QException *NoDataException::clone() const
{
return new NoDataException(this);
}
InvalidDataException::InvalidDataException(const Defaults &defaults, const QByteArray &typeName, const QString &message) :
DataStoreException(defaults, message),
_typeName(typeName)
{}
InvalidDataException::InvalidDataException(const InvalidDataException * const other) :
DataStoreException(other),
_typeName(other->_typeName)
{}
QByteArray InvalidDataException::typeName() const
{
return _typeName;
}
QByteArray InvalidDataException::className() const noexcept
{
return QTDATASYNC_EXCEPTION_NAME(InvalidDataException);
}
QString InvalidDataException::qWhat() const
{
return Exception::qWhat() +
QStringLiteral("\n\tTypeName: %1")
.arg(QString::fromUtf8(_typeName));
}
void InvalidDataException::raise() const
{
throw (*this);
}
QException *InvalidDataException::clone() const
{
return new InvalidDataException(this);
} | c++ | code | 8,876 | 2,198 |
#include "robot_localization/ros_filter_types.h"
#include <limits>
#include <gtest/gtest.h>
using namespace RobotLocalization;
class RosEkfPassThrough : public RosEkf
{
public:
RosEkfPassThrough()
{
}
Ekf getFilter()
{
return filter_;
}
};
TEST (EkfTest, Measurements)
{
RosEkfPassThrough ekf;
Eigen::VectorXd measurement(STATE_SIZE);
for(size_t i = 0; i < STATE_SIZE; ++i)
{
measurement[i] = i;
}
Eigen::MatrixXd measurementCovariance(STATE_SIZE, STATE_SIZE);
for(size_t i = 0; i < STATE_SIZE; ++i)
{
measurementCovariance(i, i) = 0.5;
}
std::vector<int> updateVector(STATE_SIZE, true);
// Ensure that measurements are being placed in the queue correctly
ros::Time time;
time.fromSec(1000);
ekf.enqueueMeasurement("odom0",
measurement,
measurementCovariance,
updateVector,
std::numeric_limits<double>::max(),
time);
std::map<std::string, Eigen::VectorXd> postUpdateStates;
ekf.integrateMeasurements(1001);
EXPECT_EQ(ekf.getFilter().getState(), measurement);
EXPECT_EQ(ekf.getFilter().getEstimateErrorCovariance(), measurementCovariance);
// Now fuse another measurement and check the output.
// We know what the filter's state should be when
// this is complete, so we'll check the difference and
// make sure it's suitably small.
Eigen::VectorXd measurement2 = measurement;
measurement2 *= 2.0;
time.fromSec(1002);
ekf.enqueueMeasurement("odom0",
measurement2,
measurementCovariance,
updateVector,
std::numeric_limits<double>::max(),
time);
ekf.integrateMeasurements(1003);
measurement[0] = -4.5198;
measurement[1] = 0.14655;
measurement[2] = 9.4514;
measurement[3] = -2.8688;
measurement[4] = -2.2672;
measurement[5] = 0.12861;
measurement[6] = 15.481;
measurement[7] = 17.517;
measurement[8] = 19.587;
measurement[9] = 9.8351;
measurement[10] = 12.73;
measurement[11] = 13.87;
measurement[12] = 10.978;
measurement[13] = 12.008;
measurement[14] = 13.126;
measurement = measurement.eval() - ekf.getFilter().getState();
for(size_t i = 0; i < STATE_SIZE; ++i)
{
EXPECT_LT(::fabs(measurement[i]), 0.001);
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ekf");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | c++ | code | 2,548 | 542 |
// Implements the math functions for CPU.
// The implementation in this file allows us to route the underlying numerical
// computation library to different backends. Notably:
// (1) For all BLAS-related functions, one can explicitly request a BLAS backend
// such as MKL, openblas or Atlas. To see the set of supported backends
// currently provided, check //third_party/blas/.
// (2) If one chooses to link against MKL, we utilize MKL's vector math library
// (VML) for a few functions such as Exp and Log.
// (3) Fallback implementations are provided in Eigen for cross-platform
// support. Since Eigen is a header-only library and supports a number of
// platforms, it allows one to quickly port Caffe2 to different platforms
// where BLAS may not be present.
#include "caffe2/utils/math.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <limits>
#include <numeric>
#include <random>
#include <tuple>
#include <unordered_set>
#include <vector>
#include "caffe2/core/context.h"
#include "caffe2/utils/cpu_neon.h"
#include "caffe2/utils/eigen_utils.h"
#include "caffe2/utils/fixed_divisor.h"
#include "Eigen/Core"
#include "Eigen/Dense"
#ifdef CAFFE2_USE_MKL
#include <mkl.h>
#endif // CAFFE2_USE_MKL
#ifdef CAFFE2_USE_HPTT
#include <hptt.h>
#endif // CAFFE2_USE_HPTT
#if defined(_MSC_VER)
#include <process.h>
#endif
namespace caffe2 {
namespace math {
////////////////////////////////////////////////////////////////////////////////
// BLAS alternatives.
// Depending on whether we have specified an external BLAS library or not, we
// will delegate the Caffe math functions that are BLAS-related to either the
// CBLAS call or the Eigen implementation.
////////////////////////////////////////////////////////////////////////////////
#ifdef CAFFE2_USE_EIGEN_FOR_BLAS
// Caffe2 gemm provides a simpler interface to the gemm functions, with the
// limitation that the data has to be contiguous in memory.
//
// The gemm call implements the following operation:
//
// C = alpha * op(A) * op(B) + beta * C
//
// where op(A) has size M x K, op(B) has size K x N, and C has size M x N. Each
// of A, B, and C are matrices and alpha and beta are scalars. Note that the
// most common use case of gemm will involve setting alpha to 1 and beta to 0.
//
// op(A) and op(B) represent the transformations that are done to A and B before
// the matrix multiply; depending on the flags set, op(A) is equal to A or A^T
// (transpose) if the argument TransA or TransB is set to CblasNoTrans or
// CblasTrans, respectively, for each of A and B.
template <>
C10_EXPORT void Gemm<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const CBLAS_TRANSPOSE trans_B,
const int M,
const int N,
const int K,
const float alpha,
const float* A,
const float* B,
const float beta,
float* C,
CPUContext* context,
TensorProto::DataType math_type) {
auto C_mat = EigenMatrixMap<float>(C, N, M);
if (beta == 0) {
C_mat.setZero();
} else {
C_mat *= beta;
}
switch (trans_A) {
case CblasNoTrans: {
switch (trans_B) {
case CblasNoTrans:
C_mat.noalias() += alpha *
(ConstEigenMatrixMap<float>(B, N, K) *
ConstEigenMatrixMap<float>(A, K, M));
return;
case CblasTrans:
C_mat.noalias() += alpha *
(ConstEigenMatrixMap<float>(B, K, N).transpose() *
ConstEigenMatrixMap<float>(A, K, M));
return;
default:
LOG(FATAL) << "Unexpected CBLAS_TRANSPOSE for trans_B";
}
}
case CblasTrans: {
switch (trans_B) {
case CblasNoTrans:
C_mat.noalias() += alpha *
(ConstEigenMatrixMap<float>(B, N, K) *
ConstEigenMatrixMap<float>(A, M, K).transpose());
return;
case CblasTrans:
C_mat.noalias() += alpha *
(ConstEigenMatrixMap<float>(B, K, N).transpose() *
ConstEigenMatrixMap<float>(A, M, K).transpose());
return;
default:
LOG(FATAL) << "Unexpected CBLAS_TRANSPOSE for trans_B";
}
}
default:
LOG(FATAL) << "Unexpected CBLAS_TRANSPOSE for trans_A";
}
}
template <>
C10_EXPORT void GemmEx<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const CBLAS_TRANSPOSE trans_B,
const int M,
const int N,
const int K,
const float alpha,
const float* A,
const int lda,
const float* B,
const int ldb,
const float beta,
float* C,
const int ldc,
CPUContext*) {
EigenOuterStridedMatrixMap<float> C_mat(C, N, M, EigenOuterStride(ldc));
if (beta == 0) {
C_mat.setZero();
} else {
C_mat *= beta;
}
switch (trans_A) {
case CblasNoTrans: {
switch (trans_B) {
case CblasNoTrans:
C_mat.noalias() += alpha *
(ConstEigenOuterStridedMatrixMap<float>(
B, N, K, EigenOuterStride(ldb)) *
ConstEigenOuterStridedMatrixMap<float>(
A, K, M, EigenOuterStride(lda)));
return;
case CblasTrans:
C_mat.noalias() += alpha *
(ConstEigenOuterStridedMatrixMap<float>(
B, K, N, EigenOuterStride(ldb))
.transpose() *
ConstEigenOuterStridedMatrixMap<float>(
A, K, M, EigenOuterStride(lda)));
return;
default:
LOG(FATAL) << "Unexpected CBLAS_TRANSPOSE for trans_B";
}
}
case CblasTrans: {
switch (trans_B) {
case CblasNoTrans:
C_mat.noalias() += alpha *
(ConstEigenOuterStridedMatrixMap<float>(
B, N, K, EigenOuterStride(ldb)) *
ConstEigenOuterStridedMatrixMap<float>(
A, M, K, EigenOuterStride(lda))
.transpose());
return;
case CblasTrans:
C_mat.noalias() += alpha *
(ConstEigenOuterStridedMatrixMap<float>(
B, K, N, EigenOuterStride(ldb))
.transpose() *
ConstEigenOuterStridedMatrixMap<float>(
A, M, K, EigenOuterStride(lda))
.transpose());
return;
default:
LOG(FATAL) << "Unexpected CBLAS_TRANSPOSE for trans_B";
}
}
default:
LOG(FATAL) << "Unexpected CBLAS_TRANSPOSE for trans_A";
}
}
template <>
C10_EXPORT void Gemv<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const int M,
const int N,
const float alpha,
const float* A,
const float* x,
const float beta,
float* y,
CPUContext* context,
TensorProto::DataType math_type) {
EigenVectorMap<float> y_vec(y, trans_A == CblasNoTrans ? M : N);
if (beta == 0) {
// In Caffe2 we often do a lazy initialization, which may contain NaNs in
// the float values. As a result, if beta is 0, we explicitly do a setzero.
y_vec.setZero();
} else {
y_vec *= beta;
}
switch (trans_A) {
case CblasNoTrans: {
y_vec.noalias() += alpha *
(ConstEigenMatrixMap<float>(A, N, M).transpose() *
ConstEigenVectorMap<float>(x, N));
return;
}
case CblasTrans: {
y_vec.noalias() += alpha *
(ConstEigenMatrixMap<float>(A, N, M) *
ConstEigenVectorMap<float>(x, M));
return;
}
default:
LOG(FATAL) << "Gemv float found an unexpected CBLAS_TRANSPOSE input.";
}
}
#define CAFFE2_SPECIALIZED_DOT(T) \
template <> \
C10_EXPORT void Dot<T, CPUContext>( \
const int N, const T* a, const T* b, T* y, CPUContext* context) { \
*y = ConstEigenVectorMap<T>(a, N).dot(ConstEigenVectorMap<T>(b, N)); \
}
CAFFE2_SPECIALIZED_DOT(float)
#undef CAFFE2_SPECIALIZED_DOT
#else // CAFFE2_USE_EIGEN_FOR_BLAS
template <>
C10_EXPORT void Gemm<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const CBLAS_TRANSPOSE trans_B,
const int M,
const int N,
const int K,
const float alpha,
const float* A,
const float* B,
const float beta,
float* C,
CPUContext* /*context*/,
TensorProto::DataType /*math_type*/) {
const int lda = (trans_A == CblasNoTrans) ? K : M;
const int ldb = (trans_B == CblasNoTrans) ? N : K;
cblas_sgemm(
CblasRowMajor,
trans_A,
trans_B,
M,
N,
K,
alpha,
A,
lda,
B,
ldb,
beta,
C,
N);
}
template <>
C10_EXPORT void GemmEx<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const CBLAS_TRANSPOSE trans_B,
const int M,
const int N,
const int K,
const float alpha,
const float* A,
const int lda,
const float* B,
const int ldb,
const float beta,
float* C,
const int ldc,
CPUContext* /*context*/) {
cblas_sgemm(
CblasRowMajor,
trans_A,
trans_B,
M,
N,
K,
alpha,
A,
lda,
B,
ldb,
beta,
C,
ldc);
}
template <>
C10_EXPORT void Gemv<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const int M,
const int N,
const float alpha,
const float* A,
const float* x,
const float beta,
float* y,
CPUContext* /*context*/,
TensorProto::DataType /*math_type*/) {
cblas_sgemv(CblasRowMajor, trans_A, M, N, alpha, A, N, x, 1, beta, y, 1);
}
#define CAFFE2_SPECIALIZED_DOT(T, prefix) \
template <> \
C10_EXPORT void Dot<T, CPUContext>( \
const int N, const T* a, const T* b, T* y, CPUContext*) { \
*y = cblas_##prefix##dot(N, a, 1, b, 1); \
}
CAFFE2_SPECIALIZED_DOT(float, s)
#undef CAFFE2_SPECIALIZED_DOT
#endif // CAFFE2_USE_EIGEN_FOR_BLAS
template <>
C10_EXPORT void GemmBatched<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const CBLAS_TRANSPOSE trans_B,
const int batch_size,
const int M,
const int N,
const int K,
const float alpha,
const float** A,
const float** B,
const float beta,
float** C,
CPUContext* context,
TensorProto::DataType /* math_type */) {
#ifdef CAFFE2_USE_MKL
(void)context;
const int lda = (trans_A == CblasNoTrans) ? K : M;
const int ldb = (trans_B == CblasNoTrans) ? N : K;
const int ldc = N;
cblas_sgemm_batch(
CblasRowMajor,
&trans_A,
&trans_B,
&M,
&N,
&K,
&alpha,
A,
&lda,
B,
&ldb,
&beta,
C,
&ldc,
1,
&batch_size);
#else // CAFFE2_USE_MKL
// loop over matrices in the batch
for (int i = 0; i < batch_size; ++i) {
math::Gemm<float, CPUContext>(
trans_A, trans_B, M, N, K, alpha, A[i], B[i], beta, C[i], context);
}
#endif // CAFFE2_USE_MKL
}
template <>
C10_EXPORT void GemmStridedBatched<float, CPUContext>(
const CBLAS_TRANSPOSE trans_A,
const CBLAS_TRANSPOSE trans_B,
const int batch_size,
const int M,
const int N,
const int K,
const float alpha,
const float* A,
const int A_stride,
const float* B,
const int B_stride,
const float beta,
float* C,
const int C_stride,
CPUContext* context,
TensorProto::DataType /* math_type */) {
#ifdef CAFFE2_USE_MKL
(void)context;
const int lda = (trans_A == CblasNoTrans) ? K : M;
const int ldb = (trans_B == CblasNoTrans) ? N : K;
const int ldc = N;
std::vector<const float*> A_array(batch_size);
std::vector<const float*> B_array(batch_size);
std::vector<float*> C_array(batch_size);
for (int i = 0; i < batch_size; ++i) {
A_array[i] = A + i * A_stride;
B_array[i] = B + i * B_stride;
C_array[i] = C + i * C_stride;
}
cblas_sgemm_batch(
CblasRowMajor,
&trans_A,
&trans_B,
&M,
&N,
&K,
&alpha,
A_array.data(),
&lda,
B_array.data(),
&ldb,
&beta,
C_array.data(),
&ldc,
1,
&batch_size);
#else // CAFFE2_USE_MKL
// loop over matrices in the batch
for (int i = 0; i < batch_size; ++i) {
math::Gemm<float, CPUContext>(
trans_A, trans_B, M, N, K, alpha, A, B, beta, C, context);
A += A_stride;
B += B_stride;
C += C_stride;
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
// Common math functions being used in Caffe that do not have a BLAS or MKL
// equivalent. For all these functions, we will simply implement them either via
// Eigen or via custom code.
////////////////////////////////////////////////////////////////////////////////
namespace {
template <typename T>
C10_EXPORT void BroadcastImpl(
const int X_ndim,
const int* X_dims,
const int Y_ndim,
const int* Y_dims,
const T alpha,
const T* X,
T* Y,
CPUContext* context) {
CAFFE_ENFORCE_LE(X_ndim, Y_ndim);
std::vector<int> X_dims_vector(Y_ndim);
const int d = Y_ndim - X_ndim;
std::fill(X_dims_vector.begin(), X_dims_vector.begin() + d, 1);
for (int i = d; i < Y_ndim; ++i) {
CAFFE_ENFORCE(X_dims[i - d] == 1 || X_dims[i - d] == Y_dims[i]);
X_dims_vector[i] = X_dims[i - d];
}
X_dims = X_dims_vector.data();
const int Y_size =
std::accumulate(Y_dims, Y_dims + Y_ndim, 1, std::multiplies<int>());
std::vector<int> index(Y_ndim, 0);
for (int Y_index = 0; Y_index < Y_size; ++Y_index) {
const int X_index = utils::GetIndexFromDims(Y_ndim, X_dims, index.data());
Y[Y_index] = X[X_index];
utils::IncreaseIndexInDims(Y_ndim, Y_dims, index.data());
}
Scale<T, T, CPUContext>(Y_size, alpha, Y, Y, context);
}
} // namespace
#define CAFFE2_SPECIALIZED_BROADCAST(T) \
template <> \
C10_EXPORT void Broadcast<T, CPUContext>( \
const int X_ndim, \
const int* X_dims, \
const int Y_ndim, \
const int* Y_dims, \
const T alpha, \
const T* X, \
T* Y, \
CPUContext* context) { \
BroadcastImpl<T>(X_ndim, X_dims, Y_ndim, Y_dims, alpha, X, Y, context); \
}
CAFFE2_SPECIALIZED_BROADCAST(std::int32_t)
CAFFE2_SPECIALIZED_BROADCAST(std::int64_t)
CAFFE2_SPECIALIZED_BROADCAST(float)
CAFFE2_SPECIALIZED_BROADCAST(double)
#undef CAFFE2_SPECIALIZED_BROADCAST
#define CAFFE2_SPECIALIZED_INV_STD(T) \
template <> \
void InvStd<T, CPUContext>( \
const int N, \
const T epsilon, \
const T* var, \
T* inv_std, \
CPUContext* context) { \
EigenVectorArrayMap<T>(inv_std, N) = \
(ConstEigenVectorArrayMap<T>(var, N) + epsilon).rsqrt(); \
}
CAFFE2_SPECIALIZED_INV_STD(float)
#undef CAFFE2_SPECIALIZED_INV_STD
#define CAFFE2_SPECIALIZED_ROWWISEMAX(T) \
template <> \
C10_EXPORT void RowwiseMax<T, CPUContext>( \
const int N, const int D, const T* x, T* y, CPUContext*) { \
EigenVectorMap<T>(y, N) = \
ConstEigenMatrixMap<T>(x, D, N).colwise().maxCoeff(); \
}
CAFFE2_SPECIALIZED_ROWWISEMAX(float)
#undef CAFFE2_SPECIALIZED_ROWWISEMAX
#define CAFFE2_SPECIALIZED_COLWISEMAX(T) \
template <> \
C10_EXPORT void ColwiseMax<T, CPUContext>( \
const int N, const int D, const T* x, T* y, CPUContext*) { \
EigenVectorMap<T>(y, D) = \
ConstEigenMatrixMap<T>(x, D, N).rowwise().maxCoeff(); \
}
CAFFE2_SPECIALIZED_COLWISEMAX(float)
#undef CAFFE2_SPECIALIZED_COLWISEMAX
#define CAFFE2_SPECIALIZED_MAXIMUM(T) \
template <> \
C10_EXPORT void Maximum<T, CPUContext>( \
const int N, const float alpha, const T* x, T* y, CPUContext* context) { \
std::transform( \
x, x + N, y, [&alpha](const T& x_i) { return std::max(x_i, alpha); }); \
}
CAFFE2_SPECIALIZED_MAXIMUM(float)
#undef CAFFE2_SPECIALIZED_MAXIMUM
// The actual implementation uses eigen which is column major, so notice the
// row/column swap in the actual implementation.
#define DELEGATE_EIGEN_2D_BROADCAST_1ST_BINARY_FUNCTION(T, Func, expr) \
template <> \
C10_EXPORT void Rowwise##Func<T, CPUContext, true>( \
const int rows, \
const int cols, \
const T* A, \
const T* B, \
T* C, \
CPUContext*) { \
if (C == B) { \
EigenArrayMap<T>(C, cols, rows).colwise() expr## = \
ConstEigenVectorArrayMap<T>(A, cols); \
} else { \
EigenArrayMap<T>(C, cols, rows) = \
ConstEigenArrayMap<T>(B, cols, rows) \
.colwise() expr ConstEigenVectorArrayMap<T>(A, cols); \
} \
} \
template <> \
C10_EXPORT void Colwise##Func<T, CPUContext, true>( \
const int rows, \
const int cols, \
const T* A, \
const T* B, \
T* C, \
CPUContext*) { \
if (C == B) { \
EigenArrayMap<T>(C, cols, rows).rowwise() expr## = \
ConstEigenVectorArrayMap<T>(A, rows).transpose(); \
} else { \
EigenArrayMap<T>(C, cols, rows) = \
ConstEigenArrayMap<T>(B, cols, rows) \
.rowwise() expr ConstEigenVectorArrayMap<T>(A, rows) \
.transpose(); \
} \
}
#de | c++ | code | 20,000 | 3,726 |
/*!
* \file api_callback.cpp
* \brief file api_callback.cpp
*
* Copyright 2018 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#include <list>
#include <mutex>
#include <functional>
#include <iostream>
#include <fastuidraw/util/api_callback.hpp>
namespace
{
class APICallbackSetPrivate;
class CallBackPrivate;
typedef std::list<fastuidraw::APICallbackSet::CallBack*> CallBackList;
class APICallbackSetPrivate:public fastuidraw::noncopyable
{
public:
explicit
APICallbackSetPrivate(fastuidraw::c_string label);
CallBackList::iterator
insert(fastuidraw::APICallbackSet::CallBack *q);
void
erase(CallBackList::iterator iter);
template<typename F>
void
call_callbacks(const F &fptr);
void
get_proc_function(void* (*get_proc)(fastuidraw::c_string))
{
m_mutex.lock();
m_get_proc = get_proc;
m_get_proc_data = nullptr;
m_mutex.unlock();
}
void
get_proc_function(void *datum,
void* (*get_proc)(void*, fastuidraw::c_string))
{
m_mutex.lock();
m_get_proc = nullptr;
m_get_proc_data = get_proc;
m_data = datum;
m_mutex.unlock();
}
void*
get_proc(fastuidraw::c_string function_name)
{
void *return_value(nullptr);
m_mutex.lock();
if (m_get_proc)
{
return_value = m_get_proc(function_name);
}
else if (m_get_proc_data)
{
return_value = m_get_proc_data(m_data, function_name);
}
else
{
std::cerr << m_label << ": get_proc function pointer not set when "
<< "fetching function \"" << function_name << "\"\n";
}
m_mutex.unlock();
return return_value;
}
fastuidraw::c_string
label(void) const
{
return m_label.c_str();
}
private:
std::string m_label;
std::recursive_mutex m_mutex;
bool m_in_callback_sequence;
CallBackList m_list;
void* (*m_get_proc)(fastuidraw::c_string);
void* (*m_get_proc_data)(void *data, fastuidraw::c_string);
void *m_data;
};
class CallBackPrivate:public fastuidraw::noncopyable
{
public:
explicit
CallBackPrivate(APICallbackSetPrivate *s):
m_parent(s),
m_active(true)
{
FASTUIDRAWassert(m_parent);
}
CallBackList::iterator m_location;
APICallbackSetPrivate *m_parent;
bool m_active;
};
}
///////////////////////////////////////
// APICallbackSetPrivate methods
APICallbackSetPrivate::
APICallbackSetPrivate(fastuidraw::c_string label):
m_label(label ? label : ""),
m_in_callback_sequence(false),
m_get_proc(nullptr)
{}
CallBackList::iterator
APICallbackSetPrivate::
insert(fastuidraw::APICallbackSet::CallBack *q)
{
CallBackList::iterator return_value;
m_mutex.lock();
return_value = m_list.insert(m_list.end(), q);
m_mutex.unlock();
return return_value;
}
void
APICallbackSetPrivate::
erase(CallBackList::iterator iter)
{
m_mutex.lock();
m_list.erase(iter);
m_mutex.unlock();
}
template<typename F>
void
APICallbackSetPrivate::
call_callbacks(const F &fptr)
{
m_mutex.lock();
if (!m_in_callback_sequence)
{
m_in_callback_sequence = true;
for(auto iter = m_list.begin(); iter != m_list.end(); ++iter)
{
fptr(*iter);
}
m_in_callback_sequence = false;
}
m_mutex.unlock();
}
/////////////////////////////////////////////////
// fastuidraw::APICallbackSet::CallBack methods
fastuidraw::APICallbackSet::CallBack::
CallBack(APICallbackSet *parent)
{
CallBackPrivate *d;
APICallbackSetPrivate *dp;
dp = static_cast<APICallbackSetPrivate*>(parent->m_d);
FASTUIDRAWassert(dp);
d = FASTUIDRAWnew CallBackPrivate(dp);
d->m_location = dp->insert(this);
m_d = d;
}
fastuidraw::APICallbackSet::CallBack::
~CallBack()
{
CallBackPrivate *d;
d = static_cast<CallBackPrivate*>(m_d);
if (d->m_active)
{
d->m_parent->erase(d->m_location);
}
FASTUIDRAWdelete(d);
}
bool
fastuidraw::APICallbackSet::CallBack::
active(void) const
{
CallBackPrivate *d;
d = static_cast<CallBackPrivate*>(m_d);
return d->m_active;
}
void
fastuidraw::APICallbackSet::CallBack::
active(bool b)
{
CallBackPrivate *d;
d = static_cast<CallBackPrivate*>(m_d);
if (d->m_active == b)
{
return;
}
d->m_active = b;
if (b)
{
d->m_location = d->m_parent->insert(this);
}
else
{
d->m_parent->erase(d->m_location);
}
}
//////////////////////////////////////////////
// fastuidraw::APICallbackSet methods
fastuidraw::APICallbackSet::
APICallbackSet(c_string label)
{
m_d = FASTUIDRAWnew APICallbackSetPrivate(label);
}
fastuidraw::APICallbackSet::
~APICallbackSet()
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
FASTUIDRAWdelete(d);
}
fastuidraw::c_string
fastuidraw::APICallbackSet::
label(void) const
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
return d->label();
}
void
fastuidraw::APICallbackSet::
get_proc_function(void* (*get_proc)(c_string))
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
d->get_proc_function(get_proc);
}
void
fastuidraw::APICallbackSet::
get_proc_function(void *data, void* (*get_proc)(void*, c_string))
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
d->get_proc_function(data, get_proc);
}
void*
fastuidraw::APICallbackSet::
get_proc(c_string function_name)
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
return d->get_proc(function_name);
}
void
fastuidraw::APICallbackSet::
call_unloadable_function(c_string function_name)
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
d->call_callbacks(std::bind(&CallBack::on_call_unloadable_function,
std::placeholders::_1, function_name));
}
void
fastuidraw::APICallbackSet::
pre_call(c_string call_string_values,
c_string call_string_src,
c_string function_name,
void *function_ptr,
c_string src_file, int src_line)
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
d->call_callbacks(std::bind(&CallBack::pre_call,
std::placeholders::_1,
call_string_values,
call_string_src,
function_name,
function_ptr,
src_file, src_line));
}
void
fastuidraw::APICallbackSet::
post_call(c_string call_string_values,
c_string call_string_src,
c_string function_name,
c_string error_string,
void *function_ptr,
c_string src_file, int src_line)
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
d->call_callbacks(std::bind(&CallBack::post_call,
std::placeholders::_1,
call_string_values,
call_string_src,
function_name,
error_string,
function_ptr,
src_file, src_line));
}
void
fastuidraw::APICallbackSet::
message(c_string message, c_string src_file, int src_line)
{
APICallbackSetPrivate *d;
d = static_cast<APICallbackSetPrivate*>(m_d);
d->call_callbacks(std::bind(&CallBack::message,
std::placeholders::_1,
message, src_file, src_line));
} | c++ | code | 7,890 | 1,509 |
#ifndef BOOST_TMP_FUSION_REBIND_HPP_INCLUDED
#define BOOST_TMP_FUSION_REBIND_HPP_INCLUDED
// Copyright 2018 Odin Holmes.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include "capabilities.hpp"
namespace boost {
namespace tmp {
#ifdef BOOST_TMP_CPP14
namespace fusion {
// to make a metafunction fusion capable this traits must be specialized
// with the rebound version of the metafunction to be used in fusion context
template <typename T>
struct rebind;
} // namespace fusion
#endif
} // namespace tmp
} // namespace boost
#endif | c++ | code | 671 | 104 |
#include "AKSamplerGUI.h"
#include "AKSamplerDSP.h"
#include "AKSamplerParams.h"
#include "resource.h"
#include <CommCtrl.h>
#include "TRACE.h"
#include <ShlObj.h>
// APPROXIMATE initial dialog size
#define EDITOR_WIDTH 400
#define EDITOR_HEIGHT 400
#define WINDOW_CLASS "NetVSTEd"
AKSamplerGUI::AKSamplerGUI (AudioEffect* effect)
: AEffEditor(effect)
{
WIDTH = EDITOR_WIDTH;
HEIGHT = EDITOR_HEIGHT;
myRect.top = 0;
myRect.left = 0;
myRect.bottom = HEIGHT;
myRect.right = WIDTH;
effect->setEditor(this);
}
AKSamplerGUI::~AKSamplerGUI()
{
}
bool AKSamplerGUI::open (void* ptr)
{
systemWindow = ptr;
hwnd = CreateDialog(GetInstance(), MAKEINTRESOURCE(IDD_DIALOG1), (HWND)ptr, dp);
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this);
ShowWindow(hwnd, SW_SHOW);
RECT rc;
GetClientRect(hwnd, &rc);
myRect.left = (VstInt16)rc.left;
myRect.top = (VstInt16)rc.top;
myRect.right = (VstInt16)rc.right;
myRect.bottom = (VstInt16)rc.bottom;
updateAllParameters();
populatePresetsComboBox();
return true;
}
void AKSamplerGUI::close ()
{
DestroyWindow(hwnd);
hwnd = 0;
systemWindow = 0;
}
INT_PTR CALLBACK AKSamplerGUI::dp(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
AKSamplerGUI* instancePtr = (AKSamplerGUI*)GetWindowLongPtr(hDlg, GWLP_USERDATA);
if (instancePtr != NULL)
{
return instancePtr->instanceCallback(hDlg, message, wParam, lParam);
}
return (INT_PTR)FALSE;
}
INT_PTR CALLBACK AKSamplerGUI::instanceCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
AKSamplerDSP *pVst = (AKSamplerDSP*)getEffect();
float fv;
int whichSlider;
char text[50];
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_HSCROLL:
if (LOWORD(wParam) == TB_THUMBTRACK)
{
fv = HIWORD(wParam) / 100.0f;
whichSlider = GetDlgCtrlID((HWND)lParam);
switch (whichSlider)
{
case IDC_MASTER_VOLUME_SLIDER:
pVst->setParamFraction(kMasterVolume, fv);
pVst->getParamString(kMasterVolume, text);
SetDlgItemText(hwnd, IDC_MASTER_VOLUME_READOUT, text);
return (INT_PTR)TRUE;
case IDC_PITCH_OFFSET_SLIDER:
pVst->setParamFraction(kPitchBend, fv);
pVst->getParamString(kPitchBend, text);
SetDlgItemText(hwnd, IDC_PITCH_OFFSET_READOUT, text);
return (INT_PTR)TRUE;
case IDC_VIBRATO_DEPTH_SLIDER:
pVst->setParamFraction(kVibratoDepth, fv);
pVst->getParamString(kVibratoDepth, text);
SetDlgItemText(hwnd, IDC_VIBRATO_DEPTH_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_CUTOFF_SLIDER:
pVst->setParamFraction(kFilterCutoff, fv);
pVst->getParamString(kFilterCutoff, text);
SetDlgItemText(hwnd, IDC_FILTER_CUTOFF_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_RESONANCE_SLIDER:
pVst->setParamFraction(kFilterResonance, fv);
pVst->getParamString(kFilterResonance, text);
SetDlgItemText(hwnd, IDC_FILTER_RESONANCE_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_EGSTRENGTH_SLIDER:
pVst->setParamFraction(kFilterEgStrength, fv);
pVst->getParamString(kFilterEgStrength, text);
SetDlgItemText(hwnd, IDC_FILTER_EGSTRENGTH_READOUT, text);
return (INT_PTR)TRUE;
case IDC_GLIDE_RATE_SLIDER:
pVst->setParamFraction(kGlideRate, fv);
pVst->getParamString(kGlideRate, text);
SetDlgItemText(hwnd, IDC_GLIDE_RATE_READOUT, text);
return (INT_PTR)TRUE;
case IDC_AMP_ATTACK_SLIDER:
pVst->setParamFraction(kAmpAttackTime, fv);
pVst->getParamString(kAmpAttackTime, text);
SetDlgItemText(hwnd, IDC_AMP_ATTACK_READOUT, text);
return (INT_PTR)TRUE;
case IDC_AMP_DECAY_SLIDER:
pVst->setParamFraction(kAmpDecayTime, fv);
pVst->getParamString(kAmpDecayTime, text);
SetDlgItemText(hwnd, IDC_AMP_DECAY_READOUT, text);
return (INT_PTR)TRUE;
case IDC_AMP_SUSTAIN_SLIDER:
pVst->setParamFraction(kAmpSustainLevel, fv);
pVst->getParamString(kAmpSustainLevel, text);
SetDlgItemText(hwnd, IDC_AMP_SUSTAIN_READOUT, text);
return (INT_PTR)TRUE;
case IDC_AMP_RELEASE_SLIDER:
pVst->setParamFraction(kAmpReleaseTime, fv);
pVst->getParamString(kAmpReleaseTime, text);
SetDlgItemText(hwnd, IDC_AMP_RELEASE_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_ATTACK_SLIDER:
pVst->setParamFraction(kFilterAttackTime, fv);
pVst->getParamString(kFilterAttackTime, text);
SetDlgItemText(hwnd, IDC_FILTER_ATTACK_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_DECAY_SLIDER:
pVst->setParamFraction(kFilterDecayTime, fv);
pVst->getParamString(kFilterDecayTime, text);
SetDlgItemText(hwnd, IDC_FILTER_DECAY_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_SUSTAIN_SLIDER:
pVst->setParamFraction(kFilterSustainLevel, fv);
pVst->getParamString(kFilterSustainLevel, text);
SetDlgItemText(hwnd, IDC_FILTER_SUSTAIN_READOUT, text);
return (INT_PTR)TRUE;
case IDC_FILTER_RELEASE_SLIDER:
pVst->setParamFraction(kFilterReleaseTime, fv);
pVst->getParamString(kFilterReleaseTime, text);
SetDlgItemText(hwnd, IDC_FILTER_RELEASE_READOUT, text);
return (INT_PTR)TRUE;
}
}
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_LOOPTHRU_CHECK:
if (HIWORD(wParam) == BN_CLICKED)
{
float v = 0.0f;
if (SendDlgItemMessage(hDlg, IDC_LOOPTHRU_CHECK, BM_GETCHECK, 0, 0)) v = 1.0f;
pVst->setParamFraction(kLoopThruRelease, v);
return (INT_PTR)TRUE;
}
break;
case IDC_MONO_CHECK:
if (HIWORD(wParam) == BN_CLICKED)
{
float v = 0.0f;
if (SendDlgItemMessage(hDlg, IDC_MONO_CHECK, BM_GETCHECK, 0, 0)) v = 1.0f;
pVst->setParamFraction(kMonophonic, v);
return (INT_PTR)TRUE;
}
break;
case IDC_LEGATO_CHECK:
if (HIWORD(wParam) == BN_CLICKED)
{
float v = 0.0f;
if (SendDlgItemMessage(hDlg, IDC_LEGATO_CHECK, BM_GETCHECK, 0, 0)) v = 1.0f;
pVst->setParamFraction(kLegato, v);
return (INT_PTR)TRUE;
}
break;
case IDC_FILTER_ENABLE_CHECK:
if (HIWORD(wParam) == BN_CLICKED)
{
float v = 0.0f;
if (SendDlgItemMessage(hDlg, IDC_FILTER_ENABLE_CHECK, BM_GETCHECK, 0, 0)) v = 1.0f;
pVst->setParamFraction(kFilterEnable, v);
enableFilterControls(v > 0.0f);
return (INT_PTR)TRUE;
}
break;
case IDC_PRESETCB:
if (HIWORD(wParam) == CBN_SELCHANGE)
{
int sel = (int)SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_GETCURSEL, 0, 0);
if (sel != CB_ERR)
{
SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_GETLBTEXT, (WPARAM)sel, (LPARAM)(pVst->presetName));
pVst->loadPreset();
}
}
break;
case IDC_PRESETDIRBTN:
choosePresetDirectory();
break;
}
break;
}
return (INT_PTR)FALSE;
}
void AKSamplerGUI::enableFilterControls(bool show)
{
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_CUTOFF_SLIDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_EGSTRENGTH_SLIDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_RESONANCE_SLIDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_ATTACK_SLIDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_DECAY_SLIDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_SUSTAIN_SLIDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hwnd, IDC_FILTER_RELEASE_SLIDER), show ? TRUE : FALSE);
}
void AKSamplerGUI::setParameter(VstInt32 index, float value)
{
int sliderPos = (int)(100.0f * value + 0.5f);
AKSamplerDSP *pVst = (AKSamplerDSP*)getEffect();
char text[50];
pVst->getParamString(index, text);
switch (index)
{
case kMasterVolume:
SendDlgItemMessage(hwnd, IDC_MASTER_VOLUME_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_MASTER_VOLUME_READOUT, text);
break;
case kPitchBend:
SendDlgItemMessage(hwnd, IDC_PITCH_OFFSET_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_PITCH_OFFSET_READOUT, text);
break;
case kVibratoDepth:
SendDlgItemMessage(hwnd, IDC_VIBRATO_DEPTH_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_VIBRATO_DEPTH_READOUT, text);
break;
case kGlideRate:
SendDlgItemMessage(hwnd, IDC_GLIDE_RATE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_GLIDE_RATE_READOUT, text);
break;
case kFilterEnable:
SendDlgItemMessage(hwnd, IDC_FILTER_ENABLE_CHECK, BM_SETCHECK,
pVst->getParamFraction(kFilterEnable) > 0.5f ? BST_CHECKED : BST_UNCHECKED, 0);
break;
case kFilterCutoff:
SendDlgItemMessage(hwnd, IDC_FILTER_CUTOFF_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_CUTOFF_READOUT, text);
break;
case kFilterEgStrength:
SendDlgItemMessage(hwnd, IDC_FILTER_EGSTRENGTH_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_EGSTRENGTH_READOUT, text);
break;
case kFilterResonance:
SendDlgItemMessage(hwnd, IDC_FILTER_RESONANCE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_RESONANCE_READOUT, text);
break;
case kAmpAttackTime:
SendDlgItemMessage(hwnd, IDC_AMP_ATTACK_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_AMP_ATTACK_READOUT, text);
break;
case kAmpDecayTime:
SendDlgItemMessage(hwnd, IDC_AMP_DECAY_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_AMP_DECAY_READOUT, text);
break;
case kAmpSustainLevel:
SendDlgItemMessage(hwnd, IDC_AMP_SUSTAIN_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_AMP_SUSTAIN_READOUT, text);
break;
case kAmpReleaseTime:
SendDlgItemMessage(hwnd, IDC_AMP_RELEASE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_AMP_RELEASE_READOUT, text);
break;
case kFilterAttackTime:
SendDlgItemMessage(hwnd, IDC_FILTER_ATTACK_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_ATTACK_READOUT, text);
break;
case kFilterDecayTime:
SendDlgItemMessage(hwnd, IDC_FILTER_DECAY_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_DECAY_READOUT, text);
break;
case kFilterSustainLevel:
SendDlgItemMessage(hwnd, IDC_FILTER_SUSTAIN_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_SUSTAIN_READOUT, text);
break;
case kFilterReleaseTime:
SendDlgItemMessage(hwnd, IDC_FILTER_RELEASE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
SetDlgItemText(hwnd, IDC_FILTER_RELEASE_READOUT, text);
break;
case kLoopThruRelease:
SendDlgItemMessage(hwnd, IDC_LOOPTHRU_CHECK, BM_SETCHECK,
pVst->getParamFraction(kLoopThruRelease) > 0.5f ? BST_CHECKED : BST_UNCHECKED, 0);
break;
case kMonophonic:
SendDlgItemMessage(hwnd, IDC_MONO_CHECK, BM_SETCHECK,
pVst->getParamFraction(kMonophonic) > 0.5f ? BST_CHECKED : BST_UNCHECKED, 0);
break;
case kLegato:
SendDlgItemMessage(hwnd, IDC_LEGATO_CHECK, BM_SETCHECK,
pVst->getParamFraction(kLegato) > 0.5f ? BST_CHECKED : BST_UNCHECKED, 0);
break;
}
}
void AKSamplerGUI::updateAllParameters()
{
int sliderPos;
char text[50];
AKSamplerDSP *pVst = (AKSamplerDSP*)getEffect();
sliderPos = (int)(100.0f * pVst->getParamFraction(kMasterVolume) + 0.5f);
SendDlgItemMessage(hwnd, IDC_MASTER_VOLUME_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kMasterVolume, text);
SetDlgItemText(hwnd, IDC_MASTER_VOLUME_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kPitchBend) + 0.5f);
SendDlgItemMessage(hwnd, IDC_PITCH_OFFSET_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kPitchBend, text);
SetDlgItemText(hwnd, IDC_PITCH_OFFSET_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kVibratoDepth) + 0.5f);
SendDlgItemMessage(hwnd, IDC_VIBRATO_DEPTH_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kVibratoDepth, text);
SetDlgItemText(hwnd, IDC_VIBRATO_DEPTH_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kGlideRate) + 0.5f);
SendDlgItemMessage(hwnd, IDC_GLIDE_RATE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kGlideRate, text);
SetDlgItemText(hwnd, IDC_GLIDE_RATE_READOUT, text);
bool filterEnabled = pVst->getParameter(kFilterEnable) > 0.5;
SendDlgItemMessage(hwnd, IDC_FILTER_ENABLE_CHECK, BM_SETCHECK,
filterEnabled ? BST_CHECKED : BST_UNCHECKED, 0);
enableFilterControls(filterEnabled);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterCutoff) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_CUTOFF_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterCutoff, text);
SetDlgItemText(hwnd, IDC_FILTER_CUTOFF_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterEgStrength) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_EGSTRENGTH_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterEgStrength, text);
SetDlgItemText(hwnd, IDC_FILTER_EGSTRENGTH_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterResonance) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_RESONANCE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterResonance, text);
SetDlgItemText(hwnd, IDC_FILTER_RESONANCE_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kAmpAttackTime) + 0.5f);
SendDlgItemMessage(hwnd, IDC_AMP_ATTACK_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kAmpAttackTime, text);
SetDlgItemText(hwnd, IDC_AMP_ATTACK_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kAmpDecayTime) + 0.5f);
SendDlgItemMessage(hwnd, IDC_AMP_DECAY_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kAmpDecayTime, text);
SetDlgItemText(hwnd, IDC_AMP_DECAY_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kAmpSustainLevel) + 0.5f);
SendDlgItemMessage(hwnd, IDC_AMP_SUSTAIN_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kAmpSustainLevel, text);
SetDlgItemText(hwnd, IDC_AMP_SUSTAIN_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kAmpReleaseTime) + 0.5f);
SendDlgItemMessage(hwnd, IDC_AMP_RELEASE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kAmpReleaseTime, text);
SetDlgItemText(hwnd, IDC_AMP_RELEASE_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterAttackTime) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_ATTACK_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterAttackTime, text);
SetDlgItemText(hwnd, IDC_FILTER_ATTACK_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterDecayTime) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_DECAY_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterDecayTime, text);
SetDlgItemText(hwnd, IDC_FILTER_DECAY_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterSustainLevel) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_SUSTAIN_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterSustainLevel, text);
SetDlgItemText(hwnd, IDC_FILTER_SUSTAIN_READOUT, text);
sliderPos = (int)(100.0f * pVst->getParamFraction(kFilterReleaseTime) + 0.5f);
SendDlgItemMessage(hwnd, IDC_FILTER_RELEASE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)sliderPos);
pVst->getParamString(kFilterSustainLevel, text);
SetDlgItemText(hwnd, IDC_FILTER_RELEASE_READOUT, text);
bool loopThruRel = pVst->getParameter(kLoopThruRelease) > 0.5;
SendDlgItemMessage(hwnd, IDC_LOOPTHRU_CHECK, BM_SETCHECK,
loopThruRel ? BST_CHECKED : BST_UNCHECKED, 0);
bool monophonic = pVst->getParameter(kMonophonic) > 0.5;
SendDlgItemMessage(hwnd, IDC_MONO_CHECK, BM_SETCHECK,
monophonic ? BST_CHECKED : BST_UNCHECKED, 0);
bool legato = pVst->getParameter(kLegato) > 0.5;
SendDlgItemMessage(hwnd, IDC_LEGATO_CHECK, BM_SETCHECK,
legato ? BST_CHECKED : BST_UNCHECKED, 0);
}
void AKSamplerGUI::populatePresetsComboBox()
{
SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_RESETCONTENT, 0, 0);
AKSamplerDSP *pVst = (AKSamplerDSP*)getEffect();
char wildcardPath[250];
sprintf(wildcardPath, "%s\\*.sfz", pVst->presetFolderPath);
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
int count = 0;
hFind = FindFirstFile(wildcardPath, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
TRACE("populatePresetsComboBox: FindFirstFile failed (%d)\n", GetLastError());
return;
}
//TRACE("preset %s\n", FindFileData.cFileName);
SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_ADDSTRING, 0, (LPARAM)FindFileData.cFileName);
count++;
while (FindNextFile(hFind, &FindFileData))
{
//TRACE("preset %s\n", FindFileData.cFileName);
SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_ADDSTRING, 0, (LPARAM)FindFileData.cFileName);
count++;
}
FindClose(hFind);
if (count)
{
// select first preset and load it
SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_SETCURSEL, 0, 0);
SendDlgItemMessage(hwnd, IDC_PRESETCB, CB_GETLBTEXT, 0, (LPARAM)(pVst->presetName));
pVst->loadPreset();
}
}
static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
if (uMsg == BFFM_INITIALIZED)
{
AKSamplerDSP* pDSP = (AKSamplerDSP*)lpData;
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
}
return 0;
}
void AKSamplerGUI::choosePresetDirectory()
{
AKSamplerDSP* pDSP = (AKSamplerDSP*)getEffect();
BROWSEINFO bi = { 0 };
bi.lpszTitle = ("Choose a folder containing .sfz files");
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIAL | c++ | code | 20,000 | 3,501 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/fileapi/sandbox_file_stream_writer.h"
#include "base/files/file_util_proxy.h"
#include "base/platform_file.h"
#include "base/sequenced_task_runner.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "webkit/blob/local_file_stream_reader.h"
#include "webkit/fileapi/file_observers.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_operation.h"
#include "webkit/fileapi/file_system_util.h"
#include "webkit/fileapi/local_file_stream_writer.h"
#include "webkit/quota/quota_manager.h"
namespace fileapi {
namespace {
// Adjust the |quota| value in overwriting case (i.e. |file_size| > 0 and
// |file_offset| < |file_size|) to make the remaining quota calculation easier.
// Specifically this widens the quota for overlapping range (so that we can
// simply compare written bytes against the adjusted quota).
int64 AdjustQuotaForOverlap(int64 quota,
int64 file_offset,
int64 file_size) {
DCHECK_LE(file_offset, file_size);
if (quota < 0)
quota = 0;
int64 overlap = file_size - file_offset;
if (kint64max - overlap > quota)
quota += overlap;
return quota;
}
} // namespace
SandboxFileStreamWriter::SandboxFileStreamWriter(
FileSystemContext* file_system_context,
const FileSystemURL& url,
int64 initial_offset,
const UpdateObserverList& observers)
: file_system_context_(file_system_context),
url_(url),
initial_offset_(initial_offset),
observers_(observers),
file_size_(0),
total_bytes_written_(0),
allowed_bytes_to_write_(0),
has_pending_operation_(false),
default_quota_(kint64max),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(url_.is_valid());
}
SandboxFileStreamWriter::~SandboxFileStreamWriter() {}
int SandboxFileStreamWriter::Write(
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
has_pending_operation_ = true;
if (local_file_writer_.get())
return WriteInternal(buf, buf_len, callback);
base::PlatformFileError error_code;
FileSystemOperation* operation =
file_system_context_->CreateFileSystemOperation(url_, &error_code);
if (error_code != base::PLATFORM_FILE_OK)
return net::PlatformFileErrorToNetError(error_code);
DCHECK(operation);
net::CompletionCallback write_task =
base::Bind(&SandboxFileStreamWriter::DidInitializeForWrite,
weak_factory_.GetWeakPtr(),
make_scoped_refptr(buf), buf_len, callback);
operation->GetMetadata(
url_, base::Bind(&SandboxFileStreamWriter::DidGetFileInfo,
weak_factory_.GetWeakPtr(), write_task));
return net::ERR_IO_PENDING;
}
int SandboxFileStreamWriter::Cancel(const net::CompletionCallback& callback) {
if (!has_pending_operation_)
return net::ERR_UNEXPECTED;
DCHECK(!callback.is_null());
cancel_callback_ = callback;
return net::ERR_IO_PENDING;
}
int SandboxFileStreamWriter::WriteInternal(
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
// allowed_bytes_to_write could be negative if the file size is
// greater than the current (possibly new) quota.
DCHECK(total_bytes_written_ <= allowed_bytes_to_write_ ||
allowed_bytes_to_write_ < 0);
if (total_bytes_written_ >= allowed_bytes_to_write_) {
has_pending_operation_ = false;
return net::ERR_FILE_NO_SPACE;
}
if (buf_len > allowed_bytes_to_write_ - total_bytes_written_)
buf_len = allowed_bytes_to_write_ - total_bytes_written_;
DCHECK(local_file_writer_.get());
const int result = local_file_writer_->Write(
buf, buf_len,
base::Bind(&SandboxFileStreamWriter::DidWrite, weak_factory_.GetWeakPtr(),
callback));
if (result != net::ERR_IO_PENDING)
has_pending_operation_ = false;
return result;
}
void SandboxFileStreamWriter::DidGetFileInfo(
const net::CompletionCallback& callback,
base::PlatformFileError file_error,
const base::PlatformFileInfo& file_info,
const base::FilePath& platform_path) {
if (CancelIfRequested())
return;
if (file_error != base::PLATFORM_FILE_OK) {
callback.Run(net::PlatformFileErrorToNetError(file_error));
return;
}
if (file_info.is_directory) {
// We should not be writing to a directory.
callback.Run(net::ERR_ACCESS_DENIED);
return;
}
file_size_ = file_info.size;
if (initial_offset_ > file_size_) {
LOG(ERROR) << initial_offset_ << ", " << file_size_;
// This shouldn't happen as long as we check offset in the renderer.
NOTREACHED();
initial_offset_ = file_size_;
}
DCHECK(!local_file_writer_.get());
local_file_writer_.reset(
new LocalFileStreamWriter(platform_path, initial_offset_));
quota::QuotaManagerProxy* quota_manager_proxy =
file_system_context_->quota_manager_proxy();
if (!quota_manager_proxy) {
// If we don't have the quota manager or the requested filesystem type
// does not support quota, we should be able to let it go.
allowed_bytes_to_write_ = default_quota_;
callback.Run(net::OK);
return;
}
DCHECK(quota_manager_proxy->quota_manager());
quota_manager_proxy->quota_manager()->GetUsageAndQuota(
url_.origin(),
FileSystemTypeToQuotaStorageType(url_.type()),
base::Bind(&SandboxFileStreamWriter::DidGetUsageAndQuota,
weak_factory_.GetWeakPtr(), callback));
}
void SandboxFileStreamWriter::DidGetUsageAndQuota(
const net::CompletionCallback& callback,
quota::QuotaStatusCode status,
int64 usage, int64 quota) {
if (CancelIfRequested())
return;
if (status != quota::kQuotaStatusOk) {
LOG(WARNING) << "Got unexpected quota error : " << status;
callback.Run(net::ERR_FAILED);
return;
}
allowed_bytes_to_write_ = quota - usage;
callback.Run(net::OK);
}
void SandboxFileStreamWriter::DidInitializeForWrite(
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback,
int init_status) {
if (CancelIfRequested())
return;
if (init_status != net::OK) {
has_pending_operation_ = false;
callback.Run(init_status);
return;
}
allowed_bytes_to_write_ = AdjustQuotaForOverlap(
allowed_bytes_to_write_, initial_offset_, file_size_);
const int result = WriteInternal(buf, buf_len, callback);
if (result != net::ERR_IO_PENDING)
callback.Run(result);
}
void SandboxFileStreamWriter::DidWrite(
const net::CompletionCallback& callback,
int write_response) {
DCHECK(has_pending_operation_);
has_pending_operation_ = false;
if (write_response <= 0) {
if (CancelIfRequested())
return;
callback.Run(write_response);
return;
}
if (total_bytes_written_ + write_response + initial_offset_ > file_size_) {
int overlapped = file_size_ - total_bytes_written_ - initial_offset_;
if (overlapped < 0)
overlapped = 0;
observers_.Notify(&FileUpdateObserver::OnUpdate,
MakeTuple(url_, write_response - overlapped));
}
total_bytes_written_ += write_response;
if (CancelIfRequested())
return;
callback.Run(write_response);
}
bool SandboxFileStreamWriter::CancelIfRequested() {
if (cancel_callback_.is_null())
return false;
net::CompletionCallback pending_cancel = cancel_callback_;
has_pending_operation_ = false;
cancel_callback_.Reset();
pending_cancel.Run(net::OK);
return true;
}
int SandboxFileStreamWriter::Flush(const net::CompletionCallback& callback) {
// For now, Flush is meaningful only for local native file access. It is no-op
// for sandboxed filesystem files (see the discussion in crbug.com/144790).
return net::OK;
}
} // namespace fileapi | c++ | code | 7,935 | 1,400 |
//========================================================================
//
// SplashPath.cc
//
// Copyright 2003-2013 Glyph & Cog, LLC
//
//========================================================================
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include <string.h>
#include "gmem.h"
#include "gmempp.h"
#include "SplashErrorCodes.h"
#include "SplashPath.h"
//------------------------------------------------------------------------
// SplashPath
//------------------------------------------------------------------------
// A path can be in three possible states:
//
// 1. no current point -- zero or more finished subpaths
// [curSubpath == length]
//
// 2. one point in subpath
// [curSubpath == length - 1]
//
// 3. open subpath with two or more points
// [curSubpath < length - 1]
SplashPath::SplashPath() {
pts = NULL;
flags = NULL;
length = size = 0;
curSubpath = 0;
hints = NULL;
hintsLength = hintsSize = 0;
}
SplashPath::SplashPath(SplashPath *path) {
length = path->length;
size = path->size;
pts = (SplashPathPoint *)gmallocn(size, sizeof(SplashPathPoint));
flags = (Guchar *)gmallocn(size, sizeof(Guchar));
memcpy(pts, path->pts, length * sizeof(SplashPathPoint));
memcpy(flags, path->flags, length * sizeof(Guchar));
curSubpath = path->curSubpath;
if (path->hints) {
hintsLength = hintsSize = path->hintsLength;
hints = (SplashPathHint *)gmallocn(hintsSize, sizeof(SplashPathHint));
memcpy(hints, path->hints, hintsLength * sizeof(SplashPathHint));
} else {
hints = NULL;
hintsLength = hintsSize = 0;
}
}
SplashPath::~SplashPath() {
gfree(pts);
gfree(flags);
gfree(hints);
}
// Add space for <nPts> more points.
void SplashPath::grow(int nPts) {
if (length + nPts > size) {
if (size == 0) {
size = 32;
}
while (size < length + nPts) {
size *= 2;
}
pts = (SplashPathPoint *)greallocn(pts, size, sizeof(SplashPathPoint));
flags = (Guchar *)greallocn(flags, size, sizeof(Guchar));
}
}
void SplashPath::append(SplashPath *path) {
int i;
curSubpath = length + path->curSubpath;
grow(path->length);
for (i = 0; i < path->length; ++i) {
pts[length] = path->pts[i];
flags[length] = path->flags[i];
++length;
}
}
SplashError SplashPath::moveTo(SplashCoord x, SplashCoord y) {
if (onePointSubpath()) {
return splashErrBogusPath;
}
grow(1);
pts[length].x = x;
pts[length].y = y;
flags[length] = splashPathFirst | splashPathLast;
curSubpath = length++;
return splashOk;
}
SplashError SplashPath::lineTo(SplashCoord x, SplashCoord y) {
if (noCurrentPoint()) {
return splashErrNoCurPt;
}
flags[length-1] &= (Guchar)~splashPathLast;
grow(1);
pts[length].x = x;
pts[length].y = y;
flags[length] = splashPathLast;
++length;
return splashOk;
}
SplashError SplashPath::curveTo(SplashCoord x1, SplashCoord y1,
SplashCoord x2, SplashCoord y2,
SplashCoord x3, SplashCoord y3) {
if (noCurrentPoint()) {
return splashErrNoCurPt;
}
flags[length-1] &= (Guchar)~splashPathLast;
grow(3);
pts[length].x = x1;
pts[length].y = y1;
flags[length] = splashPathCurve;
++length;
pts[length].x = x2;
pts[length].y = y2;
flags[length] = splashPathCurve;
++length;
pts[length].x = x3;
pts[length].y = y3;
flags[length] = splashPathLast;
++length;
return splashOk;
}
SplashError SplashPath::close(GBool force) {
if (noCurrentPoint()) {
return splashErrNoCurPt;
}
if (force ||
curSubpath == length - 1 ||
pts[length - 1].x != pts[curSubpath].x ||
pts[length - 1].y != pts[curSubpath].y) {
lineTo(pts[curSubpath].x, pts[curSubpath].y);
}
flags[curSubpath] |= splashPathClosed;
flags[length - 1] |= splashPathClosed;
curSubpath = length;
return splashOk;
}
void SplashPath::addStrokeAdjustHint(int ctrl0, int ctrl1,
int firstPt, int lastPt,
GBool projectingCap) {
if (hintsLength == hintsSize) {
hintsSize = hintsLength ? 2 * hintsLength : 8;
hints = (SplashPathHint *)greallocn(hints, hintsSize,
sizeof(SplashPathHint));
}
hints[hintsLength].ctrl0 = ctrl0;
hints[hintsLength].ctrl1 = ctrl1;
hints[hintsLength].firstPt = firstPt;
hints[hintsLength].lastPt = lastPt;
hints[hintsLength].projectingCap = projectingCap;
++hintsLength;
}
void SplashPath::offset(SplashCoord dx, SplashCoord dy) {
int i;
for (i = 0; i < length; ++i) {
pts[i].x += dx;
pts[i].y += dy;
}
}
GBool SplashPath::getCurPt(SplashCoord *x, SplashCoord *y) {
if (noCurrentPoint()) {
return gFalse;
}
*x = pts[length - 1].x;
*y = pts[length - 1].y;
return gTrue;
}
GBool SplashPath::containsZeroLengthSubpaths() {
GBool zeroLength;
int i;
zeroLength = gTrue; // make gcc happy
for (i = 0; i < length; ++i) {
if (flags[i] & splashPathFirst) {
zeroLength = gTrue;
} else {
if (pts[i].x != pts[i-1].x || pts[i].y != pts[i-1].y) {
zeroLength = gFalse;
}
if (flags[i] & splashPathLast) {
if (zeroLength) {
return gTrue;
}
}
}
}
return gFalse;
} | c++ | code | 5,134 | 1,325 |
#include "mvPythonTranslator.h"
#include "mvApp.h"
#include "mvAppLog.h"
#include "Core/mvPythonExceptions.h"
namespace Marvel {
mvGlobalIntepreterLock::mvGlobalIntepreterLock()
{
m_gstate = PyGILState_Ensure();
}
mvGlobalIntepreterLock::~mvGlobalIntepreterLock()
{
PyGILState_Release(m_gstate);
}
void UpdatePyIntList(PyObject* pyvalue, const std::vector<int>& value)
{
if (pyvalue == nullptr)
return;
mvGlobalIntepreterLock gil;
if (!PyList_Check(pyvalue))
{
ThrowPythonException("Python value error");
return;
}
for (size_t i = 0; i < PyList_Size(pyvalue); i++)
{
if (i == value.size())
break;
PyList_SetItem(pyvalue, i, PyLong_FromLong(value[i]));
}
}
void UpdatePyFloatList(PyObject* pyvalue, const std::vector<float>& value)
{
if (pyvalue == nullptr)
return;
mvGlobalIntepreterLock gil;
if (!PyList_Check(pyvalue))
{
ThrowPythonException("Python value error");
return;
}
for (size_t i = 0; i < PyList_Size(pyvalue); i++)
{
if (i == value.size())
break;
PyList_SetItem(pyvalue, i, PyFloat_FromDouble(value[i]));
}
}
void UpdatePyStringStringList(PyObject* pyvalue, const std::vector<std::vector<std::string>>& value)
{
if (pyvalue == nullptr)
return;
mvGlobalIntepreterLock gil;
if (!PyList_Check(pyvalue))
{
ThrowPythonException("Python value error");
return;
}
for (size_t i = 0; i < PyList_Size(pyvalue); i++)
{
if (i == value.size())
break;
PyObject* row = PyList_GetItem(pyvalue, i);
for (size_t j = 0; j < PyList_Size(row); j++)
{
if (j == value[i].size())
break;
PyList_SetItem(row, i, PyUnicode_FromString(value[i][j].c_str()));
}
}
}
PyObject* GetPyNone()
{
mvGlobalIntepreterLock gil;
Py_RETURN_NONE;
}
PyObject* ToPyString(const std::string& value)
{
mvGlobalIntepreterLock gil;
return PyUnicode_FromString(value.c_str());
}
PyObject* ToPyFloat(float value)
{
mvGlobalIntepreterLock gil;
return PyFloat_FromDouble(value);
}
PyObject* ToPyInt(int value)
{
mvGlobalIntepreterLock gil;
return PyLong_FromLong(value);
}
PyObject* ToPyBool(bool value)
{
mvGlobalIntepreterLock gil;
return PyBool_FromLong(value);
}
PyObject* ToPyMPair(int x, float y)
{
mvGlobalIntepreterLock gil;
return Py_BuildValue("[if]", x, y);
}
PyObject* ToPyMTrip(int i, float x, float y)
{
mvGlobalIntepreterLock gil;
return Py_BuildValue("[iff]", i, x, y);
}
PyObject* ToPyPair(float x, float y)
{
mvGlobalIntepreterLock gil;
return Py_BuildValue("[ff]", x, y);
}
PyObject* ToPyPairII(int x, int y)
{
mvGlobalIntepreterLock gil;
return Py_BuildValue("[ii]", x, y);
}
PyObject* ToPyPair(const std::string& x, const std::string& y)
{
mvGlobalIntepreterLock gil;
return Py_BuildValue("[ss]", x.c_str(), y.c_str());
}
PyObject* ToPyList(const std::vector<int>& value)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(value.size());
for (size_t i = 0; i < value.size(); i++)
PyList_SetItem(result, i, PyLong_FromLong(value[i]));
return result;
}
PyObject* ToPyList(const std::vector<float>& value)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(value.size());
for (size_t i = 0; i < value.size(); i++)
PyList_SetItem(result, i, PyFloat_FromDouble(value[i]));
return result;
}
PyObject* ToPyList(const std::vector<std::string>& value)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(value.size());
for (size_t i = 0; i < value.size(); i++)
PyList_SetItem(result, i, PyUnicode_FromString(value[i].c_str()));
return result;
}
PyObject* ToPyList(const std::vector<std::vector<std::string>>& value)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(value.size());
for (size_t i = 0; i < value.size(); i++)
PyList_SetItem(result, i, ToPyList(value[i]));
return result;
}
PyObject* ToPyList(const std::vector<std::pair<int, int>>& value)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(value.size());
for (size_t i = 0; i < value.size(); i++)
PyList_SetItem(result, i, ToPyPairII(value[i].first, value[i].second));
return result;
}
PyObject* ToPyColor(const mvColor& color)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(4);
PyList_SetItem(result, 0, ToPyFloat(color.r));
PyList_SetItem(result, 1, ToPyFloat(color.g));
PyList_SetItem(result, 2, ToPyFloat(color.b));
PyList_SetItem(result, 3, ToPyFloat(color.a));
return result;
}
PyObject* ToPyTime(const tm& time)
{
mvGlobalIntepreterLock gil;
PyObject* dict = PyDict_New();
PyDict_SetItemString(dict, "sec", ToPyInt(time.tm_sec));
PyDict_SetItemString(dict, "min", ToPyInt(time.tm_min));
PyDict_SetItemString(dict, "hour", ToPyInt(time.tm_hour));
PyDict_SetItemString(dict, "month_day", ToPyInt(time.tm_mday));
PyDict_SetItemString(dict, "month", ToPyInt(time.tm_mon));
PyDict_SetItemString(dict, "year", ToPyInt(time.tm_year));
PyDict_SetItemString(dict, "week_day", ToPyInt(time.tm_wday));
PyDict_SetItemString(dict, "year_day", ToPyInt(time.tm_yday));
PyDict_SetItemString(dict, "daylight_savings", ToPyInt(time.tm_isdst));
return dict;
}
PyObject* ToPyIntList(int* value, int count)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(count);
for (size_t i = 0; i < count; i++)
PyList_SetItem(result, i, PyLong_FromLong(value[i]));
return result;
}
PyObject* ToPyFloatList(float* value, int count)
{
mvGlobalIntepreterLock gil;
PyObject* result = PyList_New(count);
for (size_t i = 0; i < count; i++)
PyList_SetItem(result, i, PyFloat_FromDouble(value[i]));
return result;
}
tm ToTime(PyObject* value, const std::string& message)
{
tm result = {};
if (value == nullptr)
return result;
if (!PyDict_Check(value))
{
ThrowPythonException(message);
return result;
}
if (PyObject* item = PyDict_GetItemString(value, "sec")) result.tm_sec = ToInt(item);
if (PyObject* item = PyDict_GetItemString(value, "min")) result.tm_min = ToInt(item);
if (PyObject* item = PyDict_GetItemString(value, "hour")) result.tm_hour = ToInt(item);
if (PyObject* item = PyDict_GetItemString(value, "month_day")) result.tm_mday = ToInt(item);
else result.tm_mday = 1;
if (PyObject* item = PyDict_GetItemString(value, "month")) result.tm_mon = ToInt(item);
if (PyObject* item = PyDict_GetItemString(value, "year")) result.tm_year = ToInt(item);
else result.tm_year = 70;
if (PyObject* item = PyDict_GetItemString(value, "week_day")) result.tm_wday = ToInt(item);
if (PyObject* item = PyDict_GetItemString(value, "year_day")) result.tm_yday = ToInt(item);
if (PyObject* item = PyDict_GetItemString(value, "daylight_savings")) result.tm_isdst = ToInt(item);
return result;
}
int ToInt(PyObject* value, const std::string& message)
{
if (value == nullptr)
return 0;
mvGlobalIntepreterLock gil;
if (!PyLong_Check(value))
{
ThrowPythonException(message);
return 0;
}
return PyLong_AsLong(value);
}
float ToFloat(PyObject* value, const std::string& message)
{
if (value == nullptr)
return 0.0f;
mvGlobalIntepreterLock gil;
if (!PyNumber_Check(value))
{
ThrowPythonException(message);
return 0.0f;
}
return (float)PyFloat_AsDouble(value);
}
bool ToBool(PyObject* value, const std::string& message)
{
if (value == nullptr)
return false;
mvGlobalIntepreterLock gil;
if (!PyBool_Check(value))
{
ThrowPythonException(message);
return false;
}
return PyLong_AsLong(value);
}
std::string ToString(PyObject* value, const std::string& message)
{
std::string result;
if (value == nullptr)
return result;
mvGlobalIntepreterLock gil;
if (PyUnicode_Check(value))
{
result = _PyUnicode_AsString(value);
}
else
{
PyObject* str = PyObject_Str(value);
if (str == nullptr)
{
ThrowPythonException(message);
return "";
}
result = _PyUnicode_AsString(str);
Py_XDECREF(str);
}
return result;
}
std::vector<int> ToIntVect(PyObject* value, const std::string& message)
{
std::vector<int> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
PyObject* item = PyTuple_GetItem(value, i);
if(PyLong_Check(item))
items.emplace_back(PyLong_AsLong(item));
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
PyObject* item = PyList_GetItem(value, i);
if (PyLong_Check(item))
items.emplace_back(PyLong_AsLong(item));
}
}
else
ThrowPythonException(message);
return items;
}
std::vector<float> ToFloatVect(PyObject* value, const std::string& message)
{
std::vector<float> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
PyObject* item = PyTuple_GetItem(value, i);
if (PyNumber_Check(item))
items.emplace_back(PyFloat_AsDouble(item));
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
PyObject* item = PyList_GetItem(value, i);
if (PyNumber_Check(item))
items.emplace_back(PyFloat_AsDouble(item));
}
}
else
ThrowPythonException(message);
return items;
}
std::vector<std::string> ToStringVect(PyObject* value, const std::string& message)
{
std::vector<std::string> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
PyObject* item = PyTuple_GetItem(value, i);
if (PyUnicode_Check(item))
items.emplace_back(_PyUnicode_AsString(item));
else
{
PyObject* str = PyObject_Str(item);
items.emplace_back(_PyUnicode_AsString(str));
Py_XDECREF(str);
}
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
PyObject* item = PyList_GetItem(value, i);
if (PyUnicode_Check(item))
items.emplace_back(_PyUnicode_AsString(item));
else
{
PyObject* str = PyObject_Str(item);
items.emplace_back(_PyUnicode_AsString(str));
Py_XDECREF(str);
}
}
}
else
ThrowPythonException(message);
return items;
}
mvColor ToColor(PyObject* value, const std::string& message)
{
int color[4] = { 255, 255, 255, 255 };
if (value == nullptr)
return mvColor{ color[0], color[1], color[2], color[3], false };
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
if (i >= 4)
break;
PyObject* item = PyTuple_GetItem(value, i);
if(PyNumber_Check(item))
color[i] = (int)PyFloat_AsDouble(item);
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
if (i >= 4)
break;
PyObject* item = PyList_GetItem(value, i);
if (PyNumber_Check(item))
color[i] = (int)PyFloat_AsDouble(item);
}
}
return mvColor{ color[0], color[1], color[2], color[3], true };
}
mvVec2 ToVec2(PyObject* value, const std::string& message)
{
if (value == nullptr)
return { 0.0f, 0.0f };
std::vector<float> result = ToFloatVect(value, message);
if (result.size() > 1)
return { result[0], result[1] };
else if (result.size() == 1)
return { result[0], 0.0f };
else
return { 0.0f, 0.0f };
}
mvVec4 ToVec4(PyObject* value, const std::string& message)
{
if (value == nullptr)
return { 0.0f, 0.0f, 0.0f, 0.0f };
std::vector<float> result = ToFloatVect(value, message);
if (result.size() > 3)
return { result[0], result[1], result[2], result[3] };
else if (result.size() > 2)
return { result[0], result[1], result[2], 0.0f };
else if (result.size() > 1)
return { result[0], result[1], 0.0f, 0.0f };
else if (result.size() == 1)
return { result[0], 0.0f, 0.0f, 0.0f };
else
return { 0.0f, 0.0f, 0.0f, 0.0f };
}
std::vector<std::pair<std::string, std::string>> ToVectPairString(PyObject* value, const std::string& message)
{
std::vector<std::pair<std::string, std::string>> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
PyObject* item = PyTuple_GetItem(value, i);
if (PyTuple_Size(item) == 2)
items.emplace_back(PyUnicode_AsUTF8(PyTuple_GetItem(item, 0)), PyUnicode_AsUTF8(PyTuple_GetItem(item, 1)));
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
PyObject* item = PyList_GetItem(value, i);
if (PyList_Size(item) == 2)
items.emplace_back(PyUnicode_AsUTF8(PyList_GetItem(item, 0)), PyUnicode_AsUTF8(PyList_GetItem(item, 1)));
}
}
else
ThrowPythonException(message);
return items;
}
std::vector<mvVec2> ToVectVec2(PyObject* value, const std::string& message)
{
std::vector<mvVec2> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
items.push_back(ToVec2(PyTuple_GetItem(value, i)));
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
items.push_back(ToVec2(PyList_GetItem(value, i)));
}
else
ThrowPythonException(message);
return items;
}
std::vector<mvVec4> ToVectVec4(PyObject* value, const std::string& message)
{
std::vector<mvVec4> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
items.push_back(ToVec4(PyTuple_GetItem(value, i)));
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
items.push_back(ToVec4(PyList_GetItem(value, i)));
}
else
ThrowPythonException(message);
return items;
}
std::vector<std::pair<int, int>> ToVectInt2(PyObject* value, const std::string& message)
{
std::vector<std::pair<int, int>> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
PyObject* point = PyTuple_GetItem(value, i);
if(PyTuple_Check(point))
{
if (PyTuple_Size(point) >= 2) {
int x = PyLong_AsLong(PyTuple_GetItem(point, 0));
int y = PyLong_AsLong(PyTuple_GetItem(point, 1));
items.emplace_back(x, y);
}
}
else if(PyList_Check(point))
{
if (PyList_Size(point) >= 2) {
int x = PyLong_AsLong(PyList_GetItem(point, 0));
int y = PyLong_AsLong(PyList_GetItem(point, 1));
items.emplace_back(x, y);
}
}
else
items.emplace_back(0, 0);
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
PyObject* point = PyList_GetItem(value, i);
if(PyTuple_Check(point))
{
if (PyTuple_Size(point) >= 2) {
int x = PyLong_AsLong(PyTuple_GetItem(point, 0));
int y = PyLong_AsLong(PyTuple_GetItem(point, 1));
items.emplace_back(x, y);
}
}
else if(PyList_Check(point))
{
if (PyList_Size(point) >= 2) {
int x = PyLong_AsLong(PyList_GetItem(point, 0));
int y = PyLong_AsLong(PyList_GetItem(point, 1));
items.emplace_back(x, y);
}
}
else
items.emplace_back(0, 0);
}
}
else
ThrowPythonException(message);
return items;
}
std::vector<std::vector<std::string>> ToVectVectString(PyObject* value, const std::string& message)
{
std::vector<std::vector<std::string>> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
items.emplace_back(ToStringVect(PyTuple_GetItem(value, i), message));
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
items.emplace_back(ToStringVect(PyList_GetItem(value, i), message));
}
return items;
}
std::vector<std::pair<std::string, float>> ToVectPairStringFloat(PyObject* value, const std::string& message)
{
std::vector<std::pair<std::string, float>> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
{
PyObject* item = PyTuple_GetItem(value, i);
if (PyTuple_Size(item) == 2)
items.emplace_back(PyUnicode_AsUTF8(PyTuple_GetItem(item, 0)), (float)PyFloat_AsDouble(PyTuple_GetItem(item, 1)));
}
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
{
PyObject* item = PyList_GetItem(value, i);
if (PyList_Size(item) == 2)
items.emplace_back(PyUnicode_AsUTF8(PyList_GetItem(item, 0)), (float)PyFloat_AsDouble(PyList_GetItem(item, 1)));
}
}
else
ThrowPythonException(message);
return items;
}
std::vector<std::vector<float>> ToVectVectFloat(PyObject* value, const std::string& message)
{
std::vector<std::vector<float>> items;
if (value == nullptr)
return items;
mvGlobalIntepreterLock gil;
if (PyTuple_Check(value))
{
for (size_t i = 0; i < PyTuple_Size(value); i++)
items.emplace_back(ToFloatVect(PyTuple_GetItem(value, i), message));
}
else if (PyList_Check(value))
{
for (size_t i = 0; i < PyList_Size(value); i++)
items.emplace_back(ToFloatVect(PyList_GetItem(value, i), message));
}
return items;
}
} | c++ | code | 18,296 | 4,505 |
#include <doctest/doctest.h>
#include "Aspen/StaticCommitHandler.hpp"
#include "Aspen/Queue.hpp"
#include "Aspen/Shared.hpp"
using namespace Aspen;
TEST_SUITE("StaticCommitHandler") {
TEST_CASE("empty_static_commit") {
auto reactor = StaticCommitHandler<>();
REQUIRE(reactor.commit(0) == State::COMPLETE);
}
TEST_CASE("static_immediate_complete") {
auto reactor = StaticCommitHandler(Queue<int>());
reactor.get<0>().push(1);
reactor.get<0>().commit(0);
reactor.get<0>().set_complete();
REQUIRE(reactor.commit(1) == State::COMPLETE);
}
TEST_CASE("static_complete") {
auto queue = Shared(Queue<int>());
auto reactor = StaticCommitHandler(queue, queue);
reactor.get<0>()->push(1);
REQUIRE(reactor.commit(0) == State::EVALUATED);
reactor.get<1>()->set_complete();
REQUIRE(reactor.commit(1) == State::COMPLETE);
}
TEST_CASE("static_empty_and_evaluated") {
auto reactor = StaticCommitHandler(Queue<int>(), Queue<int>());
REQUIRE(reactor.commit(0) == State::NONE);
reactor.get<0>().push(123);
REQUIRE(reactor.commit(1) == State::NONE);
reactor.get<1>().push(321);
REQUIRE(reactor.commit(2) == State::EVALUATED);
}
TEST_CASE("static_delayed_evaluation") {
auto reactor = StaticCommitHandler(Queue<int>(), constant(5));
REQUIRE(reactor.commit(0) == State::NONE);
reactor.get<0>().push(123);
REQUIRE(reactor.commit(1) == State::EVALUATED);
REQUIRE(reactor.commit(2) == State::NONE);
}
} | c++ | code | 1,498 | 427 |
// C++.
#include <cassert>
// Qt.
#include <QCheckBox>
#include <QEvent>
#include <QKeyEvent>
#include <QListWidget>
#include <QObject>
// Infra.
#include <QtCommon/CustomWidgets/ArrowIconWidget.h>
#include <QtCommon/Util/CommonDefinitions.h>
// Local.
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgHideListWidgetEventFilter.h>
// Object name associated with the column dropdown list.
static const char* STR_DISASSEMBLY_COLUMN_VISIBILITY_LIST = "DisassemblyColumnVisibilityList";
// Object name associated with the target GPU dropdown list.
static const char* STR_DISASSEMBLY_TARGET_GPU_LIST = "TargetGpuList";
// The object names for UI objects that the user can click on.
static const char* STR_COLUMN_VISIBLITY_ARROW_PUSH_BUTTON = "columnVisibilityArrowPushButton";
static const char* STR_DISASSEMBLY_TARGET_GPU_PUSH_BUTTON = "targetGpuPushButton";
static const char* STR_ISA_LIST_ARROW_PUSH_BUTTON = "isaListArrowPushButton";
static const char* STR_QT_SCROLL_AREA_VIEWPORT = "qt_scrollarea_viewport";
static const char* STR_VIEW_TITLE_BAR = "viewTitlebar";
static const char* STR_VIEW_OPEN_CL_SETTINGS_VIEW = "rgOpenClSettingsView";
static const char* STR_SETTINGS_TAB = "settingsTab";
static const char* STR_START_TAB = "startTab";
static const char* STR_TAB_WIDGET_STACKED_WIDGET = "qt_tabwidget_stackedwidget";
static const char* STR_MAIN_TAB_WIDGET = "mainTabWidget";
static const char* STR_HOME_PAGE = "homePage";
static const char* STR_STACKED_WIDGET = "stackedWidget";
static const char* STR_CENTRAL_WIDGET = "centralWidget";
static const char* STR_RG_MAIN_WINDOW = "rgMainWindow";
static const char* STR_RG_MAIN_WINDOW_TAB_BAR = "rgMainWindowTabBar";
static const char* STR_RG_MAIN_WINDOW_MENU_BAR = "menuBar";
static const char* STR_ENUM_COMBO_PUSH_BUTTON = "enumComboPushButton";
static const char* STR_PSO_EDITOR_ADD_ELEMENT_BUTTON = "addElementButton";
static const char* STR_PSO_EDITOR_DELETE_ELEMENT_BUTTON = "deleteElementButton";
static const char* STR_PSO_EDITOR_LINE_EDIT = "lineEdit";
static const char* STR_FILE_MENU_ADD_FILE_BUTTON = "addFilePushButton";
static const char* STR_BUILD_SETTINGS_BUTTON_NAME = "buildSettingsButton";
static const char* STR_FILE_MENU_NAME_GRAPHICS = "fileMenuGraphics";
static const char* STR_FILE_MENU_ITEM_NAME_GRAPHICS = "fileMenuItemGraphics";
static const char* STR_PSO_EDITOR_LOAD_BUTTON = "loadButton";
static const char* STR_PSO_EDITOR_SAVE_BUTTON = "saveButton";
QStringList rgHideListWidgetEventFilter::m_stringList =
{
STR_COLUMN_VISIBLITY_ARROW_PUSH_BUTTON,
STR_DISASSEMBLY_TARGET_GPU_PUSH_BUTTON,
STR_ISA_LIST_ARROW_PUSH_BUTTON,
STR_QT_SCROLL_AREA_VIEWPORT,
STR_VIEW_TITLE_BAR,
STR_VIEW_OPEN_CL_SETTINGS_VIEW,
STR_SETTINGS_TAB,
STR_START_TAB,
STR_TAB_WIDGET_STACKED_WIDGET,
STR_MAIN_TAB_WIDGET,
STR_HOME_PAGE,
STR_STACKED_WIDGET,
STR_CENTRAL_WIDGET,
STR_RG_MAIN_WINDOW,
STR_RG_MAIN_WINDOW_TAB_BAR,
STR_RG_MAIN_WINDOW_MENU_BAR,
STR_ENUM_COMBO_PUSH_BUTTON,
STR_PSO_EDITOR_ADD_ELEMENT_BUTTON,
STR_PSO_EDITOR_DELETE_ELEMENT_BUTTON,
STR_PSO_EDITOR_LINE_EDIT,
STR_FILE_MENU_ADD_FILE_BUTTON,
STR_BUILD_SETTINGS_BUTTON_NAME,
STR_FILE_MENU_NAME_GRAPHICS,
STR_FILE_MENU_ITEM_NAME_GRAPHICS,
STR_PSO_EDITOR_LOAD_BUTTON,
STR_PSO_EDITOR_SAVE_BUTTON,
};
rgHideListWidgetEventFilter::rgHideListWidgetEventFilter(QListWidget* pListWidget, ArrowIconWidget* pButton) :
QObject(pListWidget),
m_pListWidget(pListWidget),
m_pButton(pButton)
{
}
bool rgHideListWidgetEventFilter::eventFilter(QObject* pObject, QEvent* pEvent)
{
assert(m_pListWidget != nullptr);
bool filtered = false;
if (m_pListWidget != nullptr)
{
if (pEvent->type() == QEvent::MouseButtonPress)
{
// If the user has clicked on a widget in the list and the object clicked on is not the pushbutton registered
// with this object (since it will be cleaned up by its slot later), then hide the list widget.
if (m_stringList.contains(pObject->objectName()) && m_pButton->objectName().compare(pObject->objectName()) != 0)
{
// Hide the list widget.
m_pListWidget->hide();
// Set the button icon to down arrow.
m_pButton->SetDirection(ArrowIconWidget::Direction::DownArrow);
// Emit the list widget status changed signal.
emit EnumListWidgetStatusSignal(false);
}
}
else if (pEvent->type() == QEvent::KeyPress && m_pListWidget->isVisible())
{
QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(pEvent);
assert(pKeyEvent != nullptr);
if (pKeyEvent != nullptr)
{
int currentRow = m_pListWidget->currentRow();
int keyPressed = pKeyEvent->key();
if (keyPressed == Qt::Key_Down)
{
if (currentRow < m_pListWidget->count() - 1)
{
currentRow++;
}
}
else if (keyPressed == Qt::Key_Up)
{
if (currentRow > 0)
{
currentRow--;
}
}
else if (keyPressed == Qt::Key_Enter || keyPressed == Qt::Key_Return || keyPressed == Qt::Key_Space)
{
// If this is the columns list widget, check/un-check the check box,
// else just emit the currentRowChanged signal.
if (m_pListWidget->objectName().compare(STR_DISASSEMBLY_TARGET_GPU_LIST) == 0)
{
emit m_pListWidget->currentRowChanged(currentRow);
// Close the list widget.
m_pListWidget->hide();
// Set the button icon to down arrow.
m_pButton->SetDirection(ArrowIconWidget::Direction::DownArrow);
// Emit the list widget status changed signal.
emit EnumListWidgetStatusSignal(false);
}
else if (m_pListWidget->objectName().compare(STR_DISASSEMBLY_COLUMN_VISIBILITY_LIST) == 0)
{
// Toggle the check state in the ISA column visibility dropdown.
QListWidgetItem* pItem = m_pListWidget->currentItem();
if (pItem != nullptr)
{
QCheckBox* pCheckBox = qobject_cast<QCheckBox*>(m_pListWidget->itemWidget(pItem));
if (pCheckBox != nullptr)
{
if (pCheckBox->isChecked())
{
pCheckBox->setCheckState(Qt::Unchecked);
}
else
{
pCheckBox->setCheckState(Qt::Checked);
}
emit pCheckBox->clicked();
}
}
}
}
else if (keyPressed == Qt::Key_Tab)
{
// Close the list widget.
m_pListWidget->hide();
// Set the button icon to down arrow.
m_pButton->SetDirection(ArrowIconWidget::Direction::DownArrow);
// Emit the list widget status changed signal.
emit EnumListWidgetStatusSignal(false);
// Pop open the column list widget if this is gpu list widget,
// else if this is the column list widget, give focus to output window.
if (m_pListWidget->objectName().compare(STR_DISASSEMBLY_TARGET_GPU_LIST) == 0)
{
emit OpenColumnListWidget();
// Update the rgIsaDisassemblyCustomTableView::m_currentSubWidget as well.
emit UpdateCurrentSubWidget(DisassemblyViewSubWidgets::ColumnPushButton);
}
else if (m_pListWidget->objectName().compare(STR_DISASSEMBLY_COLUMN_VISIBILITY_LIST) == 0)
{
emit FocusCliOutputWindow();
// Update the rgIsaDisassemblyCustomTableView::m_currentSubWidget as well.
emit UpdateCurrentSubWidget(DisassemblyViewSubWidgets::OutputWindow);
}
}
else if (keyPressed == Qt::Key_Backtab)
{
// Close the list widget.
m_pListWidget->hide();
// Set the button icon to down arrow.
m_pButton->SetDirection(ArrowIconWidget::Direction::DownArrow);
// Emit the list widget status changed signal.
emit EnumListWidgetStatusSignal(false);
// Pop open the gpu list widget if this is column list widget,
// else if this is the gpu list widget, give focus to disassembly view window.
if (m_pListWidget->objectName().compare(STR_DISASSEMBLY_COLUMN_VISIBILITY_LIST) == 0)
{
emit OpenGpuListWidget();
// Update the rgIsaDisassemblyCustomTableView::m_currentSubWidget as well.
emit UpdateCurrentSubWidget(DisassemblyViewSubWidgets::TargetGpuPushButton);
}
else if (m_pListWidget->objectName().compare(STR_DISASSEMBLY_TARGET_GPU_LIST) == 0)
{
emit FrameInFocusSignal();
// Update the rgIsaDisassemblyCustomTableView::m_currentSubWidget as well.
emit UpdateCurrentSubWidget(DisassemblyViewSubWidgets::TableView);
}
}
else if (keyPressed == Qt::Key_Escape)
{
m_pListWidget->close();
// Set the button icon to down arrow.
m_pButton->SetDirection(ArrowIconWidget::Direction::DownArrow);
// Emit the list widget status changed signal.
emit EnumListWidgetStatusSignal(false);
}
m_pListWidget->setCurrentRow(currentRow);
// Do not let Qt process this event any further.
filtered = true;
}
}
}
return filtered;
}
void rgHideListWidgetEventFilter::AddObjectName(const QString& objectName)
{
m_stringList.push_back(objectName);
}
void rgHideListWidgetEventFilter::ClickPushButton()
{
assert(m_pButton != nullptr);
if (m_pButton != nullptr)
{
m_pButton->clicked();
}
} | c++ | code | 11,373 | 1,535 |
// Copyright 2015 Stefano Pogliani <[email protected]>
#include <gtest/gtest.h>
#include "core/exceptions/base.h"
#include "core/registry/base.h"
using sf::core::exception::DuplicateInjection;
using sf::core::exception::FactoryNotFound;
using sf::core::registry::Registry;
typedef int*(*test_factory)();
typedef Registry<test_factory> TestRegistry;
int* make_one() {
return new int(1);
}
TEST(Regisrty, CannotGetMissingFactory) {
TestRegistry reg;
ASSERT_THROW(reg.get("none"), FactoryNotFound);
}
TEST(Regisrty, CannotSetFactoryTwice) {
TestRegistry reg;
reg.registerFactory("one", make_one);
ASSERT_THROW(reg.registerFactory("one", make_one), DuplicateInjection);
}
TEST(Regisrty, GetFactory) {
TestRegistry reg;
reg.registerFactory("one", make_one);
test_factory factory = reg.get("one");
int* result = factory();
EXPECT_EQ(1, *result);
delete result;
}
TEST(Registry, Singleton) {
TestRegistry* reg1 = TestRegistry::instance();
TestRegistry* reg2 = TestRegistry::instance();
ASSERT_EQ(reg1, reg2);
}
TEST(Registry, SingletonProxy) {
TestRegistry::RegisterFactory("one", make_one);
test_factory factory = TestRegistry::Get("one");
int* result = factory();
EXPECT_EQ(1, *result);
delete result;
} | c++ | code | 1,256 | 297 |
// Copyright (c) 2019 PaddlePaddle 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 "lite/api/paddle_place.h"
#include "lite/backends/fpga/KD/float16.hpp"
#include "lite/backends/fpga/KD/tensor_util.hpp"
#include "lite/core/kernel.h"
#include "lite/core/op_registry.h"
#include "lite/core/target_wrapper.h"
#include "lite/core/type_system.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace fpga {
using float16 = zynqmp::float16;
template <typename T>
void convert_to_hwc(
T* chw_data, T* hwc_data, int num, int channel, int height, int width) {
int chw = channel * height * width;
int wc = width * channel;
int index = 0;
for (int n = 0; n < num; n++) {
for (int c = 0; c < channel; c++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
hwc_data[n * chw + h * wc + w * channel + c] = chw_data[index];
index++;
}
}
}
}
}
template <typename T>
void hwc_to_chw(
T* chw_data, T* hwc_data, int num, int channel, int height, int width) {
int chw = channel * height * width;
int wc = width * channel;
int wh = width * height;
int index = 0;
for (int n = 0; n < num; n++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
for (int c = 0; c < channel; c++) {
chw_data[n * chw + c * wh + h * width + w] = hwc_data[index];
index++;
}
}
}
}
}
void TransHwcToChw(Tensor* dest, const Tensor* src) {
if (src->ZynqTensor()->dataType() == zynqmp::FP32) {
float* chw = dest->mutable_data<float>();
float* hwc = const_cast<float*>(src->data<float>());
int num = dest->dims()[0];
int channel = dest->dims()[1];
int height = 1;
if (dest->dims().size() > 2) {
height = dest->dims()[2];
}
int width = 1;
if (dest->dims().size() > 3) {
width = dest->dims()[3];
}
hwc_to_chw<float>(chw, hwc, num, channel, height, width);
}
if (src->ZynqTensor()->dataType() == zynqmp::FP16) {
float16* chw = dest->mutable_data<float16>();
float16* hwc = const_cast<float16*>(src->data<float16>());
int num = dest->dims()[0];
int channel = dest->dims()[1];
int height = 1;
if (dest->dims().size() > 2) {
height = dest->dims()[2];
}
int width = 1;
if (dest->dims().size() > 3) {
width = dest->dims()[3];
}
hwc_to_chw<float16>(chw, hwc, num, channel, height, width);
}
}
void TransChwToHwc(Tensor* dest, const Tensor* src) {
int num = 1;
if (dest->dims().size() > 0) {
num = dest->dims()[0];
}
int channel = 1;
if (dest->dims().size() > 1) {
channel = dest->dims()[1];
}
int height = 1;
if (dest->dims().size() > 2) {
height = dest->dims()[2];
}
int width = 1;
if (dest->dims().size() > 3) {
width = dest->dims()[3];
}
if (src->ZynqTensor()->dataType() == zynqmp::FP32) {
float* chw = const_cast<float*>(src->data<float>());
float* hwc = dest->mutable_data<float>();
convert_to_hwc<float>(chw, hwc, num, channel, height, width);
}
if (src->ZynqTensor()->dataType() == zynqmp::FP16) {
float16* chw = const_cast<float16*>(src->data<float16>());
float16* hwc = dest->mutable_data<float16>();
convert_to_hwc<float16>(chw, hwc, num, channel, height, width);
}
}
class TransHwcToChwCompute
: public KernelLite<TARGET(kFPGA), PRECISION(kAny), DATALAYOUT(kNHWC)> {
public:
void Run() override {
auto& param = Param<operators::LayoutParam>();
param.x->ZynqTensor()->syncToCPU();
TransHwcToChw(param.y, param.x);
param.y->ZynqTensor()->flush();
param.y->ZynqTensor()->copyScaleFrom(param.x->ZynqTensor());
param.y->ZynqTensor()->copyMaxFrom(param.x->ZynqTensor());
auto out_lod = param.y->mutable_lod();
*out_lod = param.x->lod();
}
std::unique_ptr<type_infer_handler_t> GetTypeInferHandler() override {
std::unique_ptr<type_infer_handler_t> res(new type_infer_handler_t);
*res = [](const std::map<std::string, const Type*>& inputs,
const std::string& out) -> const Type* {
CHECK(!inputs.empty());
auto* type = inputs.at("Input");
CHECK(type->layout() == DATALAYOUT(kNHWC));
auto out_place = type->place();
out_place.layout = DATALAYOUT(kNHWC);
auto* out_type = Type::Get(type->id(),
out_place.target,
out_place.precision,
out_place.layout,
out_place.device);
return out_type;
};
return res;
}
std::string doc() const override { return "Trans Layout from NHWC to NCHW"; }
};
/*
* This kernel copies a tensor from FPGA to host space.
*/
class TransChwToHwcCompute
: public KernelLite<TARGET(kFPGA), PRECISION(kAny), DATALAYOUT(kNHWC)> {
public:
void Run() override {
auto& param = Param<operators::LayoutParam>();
auto out_data = param.y->mutable_data<float16>(TARGET(kFPGA));
TransChwToHwc(param.y, param.x);
}
std::string doc() const override { return "Trans Layout from NHWC to NCHW"; }
};
} // namespace fpga
} // namespace kernels
} // namespace lite
} // namespace paddle
REGISTER_LITE_KERNEL(layout,
kFPGA,
kAny,
kNHWC,
paddle::lite::kernels::fpga::TransHwcToChwCompute,
hwc_to_chw_fpga_fp16)
.BindInput("Input",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNCHW))})
.Finalize();
REGISTER_LITE_KERNEL(layout,
kFPGA,
kAny,
kNHWC,
paddle::lite::kernels::fpga::TransHwcToChwCompute,
hwc_to_chw_arm_float)
.BindInput("Input",
{LiteType::GetTensorTy(TARGET(kARM),
PRECISION(kFloat),
DATALAYOUT(kNHWC))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kARM),
PRECISION(kFloat),
DATALAYOUT(kNCHW))})
.Finalize();
REGISTER_LITE_KERNEL(layout,
kFPGA,
kAny,
kNHWC,
paddle::lite::kernels::fpga::TransChwToHwcCompute,
chw_to_hwc_fpga_fp16)
.BindInput("Input",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNCHW))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.Finalize();
REGISTER_LITE_KERNEL(layout_once,
kFPGA,
kAny,
kNHWC,
paddle::lite::kernels::fpga::TransHwcToChwCompute,
hwc_to_chw_fpga_fp16)
.BindInput("Input",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNCHW))})
.Finalize();
REGISTER_LITE_KERNEL(layout_once,
kFPGA,
kAny,
kNHWC,
paddle::lite::kernels::fpga::TransChwToHwcCompute,
chw_to_hwc_fpga_fp16)
.BindInput("Input",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNCHW))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.Finalize(); | c++ | code | 8,930 | 2,046 |
/*
Copyright (c) 2020, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include "application_manager/application_manager.h"
#include "application_manager/commands/command_impl.h"
#include "application_manager/display_capabilities_builder.h"
#include "application_manager/event_engine/event_observer.h"
#include "application_manager/message_helper.h"
#include "application_manager/resumption/resumption_data_processor_impl.h"
#include "application_manager/rpc_plugins/rc_rpc_plugin/include/rc_rpc_plugin/rc_module_constants.h"
#include "application_manager/smart_object_keys.h"
namespace resumption {
using app_mngr::AppFile;
using app_mngr::ApplicationSharedPtr;
using app_mngr::ButtonSubscriptions;
using app_mngr::ChoiceSetMap;
using app_mngr::MessageHelper;
namespace strings = app_mngr::strings;
namespace event_engine = app_mngr::event_engine;
namespace commands = app_mngr::commands;
namespace message_params = rc_rpc_plugin::message_params;
SDL_CREATE_LOG_VARIABLE("Resumption")
bool ResumptionRequestID::operator<(const ResumptionRequestID& other) const {
return correlation_id < other.correlation_id ||
function_id < other.function_id;
}
ResumptionDataProcessorImpl::ResumptionDataProcessorImpl(
app_mngr::ApplicationManager& application_manager)
: event_engine::EventObserver(application_manager.event_dispatcher())
, application_manager_(application_manager)
, resumption_status_lock_()
, register_callbacks_lock_()
, request_app_ids_lock_() {}
ResumptionDataProcessorImpl::~ResumptionDataProcessorImpl() {}
void ResumptionDataProcessorImpl::Restore(
ApplicationSharedPtr application,
smart_objects::SmartObject& saved_app,
ResumeCtrl::ResumptionCallBack callback) {
SDL_LOG_AUTO_TRACE();
AddFiles(application, saved_app);
AddSubmenus(application, saved_app);
AddCommands(application, saved_app);
AddChoicesets(application, saved_app);
SetGlobalProperties(application, saved_app);
AddSubscriptions(application, saved_app);
AddWindows(application, saved_app);
const auto app_id = application->app_id();
if (!IsResumptionFinished(app_id)) {
sync_primitives::AutoWriteLock lock(register_callbacks_lock_);
register_callbacks_[app_id] = callback;
} else {
FinalizeResumption(callback, app_id);
}
}
utils::Optional<uint32_t>
ResumptionDataProcessorImpl::GetAppIdWaitingForResponse(
const hmi_apis::FunctionID::eType function_id, const int32_t corr_id) {
SDL_LOG_AUTO_TRACE();
auto predicate =
[function_id,
corr_id](const std::pair<ResumptionRequestID, std::uint32_t>& item) {
return item.first.function_id == function_id &&
item.first.correlation_id == corr_id;
};
sync_primitives::AutoReadLock lock(request_app_ids_lock_);
auto app_id_ptr =
std::find_if(request_app_ids_.begin(), request_app_ids_.end(), predicate);
if (app_id_ptr == request_app_ids_.end()) {
return utils::Optional<uint32_t>::OptionalEmpty::EMPTY;
}
return utils::Optional<uint32_t>(app_id_ptr->second);
}
utils::Optional<ResumptionRequest> ResumptionDataProcessorImpl::GetRequest(
const uint32_t app_id,
const hmi_apis::FunctionID::eType function_id,
const int32_t corr_id) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoReadLock lock(resumption_status_lock_);
std::vector<ResumptionRequest>& list_of_sent_requests =
resumption_status_[app_id].list_of_sent_requests;
if (resumption_status_.find(app_id) == resumption_status_.end()) {
SDL_LOG_ERROR("No resumption status info found for app_id: " << app_id);
return utils::Optional<ResumptionRequest>::OptionalEmpty::EMPTY;
}
auto request_iter =
std::find_if(list_of_sent_requests.begin(),
list_of_sent_requests.end(),
[function_id, corr_id](const ResumptionRequest& request) {
return request.request_id.correlation_id == corr_id &&
request.request_id.function_id == function_id;
});
if (list_of_sent_requests.end() == request_iter) {
return utils::Optional<ResumptionRequest>::OptionalEmpty::EMPTY;
}
return utils::Optional<ResumptionRequest>(*request_iter);
}
void ResumptionDataProcessorImpl::ProcessResumptionStatus(
const uint32_t app_id,
const smart_objects::SmartObject& response,
const ResumptionRequest& found_request) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoWriteLock lock(resumption_status_lock_);
ApplicationResumptionStatus& status = resumption_status_[app_id];
if (IsResponseSuccessful(response)) {
status.successful_requests.push_back(found_request);
} else {
status.error_requests.push_back(found_request);
}
if (hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData ==
found_request.request_id.function_id) {
CheckVehicleDataResponse(found_request.message, response, status);
}
if (hmi_apis::FunctionID::UI_CreateWindow ==
found_request.request_id.function_id) {
CheckCreateWindowResponse(found_request.message, response);
}
if (hmi_apis::FunctionID::RC_GetInteriorVehicleData ==
found_request.request_id.function_id) {
CheckModuleDataSubscription(found_request.message, response, status);
}
}
void ResumptionDataProcessorImpl::EraseProcessedRequest(
const uint32_t app_id, const ResumptionRequest& found_request) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoWriteLock lock(resumption_status_lock_);
auto& list_of_sent_requests =
resumption_status_[app_id].list_of_sent_requests;
auto request_iter =
std::find_if(list_of_sent_requests.begin(),
list_of_sent_requests.end(),
[found_request](const ResumptionRequest& request) {
return request.request_id.correlation_id ==
found_request.request_id.correlation_id &&
request.request_id.function_id ==
found_request.request_id.function_id;
});
list_of_sent_requests.erase(request_iter);
}
bool ResumptionDataProcessorImpl::IsResumptionFinished(
const uint32_t app_id) const {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoReadLock lock(resumption_status_lock_);
bool is_requests_list_empty = true;
const auto app_status = resumption_status_.find(app_id);
if (app_status != resumption_status_.end()) {
is_requests_list_empty = app_status->second.list_of_sent_requests.empty();
}
return is_requests_list_empty;
}
utils::Optional<ResumeCtrl::ResumptionCallBack>
ResumptionDataProcessorImpl::GetResumptionCallback(const uint32_t app_id) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoReadLock lock(register_callbacks_lock_);
auto it = register_callbacks_.find(app_id);
if (it == register_callbacks_.end()) {
return utils::Optional<
ResumeCtrl::ResumptionCallBack>::OptionalEmpty::EMPTY;
}
return utils::Optional<ResumeCtrl::ResumptionCallBack>(it->second);
}
bool ResumptionDataProcessorImpl::IsResumptionSuccessful(
const uint32_t app_id) {
sync_primitives::AutoReadLock lock(resumption_status_lock_);
auto it = resumption_status_.find(app_id);
if (resumption_status_.end() == it) {
return true;
}
const ApplicationResumptionStatus& status = it->second;
return status.error_requests.empty() &&
status.unsuccessful_vehicle_data_subscriptions_.empty() &&
status.unsuccessful_module_subscriptions_.empty();
}
void ResumptionDataProcessorImpl::EraseAppResumptionData(
const uint32_t app_id) {
SDL_LOG_AUTO_TRACE();
std::vector<ResumptionRequest> all_requests;
resumption_status_lock_.AcquireForWriting();
all_requests.insert(all_requests.end(),
resumption_status_[app_id].successful_requests.begin(),
resumption_status_[app_id].successful_requests.end());
all_requests.insert(all_requests.end(),
resumption_status_[app_id].error_requests.begin(),
resumption_status_[app_id].error_requests.end());
resumption_status_.erase(app_id);
resumption_status_lock_.Release();
request_app_ids_lock_.AcquireForWriting();
for (auto request : all_requests) {
request_app_ids_.erase(
{request.request_id.function_id, request.request_id.correlation_id});
}
request_app_ids_lock_.Release();
register_callbacks_lock_.AcquireForWriting();
register_callbacks_.erase(app_id);
register_callbacks_lock_.Release();
}
void ResumptionDataProcessorImpl::ProcessResponseFromHMI(
const smart_objects::SmartObject& response,
const hmi_apis::FunctionID::eType function_id,
const int32_t corr_id) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_TRACE("Now processing event with function id: "
<< function_id << " correlation id: " << corr_id);
auto found_app_id = GetAppIdWaitingForResponse(function_id, corr_id);
if (!found_app_id) {
SDL_LOG_ERROR("Application id for correlation id "
<< corr_id << " and function id: " << function_id
<< " was not found, such response is not expected.");
return;
}
const uint32_t app_id = *found_app_id;
SDL_LOG_DEBUG("app_id is: " << app_id);
auto found_request = GetRequest(app_id, function_id, corr_id);
if (!found_request) {
SDL_LOG_ERROR("Request with function id " << function_id << " and corr id "
<< corr_id << " not found");
return;
}
auto request = *found_request;
ProcessResumptionStatus(app_id, response, request);
EraseProcessedRequest(app_id, request);
if (!IsResumptionFinished(app_id)) {
SDL_LOG_DEBUG("Resumption app "
<< app_id << " not finished. Some requests are still waited");
return;
}
auto found_callback = GetResumptionCallback(app_id);
if (!found_callback) {
SDL_LOG_ERROR("Callback for app_id: " << app_id << " not found");
return;
}
auto callback = *found_callback;
FinalizeResumption(callback, app_id);
}
void ResumptionDataProcessorImpl::FinalizeResumption(
const ResumeCtrl::ResumptionCallBack& callback, const uint32_t app_id) {
if (IsResumptionSuccessful(app_id)) {
SDL_LOG_DEBUG("Resumption for app " << app_id << " successful");
callback(mobile_apis::Result::SUCCESS, "Data resumption successful");
application_manager_.state_controller().ResumePostponedWindows(app_id);
} else {
SDL_LOG_ERROR("Resumption for app " << app_id << " failed");
callback(mobile_apis::Result::RESUME_FAILED, "Data resumption failed");
RevertRestoredData(application_manager_.application(app_id));
application_manager_.state_controller().DropPostponedWindows(app_id);
}
EraseAppResumptionData(app_id);
}
void ResumptionDataProcessorImpl::HandleOnTimeOut(
const uint32_t corr_id, const hmi_apis::FunctionID::eType function_id) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_DEBUG("Handling timeout with corr id: "
<< corr_id << " and function_id: " << function_id);
auto error_response = MessageHelper::CreateNegativeResponseFromHmi(
function_id,
corr_id,
hmi_apis::Common_Result::GENERIC_ERROR,
std::string());
ProcessResponseFromHMI(*error_response, function_id, corr_id);
}
void ResumptionDataProcessorImpl::on_event(const event_engine::Event& event) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_DEBUG(
"Handling response message from HMI "
<< event.id() << " "
<< event.smart_object()[strings::params][strings::correlation_id]
.asInt());
ProcessResponseFromHMI(
event.smart_object(), event.id(), event.smart_object_correlation_id());
}
std::vector<ResumptionRequest> GetAllFailedRequests(
uint32_t app_id,
const std::map<std::int32_t, ApplicationResumptionStatus>&
resumption_status,
sync_primitives::RWLock& resumption_status_lock) {
resumption_status_lock.AcquireForReading();
std::vector<ResumptionRequest> failed_requests;
std::vector<ResumptionRequest> missed_requests;
auto it = resumption_status.find(app_id);
if (it != resumption_status.end()) {
failed_requests = it->second.error_requests;
missed_requests = it->second.list_of_sent_requests;
}
resumption_status_lock.Release();
failed_requests.insert(
failed_requests.end(), missed_requests.begin(), missed_requests.end());
return failed_requests;
}
void ResumptionDataProcessorImpl::RevertRestoredData(
ApplicationSharedPtr application) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_DEBUG("Reverting for app: " << application->app_id());
DeleteSubmenus(application);
DeleteCommands(application);
DeleteChoicesets(application);
DeleteGlobalProperties(application);
DeleteSubscriptions(application);
DeleteWindowsSubscriptions(application);
resumption_status_lock_.AcquireForWriting();
resumption_status_.erase(application->app_id());
resumption_status_lock_.Release();
register_callbacks_lock_.AcquireForWriting();
register_callbacks_.erase(application->app_id());
register_callbacks_lock_.Release();
}
void ResumptionDataProcessorImpl::SubscribeToResponse(
const int32_t app_id, const ResumptionRequest& request) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_DEBUG("App " << app_id << " subscribe on "
<< request.request_id.function_id << " "
<< request.request_id.correlation_id);
subscribe_on_event(request.request_id.function_id,
request.request_id.correlation_id);
resumption_status_lock_.AcquireForWriting();
resumption_status_[app_id].list_of_sent_requests.push_back(request);
resumption_status_lock_.Release();
request_app_ids_lock_.AcquireForWriting();
request_app_ids_.insert(std::make_pair(request.request_id, app_id));
request_app_ids_lock_.Release();
}
void ResumptionDataProcessorImpl::ProcessMessageToHMI(
smart_objects::SmartObjectSPtr message, bool subscribe_on_response) {
SDL_LOG_AUTO_TRACE();
if (subscribe_on_response) {
auto function_id = static_cast<hmi_apis::FunctionID::eType>(
(*message)[strings::params][strings::function_id].asInt());
const int32_t hmi_correlation_id =
(*message)[strings::params][strings::correlation_id].asInt();
const int32_t app_id =
(*message)[strings::msg_params][strings::app_id].asInt();
ResumptionRequest wait_for_response;
wait_for_response.request_id.correlation_id = hmi_correlation_id;
wait_for_response.request_id.function_id = function_id;
wait_for_response.message = *message;
SubscribeToResponse(app_id, wait_for_response);
}
if (!application_manager_.GetRPCService().ManageHMICommand(message)) {
SDL_LOG_ERROR("Unable to send request");
}
}
void ResumptionDataProcessorImpl::ProcessMessagesToHMI(
const smart_objects::SmartObjectList& messages) {
SDL_LOG_AUTO_TRACE();
for (const auto& message : messages) {
const bool is_request_message =
application_manager::MessageType::kRequest ==
(*message)[strings::params][strings::message_type].asInt();
ProcessMessageToHMI(message, is_request_message);
}
}
void ResumptionDataProcessorImpl::AddFiles(
app_mngr::ApplicationSharedPtr application,
const smart_objects::SmartObject& saved_app) {
SDL_LOG_AUTO_TRACE();
if (!saved_app.keyExists(strings::application_files)) {
SDL_LOG_ERROR("application_files section is not exists");
return;
}
const auto application_files =
saved_app[strings::application_files].asArray();
for (const auto file_data : *application_files) {
const bool is_persistent = file_data.keyExists(strings::persistent_file) &&
file_data[strings::persistent_file].asBool();
if (is_persistent) {
AppFile file;
file.is_persistent = is_persistent;
file.is_download_complete =
file_data[strings::is_download_complete].asBool();
file.file_name = file_data[strings::sync_file_name].asString();
file.file_type = static_cast<mobile_apis::FileType::eType>(
file_data[strings::file_type].asInt());
application->AddFile(file);
}
}
}
void ResumptionDataProcessorImpl::AddWindows(
application_manager::ApplicationSharedPtr application,
const ns_smart_device_link::ns_smart_objects::SmartObject& saved_app) {
SDL_LOG_AUTO_TRACE();
if (!saved_app.keyExists(strings::windows_info)) {
SDL_LOG_ERROR("windows_info section does not exist");
return;
}
const auto& windows_info = saved_app[strings::windows_info];
auto request_list = MessageHelper::CreateUICreateWindowRequestsToHMI(
application, application_manager_, windows_info);
ProcessMessagesToHMI(request_list);
}
void ResumptionDataProcessorImpl::AddSubmenus(
ApplicationSharedPtr application,
const smart_objects::SmartObject& saved_app) {
SDL_LOG_AUTO_TRACE();
if (!saved_app.keyExists(strings::application_submenus)) {
SDL_LOG_ERROR("application_submenus section is not exists");
return;
}
const smart_objects::SmartObject& app_submenus =
saved_app[strings::application_submenus];
for (size_t i = 0; i < app_submenus.length(); ++i) {
const smart_objects::SmartObject& submenu = app_submenus[i];
application->AddSubMenu(submenu[strings::menu_id].asUInt(), submenu);
}
ProcessMessagesToHMI(MessageHelper::CreateAddSubMenuRequestsToHMI(
application, application_manager_));
}
utils::Optional<ResumptionRequest> FindResumptionSubmenuRequest(
uint32_t menu_id, std::vector<ResumptionRequest>& requests) {
using namespace utils;
auto request_it = std::find_if(
requests.begin(),
requests.end(),
[menu_id](const ResumptionRequest& request) {
auto& msg_params = request.message[strings::msg_params];
if (hmi_apis::FunctionID::UI_AddSubMenu ==
request.request_id.function_id) {
uint32_t failed_menu_id = msg_params[strings::menu_id].asUInt();
return failed_menu_id == menu_id;
}
return false;
});
if (requests.end() != request_it) {
return Optional<ResumptionRequest>(*request_it);
}
return Optional<ResumptionRequest>::OptionalEmpty::EMPTY;
}
void ResumptionDataProcessorImpl::DeleteSubmenus(
ApplicationSharedPtr application) {
SDL_LOG_AUTO_TRACE();
auto failed_requests = GetAllFailedRequests(
application->app_id(), resumption_status_, resumption_status_lock_);
auto accessor = application->sub_menu_map();
const auto& sub_menu_map = accessor.GetData();
for (co | c++ | code | 20,000 | 3,480 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/system/proxy_message_pipe_endpoint.h"
#include <string.h>
#include "base/logging.h"
#include "mojo/system/channel.h"
#include "mojo/system/local_message_pipe_endpoint.h"
#include "mojo/system/message_pipe_dispatcher.h"
namespace mojo {
namespace system {
ProxyMessagePipeEndpoint::ProxyMessagePipeEndpoint()
: local_id_(MessageInTransit::kInvalidEndpointId),
remote_id_(MessageInTransit::kInvalidEndpointId),
is_peer_open_(true) {
}
ProxyMessagePipeEndpoint::ProxyMessagePipeEndpoint(
LocalMessagePipeEndpoint* local_message_pipe_endpoint,
bool is_peer_open)
: local_id_(MessageInTransit::kInvalidEndpointId),
remote_id_(MessageInTransit::kInvalidEndpointId),
is_peer_open_(is_peer_open),
paused_message_queue_(MessageInTransitQueue::PassContents(),
local_message_pipe_endpoint->message_queue()) {
local_message_pipe_endpoint->Close();
}
ProxyMessagePipeEndpoint::~ProxyMessagePipeEndpoint() {
DCHECK(!is_running());
DCHECK(!is_attached());
AssertConsistentState();
DCHECK(paused_message_queue_.IsEmpty());
}
MessagePipeEndpoint::Type ProxyMessagePipeEndpoint::GetType() const {
return kTypeProxy;
}
bool ProxyMessagePipeEndpoint::OnPeerClose() {
DCHECK(is_peer_open_);
is_peer_open_ = false;
// If our outgoing message queue isn't empty, we shouldn't be destroyed yet.
if (!paused_message_queue_.IsEmpty())
return true;
if (is_attached()) {
if (!is_running()) {
// If we're not running yet, we can't be destroyed yet, because we're
// still waiting for the "run" message from the other side.
return true;
}
Detach();
}
return false;
}
// Note: We may have to enqueue messages even when our (local) peer isn't open
// -- it may have been written to and closed immediately, before we were ready.
// This case is handled in |Run()| (which will call us).
void ProxyMessagePipeEndpoint::EnqueueMessage(
scoped_ptr<MessageInTransit> message) {
if (is_running()) {
message->SerializeAndCloseDispatchers(channel_.get());
message->set_source_id(local_id_);
message->set_destination_id(remote_id_);
if (!channel_->WriteMessage(message.Pass()))
LOG(WARNING) << "Failed to write message to channel";
} else {
paused_message_queue_.AddMessage(message.Pass());
}
}
void ProxyMessagePipeEndpoint::Attach(scoped_refptr<Channel> channel,
MessageInTransit::EndpointId local_id) {
DCHECK(channel);
DCHECK_NE(local_id, MessageInTransit::kInvalidEndpointId);
DCHECK(!is_attached());
AssertConsistentState();
channel_ = channel;
local_id_ = local_id;
AssertConsistentState();
}
bool ProxyMessagePipeEndpoint::Run(MessageInTransit::EndpointId remote_id) {
// Assertions about arguments:
DCHECK_NE(remote_id, MessageInTransit::kInvalidEndpointId);
// Assertions about current state:
DCHECK(is_attached());
DCHECK(!is_running());
AssertConsistentState();
remote_id_ = remote_id;
AssertConsistentState();
while (!paused_message_queue_.IsEmpty())
EnqueueMessage(paused_message_queue_.GetMessage());
if (is_peer_open_)
return true; // Stay alive.
// We were just waiting to die.
Detach();
return false;
}
void ProxyMessagePipeEndpoint::OnRemove() {
Detach();
}
void ProxyMessagePipeEndpoint::Detach() {
DCHECK(is_attached());
AssertConsistentState();
channel_->DetachMessagePipeEndpoint(local_id_, remote_id_);
channel_ = NULL;
local_id_ = MessageInTransit::kInvalidEndpointId;
remote_id_ = MessageInTransit::kInvalidEndpointId;
paused_message_queue_.Clear();
AssertConsistentState();
}
#ifndef NDEBUG
void ProxyMessagePipeEndpoint::AssertConsistentState() const {
if (is_attached()) {
DCHECK_NE(local_id_, MessageInTransit::kInvalidEndpointId);
} else { // Not attached.
DCHECK_EQ(local_id_, MessageInTransit::kInvalidEndpointId);
DCHECK_EQ(remote_id_, MessageInTransit::kInvalidEndpointId);
}
}
#endif
} // namespace system
} // namespace mojo | c++ | code | 4,224 | 768 |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2008 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
//
// This file includes implementation of GIF file metadata, according to GIF89a Specification.
// https://www.w3.org/Graphics/GIF/spec-gif89a.txt
// The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated.
// GIF(sm) is a Service Mark property of CompuServe Incorporated.
// All Rights Reserved . http://www.w3.org/Consortium/Legal
//
// =================================================================================================
#include "public/include/XMP_Environment.h" // ! Must be the first #include!
#include "XMPFiles/source/FileHandlers/GIF_Handler.hpp"
#include "source/XIO.hpp"
// =================================================================================================
/// \file GIF_Handler.hpp
/// \brief File format handler for GIF.
///
/// This handler ...
///
// =================================================================================================
// =================================================================================================
// GIF_MetaHandlerCTor
// ====================
XMPFileHandler * GIF_MetaHandlerCTor ( XMPFiles * parent )
{
return new GIF_MetaHandler ( parent );
} // GIF_MetaHandlerCTor
#define GIF_89_Header_LEN 6
#define GIF_89_Header_DATA "\x47\x49\x46\x38\x39\x61" // must be GIF89a, nothing else as XMP is supported only in 89a version
#define APP_ID_LEN 11
#define XMP_APP_ID_DATA "\x58\x4D\x50\x20\x44\x61\x74\x61\x58\x4D\x50"
#define MAGIC_TRAILER_LEN 258
// =================================================================================================
// GIF_CheckFormat
// ===============
bool GIF_CheckFormat ( XMP_FileFormat format,
XMP_StringPtr filePath,
XMP_IO* fileRef,
XMPFiles * parent )
{
IgnoreParam(format); IgnoreParam(filePath); IgnoreParam(parent);
XMP_Assert ( format == kXMP_GIFFile );
if ( fileRef->Length() < GIF_89_Header_LEN ) return false;
XMP_Uns8 buffer[ GIF_89_Header_LEN ];
fileRef->Rewind();
fileRef->Read( buffer, GIF_89_Header_LEN );
if ( !CheckBytes( buffer, GIF_89_Header_DATA, GIF_89_Header_LEN ) ) return false;
return true;
} // GIF_CheckFormat
// =================================================================================================
// GIF_MetaHandler::GIF_MetaHandler
// ==================================
GIF_MetaHandler::GIF_MetaHandler( XMPFiles * _parent ) : XMPPacketOffset( 0 ), XMPPacketLength( 0 ), trailerOffset( 0 )
{
this->parent = _parent;
this->handlerFlags = kGIF_HandlerFlags;
// It MUST be UTF-8.
this->stdCharForm = kXMP_Char8Bit;
}
// =================================================================================================
// GIF_MetaHandler::~GIF_MetaHandler
// ===================================
GIF_MetaHandler::~GIF_MetaHandler()
{
}
// =================================================================================================
// GIF_MetaHandler::CacheFileData
// ===============================
void GIF_MetaHandler::CacheFileData()
{
this->containsXMP = false;
XMP_IO * fileRef = this->parent->ioRef;
// Try to navigate through the blocks to find the XMP block.
if ( this->ParseGIFBlocks( fileRef ) )
{
// XMP packet present
this->xmpPacket.assign( XMPPacketLength, ' ' );
// 13 bytes for the block size and 2 bytes for Extension ID and Label
this->SeekFile( fileRef, XMPPacketOffset, kXMP_SeekFromStart );
fileRef->ReadAll( ( void* )this->xmpPacket.data(), XMPPacketLength );
this->packetInfo.offset = XMPPacketOffset;
this->packetInfo.length = XMPPacketLength;
this->containsXMP = true;
}
// else no XMP
} // GIF_MetaHandler::CacheFileData
// =================================================================================================
// GIF_MetaHandler::ProcessXMP
// ===========================
//
// Process the raw XMP and legacy metadata that was previously cached.
void GIF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
// Process the XMP packet.
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen) this->xmpPacket.size();
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
this->containsXMP = true;
}
} // GIF_MetaHandler::ProcessXMP
// =================================================================================================
// GIF_MetaHandler::ParseGIFBlocks
// ===========================
bool GIF_MetaHandler::ParseGIFBlocks( XMP_IO* fileRef )
{
fileRef->Rewind();
// Checking for GIF header
XMP_Uns8 buffer[ GIF_89_Header_LEN ];
fileRef->Read( buffer, GIF_89_Header_LEN );
XMP_Enforce( memcmp( buffer, GIF_89_Header_DATA, GIF_89_Header_LEN ) == 0 );
bool IsXMPExists = false;
bool IsTrailerExists = false;
ReadLogicalScreenDesc( fileRef );
// Parsing rest of the blocks
while ( fileRef->Offset() != fileRef->Length() )
{
XMP_Uns8 blockType;
// Read the block type byte
fileRef->Read( &blockType, 1 );
if ( blockType == kXMP_block_ImageDesc )
{
// ImageDesc is a special case, So read data just like its structure.
long tableSize = 0;
XMP_Uns8 fields;
// Reading Dimesnions of image as
// 2 bytes = Image Left Position
// + 2 bytes = Image Right Position
// + 2 bytes = Image Width
// + 2 bytes = Image Height
// = 8 bytes
this->SeekFile( fileRef, 8, kXMP_SeekFromCurrent );
// Reading one byte for Packed Fields
fileRef->Read( &fields, 1 );
// Getting Local Table Size and skipping table size
if ( fields & 0x80 )
{
tableSize = ( 1 << ( ( fields & 0x07 ) + 1 ) ) * 3;
this->SeekFile( fileRef, tableSize, kXMP_SeekFromCurrent );
}
// 1 byte LZW Minimum code size
this->SeekFile( fileRef, 1, kXMP_SeekFromCurrent );
XMP_Uns8 subBlockSize;
// 1 byte compressed sub-block size
fileRef->Read( &subBlockSize, 1 );
while ( subBlockSize != 0x00 )
{
// Skipping compressed data sub-block
this->SeekFile( fileRef, subBlockSize, kXMP_SeekFromCurrent );
// 1 byte compressed sub-block size
fileRef->Read( &subBlockSize, 1 );
}
}
else if ( blockType == kXMP_block_Extension )
{
XMP_Uns8 extensionLbl;
XMP_Uns32 blockSize = 0;
/*XMP_Uns64 blockOffset = fileRef->Offset();*/
// Extension Label
fileRef->Read( &extensionLbl, 1 );
// Block or Sub-Block size
fileRef->Read( &blockSize, 1 );
// Checking for Application Extension label and blockSize
if ( extensionLbl == 0xFF && blockSize == APP_ID_LEN )
{
XMP_Uns8 idData[ APP_ID_LEN ];
fileRef->Read( idData, APP_ID_LEN, true );
// Checking For XMP ID
if ( memcmp( idData, XMP_APP_ID_DATA, APP_ID_LEN ) == 0 )
{
XMPPacketOffset = fileRef->Offset();
IsXMPExists = true;
}
// Parsing sub-blocks
XMP_Uns8 subBlockSize;
fileRef->Read( &subBlockSize, 1 );
while ( subBlockSize != 0x00 )
{
this->SeekFile( fileRef, subBlockSize, kXMP_SeekFromCurrent );
fileRef->Read( &subBlockSize, 1 );
}
if ( IsXMPExists )
XMPPacketLength = static_cast< XMP_Uns32 >( fileRef->Offset() - XMPPacketOffset - MAGIC_TRAILER_LEN );
}
else
{
// Extension block other than Application Extension
while ( blockSize != 0x00 )
{
// Seeking block size or sub-block size
this->SeekFile( fileRef, blockSize, kXMP_SeekFromCurrent );
// Block Size
fileRef->Read( &blockSize, 1 );
}
}
}
else if ( blockType == kXMP_block_Trailer )
{
// 1 byte is subtracted for block type
trailerOffset = fileRef->Offset() - 1;
IsTrailerExists = true;
break;
}
else
XMP_Throw( "Invaild GIF Block", kXMPErr_BadBlockFormat );
}
if ( !IsTrailerExists )
XMP_Throw( "No trailer exists for GIF file", kXMPErr_BadFileFormat );
return IsXMPExists;
} // GIF_MetaHandler::ParseGIFBlocks
// =================================================================================================
// GIF_MetaHandler::ReadLogicalScreenDesc
// ===========================
void GIF_MetaHandler::ReadLogicalScreenDesc( XMP_IO* fileRef )
{
XMP_Uns8 fields;
// 2 bytes for Screen Width
// + 2 bytes for Screen Height
// = 4 Bytes
this->SeekFile( fileRef, 4, kXMP_SeekFromCurrent );
// 1 byte for Packed Fields
fileRef->Read( &fields, 1 );
// 1 byte for Background Color Index
// + 1 byte for Pixel Aspect Ratio
// = 2 bytes
this->SeekFile( fileRef, 2, kXMP_SeekFromCurrent );
// Look for Global Color Table if exists
if ( fields & 0x80 )
{
long tableSize = ( 1 << ( ( fields & 0x07 ) + 1 ) ) * 3;
this->SeekFile( fileRef, tableSize, kXMP_SeekFromCurrent );
}
} // GIF_MetaHandler::ReadLogicalScreenDesc
// =================================================================================================
// GIF_MetaHandler::SeekFile
// ===========================
void GIF_MetaHandler::SeekFile( XMP_IO * fileRef, XMP_Int64 offset, SeekMode mode )
{
if ( offset > fileRef->Length() || ( mode == kXMP_SeekFromCurrent && fileRef->Offset() + offset > fileRef->Length() ) )
{
XMP_Throw( "Out of range seek operation", kXMPErr_InternalFailure );
}
else
fileRef->Seek( offset, mode );
} // GIF_MetaHandler::SeekFile
// =================================================================================================
// GIF_MetaHandler::UpdateFile
// ===========================
void GIF_MetaHandler::UpdateFile ( bool doSafeUpdate )
{
IgnoreParam(doSafeUpdate);
XMP_Assert( !doSafeUpdate ); // This should only be called for "unsafe" updates.
if ( ! this->needsUpdate ) return;
XMP_IO * fileRef = this->parent->ioRef;
/*XMP_StringPtr packetStr = xmpPacket.c_str();*/
XMP_StringLen newPacketLength = (XMP_StringLen)xmpPacket.size();
if ( newPacketLength == XMPPacketLength )
{
this->SeekFile( fileRef, this->packetInfo.offset, kXMP_SeekFromStart );
fileRef->Write( this->xmpPacket.c_str(), newPacketLength );
}
else
{
XMP_IO* tempFile = fileRef->DeriveTemp();
if ( tempFile == 0 ) XMP_Throw( "Failure creating GIF temp file", kXMPErr_InternalFailure );
this->WriteTempFile( tempFile );
fileRef->AbsorbTemp();
}
this->needsUpdate = false;
} // GIF_MetaHandler::UpdateFile
// =================================================================================================
// GIF_MetaHandler::WriteTempFile
// ==============================
void GIF_MetaHandler::WriteTempFile ( XMP_IO* tempRef )
{
XMP_Assert( this->needsUpdate );
XMP_IO* originalRef = this->parent->ioRef;
originalRef->Rewind();
tempRef->Truncate ( 0 );
if ( XMPPacketOffset != 0 )
{
// Copying blocks before XMP Application Block
XIO::Copy( originalRef, tempRef, XMPPacketOffset );
// Writing XMP Packet
tempRef->Write( this->xmpPacket.c_str(), (XMP_Uns32)this->xmpPacket.size() );
// Copying Rest of the file
originalRef->Seek( XMPPacketLength, kXMP_SeekFromCurrent );
XIO::Copy( originalRef, tempRef, originalRef->Length() - originalRef->Offset() );
}
else
{
if ( trailerOffset == 0 )
XMP_Throw( "Not able to write XMP packet in GIF file", kXMPErr_BadFileFormat );
// Copying blocks before XMP Application Block
XIO::Copy( originalRef, tempRef, trailerOffset );
// Writing Extension Introducer
XIO::WriteUns8( tempRef, kXMP_block_Extension );
// Writing Application Extension label
XIO::WriteUns8( tempRef, 0xFF );
// Writing Application Extension label
XIO::WriteUns8( tempRef, APP_ID_LEN );
// Writing Application Extension label
tempRef->Write( XMP_APP_ID_DATA, APP_ID_LEN );
// Writing XMP Packet
tempRef->Write( this->xmpPacket.c_str(), (XMP_Uns32)this->xmpPacket.size() );
// Writing Magic trailer
XMP_Uns8 magicByte = 0x01;
tempRef->Write( &magicByte, 1 );
for ( magicByte = 0xFF; magicByte != 0x00; --magicByte )
tempRef->Write( &magicByte, 1 );
tempRef->Write( &magicByte, 1 );
tempRef->Write( &magicByte, 1 );
// Copying Rest of the file
XIO::Copy( originalRef, tempRef, originalRef->Length() - originalRef->Offset() );
}
} // GIF_MetaHandler::WriteTempFile
// ================================================================================================= | c++ | code | 12,610 | 2,199 |
**
** Copyright 2012, The Android Open Source Project
**
** 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.
*/
// This source file is automatically generated
#include "jni.h"
#include "JNIHelp.h"
#include <android_runtime/AndroidRuntime.h>
#include <android_runtime/android_view_Surface.h>
#include <android_runtime/android_graphics_SurfaceTexture.h>
#include <utils/misc.h>
#include <assert.h>
#include <EGL/egl.h>
#include <gui/Surface.h>
#include <gui/SurfaceTexture.h>
#include <gui/SurfaceTextureClient.h>
#include <ui/ANativeObjectBase.h>
static int initialized = 0;
static jclass egldisplayClass;
static jclass eglcontextClass;
static jclass eglsurfaceClass;
static jclass eglconfigClass;
static jmethodID egldisplayGetHandleID;
static jmethodID eglcontextGetHandleID;
static jmethodID eglsurfaceGetHandleID;
static jmethodID eglconfigGetHandleID;
static jmethodID egldisplayConstructor;
static jmethodID eglcontextConstructor;
static jmethodID eglsurfaceConstructor;
static jmethodID eglconfigConstructor;
static jobject eglNoContextObject;
static jobject eglNoDisplayObject;
static jobject eglNoSurfaceObject;
/* Cache method IDs each time the class is loaded. */
static void
nativeClassInit(JNIEnv *_env, jclass glImplClass)
{
jclass egldisplayClassLocal = _env->FindClass("android/opengl/EGLDisplay");
egldisplayClass = (jclass) _env->NewGlobalRef(egldisplayClassLocal);
jclass eglcontextClassLocal = _env->FindClass("android/opengl/EGLContext");
eglcontextClass = (jclass) _env->NewGlobalRef(eglcontextClassLocal);
jclass eglsurfaceClassLocal = _env->FindClass("android/opengl/EGLSurface");
eglsurfaceClass = (jclass) _env->NewGlobalRef(eglsurfaceClassLocal);
jclass eglconfigClassLocal = _env->FindClass("android/opengl/EGLConfig");
eglconfigClass = (jclass) _env->NewGlobalRef(eglconfigClassLocal);
egldisplayGetHandleID = _env->GetMethodID(egldisplayClass, "getHandle", "()I");
eglcontextGetHandleID = _env->GetMethodID(eglcontextClass, "getHandle", "()I");
eglsurfaceGetHandleID = _env->GetMethodID(eglsurfaceClass, "getHandle", "()I");
eglconfigGetHandleID = _env->GetMethodID(eglconfigClass, "getHandle", "()I");
egldisplayConstructor = _env->GetMethodID(egldisplayClass, "<init>", "(I)V");
eglcontextConstructor = _env->GetMethodID(eglcontextClass, "<init>", "(I)V");
eglsurfaceConstructor = _env->GetMethodID(eglsurfaceClass, "<init>", "(I)V");
eglconfigConstructor = _env->GetMethodID(eglconfigClass, "<init>", "(I)V");
jobject localeglNoContextObject = _env->NewObject(eglcontextClass, eglcontextConstructor, (jint)EGL_NO_CONTEXT);
eglNoContextObject = _env->NewGlobalRef(localeglNoContextObject);
jobject localeglNoDisplayObject = _env->NewObject(egldisplayClass, egldisplayConstructor, (jint)EGL_NO_DISPLAY);
eglNoDisplayObject = _env->NewGlobalRef(localeglNoDisplayObject);
jobject localeglNoSurfaceObject = _env->NewObject(eglsurfaceClass, eglsurfaceConstructor, (jint)EGL_NO_SURFACE);
eglNoSurfaceObject = _env->NewGlobalRef(localeglNoSurfaceObject);
jclass eglClass = _env->FindClass("android/opengl/EGL14");
jfieldID noContextFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_CONTEXT", "Landroid/opengl/EGLContext;");
_env->SetStaticObjectField(eglClass, noContextFieldID, eglNoContextObject);
jfieldID noDisplayFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_DISPLAY", "Landroid/opengl/EGLDisplay;");
_env->SetStaticObjectField(eglClass, noDisplayFieldID, eglNoDisplayObject);
jfieldID noSurfaceFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_SURFACE", "Landroid/opengl/EGLSurface;");
_env->SetStaticObjectField(eglClass, noSurfaceFieldID, eglNoSurfaceObject);
}
static void *
fromEGLHandle(JNIEnv *_env, jmethodID mid, jobject obj) {
if (obj == NULL){
jniThrowException(_env, "java/lang/IllegalArgumentException",
"Object is set to null.");
}
return (void*) (_env->CallIntMethod(obj, mid));
}
static jobject
toEGLHandle(JNIEnv *_env, jclass cls, jmethodID con, void * handle) {
if (cls == eglcontextClass &&
(EGLContext)handle == EGL_NO_CONTEXT) {
return eglNoContextObject;
}
if (cls == egldisplayClass &&
(EGLDisplay)handle == EGL_NO_DISPLAY) {
return eglNoDisplayObject;
}
if (cls == eglsurfaceClass &&
(EGLSurface)handle == EGL_NO_SURFACE) {
return eglNoSurfaceObject;
}
return _env->NewObject(cls, con, (jint)handle);
}
// -------------------------------------------------------------------------- | c++ | code | 5,117 | 959 |
/*
* Copyright (c) 2015, 2020, 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_GC_Z_ZLOCK_INLINE_HPP
#define SHARE_GC_Z_ZLOCK_INLINE_HPP
#include "gc/z/zLock.hpp"
#include "runtime/atomic.hpp"
#include "runtime/os.inline.hpp"
#include "runtime/thread.hpp"
#include "utilities/debug.hpp"
inline void ZLock::lock() {
_lock.lock();
}
inline bool ZLock::try_lock() {
return _lock.try_lock();
}
inline void ZLock::unlock() {
_lock.unlock();
}
inline ZReentrantLock::ZReentrantLock() :
_lock(),
_owner(NULL),
_count(0) {}
inline void ZReentrantLock::lock() {
Thread* const thread = Thread::current();
Thread* const owner = Atomic::load(&_owner);
if (owner != thread) {
_lock.lock();
Atomic::store(&_owner, thread);
}
_count++;
}
inline void ZReentrantLock::unlock() {
assert(is_owned(), "Invalid owner");
assert(_count > 0, "Invalid count");
_count--;
if (_count == 0) {
Atomic::store(&_owner, (Thread*)NULL);
_lock.unlock();
}
}
inline bool ZReentrantLock::is_owned() const {
Thread* const thread = Thread::current();
Thread* const owner = Atomic::load(&_owner);
return owner == thread;
}
inline void ZConditionLock::lock() {
_lock.lock();
}
inline bool ZConditionLock::try_lock() {
return _lock.try_lock();
}
inline void ZConditionLock::unlock() {
_lock.unlock();
}
inline bool ZConditionLock::wait(uint64_t millis) {
return _lock.wait(millis) == OS_OK;
}
inline void ZConditionLock::notify() {
_lock.notify();
}
inline void ZConditionLock::notify_all() {
_lock.notify_all();
}
template <typename T>
inline ZLocker<T>::ZLocker(T* lock) :
_lock(lock) {
if (_lock != NULL) {
_lock->lock();
}
}
template <typename T>
inline ZLocker<T>::~ZLocker() {
if (_lock != NULL) {
_lock->unlock();
}
}
#endif // SHARE_GC_Z_ZLOCK_INLINE_HPP | c++ | code | 2,828 | 670 |
/*
* Copyright (c) 2018, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed_assert.h"
#include "platform/arm_hal_interrupt.h"
#ifdef MBED_CONF_RTOS_PRESENT
#include "cmsis.h"
#include "cmsis_os2.h"
#include "mbed_rtos_storage.h"
#endif
#include "ns_trace.h"
#include "eventOS_scheduler.h"
#include "mbed_error.h"
#include "mbed_shared_queues.h"
#include "events/Event.h"
#include "ns_event_loop_mutex.h"
#include "ns_event_loop.h"
#define TRACE_GROUP "evlp"
#if MBED_CONF_NANOSTACK_HAL_EVENT_LOOP_USE_MBED_EVENTS
using events::EventQueue;
using events::Event;
static Event<void()> *event;
static volatile int event_pending;
static volatile bool started;
void eventOS_scheduler_signal(void)
{
platform_enter_critical();
if (started && event_pending == 0) {
event_pending = event->post();
MBED_ASSERT(event_pending != 0);
}
platform_exit_critical();
}
void eventOS_scheduler_idle(void)
{
error("Shouldn't be called");
}
static void do_dispatch_with_mutex_held()
{
platform_enter_critical();
event_pending = 0;
platform_exit_critical();
/* Process only 1 Nanostack event at a time, to try to be nice to
* others on the global queue.
*/
eventOS_scheduler_mutex_wait();
bool dispatched = eventOS_scheduler_dispatch_event();
eventOS_scheduler_mutex_release();
/* Go round again if (potentially) more */
if (dispatched) {
eventOS_scheduler_signal();
}
}
void ns_event_loop_init(void)
{
ns_event_loop_mutex_init();
}
void ns_event_loop_thread_create(void)
{
EventQueue *equeue = mbed::mbed_event_queue();
MBED_ASSERT(equeue != NULL);
event = new Event<void()>(equeue, do_dispatch_with_mutex_held);
MBED_ASSERT(event != NULL);
}
void ns_event_loop_thread_start(void)
{
started = true;
eventOS_scheduler_signal();
}
#endif // MBED_CONF_NANOSTACK_HAL_EVENT_LOOP_USE_MBED_EVENTS | c++ | code | 2,499 | 454 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/experimental/map_and_batch_dataset_op.h"
#include <atomic>
#include <utility>
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/input_colocation_exemption_registry.h"
#include "tensorflow/core/common_runtime/metrics.h"
#include "tensorflow/core/framework/model.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/stats_aggregator.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/name_utils.h"
#include "tensorflow/core/kernels/data/stats_utils.h"
#include "tensorflow/core/kernels/inplace_ops_functor.h"
#include "tensorflow/core/lib/core/blocking_counter.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/stringprintf.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
namespace data {
namespace experimental {
/* static */ constexpr const char* const MapAndBatchDatasetOp::kDatasetType;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kInputDataset;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kOtherArguments;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kBatchSize;
/* static */ constexpr const char* const
MapAndBatchDatasetOp::kNumParallelCalls;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kDropRemainder;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kFunc;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kTarguments;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kOutputTypes;
/* static */ constexpr const char* const MapAndBatchDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
MapAndBatchDatasetOp::kPreserveCardinality;
// Maximum number of batch results to buffer.
constexpr int64 kMaxBatchResults = 16;
constexpr char kParallelism[] = "parallelism";
constexpr char kCallCounter[] = "call_counter";
constexpr char kBatchResultsSize[] = "batch_results_size";
constexpr char kTFDataMapAndBatch[] = "tf_data_map_and_batch";
constexpr char kBatchResults[] = "batch_results";
constexpr char kEndOfInput[] = "end_of_input";
constexpr char kNumCalls[] = "num_calls";
constexpr char kNumElements[] = "num_elements";
constexpr char kOutputAllocated[] = "output_allocated";
constexpr char kOutputSize[] = "output_size";
constexpr char kOutput[] = "output";
constexpr char kStatus[] = "status";
constexpr char kCode[] = "code";
constexpr char kMessage[] = "msg";
class MapAndBatchDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input, int64 batch_size,
int64 num_parallel_calls, bool drop_remainder,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes,
std::unique_ptr<CapturedFunction> captured_func,
bool preserve_cardinality)
: DatasetBase(DatasetContext(ctx)),
input_(input),
batch_size_(batch_size),
num_parallel_calls_(num_parallel_calls),
drop_remainder_(drop_remainder),
output_types_(output_types),
output_shapes_(output_shapes),
captured_func_(std::move(captured_func)),
preserve_cardinality_(preserve_cardinality),
traceme_metadata_(
{{"autotune",
num_parallel_calls == model::kAutotune ? "true" : "false"},
{"batch_size", strings::Printf("%lld", batch_size)},
{"drop_remainder", drop_remainder ? "true" : "false"}}) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
const DataTypeVector& output_dtypes() const override { return output_types_; }
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
int64 Cardinality() const override {
int64 n = input_->Cardinality();
if (n == kInfiniteCardinality || n == kUnknownCardinality) {
return n;
}
return n / batch_size_ + (n % batch_size_ == 0 || drop_remainder_ ? 0 : 1);
}
Status CheckExternalState() const override {
TF_RETURN_IF_ERROR(captured_func_->CheckExternalState());
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* batch_size_node;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size_node));
Node* num_parallel_calls_node;
TF_RETURN_IF_ERROR(
b->AddScalar(num_parallel_calls_, &num_parallel_calls_node));
Node* drop_remainder_node;
TF_RETURN_IF_ERROR(b->AddScalar(drop_remainder_, &drop_remainder_node));
std::vector<Node*> other_arguments;
DataTypeVector other_arguments_types;
TF_RETURN_IF_ERROR(captured_func_->AddToGraph(ctx, b, &other_arguments,
&other_arguments_types));
AttrValue f;
b->BuildAttrValue(captured_func_->func(), &f);
AttrValue other_arguments_types_attr;
b->BuildAttrValue(other_arguments_types, &other_arguments_types_attr);
AttrValue preserve_cardinality_attr;
b->BuildAttrValue(preserve_cardinality_, &preserve_cardinality_attr);
TF_RETURN_IF_ERROR(b->AddDataset(
this,
{std::make_pair(0, input_graph_node),
std::make_pair(2, batch_size_node),
std::make_pair(3, num_parallel_calls_node),
std::make_pair(4, drop_remainder_node)}, // Single tensor inputs.
{std::make_pair(1, other_arguments)}, // Tensor list inputs.
{std::make_pair(kFunc, f),
std::make_pair(kTarguments, other_arguments_types_attr),
std::make_pair(kPreserveCardinality,
preserve_cardinality_attr)}, // Attrs
output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
mu_(std::make_shared<mutex>()),
cond_var_(std::make_shared<condition_variable>()),
num_parallel_calls_(std::make_shared<model::SharedState>(
params.dataset->num_parallel_calls_, mu_, cond_var_)),
max_batch_results_(
params.dataset->num_parallel_calls_ == model::kAutotune
? kMaxBatchResults
: std::min(kMaxBatchResults,
(params.dataset->num_parallel_calls_ +
params.dataset->batch_size_ - 1) /
params.dataset->batch_size_)) {}
~Iterator() override {
CancelThreads(/*wait=*/true);
if (deregister_fn_) deregister_fn_();
}
Status Initialize(IteratorContext* ctx) override {
mutex_lock l(*mu_);
if (num_parallel_calls_->value == model::kAutotune) {
num_parallel_calls_->value = ctx->runner_threadpool_size();
}
TF_RETURN_IF_ERROR(RegisterCancellationCallback(
ctx->cancellation_manager(),
[this]() { CancelThreads(/*wait=*/false); }, &deregister_fn_));
TF_RETURN_IF_ERROR(
dataset()->input_->MakeIterator(ctx, this, prefix(), &input_impl_));
return dataset()->captured_func_->Instantiate(
ctx, &instantiated_captured_func_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
std::shared_ptr<BatchResult> result;
{
mutex_lock l(*mu_);
EnsureRunnerThreadStarted(ctx);
while (!cancelled_ && (batch_results_.empty() ||
batch_results_.front()->num_calls > 0)) {
++waiting_;
RecordStop(ctx);
cond_var_->wait(l);
RecordStart(ctx);
--waiting_;
}
if (cancelled_) {
return errors::Cancelled("Iterator was cancelled");
}
std::swap(result, batch_results_.front());
batch_results_.pop_front();
cond_var_->notify_all();
}
return ProcessResult(ctx, result, out_tensors, end_of_sequence);
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeAsyncKnownRatioNode(
std::move(args), dataset()->batch_size_,
{model::MakeParameter(kParallelism, num_parallel_calls_, /*min=*/1,
/*max=*/ctx->runner_threadpool_size())});
}
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(*mu_);
// Wait for all in-flight calls to complete.
while (num_calls_ > 0) {
cond_var_->wait(l);
}
DCHECK_EQ(num_calls_, 0);
TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name(kCallCounter), call_counter_));
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name(kBatchResultsSize),
batch_results_.size()));
for (size_t i = 0; i < batch_results_.size(); ++i) {
TF_RETURN_IF_ERROR(WriteBatchResult(writer, i));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(*mu_);
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name(kCallCounter), &call_counter_));
int64 batch_results_size;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kBatchResultsSize),
&batch_results_size));
for (int i = 0; i < batch_results_size; ++i) {
TF_RETURN_IF_ERROR(ReadBatchResult(ctx, reader, i));
}
return Status::OK();
}
TraceMeMetadata GetTraceMeMetadata() const override {
int64 parallelism = -1;
// NOTE: We only set the parallelism value if the lock can be acquired
// right away to avoid introducing tracing overhead.
if (mu_->try_lock()) {
parallelism = num_parallel_calls_->value;
mu_->unlock();
}
auto result = dataset()->traceme_metadata_;
result.push_back(
std::make_pair("parallelism", strings::Printf("%lld", parallelism)));
return result;
}
private:
// BatchResult encapsulates the output batch, as well as ancillary
// metadata required to execute the fused map-and-batch operation.
struct BatchResult {
explicit BatchResult(int64 batch_size) {
end_of_input = false;
num_calls = batch_size;
num_elements = 0;
output_allocated = false;
status = Status::OK();
status_offset = -1;
}
// UpdateStatus updates the batch's aggregate Status.
//
// In order to ensure that exactly the first non-OK status is returned
// (required to make the behavior is observably identical to a
// sequential execution of map followed by batch), we must also keep
// track of the offset into the batch that produced `s`.
void UpdateStatus(const Status& s, int64 offset) {
if (TF_PREDICT_FALSE(!s.ok())) {
mutex_lock l(mu);
if (status.ok() || offset < status_offset) {
status = s;
status_offset = offset;
}
}
}
mutex mu;
bool end_of_input GUARDED_BY(mu);
int64 num_elements GUARDED_BY(mu);
std::vector<Tensor> output;
bool output_allocated GUARDED_BY(mu);
Status status GUARDED_BY(mu);
int64 status_offset GUARDED_BY(mu);
// Counts the number of outstanding calls for this batch.
int64 num_calls; // access guarded by owner's mutex
};
void CallCompleted(const std::shared_ptr<IteratorContext>& ctx,
const std::shared_ptr<BatchResult>& result)
LOCKS_EXCLUDED(*mu_) {
mutex_lock l(*mu_);
num_calls_--;
result->num_calls--;
const auto& stats_aggregator = ctx->stats_aggregator();
if (stats_aggregator) {
stats_aggregator->AddScalar(
stats_utils::ThreadUtilizationScalarName(dataset()->node_name()),
static_cast<float>(num_calls_) /
static_cast<float>(num_parallel_calls_->value),
num_elements());
}
cond_var_->notify_all();
}
void CallFunction(std::shared_ptr<IteratorContext> ctx,
const std::shared_ptr<BatchResult>& result, int64 offset)
LOCKS_EXCLUDED(*mu_) {
// Get the next input element.
std::vector<Tensor> input_element;
bool end_of_input = false;
Status status =
input_impl_->GetNext(ctx.get(), &input_element, &end_of_input);
bool return_early;
{
mutex_lock l(result->mu);
result->end_of_input = result->end_of_input || end_of_input;
result->status.Update(status);
return_early = result->end_of_input || !result->status.ok();
}
if (return_early) {
CallCompleted(ctx, result);
return;
}
std::shared_ptr<std::vector<Tensor>> return_values =
std::make_shared<std::vector<Tensor>>();
auto done = [this, ctx, result, return_values, offset](Status status) {
if (dataset()->preserve_cardinality_ && errors::IsOutOfRange(status)) {
// To guarantee that the transformation preserves the cardinality of
// the dataset, we convert `OutOfRange` to `InvalidArgument` as the
// former may be interpreted by a caller as the end of sequence.
status = errors::InvalidArgument(
"Function invocation produced OutOfRangeError: ",
status.error_message());
}
result->UpdateStatus(status, offset);
if (status.ok()) {
Status allocate_status =
EnsureOutputAllocated(ctx, result, return_values);
if (!allocate_status.ok()) {
result->UpdateStatus(allocate_status, offset);
} else {
for (size_t i = 0; i < return_values->size(); ++i) {
Tensor& tensor = return_values->at(i);
Tensor* batch = &(result->output)[i];
if (tensor.NumElements() !=
(batch->NumElements() / batch->dim_size(0))) {
TensorShape batch_shape = batch->shape();
batch_shape.RemoveDim(0);
result->UpdateStatus(
errors::InvalidArgument(
"Cannot add tensor to the batch: number of elements "
"does not match. Shapes are: [tensor]: ",
tensor.shape().DebugString(),
", [batch]: ", batch_shape.DebugString()),
offset);
break;
}
// TODO(mrry): Add a version of DoParallelConcat that allows us
// to move `tensor` where possible, to speed up string tensor
// batching.
Status copy_status = batch_util::CopyElementToSlice(
std::move(tensor), batch, offset);
if (!copy_status.ok()) {
result->UpdateStatus(copy_status, offset);
break;
}
}
}
{
mutex_lock l(result->mu);
result->num_elements++;
}
}
CallCompleted(ctx, result);
};
// Apply the map function on `input_element`, storing the result in
// `return_values`, and invoking `done` when finished.
instantiated_captured_func_->RunAsync(ctx.get(), std::move(input_element),
return_values.get(),
std::move(done), prefix());
}
void CancelThreads(bool wait) LOCKS_EXCLUDED(mu_) {
mutex_lock l(*mu_);
cancelled_ = true;
cond_var_->notify_all();
// Wait for all in-flight calls to complete.
while (wait && num_calls_ > 0) {
cond_var_->wait(l);
}
}
Status CopyPartialBatch(Tensor* output, const Tensor& value,
int64 num_elements) {
switch (value.dtype()) {
#define HANDLE_TYPE(type) \
case DataTypeToEnum<type>::value: { \
auto output_t = output->flat_outer_dims<type>(); \
auto value_t = value.flat_outer_dims<type>(); \
for (size_t i = 0; i < num_elements; i++) { \
output_t.template chip<0>(i) = value_t.template chip<0>(i); \
} \
return Status::OK(); \
}
TF_CALL_DATASET_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
default:
return errors::InvalidArgument("Unsupported data type: ",
DataTypeString(value.dtype()));
}
return Status::OK();
}
void EnsureRunnerThreadStarted(IteratorContext* ctx)
EXCLUSIVE_LOCKS_REQUIRED(*mu_) {
if (!runner_thread_) {
auto ctx_copy = std::make_shared<IteratorContext>(*ctx);
runner_thread_ = ctx->StartThread(
kTFDataMapAndBatch,
std::bind(&Iterator::RunnerThread, this, ctx_copy));
}
}
Status EnsureOutputAllocated(
const std::shared_ptr<IteratorContext>& ctx,
const std::shared_ptr<BatchResult>& result,
const std::shared_ptr<std::vector<Tensor>>& return_values) {
mutex_lock l(result->mu);
if (result->output_allocated) {
return Status::OK();
}
const size_t num_components = return_values->size();
result->output.reserve(num_components);
for (size_t i = 0; i < num_components; ++i) {
TensorShape component_shape({dataset()->batch_size_});
component_shape.AppendShape(return_values->at(i).shape());
AllocatorAttributes attr;
attr.set_gpu_compatible(true);
result->output.emplace_back(ctx->allocator(attr),
return_values->at(i).dtype(),
component_shape);
if (!result->output.back().IsInitialized()) {
return errors::ResourceExhausted(
"Failed to allocate memory for the batch of component ", i);
}
}
result->output_allocated = true;
return | c++ | code | 19,999 | 3,615 |
// Copyright 2018 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 <lib/fidl/coding.h>
#include <lib/fidl/internal.h>
#include <lib/zx/event.h>
#include <lib/zx/eventpair.h>
#include <limits.h>
#include <zircon/syscalls.h>
#include <cstddef>
#include <iterator>
#include <memory>
#include <new>
#include <fbl/algorithm.h>
#include <zxtest/zxtest.h>
#include "extra_messages.h"
#include "fidl_coded_types.h"
#include "fidl_structs.h"
namespace fidl {
namespace {
// test utility functions
bool IsPeerValid(const zx::unowned_eventpair& handle) {
zx_signals_t observed_signals = {};
switch (handle->wait_one(ZX_EVENTPAIR_PEER_CLOSED, zx::deadline_after(zx::msec(1)),
&observed_signals)) {
case ZX_ERR_TIMED_OUT:
// timeout implies peer-closed was not observed
return true;
case ZX_OK:
return (observed_signals & ZX_EVENTPAIR_PEER_CLOSED) == 0;
default:
return false;
}
}
TEST(OnErrorCloseHandle, EncodeErrorTest) {
// If there is only one handle in the message, fidl_encode should not close beyond one handles.
// Specifically, |event_handle| should remain intact.
zx_handle_t event_handle;
ASSERT_EQ(zx_event_create(0, &event_handle), ZX_OK);
zx_handle_t handles[2] = {
ZX_HANDLE_INVALID,
event_handle,
};
constexpr uint32_t kMessageSize = sizeof(nonnullable_handle_message_layout);
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(kMessageSize);
nonnullable_handle_message_layout& message =
*reinterpret_cast<nonnullable_handle_message_layout*>(buffer.get());
message.inline_struct.handle = ZX_HANDLE_INVALID;
const char* error = nullptr;
uint32_t actual_handles;
auto status = fidl_encode(&nonnullable_handle_message_type, &message, kMessageSize, handles,
std::size(handles), &actual_handles, &error);
ASSERT_EQ(status, ZX_ERR_INVALID_ARGS);
ASSERT_NOT_NULL(error);
ASSERT_EQ(handles[0], ZX_HANDLE_INVALID);
ASSERT_EQ(handles[1], event_handle);
ASSERT_EQ(zx_handle_close(event_handle), ZX_OK);
}
TEST(OnErrorCloseHandle, EncodeWithNullHandlesTest) {
// When the |handles| parameter to fidl_encode is nullptr, it should still close all handles
// inside the message.
for (uint32_t num_handles : {0u, 1u}) {
zx::eventpair eventpair_a;
zx::eventpair eventpair_b;
ASSERT_EQ(zx::eventpair::create(0, &eventpair_a, &eventpair_b), ZX_OK);
constexpr uint32_t kMessageSize = sizeof(nonnullable_handle_message_layout);
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(kMessageSize);
nonnullable_handle_message_layout& message =
*reinterpret_cast<nonnullable_handle_message_layout*>(buffer.get());
message.inline_struct.handle = eventpair_a.release();
const char* error = nullptr;
uint32_t actual_handles;
auto status = fidl_encode(&nonnullable_handle_message_type, &message, kMessageSize, nullptr,
num_handles, &actual_handles, &error);
ASSERT_EQ(status, ZX_ERR_INVALID_ARGS);
ASSERT_NOT_NULL(error);
ASSERT_FALSE(IsPeerValid(zx::unowned_eventpair(eventpair_b)));
}
}
TEST(OnErrorCloseHandle, EncodeWithNullOutActualHandlesTest) {
// When the |out_actual_handles| parameter to fidl_encode is nullptr, it should still close
// all handles inside the message.
zx::eventpair eventpair_a;
zx::eventpair eventpair_b;
ASSERT_EQ(zx::eventpair::create(0, &eventpair_a, &eventpair_b), ZX_OK);
zx_handle_t handles[1] = {};
constexpr uint32_t kMessageSize = sizeof(nonnullable_handle_message_layout);
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(kMessageSize);
nonnullable_handle_message_layout& message =
*reinterpret_cast<nonnullable_handle_message_layout*>(buffer.get());
message.inline_struct.handle = eventpair_a.release();
const char* error = nullptr;
auto status = fidl_encode(&nonnullable_handle_message_type, &message, kMessageSize, handles,
std::size(handles), nullptr, &error);
ASSERT_EQ(status, ZX_ERR_INVALID_ARGS);
ASSERT_NOT_NULL(error);
ASSERT_FALSE(IsPeerValid(zx::unowned_eventpair(eventpair_b)));
}
TEST(OnErrorCloseHandle, DecodeErrorTest) {
// If an unknown envelope causes the handles contained within to be closed, and later on
// an error was encountered, the handles in the unknown envelope should not be closed again.
zx::eventpair eventpair_a;
zx::eventpair eventpair_b;
ASSERT_EQ(zx::eventpair::create(0, &eventpair_a, &eventpair_b), ZX_OK);
// It should close all handles in case of failure. Add an extra handle at the end of the
// handle array to detect this.
zx::eventpair eventpair_x;
zx::eventpair eventpair_y;
ASSERT_EQ(zx::eventpair::create(0, &eventpair_x, &eventpair_y), ZX_OK);
// Assemble an encoded TableOfStructWithHandle, with first field correctly populated,
// but second field missing non-nullable handles.
constexpr uint32_t buf_size = 512;
uint8_t buffer[buf_size] = {};
TableOfStructLayout* msg = reinterpret_cast<TableOfStructLayout*>(&buffer[0]);
msg->envelope_vector = fidl::VectorView<fidl_envelope_t>::FromExternal(
reinterpret_cast<fidl_envelope_t*>(FIDL_ALLOC_PRESENT), 2);
msg->envelopes.a = fidl_envelope_t{.num_bytes = sizeof(OrdinalOneStructWithHandle),
.num_handles = 1,
.presence = FIDL_ALLOC_PRESENT};
msg->envelopes.b = fidl_envelope_t{.num_bytes = sizeof(OrdinalTwoStructWithManyHandles),
.num_handles = 0,
.presence = FIDL_ALLOC_PRESENT};
msg->a = OrdinalOneStructWithHandle{.h = FIDL_HANDLE_PRESENT, .foo = 42};
msg->b =
OrdinalTwoStructWithManyHandles{.h1 = ZX_HANDLE_INVALID, .h2 = ZX_HANDLE_INVALID, .hs = {}};
ASSERT_TRUE(IsPeerValid(zx::unowned_eventpair(eventpair_a)));
const char* out_error = nullptr;
zx_handle_t handles[] = {eventpair_b.release(), eventpair_y.release()};
auto status = fidl_decode(&fidl_test_coding_fuchsia_SmallerTableOfStructWithHandleTable, buffer,
buf_size, handles, std::size(handles), &out_error);
ASSERT_EQ(status, ZX_ERR_INVALID_ARGS);
ASSERT_NOT_NULL(out_error);
// The peer was closed by the decoder
ASSERT_FALSE(IsPeerValid(zx::unowned_eventpair(eventpair_a)));
ASSERT_FALSE(IsPeerValid(zx::unowned_eventpair(eventpair_x)));
}
} // namespace
} // namespace fidl | c++ | code | 6,589 | 1,234 |
// Copyright (C) 2006, 2007 Damien Hocking, KBC Advanced Technologies
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// Authors: Damien Hocking KBC 2006-03-20
// (included his original contribution into Ipopt package on 2006-03-25)
// Andreas Waechter IBM 2006-03-25
// (minor changes and corrections)
// Scott Turnberg CMU 2006-05-12
// (major revision)
// (incorporated by AW on 2006-11-11 into Ipopt package)
#ifndef __IPMUMPSSOLVERINTERFACE_HPP__
#define __IPMUMPSSOLVERINTERFACE_HPP__
#include "IpSparseSymLinearSolverInterface.hpp"
namespace Ipopt
{
/** Interface to the linear solver Mumps, derived from
* SparseSymLinearSolverInterface. For details, see description of
* SparseSymLinearSolverInterface base class.
*/
class MumpsSolverInterface: public SparseSymLinearSolverInterface
{
public:
/** @name Constructor/Destructor */
//@{
/** Constructor */
MumpsSolverInterface();
/** Destructor */
virtual ~MumpsSolverInterface();
//@}
/** overloaded from AlgorithmStrategyObject */
bool InitializeImpl(const OptionsList& options,
const std::string& prefix);
/** @name Methods for requesting solution of the linear system. */
//@{
/** Method for initializing internal stuctures. Here, ndim gives
* the number of rows and columns of the matrix, nonzeros give
* the number of nonzero elements, and airn and acjn give the
* positions of the nonzero elements.
*/
virtual ESymSolverStatus InitializeStructure(Index dim, Index nonzeros,
const Index *airn,
const Index *ajcn);
/** Method returing an internal array into which the nonzero
* elements (in the same order as airn and ajcn) are to be stored
* by the calling routine before a call to MultiSolve with a
* new_matrix=true. The returned array must have space for at least
* nonzero elements. */
virtual double* GetValuesArrayPtr();
/** Solve operation for multiple right hand sides. Overloaded
* from SparseSymLinearSolverInterface.
*/
virtual ESymSolverStatus MultiSolve(bool new_matrix,
const Index* airn,
const Index* ajcn,
Index nrhs,
double* rhs_vals,
bool check_NegEVals,
Index numberOfNegEVals);
/** Number of negative eigenvalues detected during last
* factorization. Returns the number of negative eigenvalues of
* the most recent factorized matrix. This must not be called if
* the linear solver does not compute this quantities (see
* ProvidesInertia).
*/
virtual Index NumberOfNegEVals() const;
//@}
//* @name Options of Linear solver */
//@{
/** Request to increase quality of solution for next solve.
* Ask linear solver to increase quality of solution for the next
* solve (e.g. increase pivot tolerance). Returns false, if this
* is not possible (e.g. maximal pivot tolerance already used.)
*/
virtual bool IncreaseQuality();
/** Query whether inertia is computed by linear solver.
* Returns true, if linear solver provides inertia.
*/
virtual bool ProvidesInertia() const
{
return true;
}
/** Query of requested matrix type that the linear solver
* understands.
*/
EMatrixFormat MatrixFormat() const
{
return Triplet_Format;
}
//@}
/** Methods for IpoptType */
//@{
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
/** Query whether the indices of linearly dependent rows/columns
* can be determined by this linear solver. */
virtual bool ProvidesDegeneracyDetection() const;
/** This method determines the list of row indices of the linearly
* dependent rows. */
virtual ESymSolverStatus DetermineDependentRows(const Index* ia,
const Index* ja,
std::list<Index>& c_deps);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
MumpsSolverInterface(const MumpsSolverInterface&);
/** Overloaded Equals Operator */
void operator=(const MumpsSolverInterface&);
//@}
/** @name Information about the matrix */
//@{
/** Primary MUMP data structure */
void* mumps_ptr_;
//@}
/** @name Information about most recent factorization/solve */
//@{
/** Number of negative eigenvalues */
Index negevals_;
//@}
/** @name Initialization flags */
//@{
/** Flag indicating if internal data is initialized.
* For initialization, this object needs to have seen a matrix */
bool initialized_;
/** Flag indicating if the matrix has to be refactorized because
* the pivot tolerance has been changed. */
bool pivtol_changed_;
/** Flag that is true if we just requested the values of the
* matrix again (SYMSOLVER_CALL_AGAIN) and have to factorize
* again. */
bool refactorize_;
//@}
/** @name Solver specific data/options */
//@{
/** Pivol tolerance */
Number pivtol_;
/** Maximal pivot tolerance */
Number pivtolmax_;
/** Percent increase in memory */
Index mem_percent_;
/** Permution and scaling method in MUMPS */
Index mumps_permuting_scaling_;
/** Pivot order in MUMPS. */
Index mumps_pivot_order_;
/** Scaling in MUMPS */
Index mumps_scaling_;
/** Threshold in MUMPS to stay that a constraint is linearly
* dependent */
Number mumps_dep_tol_;
/** Flag indicating whether the TNLP with identical structure has
* already been solved before. */
bool warm_start_same_structure_;
//@}
/** Flag indicating if symbolic factorization has already been
* called */
bool have_symbolic_factorization_;
/** @name Internal functions */
//@{
/** Call MUMPS (job=1) to perform symbolic manipulations, and reserve
* memory.
*/
ESymSolverStatus SymbolicFactorization();
/** Call MUMPS (job=2) to factorize the Matrix.
* It is assumed that the first nonzeros_ element of a_ contain the values
* of the matrix to be factorized.
*/
ESymSolverStatus Factorization(bool check_NegEVals,
Index numberOfNegEVals);
/** Call MUMPS (job=3) to do the solve.
*/
ESymSolverStatus Solve(Index nrhs, double *rhs_vals);
//@}
};
} // namespace Ipopt
#endif | c++ | code | 7,050 | 1,229 |
#pragma once
#include "../AliveLibCommon/FunctionFwd.hpp"
#include "Map.hpp"
#include "BaseAnimatedWithPhysicsGameObject.hpp"
#include "FixedPoint.hpp"
#include "../AliveLibAE/Path.hpp"
namespace AO {
enum class BgAnimSounds : s16
{
eNone_m1 = -1,
eNone_0 = 0,
eFire_1 = 1,
eFireIdx_40 = 40
};
struct Path_BackgroundAnimation final : public Path_TLV
{
u16 field_18_animation_id;
Choice_short field_1A_is_semi_trans;
TPageAbr field_1C_semi_trans_mode;
// pad
BgAnimSounds field_1E_sound_effect;
};
ALIVE_ASSERT_SIZEOF(Path_BackgroundAnimation, 0x20);
class BackgroundAnimation final : public BaseAnimatedWithPhysicsGameObject
{
public:
EXPORT BackgroundAnimation* ctor_405A90(Path_BackgroundAnimation* pTlv, s32 tlvInfo);
EXPORT BaseGameObject* dtor_405CB0();
virtual BaseGameObject* VDestructor(s32 flags) override;
EXPORT BackgroundAnimation* Vdtor_405D70(s32 flags);
virtual void VScreenChanged() override;
EXPORT void VScreenChanged_405D30();
virtual void VStopAudio() override;
EXPORT void VStopAudio_405D40();
virtual void VUpdate() override;
EXPORT void VUpdate_405C30();
s32 field_D4_padding;
s32 field_D8_padding;
s32 field_DC_padding;
s32 field_E0_padding;
u8** field_E4_res;
s16 field_E8_xpos;
s16 field_EA_ypos;
s16 field_EC_w;
s16 field_EE_h;
s32 field_F0_tlvInfo;
s32 field_F4_padding;
FP field_F8_animXPos;
FP field_FC_animYPos;
BgAnimSounds field_100_sound_effect;
s16 field_102_padding;
s32 field_104_sound_channels_mask;
};
ALIVE_ASSERT_SIZEOF(BackgroundAnimation, 0x108);
} // namespace AO | c++ | code | 1,663 | 236 |
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
//=========================================================
// Zombie
//=========================================================
// UNDONE: Don't flinch every time you get hit
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "schedule.h"
//=========================================================
// Monster's Anim Events Go Here
//=========================================================
#define ZOMBIE_AE_ATTACK_RIGHT 0x01
#define ZOMBIE_AE_ATTACK_LEFT 0x02
#define ZOMBIE_AE_ATTACK_BOTH 0x03
#define ZOMBIE_FLINCH_DELAY 2 // at most one flinch every n secs
class CZombie : public CBaseMonster
{
public:
void Spawn( void );
void Precache( void );
void SetYawSpeed( void );
int Classify ( void );
void HandleAnimEvent( MonsterEvent_t *pEvent );
int IgnoreConditions ( void );
float m_flNextFlinch;
void PainSound( void );
void AlertSound( void );
void IdleSound( void );
void AttackSound( void );
static const char *pAttackSounds[];
static const char *pIdleSounds[];
static const char *pAlertSounds[];
static const char *pPainSounds[];
static const char *pAttackHitSounds[];
static const char *pAttackMissSounds[];
// No range attacks
BOOL CheckRangeAttack1 ( float flDot, float flDist ) { return FALSE; }
BOOL CheckRangeAttack2 ( float flDot, float flDist ) { return FALSE; }
int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType );
};
LINK_ENTITY_TO_CLASS( monster_zombie, CZombie );
const char *CZombie::pAttackHitSounds[] =
{
"zombie/claw_strike1.wav",
"zombie/claw_strike2.wav",
"zombie/claw_strike3.wav",
};
const char *CZombie::pAttackMissSounds[] =
{
"zombie/claw_miss1.wav",
"zombie/claw_miss2.wav",
};
const char *CZombie::pAttackSounds[] =
{
"zombie/zo_attack1.wav",
"zombie/zo_attack2.wav",
};
const char *CZombie::pIdleSounds[] =
{
"zombie/zo_idle1.wav",
"zombie/zo_idle2.wav",
"zombie/zo_idle3.wav",
"zombie/zo_idle4.wav",
};
const char *CZombie::pAlertSounds[] =
{
"zombie/zo_alert10.wav",
"zombie/zo_alert20.wav",
"zombie/zo_alert30.wav",
};
const char *CZombie::pPainSounds[] =
{
"zombie/zo_pain1.wav",
"zombie/zo_pain2.wav",
};
//=========================================================
// Classify - indicates this monster's place in the
// relationship table.
//=========================================================
int CZombie :: Classify ( void )
{
return m_iClass?m_iClass:CLASS_ALIEN_MONSTER;
}
//=========================================================
// SetYawSpeed - allows each sequence to have a different
// turn rate associated with it.
//=========================================================
void CZombie :: SetYawSpeed ( void )
{
int ys;
ys = 120;
#if 0
switch ( m_Activity )
{
}
#endif
pev->yaw_speed = ys;
}
int CZombie :: TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType )
{
// Take 30% damage from bullets
if ( bitsDamageType == DMG_BULLET )
{
Vector vecDir = pev->origin - (pevInflictor->absmin + pevInflictor->absmax) * 0.5;
vecDir = vecDir.Normalize();
float flForce = DamageForce( flDamage );
pev->velocity = pev->velocity + vecDir * flForce;
flDamage *= 0.3;
}
// HACK HACK -- until we fix this.
if ( IsAlive() )
PainSound();
return CBaseMonster::TakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
void CZombie :: PainSound( void )
{
int pitch = 95 + RANDOM_LONG(0,9);
if (RANDOM_LONG(0,5) < 2)
EMIT_SOUND_DYN ( ENT(pev), CHAN_VOICE, pPainSounds[ RANDOM_LONG(0,ARRAYSIZE(pPainSounds)-1) ], 1.0, ATTN_NORM, 0, pitch );
}
void CZombie :: AlertSound( void )
{
int pitch = 95 + RANDOM_LONG(0,9);
EMIT_SOUND_DYN ( ENT(pev), CHAN_VOICE, pAlertSounds[ RANDOM_LONG(0,ARRAYSIZE(pAlertSounds)-1) ], 1.0, ATTN_NORM, 0, pitch );
}
void CZombie :: IdleSound( void )
{
int pitch = 100 + RANDOM_LONG(-5, 5);
// Play a random idle sound
EMIT_SOUND_DYN ( ENT(pev), CHAN_VOICE, pIdleSounds[ RANDOM_LONG(0,ARRAYSIZE(pIdleSounds)-1) ], 1.0, ATTN_NORM, 0, pitch);
}
void CZombie :: AttackSound( void )
{
int pitch = 100 + RANDOM_LONG(-5, 5);
// Play a random attack sound
EMIT_SOUND_DYN ( ENT(pev), CHAN_VOICE, pAttackSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackSounds)-1) ], 1.0, ATTN_NORM, 0, pitch);
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//=========================================================
void CZombie :: HandleAnimEvent( MonsterEvent_t *pEvent )
{
switch( pEvent->event )
{
case ZOMBIE_AE_ATTACK_RIGHT:
{
// do stuff for this event.
// ALERT( at_console, "Slash right!\n" );
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.zombieDmgOneSlash, DMG_SLASH );
if ( pHurt )
{
if ( pHurt->pev->flags & (FL_MONSTER|FL_CLIENT) )
{
pHurt->pev->punchangle.z = -18;
pHurt->pev->punchangle.x = 5;
pHurt->pev->velocity = pHurt->pev->velocity - gpGlobals->v_right * 100;
}
// Play a random attack hit sound
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackHitSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackHitSounds)-1) ], 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5,5) );
}
else // Play a random attack miss sound
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackMissSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackMissSounds)-1) ], 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5,5) );
if (RANDOM_LONG(0,1))
AttackSound();
}
break;
case ZOMBIE_AE_ATTACK_LEFT:
{
// do stuff for this event.
// ALERT( at_console, "Slash left!\n" );
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.zombieDmgOneSlash, DMG_SLASH );
if ( pHurt )
{
if ( pHurt->pev->flags & (FL_MONSTER|FL_CLIENT) )
{
pHurt->pev->punchangle.z = 18;
pHurt->pev->punchangle.x = 5;
pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_right * 100;
}
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackHitSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackHitSounds)-1) ], 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5,5) );
}
else
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackMissSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackMissSounds)-1) ], 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5,5) );
if (RANDOM_LONG(0,1))
AttackSound();
}
break;
case ZOMBIE_AE_ATTACK_BOTH:
{
// do stuff for this event.
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.zombieDmgBothSlash, DMG_SLASH );
if ( pHurt )
{
if ( pHurt->pev->flags & (FL_MONSTER|FL_CLIENT) )
{
pHurt->pev->punchangle.x = 5;
pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_forward * -100;
}
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackHitSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackHitSounds)-1) ], 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5,5) );
}
else
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackMissSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackMissSounds)-1) ], 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5,5) );
if (RANDOM_LONG(0,1))
AttackSound();
}
break;
default:
CBaseMonster::HandleAnimEvent( pEvent );
break;
}
}
//=========================================================
// Spawn
//=========================================================
void CZombie :: Spawn()
{
Precache( );
if (pev->model)
SET_MODEL(ENT(pev), STRING(pev->model)); //LRC
else
SET_MODEL(ENT(pev), "models/zombie.mdl");
UTIL_SetSize( pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX );
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
m_bloodColor = BLOOD_COLOR_GREEN;
if (pev->health == 0)
pev->health = gSkillData.zombieHealth;
pev->view_ofs = VEC_VIEW;// position of the eyes relative to monster's origin.
m_flFieldOfView = 0.5;// indicates the width of this monster's forward view cone ( as a dotproduct result )
m_MonsterState = MONSTERSTATE_NONE;
m_afCapability = bits_CAP_DOORS_GROUP;
MonsterInit();
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CZombie :: Precache()
{
int i;
if (pev->model)
PRECACHE_MODEL((char*)STRING(pev->model)); //LRC
else
PRECACHE_MODEL("models/zombie.mdl");
for ( i = 0; i < ARRAYSIZE( pAttackHitSounds ); i++ )
PRECACHE_SOUND((char *)pAttackHitSounds[i]);
for ( i = 0; i < ARRAYSIZE( pAttackMissSounds ); i++ )
PRECACHE_SOUND((char *)pAttackMissSounds[i]);
for ( i = 0; i < ARRAYSIZE( pAttackSounds ); i++ )
PRECACHE_SOUND((char *)pAttackSounds[i]);
for ( i = 0; i < ARRAYSIZE( pIdleSounds ); i++ )
PRECACHE_SOUND((char *)pIdleSounds[i]);
for ( i = 0; i < ARRAYSIZE( pAlertSounds ); i++ )
PRECACHE_SOUND((char *)pAlertSounds[i]);
for ( i = 0; i < ARRAYSIZE( pPainSounds ); i++ )
PRECACHE_SOUND((char *)pPainSounds[i]);
}
//=========================================================
// AI Schedules Specific to this monster
//=========================================================
int CZombie::IgnoreConditions ( void )
{
int iIgnore = CBaseMonster::IgnoreConditions();
if ((m_Activity == ACT_MELEE_ATTACK1) || (m_Activity == ACT_MELEE_ATTACK1))
{
#if 0
if (pev->health < 20)
iIgnore |= (bits_COND_LIGHT_DAMAGE|bits_COND_HEAVY_DAMAGE);
else
#endif
if (m_flNextFlinch >= gpGlobals->time)
iIgnore |= (bits_COND_LIGHT_DAMAGE|bits_COND_HEAVY_DAMAGE);
}
if ((m_Activity == ACT_SMALL_FLINCH) || (m_Activity == ACT_BIG_FLINCH))
{
if (m_flNextFlinch < gpGlobals->time)
m_flNextFlinch = gpGlobals->time + ZOMBIE_FLINCH_DELAY;
}
return iIgnore;
} | c++ | code | 10,191 | 2,129 |
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "txdb.h"
#include "main.h"
#include "uint256.h"
enum Checkpoints::CPMode CheckpointsMode;
static const int nCheckpointSpan = 500;
namespace Checkpoints
{
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x00000e8ee14c2a4ef21d6b66c0f0f4cf5a87be63a627648bda7c23dacafd389d") ) // Params().HashGenesisBlock())
;
// TestNet has no checkpoints
MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x0000186936a5e29f90d4c2181715a014e451597a39920297539eaaaba4228d3c") ) // hashGenesisBlockTestNet
;
bool CheckHardened(int nHeight, const uint256& hash)
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end())
return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
};
return NULL;
}
// ppcoin: synchronized checkpoint (centrally broadcasted)
uint256 hashSyncCheckpoint = 0;
uint256 hashPendingCheckpoint = 0;
CSyncCheckpoint checkpointMessage;
CSyncCheckpoint checkpointMessagePending;
uint256 hashInvalidCheckpoint = 0;
CCriticalSection cs_hashSyncCheckpoint;
// ppcoin: get last synchronized checkpoint
CBlockIndex* GetLastSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
if (!mapBlockIndex.count(hashSyncCheckpoint))
LogPrintf("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
else
return mapBlockIndex[hashSyncCheckpoint];
return NULL;
}
CBlockThinIndex* GetLastSyncCheckpointHeader()
{
LOCK(cs_hashSyncCheckpoint);
if (!mapBlockThinIndex.count(hashSyncCheckpoint))
error("GetLastSyncCheckpointHeader: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
else
return mapBlockThinIndex[hashSyncCheckpoint];
return NULL;
}
// ppcoin: only descendant of current sync-checkpoint is allowed
bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
{
if (!mapBlockIndex.count(hashSyncCheckpoint))
return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
if (!mapBlockIndex.count(hashCheckpoint))
return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
{
// Received an older checkpoint, trace back from current checkpoint
// to the same height of the received checkpoint to verify
// that current checkpoint should be a descendant block
CBlockIndex* pindex = pindexSyncCheckpoint;
while (pindex->nHeight > pindexCheckpointRecv->nHeight)
if (!(pindex = pindex->pprev))
return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
if (pindex->GetBlockHash() != hashCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
}
return false; // ignore older checkpoint
}
// Received checkpoint should be a descendant block of the current
// checkpoint. Trace back to the same height of current checkpoint
// to verify.
CBlockIndex* pindex = pindexCheckpointRecv;
while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
if (!(pindex = pindex->pprev))
return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
if (pindex->GetBlockHash() != hashSyncCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
};
return true;
}
bool ValidateSyncCheckpointHeaders(uint256 hashCheckpoint)
{
if (!mapBlockThinIndex.count(hashCheckpoint))
return error("ValidateSyncCheckpointHeaders: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
CBlockThinIndex* pindexCheckpointRecv = mapBlockThinIndex[hashCheckpoint];
if (!mapBlockThinIndex.count(hashSyncCheckpoint))
{
if (fThinFullIndex)
return error("ValidateSyncCheckpointHeaders: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
//if hashSyncCheckpoint
//LogPrintf("[rem] ValidateSyncCheckpointHeaders ReadBlockThinIndex\n");
CTxDB txdb("r");
CDiskBlockThinIndex diskindex;
if (!txdb.ReadBlockThinIndex(hashCheckpoint, diskindex)
|| diskindex.hashNext == 0)
return error("ValidateSyncCheckpointHeaders() : block not in db %s", hashCheckpoint.ToString().c_str());
// TODO: add checks
// so long as it's in the db with hashNext it should be in the main chain
return true;
};
CBlockThinIndex* pindexSyncCheckpoint = mapBlockThinIndex[hashSyncCheckpoint];
if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
{
// Received an older checkpoint, trace back from current checkpoint
// to the same height of the received checkpoint to verify
// that current checkpoint should be a descendant block
CBlockThinIndex* pindex = pindexSyncCheckpoint;
while (pindex->nHeight > pindexCheckpointRecv->nHeight)
{
if (!(pindex = pindex->pprev))
return error("ValidateSyncCheckpointHeaders: pprev null - block index structure failure");
};
if (pindex->GetBlockHash() != hashCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("ValidateSyncCheckpointHeaders: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
};
return false; // ignore older checkpoint
};
// Received checkpoint should be a descendant block of the current
// checkpoint. Trace back to the same height of current checkpoint
// to verify.
CBlockThinIndex* pindex = pindexCheckpointRecv;
while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
{
if (!(pindex = pindex->pprev))
return error("ValidateSyncCheckpointHeaders: pprev2 null - block index structure failure");
};
if (pindex->GetBlockHash() != hashSyncCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("ValidateSyncCheckpointHeaders: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
};
return true;
}
bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
{
CTxDB txdb;
txdb.TxnBegin();
if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
{
txdb.TxnAbort();
return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
}
if (!txdb.TxnCommit())
return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
Checkpoints::hashSyncCheckpoint = hashCheckpoint;
return true;
}
bool AcceptPendingSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
{
if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
{
hashPendingCheckpoint = 0;
checkpointMessagePending.SetNull();
return false;
}
CTxDB txdb;
CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
if (!pindexCheckpoint->IsInMainChain())
{
CBlock block;
if (!block.ReadFromDisk(pindexCheckpoint))
return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
if (!block.SetBestChain(txdb, pindexCheckpoint))
{
hashInvalidCheckpoint = hashPendingCheckpoint;
return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
};
};
if (!WriteSyncCheckpoint(hashPendingCheckpoint))
return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
hashPendingCheckpoint = 0;
checkpointMessage = checkpointMessagePending;
checkpointMessagePending.SetNull();
LogPrintf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
// relay the checkpoint
if (!checkpointMessage.IsNull())
{
BOOST_FOREACH(CNode* pnode, vNodes)
checkpointMessage.RelayTo(pnode);
}
return true;
}
return false;
}
// Automatically select a suitable sync-checkpoint
uint256 AutoSelectSyncCheckpoint()
{
const CBlockIndex *pindex = pindexBest;
// Search backward for a block within max span and maturity window
while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
pindex = pindex->pprev;
return pindex->GetBlockHash();
}
// Check against synchronized checkpoint
bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
{
if (fTestNet) return true; // Testnet has no checkpoints
int nHeight = pindexPrev->nHeight + 1;
LOCK(cs_hashSyncCheckpoint);
// sync-checkpoint should always be accepted block
assert(mapBlockIndex.count(hashSyncCheckpoint));
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
if (nHeight > pindexSync->nHeight)
{
// trace back to same height as sync-checkpoint
const CBlockIndex* pindex = pindexPrev;
while (pindex->nHeight > pindexSync->nHeight)
if (!(pindex = pindex->pprev))
return error("CheckSync: pprev null - block index structure failure");
if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
return false; // only descendant of sync-checkpoint can pass check
};
if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
return false; // same height with sync-checkpoint
if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
return false; // lower height than sync-checkpoint
return true;
}
bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
{
LOCK(cs_hashSyncCheckpoint);
if (hashPendingCheckpoint == 0)
return false;
if (hashBlock == hashPendingCheckpoint)
return true;
if (mapOrphanBlocks.count(hashPendingCheckpoint)
&& hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
return true;
return false;
}
bool WantedByPendingSyncCheckpointHeader(uint256 hashBlock)
{
LOCK(cs_hashSyncCheckpoint);
if (hashPendingCheckpoint == 0)
return false;
if (hashBlock == hashPendingCheckpoint)
return true;
if (mapOrphanBlockThins.count(hashPendingCheckpoint)
&& hashBlock == WantedByOrphanHeader(mapOrphanBlockThins[hashPendingCheckpoint]))
return true;
return false;
}
// ppcoin: reset synchronized checkpoint to last hardened checkpoint
bool ResetSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
const uint256& hash = mapCheckpoints.rbegin()->second;
if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
{
// checkpoint block accepted but not yet in main chain
LogPrintf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
CTxDB txdb;
CBlock block;
if (!block.ReadFromDisk(mapBlockIndex[hash]))
return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
{
return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
};
} else
if (!mapBlockIndex.count(hash))
{
// checkpoint block not yet accepted
hashPendingCheckpoint = hash;
checkpointMessagePending.SetNull();
LogPrintf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
};
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
{
if (!WriteSyncCheckpoint(hash))
return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
LogPrintf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
return true;
};
};
return false;
}
bool ResetSyncCheckpointThin()
{
LOCK(cs_hashSyncCheckpoint);
const uint256& hash = mapCheckpoints.rbegin()->second;
if (mapBlockThinIndex.count(hash) && !mapBlockThinIndex[hash]->IsInMainChain())
{
// checkpoint block accepted but not yet in main chain
LogPrintf("ResetSyncCheckpointThin: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
CBlockThin block = mapBlockThinIndex[hash]->GetBlockThin();
CTxDB txdb;
if (!block.SetBestThinChain(txdb, mapBlockThinIndex[hash]))
{
return error("ResetSyncCheckpointThin: SetBestChain failed for sync checkpoint %s", hash.ToString().c_str());
};
} else
if (!mapBlockThinIndex.count(hash))
{
// checkpoint block not yet accepted
hashPendingCheckpoint = hash;
checkpointMessagePending.SetNull();
LogPrintf("ResetSyncCheckpointThin: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
};
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
if (mapBlockThinIndex.count(hash) && mapBlockThinIndex[hash]->IsInMainChain())
{
if (!WriteSyncCheckpoint(hash))
return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
LogPrintf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
return true;
};
};
return false;
}
void AskForPendingSyncCheckpoint(CNode* pfrom)
{
LOCK(cs_hashSyncCheckpoint);
if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
}
bool SetCheckpointPrivKey(std::string strPrivKey) // TODO: posv2 remove
{
LogPrintf("SetCheckpointPrivKey()\n");
// Test signing a sync-checkpoint with genesis block
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = Params().HashGenesisBlock();
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
CKey key;
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end()), false); // if key is not correct openssl may crash
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return false;
// Test signing successful, proceed
CSyncCheckpoint::strMasterPrivKey = strPrivKey;
return true;
}
bool SendSyncCheckpoint(uint256 hashCheckpoint) // TODO: posv2 remove
{
if (fDebug)
LogPrintf("SendSyncCheckpoint()\n");
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = hashCheckpoint;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
if (CSyncCheckpoint::strMasterPrivKey.empty())
return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
CKey key;
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end()), false); // if key is not correct openssl may crash
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
if(!checkpoint.ProcessSyncCheckpoint(NULL))
{
LogPrintf("WARNING: SendSyncChe | c++ | code | 20,000 | 3,356 |
/**
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include "api/nanofi.h"
#include "blocks/file_blocks.h"
#include "blocks/comms.h"
#include "core/processors.h"
#include "HTTPCurlLoader.h"
#include "python_lib.h"
#ifdef __cplusplus
extern "C" {
#endif
int init_api(const char *resource){
core::ClassLoader::getDefaultClassLoader().registerResource(resource, "createHttpCurlFactory");
return 0;
}
#ifdef __cplusplus
}
#endif | c++ | code | 1,333 | 265 |
/*
filters.cpp: Filter class implementations
*/
//#include <cmath>
#include <stdlib.h> // XXX eventually use fabs() instead of abs() ?
#include "filters.h"
void KalmanFilter::getPredictionCovariance(float covariance[3][3], float previousState[3], float deltat)
{
// required matrices for the operations
float sigma[3][3];
float identity[3][3];
identityMatrix3x3(identity);
float skewMatrix[3][3];
skew(skewMatrix, previousState);
float tmp[3][3];
// Compute the prediction covariance matrix
scaleMatrix3x3(sigma, pow(sigmaGyro, 2), identity);
matrixProduct3x3(tmp, skewMatrix, sigma);
matrixProduct3x3(covariance, tmp, skewMatrix);
scaleMatrix3x3(covariance, -pow(deltat, 2), covariance);
}
void KalmanFilter::getMeasurementCovariance(float covariance[3][3])
{
// required matrices for the operations
float sigma[3][3];
float identity[3][3];
identityMatrix3x3(identity);
float norm;
// Compute measurement covariance
scaleMatrix3x3(sigma, pow(sigmaAccel, 2), identity);
vectorLength(& norm, previousAccelSensor);
scaleAndAccumulateMatrix3x3(sigma, (1.0/3.0)*pow(ca, 2)*norm, identity);
copyMatrix3x3(covariance, sigma);
}
void KalmanFilter::predictState(float predictedState[3], float gyro[3], float deltat)
{
// helper matrices
float identity[3][3];
identityMatrix3x3(identity);
float skewFromGyro[3][3];
skew(skewFromGyro, gyro);
// Predict state
scaleAndAccumulateMatrix3x3(identity, -deltat, skewFromGyro);
matrixDotVector3x3(predictedState, identity, currentState);
normalizeVector(predictedState);
}
void KalmanFilter::predictErrorCovariance(float covariance[3][3], float gyro[3], float deltat)
{
// required matrices
float Q[3][3];
float identity[3][3];
identityMatrix3x3(identity);
float skewFromGyro[3][3];
skew(skewFromGyro, gyro);
float tmp[3][3];
float tmpTransposed[3][3];
float tmp2[3][3];
// predict error covariance
getPredictionCovariance(Q, currentState, deltat);
scaleAndAccumulateMatrix3x3(identity, -deltat, skewFromGyro);
copyMatrix3x3(tmp, identity);
transposeMatrix3x3(tmpTransposed, tmp);
matrixProduct3x3(tmp2, tmp, currErrorCovariance);
matrixProduct3x3(covariance, tmp2, tmpTransposed);
scaleAndAccumulateMatrix3x3(covariance, 1.0, Q);
}
void KalmanFilter::updateGain(float gain[3][3], float errorCovariance[3][3])
{
// required matrices
float R[3][3];
float HTransposed[3][3];
transposeMatrix3x3(HTransposed, H);
float tmp[3][3];
float tmp2[3][3];
float tmp2Inverse[3][3];
// update kalman gain
// P.dot(H.T).dot(inv(H.dot(P).dot(H.T) + R))
getMeasurementCovariance(R);
matrixProduct3x3(tmp, errorCovariance, HTransposed);
matrixProduct3x3(tmp2, H, tmp);
scaleAndAccumulateMatrix3x3(tmp2, 1.0, R);
invert3x3(tmp2Inverse, tmp2);
matrixProduct3x3(gain, tmp, tmp2Inverse);
}
void KalmanFilter::updateState(float updatedState[3], float predictedState[3], float gain[3][3], float accel[3])
{
// required matrices
float tmp[3];
float tmp2[3];
float measurement[3];
scaleVector(tmp, ca, previousAccelSensor);
subtractVectors(measurement, accel, tmp);
// update state with measurement
// predicted_state + K.dot(measurement - H.dot(predicted_state))
matrixDotVector3x3(tmp, H, predictedState);
subtractVectors(tmp, measurement, tmp);
matrixDotVector3x3(tmp2, gain, tmp);
sumVectors(updatedState, predictedState, tmp2);
normalizeVector(updatedState);
}
void KalmanFilter::updateErrorCovariance(float covariance[3][3], float errorCovariance[3][3], float gain[3][3])
{
// required matrices
float identity[3][3];
identityMatrix3x3(identity);
float tmp[3][3];
float tmp2[3][3];
// update error covariance with measurement
matrixProduct3x3(tmp, gain, H);
matrixProduct3x3(tmp2, tmp, errorCovariance);
scaleAndAccumulateMatrix3x3(identity, -1.0, tmp2);
copyMatrix3x3(covariance, tmp2);
}
KalmanFilter::KalmanFilter(float ca, float sigmaGyro, float sigmaAccel)
{
this->ca = ca;
this->sigmaGyro = sigmaGyro;
this->sigmaAccel = sigmaAccel;
}
float KalmanFilter::estimate(float gyro[3], float accel[3], float deltat)
{
float predictedState[3];
float updatedState[3];
float errorCovariance[3][3];
float updatedErrorCovariance[3][3];
float gain[3][3];
float accelSensor[3];
float tmp[3];
float accelEarth;
scaleVector(accel, 9.81, accel); // Scale accel readings since they are measured in gs
// perform estimation
// predictions
predictState(predictedState, gyro, deltat);
predictErrorCovariance(errorCovariance, gyro, deltat);
// updates
updateGain(gain, errorCovariance);
updateState(updatedState, predictedState, gain, accel);
updateErrorCovariance(updatedErrorCovariance, errorCovariance, gain);
// Store required values for next iteration
copyVector(currentState, updatedState);
copyMatrix3x3(currErrorCovariance, updatedErrorCovariance);
// return vertical acceleration estimate
scaleVector(tmp, 9.81, updatedState);
subtractVectors(accelSensor, accel, tmp);
copyVector(previousAccelSensor, accelSensor);
dotProductVectors(& accelEarth, accelSensor, updatedState);
return accelEarth;
}
float ComplementaryFilter::ApplyZUPT(float accel, float vel)
{
// first update ZUPT array with latest estimation
ZUPT[ZUPTIdx] = accel;
// and move index to next slot
uint8_t nextIndex = (ZUPTIdx + 1) % ZUPT_SIZE;
ZUPTIdx = nextIndex;
// Apply Zero-velocity update
for (uint8_t k = 0; k < ZUPT_SIZE; ++k) {
if (abs(ZUPT[k]) > accelThreshold) return vel;
}
return 0.0;
}
ComplementaryFilter::ComplementaryFilter(float sigmaAccel, float sigmaBaro, float accelThreshold)
{
// Compute the filter gain
gain[0] = sqrt(2 * sigmaAccel / sigmaBaro);
gain[1] = sigmaAccel / sigmaBaro;
// If acceleration is below the threshold the ZUPT counter
// will be increased
this->accelThreshold = accelThreshold;
// initialize zero-velocity update
ZUPTIdx = 0;
for (uint8_t k = 0; k < ZUPT_SIZE; ++k) {
ZUPT[k] = 0;
}
}
void ComplementaryFilter::estimate(float * velocity, float * altitude, float baroAltitude,
float pastAltitude, float pastVelocity, float accel, float deltat)
{
// Apply complementary filter
*altitude = pastAltitude + deltat*(pastVelocity + (gain[0] + gain[1]*deltat/2)*(baroAltitude-pastAltitude))+
accel*pow(deltat, 2)/2;
*velocity = pastVelocity + deltat*(gain[1]*(baroAltitude-pastAltitude) + accel);
// Compute zero-velocity update
*velocity = ApplyZUPT(accel, *velocity);
} | c++ | code | 6,789 | 1,444 |
/*判断程序是否有误,如果有 请改正*/
#include<iostream>
#include<iterator>
#include<vector>
#include<list>
#include<algorithm>
using namespace std;
template <typename Sequence> void print(Sequence const &seq)
{
for (const auto &x : seq)
cout << x << " ";
cout << endl;
}
int main()
{
// (a)
vector<int> vec;
list<int> lst;
int i;
while (cin >> i)
lst.push_back(i);
// vec的大小与lst不相等,无法copy
// resolution 1: 将vec的大小变成与lst相等的大小
vec.resize(lst.size());
//copy(lst.cbegin(), lst.cend(), vec.begin());
// resolution 2: vec.begin() 改为 back_insert(vec)
// copy(lst.cbegin(), lst.cend(), back_insertr(vec));
// (b)
vector<int> v;
v.reserve(10);
//fill_n(v.begin(), 10, 0); // 错误
// 修改如下
fill_n(back_inserter(v), 10, 0);
print(vec);
print(v);
return 0;
} | c++ | code | 761 | 231 |
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <climits>
#include <csignal>
#include <map>
#include <memory>
#include <string>
#include "test/cctest/test-api.h"
#if V8_OS_POSIX
#include <unistd.h> // NOLINT
#endif
#include "include/v8-util.h"
#include "src/api.h"
#include "src/arguments.h"
#include "src/base/platform/platform.h"
#include "src/code-stubs.h"
#include "src/compilation-cache.h"
#include "src/debug/debug.h"
#include "src/execution.h"
#include "src/futex-emulation.h"
#include "src/global-handles.h"
#include "src/heap/incremental-marking.h"
#include "src/heap/local-allocator.h"
#include "src/lookup.h"
#include "src/objects-inl.h"
#include "src/objects/hash-table-inl.h"
#include "src/objects/js-promise-inl.h"
#include "src/parsing/preparse-data.h"
#include "src/profiler/cpu-profiler.h"
#include "src/unicode-inl.h"
#include "src/utils.h"
#include "src/vm-state.h"
#include "test/cctest/heap/heap-tester.h"
#include "test/cctest/heap/heap-utils.h"
static const bool kLogThreading = false;
using ::v8::Array;
using ::v8::Boolean;
using ::v8::BooleanObject;
using ::v8::Context;
using ::v8::Extension;
using ::v8::Function;
using ::v8::FunctionTemplate;
using ::v8::HandleScope;
using ::v8::Local;
using ::v8::Maybe;
using ::v8::Message;
using ::v8::MessageCallback;
using ::v8::Module;
using ::v8::Name;
using ::v8::None;
using ::v8::Object;
using ::v8::ObjectTemplate;
using ::v8::Persistent;
using ::v8::PropertyAttribute;
using ::v8::Script;
using ::v8::StackTrace;
using ::v8::String;
using ::v8::Symbol;
using ::v8::TryCatch;
using ::v8::Undefined;
using ::v8::V8;
using ::v8::Value;
#define THREADED_PROFILED_TEST(Name) \
static void Test##Name(); \
TEST(Name##WithProfiler) { \
RunWithProfiler(&Test##Name); \
} \
THREADED_TEST(Name)
void RunWithProfiler(void (*test)()) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Local<v8::String> profile_name = v8_str("my_profile1");
v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
cpu_profiler->StartProfiling(profile_name);
(*test)();
reinterpret_cast<i::CpuProfiler*>(cpu_profiler)->DeleteAllProfiles();
cpu_profiler->Dispose();
}
static int signature_callback_count;
static Local<Value> signature_expected_receiver;
static void IncrementingSignatureCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
signature_callback_count++;
CHECK(signature_expected_receiver->Equals(
args.GetIsolate()->GetCurrentContext(),
args.Holder())
.FromJust());
CHECK(signature_expected_receiver->Equals(
args.GetIsolate()->GetCurrentContext(),
args.This())
.FromJust());
v8::Local<v8::Array> result =
v8::Array::New(args.GetIsolate(), args.Length());
for (int i = 0; i < args.Length(); i++) {
CHECK(result->Set(args.GetIsolate()->GetCurrentContext(),
v8::Integer::New(args.GetIsolate(), i), args[i])
.FromJust());
}
args.GetReturnValue().Set(result);
}
static void Returns42(const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(42);
}
// Tests that call v8::V8::Dispose() cannot be threaded.
UNINITIALIZED_TEST(InitializeAndDisposeOnce) {
CHECK(v8::V8::Initialize());
CHECK(v8::V8::Dispose());
}
// Tests that call v8::V8::Dispose() cannot be threaded.
UNINITIALIZED_TEST(InitializeAndDisposeMultiple) {
for (int i = 0; i < 3; ++i) CHECK(v8::V8::Dispose());
for (int i = 0; i < 3; ++i) CHECK(v8::V8::Initialize());
for (int i = 0; i < 3; ++i) CHECK(v8::V8::Dispose());
for (int i = 0; i < 3; ++i) CHECK(v8::V8::Initialize());
for (int i = 0; i < 3; ++i) CHECK(v8::V8::Dispose());
}
// Tests that Smi::kZero is set up properly.
UNINITIALIZED_TEST(SmiZero) { CHECK_EQ(i::Smi::kZero, i::Smi::kZero); }
THREADED_TEST(Handles) {
v8::HandleScope scope(CcTest::isolate());
Local<Context> local_env;
{
LocalContext env;
local_env = env.local();
}
// Local context should still be live.
CHECK(!local_env.IsEmpty());
local_env->Enter();
v8::Local<v8::Primitive> undef = v8::Undefined(CcTest::isolate());
CHECK(!undef.IsEmpty());
CHECK(undef->IsUndefined());
const char* source = "1 + 2 + 3";
Local<Script> script = v8_compile(source);
CHECK_EQ(6, v8_run_int32value(script));
local_env->Exit();
}
THREADED_TEST(IsolateOfContext) {
v8::HandleScope scope(CcTest::isolate());
v8::Local<Context> env = Context::New(CcTest::isolate());
CHECK(!env->GetIsolate()->InContext());
CHECK(env->GetIsolate() == CcTest::isolate());
env->Enter();
CHECK(env->GetIsolate()->InContext());
CHECK(env->GetIsolate() == CcTest::isolate());
env->Exit();
CHECK(!env->GetIsolate()->InContext());
CHECK(env->GetIsolate() == CcTest::isolate());
}
static void TestSignatureLooped(const char* operation, Local<Value> receiver,
v8::Isolate* isolate) {
i::ScopedVector<char> source(200);
i::SNPrintF(source,
"for (var i = 0; i < 10; i++) {"
" %s"
"}",
operation);
signature_callback_count = 0;
signature_expected_receiver = receiver;
bool expected_to_throw = receiver.IsEmpty();
v8::TryCatch try_catch(isolate);
CompileRun(source.start());
CHECK_EQ(expected_to_throw, try_catch.HasCaught());
if (!expected_to_throw) {
CHECK_EQ(10, signature_callback_count);
} else {
CHECK(v8_str("TypeError: Illegal invocation")
->Equals(isolate->GetCurrentContext(),
try_catch.Exception()
->ToString(isolate->GetCurrentContext())
.ToLocalChecked())
.FromJust());
}
}
static void TestSignatureOptimized(const char* operation, Local<Value> receiver,
v8::Isolate* isolate) {
i::ScopedVector<char> source(200);
i::SNPrintF(source,
"function test() {"
" %s"
"}"
"try { test() } catch(e) {}"
"try { test() } catch(e) {}"
"%%OptimizeFunctionOnNextCall(test);"
"test()",
operation);
signature_callback_count = 0;
signature_expected_receiver = receiver;
bool expected_to_throw = receiver.IsEmpty();
v8::TryCatch try_catch(isolate);
CompileRun(source.start());
CHECK_EQ(expected_to_throw, try_catch.HasCaught());
if (!expected_to_throw) {
CHECK_EQ(3, signature_callback_count);
} else {
CHECK(v8_str("TypeError: Illegal invocation")
->Equals(isolate->GetCurrentContext(),
try_catch.Exception()
->ToString(isolate->GetCurrentContext())
.ToLocalChecked())
.FromJust());
}
}
static void TestSignature(const char* operation, Local<Value> receiver,
v8::Isolate* isolate) {
TestSignatureLooped(operation, receiver, isolate);
TestSignatureOptimized(operation, receiver, isolate);
}
THREADED_TEST(ReceiverSignature) {
i::FLAG_allow_natives_syntax = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
// Setup templates.
v8::Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(isolate);
v8::Local<v8::Signature> sig = v8::Signature::New(isolate, fun);
v8::Local<v8::FunctionTemplate> callback_sig = v8::FunctionTemplate::New(
isolate, IncrementingSignatureCallback, Local<Value>(), sig);
v8::Local<v8::FunctionTemplate> callback =
v8::FunctionTemplate::New(isolate, IncrementingSignatureCallback);
v8::Local<v8::FunctionTemplate> sub_fun = v8::FunctionTemplate::New(isolate);
sub_fun->Inherit(fun);
v8::Local<v8::FunctionTemplate> direct_sub_fun =
v8::FunctionTemplate::New(isolate);
direct_sub_fun->Inherit(fun);
v8::Local<v8::FunctionTemplate> unrel_fun =
v8::FunctionTemplate::New(isolate);
// Install properties.
v8::Local<v8::ObjectTemplate> fun_proto = fun->PrototypeTemplate();
fun_proto->Set(v8_str("prop_sig"), callback_sig);
fun_proto->Set(v8_str("prop"), callback);
fun_proto->SetAccessorProperty(
v8_str("accessor_sig"), callback_sig, callback_sig);
fun_proto->SetAccessorProperty(v8_str("accessor"), callback, callback);
// Instantiate templates.
Local<Value> fun_instance =
fun->InstanceTemplate()->NewInstance(env.local()).ToLocalChecked();
Local<Value> sub_fun_instance =
sub_fun->InstanceTemplate()->NewInstance(env.local()).ToLocalChecked();
// Instance template with properties.
v8::Local<v8::ObjectTemplate> direct_instance_templ =
direct_sub_fun->InstanceTemplate();
direct_instance_templ->Set(v8_str("prop_sig"), callback_sig);
direct_instance_templ->Set(v8_str("prop"), callback);
direct_instance_templ->SetAccessorProperty(v8_str("accessor_sig"),
callback_sig, callback_sig);
direct_instance_templ->SetAccessorProperty(v8_str("accessor"), callback,
callback);
Local<Value> direct_instance =
direct_instance_templ->NewInstance(env.local()).ToLocalChecked();
// Setup global variables.
CHECK(env->Global()
->Set(env.local(), v8_str("Fun"),
fun->GetFunction(env.local()).ToLocalChecked())
.FromJust());
CHECK(env->Global()
->Set(env.local(), v8_str("UnrelFun"),
unrel_fun->GetFunction(env.local()).ToLocalChecked())
.FromJust());
CHECK(env->Global()
->Set(env.local(), v8_str("fun_instance"), fun_instance)
.FromJust());
CHECK(env->Global()
->Set(env.local(), v8_str("sub_fun_instance"), sub_fun_instance)
.FromJust());
CHECK(env->Global()
->Set(env.local(), v8_str("direct_instance"), direct_instance)
.FromJust());
CompileRun(
"var accessor_sig_key = 'accessor_sig';"
"var accessor_key = 'accessor';"
"var prop_sig_key = 'prop_sig';"
"var prop_key = 'prop';"
""
"function copy_props(obj) {"
" var keys = [accessor_sig_key, accessor_key, prop_sig_key, prop_key];"
" var source = Fun.prototype;"
" for (var i in keys) {"
" var key = keys[i];"
" var desc = Object.getOwnPropertyDescriptor(source, key);"
" Object.defineProperty(obj, key, desc);"
" }"
"}"
""
"var plain = {};"
"copy_props(plain);"
"var unrelated = new UnrelFun();"
"copy_props(unrelated);"
"var inherited = { __proto__: fun_instance };"
"var inherited_direct = { __proto__: direct_instance };");
// Test with and without ICs
const char* test_objects[] = {
"fun_instance", "sub_fun_instance", "direct_instance", "plain",
"unrelated", "inherited", "inherited_direct"};
unsigned bad_signature_start_offset = 3;
for (unsigned i = 0; i < arraysize(test_objects); i++) {
i::ScopedVector<char> source(200);
i::SNPrintF(
source, "var test_object = %s; test_object", test_objects[i]);
Local<Value> test_object = CompileRun(source.start());
TestSignature("test_object.prop();", test_object, isolate);
TestSignature("test_object.accessor;", test_object, isolate);
TestSignature("test_object[accessor_key];", test_object, isolate);
TestSignature("test_object.accessor = 1;", test_object, isolate);
TestSignature("test_object[accessor_key] = 1;", test_object, isolate);
if (i >= bad_signature_start_offset) test_object = Local<Value>();
TestSignature("test_object.prop_sig();", test_object, isolate);
TestSignature("test_object.accessor_sig;", test_object, isolate);
TestSignature("test_object[accessor_sig_key];", test_object, isolate);
TestSignature("test_object.accessor_sig = 1;", test_object, isolate);
TestSignature("test_object[accessor_sig_key] = 1;", test_object, isolate);
}
}
THREADED_TEST(HulIgennem) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Primitive> undef = v8::Undefined(isolate);
Local<String> undef_str = undef->ToString(env.local()).ToLocalChecked();
char* value = i::NewArray<char>(undef_str->Utf8Length() + 1);
undef_str->WriteUtf8(value);
CHECK_EQ(0, strcmp(value, "undefined"));
i::DeleteArray(value);
}
THREADED_TEST(Access) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
Local<v8::Object> obj = v8::Object::New(isolate);
Local<Value> foo_before =
obj->Get(env.local(), v8_str("foo")).ToLocalChecked();
CHECK(foo_before->IsUndefined());
Local<String> bar_str = v8_str("bar");
CHECK(obj->Set(env.local(), v8_str("foo"), bar_str).FromJust());
Local<Value> foo_after =
obj->Get(env.local(), v8_str("foo")).ToLocalChecked();
CHECK(!foo_after->IsUndefined());
CHECK(foo_after->IsString());
CHECK(bar_str->Equals(env.local(), foo_after).FromJust());
CHECK(obj->Set(env.local(), v8_str("foo"), bar_str).ToChecked());
bool result;
CHECK(obj->Set(env.local(), v8_str("foo"), bar_str).To(&result));
CHECK(result);
}
THREADED_TEST(AccessElement) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::Object> obj = v8::Object::New(env->GetIsolate());
Local<Value> before = obj->Get(env.local(), 1).ToLocalChecked();
CHECK(before->IsUndefined());
Local<String> bar_str = v8_str("bar");
CHECK(obj->Set(env.local(), 1, bar_str).FromJust());
Local<Value> after = obj->Get(env.local(), 1).ToLocalChecked();
CHECK(!after->IsUndefined());
CHECK(after->IsString());
CHECK(bar_str->Equals(env.local(), after).FromJust());
Local<v8::Array> value = CompileRun("[\"a\", \"b\"]").As<v8::Array>();
CHECK(v8_str("a")
->Equals(env.local(), value->Get(env.local(), 0).ToLocalChecked())
.FromJust());
CHECK(v8_str("b")
->Equals(env.local(), value->Get(env.local(), 1).ToLocalChecked())
.FromJust());
}
THREADED_TEST(Script) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* source = "1 + 2 + 3";
Local<Script> script = v8_compile(source);
CHECK_EQ(6, v8_run_int32value(script));
}
class TestResource: public String::ExternalStringResource {
public:
explicit TestResource(uint16_t* data, int* counter = nullptr,
bool owning_data = true)
: data_(data), length_(0), counter_(counter), owning_data_(owning_data) {
while (data[length_]) ++length_;
}
~TestResource() {
if (owning_data_) i::DeleteArray(data_);
if (counter_ != nullptr) ++*counter_;
}
const uint16_t* data() const {
return data_;
}
size_t length() const {
return length_;
}
private:
uint16_t* data_;
size_t length_;
int* counter_;
bool owning_data_;
};
class TestOneByteResource : public String::ExternalOneByteStringResource {
public:
explicit TestOneByteResource(const char* data, int* counter = nullptr,
size_t offset = 0)
: orig_data_(data),
data_(data + offset),
length_(strlen(data) - offset),
counter_(counter) {}
~TestOneByteResource() {
i::DeleteArray(orig_data_);
if (counter_ != nullptr) ++*counter_;
}
const char* data() const {
return data_;
}
size_t length() const {
return length_;
}
private:
const char* orig_data_;
const char* data_;
size_t length_;
int* counter_;
};
THREADED_TEST(ScriptUsingStringResource) {
int dispose_count = 0;
const char* c_source = "1 + 2 * 3";
uint16_t* two_byte_source = AsciiToTwoByteString(c_source);
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
TestResource* resource = new TestResource(two_byte_source, &dispose_count);
Local<String> source =
String::NewExternalTwoByte(env->GetIsolate(), resource)
.ToLocalChecked();
Local<Script> script = v8_compile(source);
Local<Value> value = script->Run(env.local()).ToLocalChecked();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value(env.local()).FromJust());
CHECK(source->IsExternal());
CHECK_EQ(resource,
static_cast<TestResource*>(source->GetExternalStringResource()));
String::Encoding encoding = String::UNKNOWN_ENCODING;
CHECK_EQ(static_cast<const String::ExternalStringResourceBase*>(resource),
source->GetExternalStringResourceBase(&encoding));
CHECK_EQ(String::TWO_BYTE_ENCODING, encoding);
CcTest::CollectAllGarbage();
CHECK_EQ(0, dispose_count);
}
CcTest::i_isolate()->compilation_cache()->Clear();
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(1, dispose_count);
}
THREADED_TEST(ScriptUsingOneByteStringResource) {
int dispose_count = 0;
const char* c_source = "1 + 2 * 3";
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
TestOneByteResource* resource =
new TestOneByteResource(i::StrDup(c_source), &dispose_count);
Local<String> source =
String::NewExternalOneByte(env->GetIsolate(), resource)
.ToLocalChecked();
CHECK(source->IsExternalOneByte());
CHECK_EQ(static_cast<const String::ExternalStringResourceBase*>(resource),
source->GetExternalOneByteStringResource());
String::Encoding encoding = String::UNKNOWN_ENCODING;
CHECK_EQ(static_cast<const String::ExternalStringResourceBase*>(resource),
source->GetExternalStringResourceBase(&encoding));
CHECK_EQ(String::ONE_BYTE_ENCODING, encoding);
Local<Script> script = v8_compile(source);
Local<Value> value = script->Run(env.local()).ToLocalChecked();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value(env.local()).FromJust());
CcTest::CollectAllGarbage();
CHECK_EQ(0, dispose_count);
}
CcTest::i_isolate()->compilation_cache()->Clear();
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(1, dispose_count);
}
THREADED_TEST(ScriptMakingExternalString) {
int dispose_count = 0;
uint16_t* two_by | c++ | code | 20,000 | 4,775 |
/*
* MOAB, a Mesh-Oriented datABase, is a software component for creating,
* storing and accessing finite element mesh data.
*
* Copyright 2004 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
/**\file MeshSetSequence.hpp
*\author Jason Kraftcheck ([email protected])
*\date 2007-04-30
*/
#ifndef MESH_SET_SEQUENCE_HPP
#define MESH_SET_SEQUENCE_HPP
#include "EntitySequence.hpp"
#include "MeshSet.hpp"
#include "SequenceData.hpp"
namespace moab {
class SequenceManager;
class MeshSetSequence : public EntitySequence
{
public:
MeshSetSequence( EntityHandle start,
EntityID count,
const unsigned* flags,
SequenceData* data );
MeshSetSequence( EntityHandle start,
EntityID count,
unsigned flags,
SequenceData* data );
MeshSetSequence( EntityHandle start,
EntityID count,
const unsigned* flags,
EntityID sequence_size );
MeshSetSequence( EntityHandle start,
EntityID count,
unsigned flags,
EntityID sequence_size );
virtual ~MeshSetSequence();
EntitySequence* split( EntityHandle here );
SequenceData* create_data_subset( EntityHandle, EntityHandle ) const
{ return 0; }
ErrorCode pop_back( EntityID count );
ErrorCode pop_front( EntityID count );
ErrorCode push_back( EntityID count, const unsigned* flags );
ErrorCode push_front( EntityID count, const unsigned* flags );
void get_const_memory_use( unsigned long& bytes_per_entity,
unsigned long& size_of_sequence ) const;
unsigned long get_per_entity_memory_use( EntityHandle first,
EntityHandle last ) const;
inline MeshSet* get_set( EntityHandle h );
inline const MeshSet* get_set( EntityHandle h ) const;
ErrorCode get_entities( EntityHandle set, std::vector<EntityHandle>& entities ) const;
ErrorCode get_entities( SequenceManager const* seqman, EntityHandle set, Range& entities, bool recursive ) const;
ErrorCode get_dimension( SequenceManager const* seqman, EntityHandle set, int dim, std::vector<EntityHandle>& entities, bool recursive ) const;
ErrorCode get_dimension( SequenceManager const* seqman, EntityHandle set, int dim, Range& entities, bool recursive ) const;
ErrorCode get_type( SequenceManager const* seqman, EntityHandle set, EntityType type, std::vector<EntityHandle>& entities, bool recursive ) const;
ErrorCode get_type( SequenceManager const* seqman, EntityHandle set, EntityType type, Range& entities, bool recursive ) const;
ErrorCode num_entities( SequenceManager const* seqman, EntityHandle set, int& count, bool recursive ) const;
ErrorCode num_dimension( SequenceManager const* seqman, EntityHandle set, int dim, int& count, bool recursive ) const;
ErrorCode num_type( SequenceManager const* seqman, EntityHandle set, EntityType type, int& count, bool recursive ) const;
ErrorCode get_parents ( SequenceManager const* seqman, EntityHandle of, std::vector<EntityHandle>& parents, int num_hops ) const;
ErrorCode get_children ( SequenceManager const* seqman, EntityHandle of, std::vector<EntityHandle>& children, int num_hops ) const;
ErrorCode get_contained_sets( SequenceManager const* seqman, EntityHandle of, std::vector<EntityHandle>& contents, int num_hops ) const;
ErrorCode num_parents ( SequenceManager const* seqman, EntityHandle of, int& number, int num_hops ) const;
ErrorCode num_children ( SequenceManager const* seqman, EntityHandle of, int& number, int num_hops ) const;
ErrorCode num_contained_sets( SequenceManager const* seqman, EntityHandle of, int& number, int num_hops ) const;
private:
enum SearchType { PARENTS, CHILDREN, CONTAINED };
MeshSetSequence( MeshSetSequence& split_from, EntityHandle split_at )
: EntitySequence( split_from, split_at )
{}
void initialize( const unsigned* set_flags );
ErrorCode get_parent_child_meshsets( EntityHandle meshset,
SequenceManager const* set_sequences,
std::vector<EntityHandle>& results,
int num_hops, SearchType link_type ) const;
static ErrorCode recursive_get_sets( EntityHandle start_set,
SequenceManager const* set_sequences,
std::vector<const MeshSet*>* sets_out = 0,
Range* set_handles_out = 0,
std::vector<EntityHandle>* set_handle_vect_out = 0 );
static ErrorCode recursive_get_sets( EntityHandle start_set,
SequenceManager* set_sequences,
std::vector<MeshSet*>& sets_out );
enum { SET_SIZE = sizeof(MeshSet) };
inline const unsigned char* array() const
{ return reinterpret_cast<const unsigned char*>(data()->get_sequence_data(0)); }
inline unsigned char* array()
{ return reinterpret_cast<unsigned char*>(data()->get_sequence_data(0)); }
inline void allocate_set( unsigned flags, EntityID index )
{
unsigned char* const ptr = array() + index * SET_SIZE;
new (ptr) MeshSet(flags);
}
inline void deallocate_set( EntityID index )
{
MeshSet* set = reinterpret_cast<MeshSet*>(array() + SET_SIZE * index );
set->~MeshSet();
}
};
inline MeshSet* MeshSetSequence::get_set( EntityHandle h )
{
return reinterpret_cast<MeshSet*>(array() + SET_SIZE*(h - data()->start_handle()));
}
inline const MeshSet* MeshSetSequence::get_set( EntityHandle h ) const
{
return reinterpret_cast<const MeshSet*>(array() + SET_SIZE*(h - data()->start_handle()));
}
} // namespace moab
#endif | c++ | code | 6,322 | 1,050 |
/*
* Copyright (C) 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "aidl.h"
#include "io_delegate.h"
#include "logging.h"
#include "options.h"
using android::aidl::CppOptions;
int main(int argc, char** argv) {
android::base::InitLogging(argv);
LOG(DEBUG) << "aidl starting";
std::unique_ptr<CppOptions> options = CppOptions::Parse(argc, argv);
if (!options) {
return 1;
}
android::aidl::IoDelegate io_delegate;
return android::aidl::compile_aidl_to_cpp(*options, io_delegate);
} | c++ | code | 1,082 | 244 |
/*
* 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.
*/
/*!
* \file src/relay/qnn/op/convolution.cc
* \brief Property def of qnn convolution operator.
*/
#include <tvm/tir/data_layout.h>
#include <tvm/relay/analysis.h>
#include <tvm/relay/base.h>
#include <tvm/relay/op.h>
#include <tvm/relay/qnn/attrs.h>
#include <tvm/relay/transform.h>
#include "../../op/nn/convolution.h"
#include "../../transforms/pattern_util.h"
#include "../util.h"
namespace tvm {
namespace relay {
namespace qnn {
// relay.op.qnn.conv2d
bool QnnConv2DRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
CHECK_EQ(types.size(), 7);
const auto* data = types[0].as<TensorTypeNode>();
const auto* weight = types[1].as<TensorTypeNode>();
if (data == nullptr || weight == nullptr) return false;
const auto* param = attrs.as<Conv2DAttrs>();
CHECK(param != nullptr) << "Conv2DAttrs cannot be nullptr.";
CHECK(data->dtype == DataType::Int(8) || data->dtype == DataType::UInt(8))
<< "Expected qnn conv2d type(int8, uint8) for input but was " << data->dtype;
CHECK(weight->dtype == DataType::Int(8) || weight->dtype == DataType::UInt(8))
<< "Expected qnn conv2d type(int8, uint8) for weight but was " << weight->dtype;
CHECK(param->out_dtype == DataType::Int(16) || param->out_dtype == DataType::Int(32))
<< "Expected qnn conv2d type(int32, int16) for output but was " << param->out_dtype;
CHECK(param->out_dtype.bits() > 0) << "Output dtype bits should be greater than 0.";
// Check the types of scale and zero points.
CHECK(IsScalarType(types[2], DataType::Int(32))); // input_zero_point
CHECK(IsScalarType(types[3], DataType::Int(32))); // kernel_zero_point
CHECK(IsScalarType(types[4], DataType::Float(32))); // input_scale
// Kernel scale can be a vector of length output_channels or a scalar.
size_t axis = param->kernel_layout.find('O');
CHECK(axis != std::string::npos) << "Kernel layout attribute is not defined";
AssignType(types[5], DataType::Float(32), weight->shape[axis], reporter); // kernel scale
// Collect the input tensor and output tensor devoid of scale and zero points to reuse Relay
// Conv2D infer type function.
Array<Type> tensor_types = {types[0], types[1], types[6]};
return Conv2DRel<Conv2DAttrs>(tensor_types, 3, attrs, reporter);
}
Array<Array<Layout>> QnnConvInferCorrectLayout(const Attrs& attrs,
const Array<Layout>& new_in_layouts,
const Array<Layout>& old_in_layouts,
const Array<tvm::relay::Type>& old_in_types) {
// Use Relay Conv2D Infer correct layout.
auto layouts =
ConvInferCorrectLayout<Conv2DAttrs>(attrs, new_in_layouts, old_in_layouts, old_in_types);
// Fill the layouts of remaining input tensors - scales and zero points. The layouts of these
// tensors can be treated as channel layout.
Layout channel_layout = Layout("C");
Array<Layout> input_layouts = {layouts[0][0], layouts[0][1], channel_layout,
channel_layout, channel_layout, channel_layout};
Array<Layout> output_layouts = layouts[1];
return {input_layouts, output_layouts};
}
bool is_depthwise(const Conv2DAttrs* param) {
return param->channels.defined() && tvm::tir::Equal(param->channels, param->groups) &&
param->groups != 1;
}
// Workload - batch_size, in_channels, out_channels, kernel_h, kernel_w, channel_multiplier
using WorkloadType = std::tuple<int, int, int, int, int, int>;
/*
* \brief Get the conv parameters like batch_size, kernel_height etc.
* \param ref_call The original callnode.
* \param param The qnn conv2d attributes.
* \return A tuple of workload.
*/
WorkloadType GetWorkload(const Array<tvm::relay::Type>& arg_types, const Conv2DAttrs* param) {
// Get conv parameters.
const auto in_shape = get_shape(arg_types[0]);
int batch_size, in_channels;
if (param->data_layout == "NCHW") {
batch_size = get_const_int(in_shape[0]);
in_channels = get_const_int(in_shape[1]);
} else if (param->data_layout == "NHWC") {
batch_size = get_const_int(in_shape[0]);
in_channels = get_const_int(in_shape[3]);
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->data_layout << " layout";
}
const auto kernel_shape = get_shape(arg_types[1]);
int out_channels, kernel_h, kernel_w;
int channel_multiplier = -1;
bool depthwise = is_depthwise(param);
if (param->kernel_layout == "OIHW") {
out_channels = get_const_int(kernel_shape[0]);
kernel_h = get_const_int(kernel_shape[2]);
kernel_w = get_const_int(kernel_shape[3]);
if (depthwise) {
channel_multiplier = get_const_int(kernel_shape[1]);
}
} else if (param->kernel_layout == "HWIO") {
kernel_h = get_const_int(kernel_shape[0]);
kernel_w = get_const_int(kernel_shape[1]);
out_channels = get_const_int(kernel_shape[3]);
if (depthwise) {
channel_multiplier = get_const_int(kernel_shape[2]);
}
} else if (param->kernel_layout == "HWOI") {
kernel_h = get_const_int(kernel_shape[0]);
kernel_w = get_const_int(kernel_shape[1]);
out_channels = get_const_int(kernel_shape[2]);
if (depthwise) {
channel_multiplier = get_const_int(kernel_shape[3]);
}
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->kernel_layout << " layout";
}
return std::make_tuple(batch_size, in_channels, out_channels, kernel_h, kernel_w,
channel_multiplier);
}
/*
* \brief Fallback to simpler lowering for dilation (when non-zero kernel point) or grouped conv.
* \param data The input expr.
* \param weight The weight expr.
* \param input_zero_point The input zero point expr.
* \param kernel_zero_point The kernel zero point expr.
* \param param The qnn conv2d attributes.
* \return The fallback lowered sequence of Relay expr.
* \note In case of dilation with non-zero kernel zero point, normal lowering would require a
* dilated pool. Since, we don't have dilated pool, we fallback to a simpler sequence of Relay
* operations. This will potentially lead to performance degradation as the convolution is called on
* int32 tensors instead of int8 tensors.
*/
Expr Conv2DFallBack(const Expr& data, const Expr& weight, const Expr& input_zero_point,
const Expr& kernel_zero_point, const Conv2DAttrs* param) {
// Upcast the zero point to Int16.
auto zp_data = Cast(input_zero_point, DataType::Int(16));
auto zp_kernel = Cast(kernel_zero_point, DataType::Int(16));
auto shifted_data = Cast(data, DataType::Int(16));
auto zero_scalar = MakeConstantScalar(DataType::Int(32), 0);
if (!IsEqualScalar(input_zero_point, zero_scalar)) {
shifted_data = Subtract(Cast(data, DataType::Int(16)), zp_data);
}
auto shifted_kernel = Cast(weight, DataType::Int(16));
if (!IsEqualScalar(kernel_zero_point, zero_scalar)) {
shifted_kernel = Subtract(Cast(weight, DataType::Int(16)), zp_kernel);
}
return Conv2D(shifted_data, shifted_kernel, param->strides, param->padding, param->dilation,
param->groups, param->channels, param->kernel_size, param->data_layout,
param->kernel_layout, param->out_layout, param->out_dtype);
}
/*
* \brief Pad the input data.
* \param data The input expr.
* \param input_zero_point The input zero point expr.
* \return The padded input expr.
* \note For quantized convolution, the input has to be padded with zero point
* instead of zero. This might lead to performance degradation as pad
* cannot be fused with conv in Relay. In case we see performance
* degradation, we can change the conv2D API to accept a pad_const value.
*/
Expr Conv2DPadInput(const Expr& data, const Expr& input_zero_point, const Conv2DAttrs* param) {
// 1) Pad the input data
auto padded_data = data;
auto pad_top_value = get_const_int(param->padding[0]);
auto pad_left_value = get_const_int(param->padding[1]);
auto pad_bottom_value = get_const_int(param->padding[2]);
auto pad_right_value = get_const_int(param->padding[3]);
bool do_pad = pad_top_value != 0 || pad_left_value != 0 ||
pad_bottom_value != 0 || pad_right_value != 0;
if (do_pad) {
Array<IndexExpr> pad_n({0, 0});
Array<IndexExpr> pad_c({0, 0});
Array<IndexExpr> pad_h({param->padding[0], param->padding[2]});
Array<IndexExpr> pad_w({param->padding[1], param->padding[3]});
Array<Array<IndexExpr>> pad_width;
if (param->data_layout == "NCHW") {
pad_width = {pad_n, pad_c, pad_h, pad_w};
} else if (param->data_layout == "NHWC") {
pad_width = {pad_n, pad_h, pad_w, pad_c};
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->data_layout << " layout";
}
auto pad_value = GetScalarFromConstant<int>(input_zero_point);
padded_data = Pad(data, pad_width, pad_value, "constant");
}
return padded_data;
}
/*
* \brief Calculates the second term in the qnn.conv2d depthwise lowering sequence.
* \param padded_data The padded data expr.
* \param kernel_zero_point The kernel zero point expr.
* \param param The qnn conv2d attributes.
* \param kernel_h The height of kernel.
* \param kernel_w The width of kernel.
* \param channel_multiplier The channel/depth multiplier.
* \return The sequence of Relay operators for term2.
* \note The term2 looks like this
*
* Sigma(r, s) zp_w * Qa(n, oc/cm, oh + r, ow + s)
*
* Second term is not directly representable by one Relay operator.
* However, deeper analysis shows that we can reduce r,s using avg_pool2d,
* followed by repeat on the C axis by cm times.
*/
Expr DepthwiseConv2DSecondTerm(const Expr& padded_data, const Expr& kernel_zero_point,
const Conv2DAttrs* param, int kernel_h, int kernel_w,
int channel_multiplier) {
auto casted_t2 = Cast(padded_data, DataType::Int(32));
// We can reduce the H and W axis by using avg_pool2d. However, avg_pool2d averages the sum.
// Since, this is integer division (floor), we can first multiply the data by the pool_size and
// then perform avg_pool2d. Reversing this causes inaccuracy due to floor division. If the
// pool_size is 1x1, we don't need avg_pool2d.
auto reduced_t2 = casted_t2;
if (kernel_h * kernel_w != 1) {
auto scaled_hw_t2 =
Multiply(casted_t2, MakeConstantScalar(DataType::Int(32), kernel_h * kernel_w));
Array<IndexExpr> padding({0, 0});
reduced_t2 =
AvgPool2D(scaled_hw_t2, param->kernel_size, param->strides, padding, param->data_layout,
false, // ceil_mode
false); // count_include_pad
}
auto multiplied_t2 = reduced_t2;
auto one_scalar = MakeConstantScalar(DataType::Int(32), 1);
if (!IsEqualScalar(kernel_zero_point, one_scalar)) {
multiplied_t2 = Multiply(kernel_zero_point, reduced_t2);
}
// Reduce the C dimension. Find the dimension.
int axis_t2 = 0;
if (param->data_layout == "NCHW") {
axis_t2 = 1;
} else if (param->data_layout == "NHWC") {
axis_t2 = 3;
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->data_layout << " layout";
}
auto repeated_t2 = multiplied_t2;
if (channel_multiplier != 1) {
repeated_t2 = MakeRepeat(multiplied_t2, channel_multiplier, axis_t2);
}
return repeated_t2;
}
/*
* \brief Calculates the third term in the qnn.conv2d depthwise lowering sequence.
* \param weight The weight expr.
* \param input_zero_point The input zero point expr.
* \param param The qnn conv2d attributes.
* \param out_channels The number of output channels.
* \param channel_multiplier The channel/depth multiplier.
* \return The sequence of Relay operatos for term3.
* \note The term3 looks like this
*
* Sigma(r, s) zp_a * Qw(oc/m, oc%m, r, s)
*
* This can be achieved by calling reduce on r and s axis. The tensor can be then reshaped to
* (1, oc, 1, 1) as (oc/m, oc%m) are just contiguous memory locations.
*/
Expr DepthwiseConv2DThirdTerm(const Expr& weight, const Expr& input_zero_point,
const Conv2DAttrs* param, int out_channels, int channel_multiplier) {
// Find which dimensions are R, S.
Array<Integer> axes_t3;
if (param->kernel_layout == "OIHW") {
// For OIHW kernel layout, HW are reduce axis
axes_t3 = {2, 3};
} else if (param->kernel_layout == "HWIO") {
axes_t3 = {0, 1};
} else if (param->kernel_layout == "HWOI") {
axes_t3 = {0, 1};
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->kernel_layout << " layout";
}
auto reduced_t3 = Sum(Cast(weight, DataType::Int(32)), axes_t3, false, false);
// Find the newshape depending on NCHW/NHWC layout.
Array<Integer> newshape;
if (param->data_layout == "NCHW") {
newshape = {1, out_channels * channel_multiplier, 1, 1};
} else if (param->data_layout == "NHWC") {
newshape = {1, 1, 1, out_channels * channel_multiplier};
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->data_layout << " layout";
}
auto reshaped_t3 = Reshape(reduced_t3, newshape);
auto one_scalar = MakeConstantScalar(DataType::Int(32), 1);
if (IsEqualScalar(input_zero_point, one_scalar)) {
return reshaped_t3;
}
return Multiply(input_zero_point, reshaped_t3);
}
/*
* \brief Calculates the fourth term in the qnn.conv2d depthwise lowering sequence.
* \param input_zero_point_int The int value of input zero point.
* \param kernel_zero_point_int The int value of kernel zero point.
* \param kernel_h The height of kernel.
* \param kernel_w The width of kernel.
* \return The sequence of Relay operators for term4.
* \note The term4 looks like this
*
* Sigma(r, s) zp_a * zp_w
*/
Expr DepthwiseConv2DFourthTerm(int input_zero_point_int, int kernel_zero_point_int, int kernel_h,
int kernel_w) {
int scalar_term4 = input_zero_point_int * kernel_zero_point_int * kernel_h * kernel_w;
return MakeConstantScalar(DataType::Int(32), scalar_term4);
}
/*
* \brief Calculates the first term in the qnn.conv2d lowering sequence.
* \param data The input expr.
* \param weight The weight expr.
* \param param The qnn conv2d attributes.
* \return The sequence of Relay operators for term1.
* \note The term1 is
* Sigma(c,r,s) QW(k, c, r, s) * QA(n, c, h + r, w + s)
* This is just conv2d on int tensors.
*/
Expr Conv2DFirstTerm(const Expr& padded_data, const Expr& weight, const Conv2DAttrs* param) {
// Lowering for Term 1
Array<IndexExpr> padding({0, 0, 0, 0});
return Conv2D(padded_data, weight, param->strides, padding, param->dilation, param->groups,
param->channels, param->kernel_size, param->data_layout, param->kernel_layout,
param->out_layout, param->out_dtype);
}
/*
* \brief Calculates the second term in the qnn.conv2d lowering sequence.
* \param padded_data The padded data expr.
* \param kernel_zero_point The kernel zero point expr.
* \param param The qnn conv2d attributes.
* \param kernel_h The height of kernel.
* \param kernel_w The width of kernel.
* \return The sequence of Relay operators for term2.
* \note The term2 looks like this
*
* Sigma(c,r,s) zp_w * QA(n, c, h + r, w + s)
*
* Second term is not directly representable by one Relay operator.
* However, deeper analysis shows that we can reduce r,s using avg_pool2d,
* followed by a reduce on the C axis. Using avg_pool2d also gives an
* opportunity to reuse alter_op_layout infrastructure.
*/
Expr Conv2DSecondTerm(const Expr& padded_data, const Expr& kernel_zero_point,
const Conv2DAttrs* param, int kernel_h, int kernel_w, int out_channels) {
auto casted_t2 = Cast(padded_data, DataType::Int(32));
// We can reduce the H and W axis by using avg_pool2d. However, avg_pool2d averages the sum.
// Since, this is integer division (floor), we can first multiply the data by the pool_size and
// then perform avg_pool2d. Reversing this causes inaccuracy due to floor division.
Array<IndexExpr> padding({0, 0});
// Reduce the C dimension. Find the dimension.
Array<Integer> axes_t2;
if (param->data_layout == "NCHW") {
axes_t2 = {1};
} else if (param->data_layout == "NHWC") {
axes_t2 = {3};
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->data_layout << " layout";
}
// Keep dims true to retain 4D tensor
auto reduced_c_t2 = Sum(casted_t2, axes_t2, true, false);
// If the pool_size is 1x1, we don't need avg_pool2d.
auto reduced_t2 = reduced_c_t2;
if (kernel_h * kernel_w != 1) {
reduced_c_t2 =
Multiply(reduced_c_t2, MakeConstantScalar(DataType::Int(32), kernel_h * kernel_w));
reduced_t2 =
AvgPool2D(reduced_c_t2, param->kernel_size, param->strides, padding, param->data_layout,
false, // ceil_mode
false); // count_include_pad
}
auto multiplied_t2 = reduced_t2;
auto one_scalar = MakeConstantScalar(DataType::Int(32), 1);
if (!IsEqualScalar(kernel_zero_point, one_scalar)) {
multiplied_t2 = Multiply(kernel_zero_point, reduced_t2);
}
return multiplied_t2;
}
/*
* \brief Calculates the third term in the qnn.conv2d lowering sequence.
* \param weight The weight expr.
* \param input_zero_point The input zero point expr.
* \param param The qnn conv2d attributes.
* \param out_channels The number of output channels.
* \return The sequence of Relay operatos for term3.
* \note The term3 looks like this
*
* Sigma(c,r,s) zp_a * QW(k, c, r, s)
*
* This can be achieved by calling reduce on c, r and s axis, resulting in
* a 1D tensor. The tensor is then reshaped to conform to NHWC/NCHW
* format.
*/
Expr Conv2DThirdTerm(const Expr& weight, const Expr& input_zero_point, const Conv2DAttrs* param,
int out_channels) {
// Find which dimensions are C, R, S.
Array<Integer> axes_t3;
if (param->kernel_layout == "OIHW") {
// For OIHW kernel layout, IHW are reduce axis
axes_t3 = {1, 2, 3};
} else if (param->kernel_layout == "HWIO") {
axes_t3 = {0, 1, 2};
} else if (param->kernel_layout == "HWOI") {
axes_t3 = {0, 1, 3};
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->kernel_layout << " layout";
}
auto reduced_t3 = Sum(Cast(weight, DataType::Int(32)), axes_t3, false, false);
// Find the newshape depending on NCHW/NHWC layout.
Array<Integer> newshape;
if (param->data_layout == "NCHW") {
newshape = {1, out_channels, 1, 1};
} else if (param->data_layout == "NHWC") {
newshape = {1, 1, 1, out_channels};
} else {
LOG(FATAL) << "qnn.conv2d does not support " << param->data_layout << " layout";
}
auto reshaped_t3 = Reshape(reduced_t3, newshape);
auto one_scalar = MakeConstantScalar(DataType::Int(32), 1);
if (IsEqualScalar(input_zero_point, one_scalar)) {
return reshaped_t3;
}
return Multiply(input_zero_point, reshaped_t3);
}
/*
* \brief Calculates the fourth term in the qnn.conv2d lowering sequence.
* \param input_zero_po | c++ | code | 20,000 | 4,450 |
///
/// @file System.cpp
/// @author Alix ANNERAUD ([email protected])
/// @brief
/// @version 0.1
/// @date 11-07-2021
///
/// @copyright Copyright (c) 2021
///
#include "Core/Core.hpp"
#include "soc/rtc_wdt.h"
#include "esp_task_wdt.h"
#include "Update.h"
extern Xila_Class::Software_Handle Shell_Handle;
///
/// @brief Construct a new System_Class object
///
Xila_Class::System_Class::System_Class()
{
Task_Handle = NULL;
strlcpy(Device_Name, Default_Device_Name, sizeof(Device_Name));
}
///
/// @brief Destroy the System_Class object
///
Xila_Class::System_Class::~System_Class()
{
}
///
/// @brief Load System registry.
///
/// @return Xila_Class::Event
Xila_Class::Event Xila_Class::System_Class::Load_Registry()
{
File Temporary_File = Xila.Drive.Open((Registry("System")));
DynamicJsonDocument System_Registry(512);
if (deserializeJson(System_Registry, Temporary_File)) // error while deserialising
{
Temporary_File.close();
return Error;
}
Temporary_File.close();
if (strcmp("System", System_Registry["Registry"] | "") != 0)
{
return Error;
}
JsonObject Version = System_Registry["Version"];
if (Version["Major"] != Xila_Version_Major || Version["Minor"] != Xila_Version_Minor || Version["Revision"] != Xila_Version_Revision)
{
Panic_Handler(Installation_Conflict);
}
strlcpy(Xila.System.Device_Name, System_Registry["Device Name"] | Default_Device_Name, sizeof(Xila.System.Device_Name));
return Success;
}
///
/// @brief Save System registry.
///
/// @return Xila_Class::Event
Xila_Class::Event Xila_Class::System_Class::Save_Registry()
{
File Temporary_File = Xila.Drive.Open((Registry("System")), FILE_WRITE);
DynamicJsonDocument System_Registry(256);
System_Registry["Registry"] = "System";
System_Registry["Device Name"] = Device_Name;
JsonObject Version = System_Registry.createNestedObject("Version");
Version["Major"] = Xila_Version_Major;
Version["Minor"] = Xila_Version_Minor;
Version["Revision"] = Xila_Version_Revision;
if (serializeJson(System_Registry, Temporary_File) == 0)
{
Temporary_File.close();
return Error;
}
Temporary_File.close();
return Success;
}
///
/// @brief System task.
///
void Xila_Class::System_Class::Task(void *)
{
uint32_t Next_Refresh = 0;
Xila.Power.Button_Counter = 0;
while (1)
{
// -- Check power button interrupt
Xila.Power.Check_Button();
// -- Execute data from display.
Xila.Display.Loop();
// -- Task to refresh every 10 seconds
if (Xila.Time.Milliseconds() > Next_Refresh)
{
// -- Check if drive is not disconnected.
if (!Xila.Drive.Exists(Xila_Directory_Path) || !Xila.Drive.Exists(Software_Directory_Path))
{
Xila.System.Panic_Handler(Xila.System.System_Drive_Failure);
}
// -- Check if running software is not frozen
Xila.Software_Management.Check_Watchdog();
// -- Check WiFi is connected
if (Xila.WiFi.status() != WL_CONNECTED)
{
Xila.WiFi.Load_Registry();
}
// -- Check available (prevent memory overflow)
if (Xila.Memory.Get_Free_Heap() < Low_Memory_Threshold)
{
Xila.System.Panic_Handler(Low_Memory);
}
// -- Syncronise time
Xila.Time.Synchronize();
// -- Check if software is currently maximized
if (Xila.Software_Management.Openned[0] == NULL)
{
Xila.Task.Delay(100);
// -- If no software is currently maximized, maximize shell.
if (Xila.Software_Management.Openned[0] == NULL)
{
Xila.Software_Management.Open(Shell_Handle);
Xila.Software_Management.Shell_Send_Instruction(Xila.Desk);
Xila.Software_Management.Shell_Maximize();
}
}
// -- Clear the refresh timer.
Next_Refresh = Xila.Time.Milliseconds() + 10000;
}
Xila.Task.Delay(20);
}
}
///
/// @brief Update Xila on the MCU.
///
/// @param Update_File Executable file.
/// @return Xila_Class::Event
Xila_Class::Event Xila_Class::System_Class::Load_Executable(File Executable_File)
{
if (!Executable_File || Executable_File.isDirectory())
{
return Xila.Error;
}
if (Executable_File.isDirectory())
{
return Xila.Error;
}
if (Executable_File.size() == 0)
{
return Xila.Error;
}
if (!Update.begin(Executable_File.size(), U_FLASH))
{
return Xila.Error;
}
size_t Written = Update.writeStream(Executable_File);
if (Written != Executable_File.size())
{
return Xila.Error;
}
if (!Update.end())
{
return Xila.Error;
}
if (!Update.isFinished())
{
return Xila.Error;
}
return Xila.Success;
}
///
/// @brief Handle fatal events that the system cannot recover from.
///
/// @param Panic_Code Panic code to handle.
void Xila_Class::System_Class::Panic_Handler(Panic_Code Panic_Code)
{
Xila.Display.Set_Current_Page(F("Core_Panic"));
char Temporary_String[32];
snprintf(Temporary_String, sizeof(Temporary_String), "Error code : %X", Panic_Code);
Xila.Display.Set_Text(F("ERRORCODE_TXT"), Temporary_String);
vTaskSuspendAll();
uint32_t Delay_Time = Xila.Time.Milliseconds();
while ((Xila.Time.Milliseconds() - Delay_Time) < 5000)
{
}
abort();
}
///
/// @brief Save system dump.
///
/// @return Xila_Class::Event
Xila_Class::Event Xila_Class::System_Class::Save_Dump()
{
DynamicJsonDocument Dump_Registry(Default_Registry_Size);
JsonArray Software = Dump_Registry.createNestedArray("Software");
Dump_Registry["Registry"] = "Dump";
for (uint8_t i = 2; i <= 7; i++)
{
if (Xila.Software_Management.Openned[i] != NULL)
{
Software.add(Xila.Software_Management.Openned[i]->Handle->Name);
}
}
Dump_Registry["User"] = Xila.Account.Get_Current_Username();
File Dump_File = Xila.Drive.Open(Dump_Registry_Path, FILE_WRITE);
if (serializeJson(Dump_Registry, Dump_File) == 0)
{
Dump_File.close();
return Error;
}
Dump_File.close();
return Success;
}
///
/// @brief Load system dump.
///
/// @return Xila_Class::Event
Xila_Class::Event Xila_Class::System_Class::Load_Dump()
{
if (Xila.Drive.Exists(Dump_Registry_Path))
{
File Dump_File = Xila.Drive.Open((Dump_Registry_Path));
DynamicJsonDocument Dump_Registry(Default_Registry_Size);
if (deserializeJson(Dump_Registry, Dump_File) != DeserializationError::Ok)
{
Dump_File.close();
Xila.Drive.Remove(Dump_Registry_Path);
return Error;
}
Dump_File.close();
Xila.Drive.Remove(Dump_Registry_Path);
if (strcmp(Dump_Registry["Registry"] | "", "Dump") != 0)
{
return Error;
}
char Temporary_Software_Name[Default_Software_Name_Length];
JsonArray Software = Dump_Registry["Software"];
for (uint8_t i = 0; i < 6; i++)
{
memset(Temporary_Software_Name, '\0', sizeof(Temporary_Software_Name));
strlcpy(Temporary_Software_Name, Software[i] | "", sizeof(Temporary_Software_Name));
for (uint8_t j = 0; j < Maximum_Software; j++)
{
if (Xila.Software_Management.Handle[j] != NULL)
{
if (strcmp(Xila.Software_Management.Handle[j]->Name, Temporary_Software_Name) == 0)
{
Xila.Software_Management.Open(*Xila.Software_Management.Handle[j]);
}
}
}
}
strlcpy(Xila.Account.Current_Username, Dump_Registry["User"] | "", sizeof(Xila.Account.Current_Username));
if (Xila.Account.Current_Username[0] != '\0')
{
Xila.Account.Set_State(Xila.Account.Locked);
}
return Success;
}
else
{
return Error;
}
}
///
/// @brief Return device name.
///
/// @return const char* Device name.
const char *Xila_Class::System_Class::Get_Device_Name()
{
return Xila.System.Device_Name;
}
///
/// @brief Refresh top header.
///
void Xila_Class::System_Class::Refresh_Header()
{
if (Xila.Display.Get_State() == false) // if display sleep
{
return;
}
static char Temporary_Char_Array[6];
// -- Update clock
Temporary_Char_Array[0] = Xila.Time.Current_Time.tm_hour / 10;
Temporary_Char_Array[0] += 48;
Temporary_Char_Array[1] = Xila.Time.Current_Time.tm_hour % 10;
Temporary_Char_Array[1] += 48;
Temporary_Char_Array[2] = ':';
Temporary_Char_Array[3] = Xila.Time.Current_Time.tm_min / 10;
Temporary_Char_Array[3] += 48;
Temporary_Char_Array[4] = Xila.Time.Current_Time.tm_min % 10;
Temporary_Char_Array[4] += 48;
Temporary_Char_Array[5] = '\0';
Xila.Display.Set_Text(F("CLOCK_TXT"), Temporary_Char_Array);
// Update connection
Temporary_Char_Array[5] = Xila.WiFi.RSSI();
if (Xila.WiFi.status() == WL_CONNECTED)
{
if (Temporary_Char_Array[5] <= -70)
{
Xila.Display.Set_Text(F("CONNECTION_BUT"), Xila.Display.WiFi_Low);
}
if (Temporary_Char_Array[0] <= -50 && Temporary_Char_Array[0] > -70)
{
Xila.Display.Set_Text(F("CONNECTION_BUT"), Xila.Display.WiFi_Medium);
}
else
{
Xila.Display.Set_Text(F("CONNECTION_BUT"), Xila.Display.WiFi_High);
}
}
else
{
Xila.Display.Set_Text(F("CONNECTION_BUT"), ' ');
}
// -- Update charge level
Temporary_Char_Array[5] = Xila.Power.Get_Charge_Level();
if (Temporary_Char_Array[5] <= 5)
{
Xila.Display.Set_Text(F("BATTERY_BUT"), Xila.Display.Battery_Empty);
Xila.Display.Set_Font_Color(F("BATTERY_BUT"), Xila.Display.Red);
}
else if (Temporary_Char_Array[5] <= 10 && Temporary_Char_Array[5] > 5)
{
Xila.Display.Set_Text(F("BATTERY_BUT"), Xila.Display.Battery_Empty);
Xila.Display.Set_Font_Color(F("BATTERY_BUT"), Xila.Display.White);
}
else if (Temporary_Char_Array[5] <= 35 && Temporary_Char_Array[5] > 10)
{
Xila.Display.Set_Text(F("BATTERY_BUT"), Xila.Display.Battery_Quarter);
}
else if (Temporary_Char_Array[5] <= 60 && Temporary_Char_Array[5] > 35)
{
Xila.Display.Set_Text(F("BATTERY_BUT"), Xila.Display.Battery_Half);
}
else if (Temporary_Char_Array[5] <= 85 && Temporary_Char_Array[5] > 60)
{
Xila.Display.Set_Text(F("BATTERY_BUT"), Xila.Display.Battery_Three_Quarters);
}
else // more than 85 %
{
Xila.Display.Set_Text(F("BATTERY_BUT"), Xila.Display.Battery_Full);
}
// -- Update sound
Temporary_Char_Array[5] = Xila.Sound.Get_Volume();
if (Temporary_Char_Array[5] == 0)
{
Xila.Display.Set_Text(F("SOUND_BUT"), Xila.Display.Sound_Mute);
}
else if (Temporary_Char_Array[5] < 86)
{
Xila.Display.Set_Text(F("SOUND_BUT"), Xila.Display.Sound_Low);
}
else if (Temporary_Char_Array[5] < 172)
{
Xila.Display.Set_Text(F("SOUND_BUT"), Xila.Display.Sound_Medium);
}
else
{
Xila.Display.Set_Text(F("SOUND_BUT"), Xila.Display.Sound_High);
}
}
///
/// @brief First start routine, first function executed when Xila.Start() is called.
///
inline void Xila_Class::System_Class::First_Start_Routine()
{
#if USB_Serial == 1
Serial.begin(Default_USB_Serial_Speed);
#endif
if (Xila.System.Task_Handle != NULL) // Already started
{
return;
}
// -- Check if the power button was press or the power supply plugged.
esp_sleep_enable_ext0_wakeup(Power_Button_Pin, LOW);
esp_sleep_wakeup_cause_t Wakeup_Cause = esp_sleep_get_wakeup_cause();
#if Start_On_Power == 0
if (Wakeup_Cause != ESP_SLEEP_WAKEUP_EXT0)
{
Xila.Power.Deep_Sleep();
}
#elif Start_On_Power == 1
if (Wakeup_Cause != ESP_SLEEP_WAKEUP_EXT0 && Wakeup_Cause != ESP_SLEEP_WAKEUP_UNDEFINED)
{
Xila.Power.Deep_Sleep();
}
#endif
// -- Set power button interrupts
Xila.GPIO.Set_Mode(Power_Button_Pin, INPUT);
Xila.GPIO.Attach_Interrupt(digitalPinToInterrupt(Power_Button_Pin), Xila.Power.Button_Interrupt_Handler, Xila.GPIO.Change);
// -- Increase esp32 hardware watchdog timeout
if (esp_task_wdt_init(Maximum_Watchdog_Timeout / 1000, true) != ESP_OK)
{
ESP.restart();
}
// -- Initialize drive. -- //
#if Drive_Mode == 0
Xila.GPIO.Set_Mode(14, INPUT_PULLUP);
Xila.GPIO.Set_Mode(2, INPUT_PULLUP);
Xila.GPIO.Set_Mode(4, INPUT_PULLUP);
Xila.GPIO.Set_Mode(12, INPUT_PULLUP);
Xila.GPIO.Set_Mode(13, INPUT_PULLUP);
#endif
if (!Xila.Drive.Begin() || Xila.Drive.Type() == Xila.Drive.None)
{
Xila.Display.Set_Text(F("EVENT_TXT"), F("Failed to initialize drive."));
}
while (!Xila.Drive.Begin() || Xila.Drive.Type() == Xila.Drive.None)
{
Xila.Drive.End();
Xila.Task.Delay(200);
}
Xila.Display.Set_Text(F("EVENT_TXT"), F(""));
// -- Initialize display. -- //
Xila.Display.Set_Callback_Function_Numeric_Data(Xila.Display.Incoming_Numeric_Data_From_Display);
Xila.Display.Set_Callback_Function_String_Data(Xila.Display.Incoming_String_Data_From_Display);
Xila.Display.Set_Callback_Function_Event(Xila.Display.Incoming_Event_From_Display);
if (Xila.Display.Load_Registry() != Success)
{
Xila.Display.Save_Registry();
}
Xila.Display.Begin(Xila.Display.Baud_Rate, Xila.Display.Receive_Pin, Xila.Display.Transmit_Pin);
if (!Xila.Drive.Exists(Users_Directory_Path))
{
File Temporary_File = Xila.Drive.Open(Display_Executable_Path);
if (Xila.Display.Update(Temporary_File) != Xila.Display.Update_Succeed)
{
Panic_Handler(Failed_To_Update_Display);
}
Xila.Task.Delay(5000);
Xila.Display.Begin(Xila.Display.Baud_Rate, Xila.Display.Receive_Pin, Xila.Display.Transmit_Pin);
}
Xila.GPIO.Set_Mode(Default_Display_Switching_Pin, Xila.GPIO.Output);
Xila.GPIO.Digital_Write(Default_Display_Switching_Pin, Xila.GPIO.High);
Xila.Task.Delay(2000);
Xila.Display.Wake_Up();
Xila.Display.Set_Touch_Wake_Up(true);
Xila.Display.Set_Serial_Wake_Up(true);
Xila.Display.Set_Brightness(Xila.Display.Brightness);
Xila.Display.Set_Standby_Touch_Timer(Xila.Display.Standby_Time);
Xila.Display.Set_Current_Page(F("Core_Load")); // Play animation
Xila.Display.Set_Trigger(F("LOAD_TIM"), true);
// -- Check system integrity -- //
if (!Xila.Drive.Exists(Xila_Directory_Path) || !Xila.Drive.Exists(Software_Directory_Path))
{
Xila.System.Panic_Handler(Xila.System.Missing_System_Files);
}
// -- Load system registry -- //
if (Xila.System.Load_Registry() != Success)
{
Xila.System.Panic_Handler(Xila.System.Damaged_System_Registry);
}
Xila.WiFi.setHostname(Xila.System.Device_Name); // Set hostname
// -- Load sound registry --
if (Xila.Sound.Load_Registry() != Success)
{
Xila.Sound.Save_Registry();
}
Xila.Sound.Begin();
// -- Play startup sound
Xila.Sound.Play(Sounds("Startup.wav"));
// -- Load power registry :
if (Xila.Power.Load_Registry() != Success)
{
Xila.Power.Save_Registry();
}
// -- Network registry :
if (Xila.WiFi.Load_Registry() != Success)
{
Xila.WiFi.Save_Registry();
}
// -- Time registry
if (Xila.Time.Load_Registry() != Success)
{
Xila.Time.Save_Registry();
}
// -- Load account registry
if (Xila.Account.Load_Registry() != Success)
{
Xila.Account.Set_Autologin(false);
}
// -- Load Keyboard Registry
if (Xila.Keyboard.Load_Registry() != Success)
{
Xila.Keyboard.Save_Registry(); // recreate a keyboard registry with default values
}
}
///
/// @brief Second start routine, called secondly in Xila.Start().
///
void Xila_Class::System_Class::Second_Start_Routine()
{
#if Animations == 1
Xila.Task.Delay(3000);
#endif
Xila.Display.Set_Value(F("STATE_VAR"), 2);
#if Animations == 1
Xila.Task.Delay(3000);
#endif
Xila.Task.Delay(500);
Xila.System.Load_Dump();
Xila.Task.Delay(100);
Execute_Startup_Function();
Xila.Task.Create(Xila.System.Task, "Core Task", Memory_Chunk(4), NULL, Xila.Task.System_Task, &Xila.System.Task_Handle);
Xila.Task.Delete(); // delete main task
}
///
/// @brief Start Xila up with a custom software bundle.
///
/// @param Software_Package Custom software bundle.
/// @param Size Size of the software bundle.
void Xila_Class::System_Class::Start(Xila_Class::Software_Handle **Software_Package, uint8_t Size)
{
First_Start_Routine();
// Restore attribute
for (uint8_t i = 0; i < Size; i++)
{
Xila.Software_Management.Add_Handle(*Software_Package[i]);
}
Second_Start_Routine();
}
///
/// @brief Start Xila up with the default software bundle.
///
void Xila_Class::System_Class::Start()
{
First_Start_Routine();
extern Xila_Class::Software_Handle Calculator_Handle;
extern Xila_Class::Software_Handle Clock_Handle;
extern Xila_Class::Software_Handle Internet_Browser_Handle;
extern Xila_Class::Software_Handle Music_Player_Handle;
extern Xila_Class::Software_Handle Oscilloscope_Handle;
extern Xila_Class::Software_Handle Paint_Handle;
extern Xila_Class::Software_Handle Periodic_Handle;
extern Xila_Class::Software_Handle Piano_Handle;
extern Xila_Class::Software_Handle Pong_Handle;
extern Xila_Class::Software_Handle Simon_Handle;
extern Xila_Class::Software_Handle Text_Editor_Handle;
extern Xila_Class::Software_Handle Tiny_Basic_Handle;
Xila.Software_Management.Add_Handle(Calculator_Handle);
Xila.Software_Management.Add_Handle(Clock_Handle);
Xila.Software_Management.Add_Handle(Internet_Browser_Handle);
Xila.Software_Management.Add_Handle(Music_Player_Handle);
Xila.Software_Management.Add_Handle(Oscilloscope_Handle);
Xila.Software_Management.Add_Handle(Paint_Handle);
Xila.Software_Management.Add_Handle(Periodic_Handle);
Xila.Software_Management.Add_Handle(Piano_Handle);
Xila.Software_Management.Add_Handle(Pong_Handle);
Xila.Software_Management.Add_Handle(Simon_Handle);
Xila.Software_Management.Add_Handle(Text_Editor_Handle);
Xila.Software_Management.Add_Handle(Tiny_Basic_Handle);
Second_Start_Routine();
}
///
/// @brief Execute software startup function.
///
void Xila_Class::System_Class::Execute_Startup_Function()
{
(*Shell_Handle.Startup_Function_Pointer)();
for (uint8_t i = 0; i < Maximum_Software; i++)
{
if (Xila.Software_Management.Handle[i] != NULL)
{
if (Xila.Software_Management.Handle[i]->Startup_Function_Pointer != NULL)
{
(*Xila.Software_Management.Handle[i]->Startup_Function_Pointer)();
}
}
}
}
///
/// @brief Shutdown Xila.
///
void Xila_Class::System_Class::Shutdown()
{
Xila.Software_Management.Shell_Maximize();
Xila.Software_Management.Shell_Send_Instruction(Xila.Shutdown);
for (uint8_t i = 2; i < 8; i++)
{
if (Xila.Software_Management.Openned[i] != NULL)
{
Xila.Software_Management.Openned[i]->Send_Instruction(Xila.Shutdown);
Xila.Task.Resume(Xila.Software_Management.Openned[i]->Task_Handle);
// -- Waiting for the software to close
for (uint8_t j = 0; j <= 200; j++)
{
if (Xila.Software_Management.Openned[i] == NULL)
{
break;
}
if (j == 200 && Xila.Software_Management.Openned[i] != NULL)
{
Xila.Software_Management.Force_Close(*Xila.Software_Management.Openned[i]->Handle);
}
Xila.Task.Delay(20);
}
}
}
Second_Sleep_Routine();
Xila.Power.Deep_Sleep();
}
///
/// @brief Second sleep routine called in shutdown function.
///
void Xila_Class::System_Class::Second_Sleep_Routine()
{
Xila.Task.Delete(Xila.System.Task_Handle);
Xila.Display.Save_Registry();
Xila.Keyboard.Save_Registry();
Xila.Power.Save_Registry();
Xila.Sound.Save_Registry();
Xila.WiFi.Save_Registry();
Xila.Time.Save_Registry();
Xila.System.Save_Registry();
Xila.Sound.Play(Sounds("Shutdown.wav"));
Xila.Task.Delay(8000);
Xila.Task.Delete(Xila.Sound.Task_Handle);
// Disconnect wifi
Xila.WiFi.disconnect();
}
///
/// @brief Hibernate Xila.
///
void Xila_Class::System_Class::Hibernate()
{
Xila.System.Save_Dump();
Xila.Software_Management.Shell_Maximize();
Xila.Software_Management.Shell_Send_Instruction(Xila.Hibernate);
for (uint8_t i = 2; i < 8; i++)
{
if (Xila.Software_Management.Openned[i] != NULL)
{
Xila.Software_Management.Openned[i]->Send_Instruction(Xila.Hibernate);
Xila.Task.Resume(Xila.Software_Management.Openned[i]->Task_Handle);
// -- Waiting for the s | c++ | code | 20,000 | 4,486 |
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/sddp/model/DescribeDataTotalCountResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Sddp;
using namespace AlibabaCloud::Sddp::Model;
DescribeDataTotalCountResult::DescribeDataTotalCountResult() :
ServiceResult()
{}
DescribeDataTotalCountResult::DescribeDataTotalCountResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeDataTotalCountResult::~DescribeDataTotalCountResult()
{}
void DescribeDataTotalCountResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataCountNode = value["DataCount"];
auto instanceNode = dataCountNode["Instance"];
if(!instanceNode["TotalCount"].isNull())
dataCount_.instance.totalCount = std::stol(instanceNode["TotalCount"].asString());
if(!instanceNode["Count"].isNull())
dataCount_.instance.count = std::stol(instanceNode["Count"].asString());
if(!instanceNode["SensitiveCount"].isNull())
dataCount_.instance.sensitiveCount = std::stol(instanceNode["SensitiveCount"].asString());
if(!instanceNode["LastCount"].isNull())
dataCount_.instance.lastCount = std::stol(instanceNode["LastCount"].asString());
if(!instanceNode["LastSensitiveCount"].isNull())
dataCount_.instance.lastSensitiveCount = std::stol(instanceNode["LastSensitiveCount"].asString());
auto allRiskCountListNode = instanceNode["RiskCountList"]["RiskCount"];
for (auto instanceNodeRiskCountListRiskCount : allRiskCountListNode)
{
DataCount::Instance::RiskCount riskCountObject;
if(!instanceNodeRiskCountListRiskCount["Id"].isNull())
riskCountObject.id = std::stol(instanceNodeRiskCountListRiskCount["Id"].asString());
if(!instanceNodeRiskCountListRiskCount["Name"].isNull())
riskCountObject.name = instanceNodeRiskCountListRiskCount["Name"].asString();
if(!instanceNodeRiskCountListRiskCount["Count"].isNull())
riskCountObject.count = std::stol(instanceNodeRiskCountListRiskCount["Count"].asString());
dataCount_.instance.riskCountList.push_back(riskCountObject);
}
auto tableNode = dataCountNode["Table"];
if(!tableNode["TotalCount"].isNull())
dataCount_.table.totalCount = std::stol(tableNode["TotalCount"].asString());
if(!tableNode["Count"].isNull())
dataCount_.table.count = std::stol(tableNode["Count"].asString());
if(!tableNode["SensitiveCount"].isNull())
dataCount_.table.sensitiveCount = std::stol(tableNode["SensitiveCount"].asString());
if(!tableNode["LastCount"].isNull())
dataCount_.table.lastCount = std::stol(tableNode["LastCount"].asString());
if(!tableNode["LastSensitiveCount"].isNull())
dataCount_.table.lastSensitiveCount = std::stol(tableNode["LastSensitiveCount"].asString());
auto allRiskCountList1Node = tableNode["RiskCountList"]["RiskCount"];
for (auto tableNodeRiskCountListRiskCount : allRiskCountList1Node)
{
DataCount::Table::RiskCount2 riskCount2Object;
if(!tableNodeRiskCountListRiskCount["Id"].isNull())
riskCount2Object.id = std::stol(tableNodeRiskCountListRiskCount["Id"].asString());
if(!tableNodeRiskCountListRiskCount["Name"].isNull())
riskCount2Object.name = tableNodeRiskCountListRiskCount["Name"].asString();
if(!tableNodeRiskCountListRiskCount["Count"].isNull())
riskCount2Object.count = std::stol(tableNodeRiskCountListRiskCount["Count"].asString());
dataCount_.table.riskCountList1.push_back(riskCount2Object);
}
auto packageNode = dataCountNode["Package"];
if(!packageNode["TotalCount"].isNull())
dataCount_.package.totalCount = std::stol(packageNode["TotalCount"].asString());
if(!packageNode["Count"].isNull())
dataCount_.package.count = std::stol(packageNode["Count"].asString());
if(!packageNode["SensitiveCount"].isNull())
dataCount_.package.sensitiveCount = std::stol(packageNode["SensitiveCount"].asString());
if(!packageNode["LastCount"].isNull())
dataCount_.package.lastCount = std::stol(packageNode["LastCount"].asString());
if(!packageNode["LastSensitiveCount"].isNull())
dataCount_.package.lastSensitiveCount = std::stol(packageNode["LastSensitiveCount"].asString());
auto allRiskCountList3Node = packageNode["RiskCountList"]["RiskCount"];
for (auto packageNodeRiskCountListRiskCount : allRiskCountList3Node)
{
DataCount::Package::RiskCount4 riskCount4Object;
if(!packageNodeRiskCountListRiskCount["Id"].isNull())
riskCount4Object.id = std::stol(packageNodeRiskCountListRiskCount["Id"].asString());
if(!packageNodeRiskCountListRiskCount["Name"].isNull())
riskCount4Object.name = packageNodeRiskCountListRiskCount["Name"].asString();
if(!packageNodeRiskCountListRiskCount["Count"].isNull())
riskCount4Object.count = std::stol(packageNodeRiskCountListRiskCount["Count"].asString());
dataCount_.package.riskCountList3.push_back(riskCount4Object);
}
auto columnNode = dataCountNode["Column"];
if(!columnNode["TotalCount"].isNull())
dataCount_.column.totalCount = std::stol(columnNode["TotalCount"].asString());
if(!columnNode["Count"].isNull())
dataCount_.column.count = std::stol(columnNode["Count"].asString());
if(!columnNode["SensitiveCount"].isNull())
dataCount_.column.sensitiveCount = std::stol(columnNode["SensitiveCount"].asString());
if(!columnNode["LastCount"].isNull())
dataCount_.column.lastCount = std::stol(columnNode["LastCount"].asString());
if(!columnNode["LastSensitiveCount"].isNull())
dataCount_.column.lastSensitiveCount = std::stol(columnNode["LastSensitiveCount"].asString());
auto allRiskCountList5Node = columnNode["RiskCountList"]["RiskCount"];
for (auto columnNodeRiskCountListRiskCount : allRiskCountList5Node)
{
DataCount::Column::RiskCount6 riskCount6Object;
if(!columnNodeRiskCountListRiskCount["Id"].isNull())
riskCount6Object.id = std::stol(columnNodeRiskCountListRiskCount["Id"].asString());
if(!columnNodeRiskCountListRiskCount["Name"].isNull())
riskCount6Object.name = columnNodeRiskCountListRiskCount["Name"].asString();
if(!columnNodeRiskCountListRiskCount["Count"].isNull())
riskCount6Object.count = std::stol(columnNodeRiskCountListRiskCount["Count"].asString());
dataCount_.column.riskCountList5.push_back(riskCount6Object);
}
auto allColumnRuleTopNode = columnNode["ColumnRuleTop"]["ColumnCount"];
for (auto columnNodeColumnRuleTopColumnCount : allColumnRuleTopNode)
{
DataCount::Column::ColumnCount columnCountObject;
if(!columnNodeColumnRuleTopColumnCount["Id"].isNull())
columnCountObject.id = std::stol(columnNodeColumnRuleTopColumnCount["Id"].asString());
if(!columnNodeColumnRuleTopColumnCount["Name"].isNull())
columnCountObject.name = columnNodeColumnRuleTopColumnCount["Name"].asString();
if(!columnNodeColumnRuleTopColumnCount["Count"].isNull())
columnCountObject.count = std::stol(columnNodeColumnRuleTopColumnCount["Count"].asString());
dataCount_.column.columnRuleTop.push_back(columnCountObject);
}
auto ossNode = dataCountNode["Oss"];
if(!ossNode["TotalCount"].isNull())
dataCount_.oss.totalCount = std::stol(ossNode["TotalCount"].asString());
if(!ossNode["Count"].isNull())
dataCount_.oss.count = std::stol(ossNode["Count"].asString());
if(!ossNode["SensitiveCount"].isNull())
dataCount_.oss.sensitiveCount = std::stol(ossNode["SensitiveCount"].asString());
if(!ossNode["LastCount"].isNull())
dataCount_.oss.lastCount = std::stol(ossNode["LastCount"].asString());
if(!ossNode["LastSensitiveCount"].isNull())
dataCount_.oss.lastSensitiveCount = std::stol(ossNode["LastSensitiveCount"].asString());
auto allRiskCountList7Node = ossNode["RiskCountList"]["RiskCount"];
for (auto ossNodeRiskCountListRiskCount : allRiskCountList7Node)
{
DataCount::Oss::RiskCount8 riskCount8Object;
if(!ossNodeRiskCountListRiskCount["Id"].isNull())
riskCount8Object.id = std::stol(ossNodeRiskCountListRiskCount["Id"].asString());
if(!ossNodeRiskCountListRiskCount["Name"].isNull())
riskCount8Object.name = ossNodeRiskCountListRiskCount["Name"].asString();
if(!ossNodeRiskCountListRiskCount["Count"].isNull())
riskCount8Object.count = std::stol(ossNodeRiskCountListRiskCount["Count"].asString());
dataCount_.oss.riskCountList7.push_back(riskCount8Object);
}
auto allOssRuleTopNode = ossNode["OssRuleTop"]["OssCount"];
for (auto ossNodeOssRuleTopOssCount : allOssRuleTopNode)
{
DataCount::Oss::OssCount ossCountObject;
if(!ossNodeOssRuleTopOssCount["Id"].isNull())
ossCountObject.id = std::stol(ossNodeOssRuleTopOssCount["Id"].asString());
if(!ossNodeOssRuleTopOssCount["Name"].isNull())
ossCountObject.name = ossNodeOssRuleTopOssCount["Name"].asString();
if(!ossNodeOssRuleTopOssCount["Count"].isNull())
ossCountObject.count = std::stol(ossNodeOssRuleTopOssCount["Count"].asString());
dataCount_.oss.ossRuleTop.push_back(ossCountObject);
}
}
DescribeDataTotalCountResult::DataCount DescribeDataTotalCountResult::getDataCount()const
{
return dataCount_;
} | c++ | code | 9,494 | 2,244 |
/*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky ([email protected]) 2006-2016
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "map/hdr_map.h"
#include <cds/urcu/general_buffered.h>
#include <cds/container/lazy_list_rcu.h>
#include <cds/container/split_list_map_rcu.h>
namespace map {
namespace {
typedef cds::urcu::gc< cds::urcu::general_buffered<> > rcu_type;
struct RCU_GPB_cmp_traits: public cc::split_list::traits
{
typedef cc::lazy_list_tag ordered_list;
typedef HashMapHdrTest::hash_int hash;
typedef HashMapHdrTest::simple_item_counter item_counter;
typedef cc::opt::v::relaxed_ordering memory_model;
enum { dynamic_bucket_table = false };
struct ordered_list_traits: public cc::lazy_list::traits
{
typedef HashMapHdrTest::cmp compare;
};
};
struct RCU_GPB_less_traits: public cc::split_list::traits
{
typedef cc::lazy_list_tag ordered_list;
typedef HashMapHdrTest::hash_int hash;
typedef HashMapHdrTest::simple_item_counter item_counter;
typedef cc::opt::v::sequential_consistent memory_model;
enum { dynamic_bucket_table = true };
struct ordered_list_traits: public cc::lazy_list::traits
{
typedef HashMapHdrTest::less less;
};
};
struct RCU_cmpmix_traits: public cc::split_list::traits
{
typedef cc::lazy_list_tag ordered_list;
typedef HashMapHdrTest::hash_int hash;
typedef HashMapHdrTest::simple_item_counter item_counter;
struct ordered_list_traits: public cc::lazy_list::traits
{
typedef HashMapHdrTest::cmp compare;
typedef std::less<HashMapHdrTest::key_type> less;
};
};
struct RCU_cmpmix_stat_traits : public RCU_cmpmix_traits
{
typedef cc::split_list::stat<> stat;
};
}
void HashMapHdrTest::Split_Lazy_RCU_GPB_cmp()
{
// traits-based version
typedef cc::SplitListMap< rcu_type, key_type, value_type, RCU_GPB_cmp_traits > map_type;
test_rcu< map_type >();
// option-based version
typedef cc::SplitListMap< rcu_type,
key_type,
value_type,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::lazy_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::opt::memory_model< cc::opt::v::relaxed_ordering >
,cc::split_list::dynamic_bucket_table< true >
,cc::split_list::ordered_list_traits<
cc::lazy_list::make_traits<
cc::opt::compare< cmp >
>::type
>
>::type
> opt_map;
test_rcu< opt_map >();
}
void HashMapHdrTest::Split_Lazy_RCU_GPB_less()
{
// traits-based version
typedef cc::SplitListMap< rcu_type, key_type, value_type, RCU_GPB_less_traits > map_type;
test_rcu< map_type >();
// option-based version
typedef cc::SplitListMap< rcu_type,
key_type,
value_type,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::lazy_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::opt::memory_model< cc::opt::v::relaxed_ordering >
,cc::split_list::dynamic_bucket_table< false >
,cc::split_list::ordered_list_traits<
cc::lazy_list::make_traits<
cc::opt::less< less >
>::type
>
>::type
> opt_map;
test_rcu< opt_map >();
}
void HashMapHdrTest::Split_Lazy_RCU_GPB_cmpmix()
{
// traits-based version
typedef cc::SplitListMap< rcu_type, key_type, value_type, RCU_cmpmix_traits > map_type;
test_rcu< map_type >();
// option-based version
typedef cc::SplitListMap< rcu_type,
key_type,
value_type,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::lazy_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::split_list::ordered_list_traits<
cc::lazy_list::make_traits<
cc::opt::less< std::less<key_type> >
,cc::opt::compare< cmp >
>::type
>
>::type
> opt_map;
test_rcu< opt_map >();
}
void HashMapHdrTest::Split_Lazy_RCU_GPB_cmpmix_stat()
{
// traits-based version
typedef cc::SplitListMap< rcu_type, key_type, value_type, RCU_cmpmix_stat_traits > map_type;
test_rcu< map_type >();
// option-based version
typedef cc::SplitListMap< rcu_type,
key_type,
value_type,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::lazy_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::opt::stat< cc::split_list::stat<> >
,cc::split_list::ordered_list_traits<
cc::lazy_list::make_traits<
cc::opt::less< std::less<key_type> >
,cc::opt::compare< cmp >
>::type
>
>::type
> opt_map;
test_rcu< opt_map >();
}
} // namespace map | c++ | code | 7,405 | 1,221 |
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "uritests.h"
#include "guiutil.h"
#include "walletmodel.h"
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?label=Some Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.label == QString("Some Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=100&label=Some Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Some Example"));
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("defense://D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address", &rv));
QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"));
QVERIFY(rv.label == QString());
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-message=Some Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000&label=Some Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("defense:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000.0&label=Some Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
} | c++ | code | 2,894 | 649 |
#include <event2/thread.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include "util/etcd.h"
#include "util/libevent_wrapper.h"
#include "util/sync_task.h"
namespace libevent = cert_trans::libevent;
using cert_trans::EtcdClient;
using cert_trans::UrlFetcher;
using std::cout;
using std::endl;
using std::vector;
using util::SyncTask;
DEFINE_string(etcd, "127.0.0.1", "etcd server address");
DEFINE_int32(etcd_port, 4001, "etcd server port");
DEFINE_string(key, "/foo", "path to watch");
void Notify(const vector<EtcdClient::Node>& updates) {
for (const auto& update : updates) {
if (!update.deleted_) {
cout << "key changed: " << update.ToString() << endl;
} else {
cout << "key deleted: " << update.ToString() << endl;
}
}
}
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
evthread_use_pthreads();
libevent::Base event_base;
UrlFetcher fetcher(&event_base);
EtcdClient etcd(&fetcher, FLAGS_etcd, FLAGS_etcd_port);
SyncTask task(&event_base);
etcd.Watch(FLAGS_key, Notify, task.task());
event_base.Dispatch();
// This shouldn't really happen.
task.Wait();
LOG(INFO) << "status: " << task.status();
return 0;
} | c++ | code | 1,280 | 328 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_long_calloc_44.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-44.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: calloc Allocate data using calloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_long_calloc_44
{
#ifndef OMITBAD
static void badSink(long * data)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
void bad()
{
long * data;
/* define a function pointer */
void (*funcPtr) (long *) = badSink;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
/* use the function pointer */
funcPtr(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink(long * data)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
static void goodG2B()
{
long * data;
void (*funcPtr) (long *) = goodG2BSink;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory using new [] */
data = new long[100];
funcPtr(data);
}
/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSink(long * data)
{
/* FIX: Free memory using free() */
free(data);
}
static void goodB2G()
{
long * data;
void (*funcPtr) (long *) = goodB2GSink;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
funcPtr(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_long_calloc_44; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif | c++ | code | 3,452 | 739 |
/*
* Copyright (c) 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_UTILITIES_TICKS_INLINE_HPP
#define SHARE_VM_UTILITIES_TICKS_INLINE_HPP
#include "utilities/ticks.hpp"
inline Tickspan operator+(Tickspan lhs, const Tickspan& rhs) {
lhs += rhs;
return lhs;
}
inline bool operator==(const Tickspan& lhs, const Tickspan& rhs) {
return lhs.value() == rhs.value();
}
inline bool operator!=(const Tickspan& lhs, const Tickspan& rhs) {
return !operator==(lhs,rhs);
}
inline bool operator<(const Tickspan& lhs, const Tickspan& rhs) {
return lhs.value() < rhs.value();
}
inline bool operator>(const Tickspan& lhs, const Tickspan& rhs) {
return operator<(rhs,lhs);
}
inline bool operator<=(const Tickspan& lhs, const Tickspan& rhs) {
return !operator>(lhs,rhs);
}
inline bool operator>=(const Tickspan& lhs, const Tickspan& rhs) {
return !operator<(lhs,rhs);
}
inline Ticks operator+(Ticks lhs, const Tickspan& span) {
lhs += span;
return lhs;
}
inline Ticks operator-(Ticks lhs, const Tickspan& span) {
lhs -= span;
return lhs;
}
inline Tickspan operator-(const Ticks& end, const Ticks& start) {
return Tickspan(end, start);
}
inline bool operator==(const Ticks& lhs, const Ticks& rhs) {
return lhs.value() == rhs.value();
}
inline bool operator!=(const Ticks& lhs, const Ticks& rhs) {
return !operator==(lhs,rhs);
}
inline bool operator<(const Ticks& lhs, const Ticks& rhs) {
return lhs.value() < rhs.value();
}
inline bool operator>(const Ticks& lhs, const Ticks& rhs) {
return operator<(rhs,lhs);
}
inline bool operator<=(const Ticks& lhs, const Ticks& rhs) {
return !operator>(lhs,rhs);
}
inline bool operator>=(const Ticks& lhs, const Ticks& rhs) {
return !operator<(lhs,rhs);
}
#endif // SHARE_VM_UTILITIES_TICKS_INLINE_HPP | c++ | code | 2,781 | 670 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Exception
#include "System/Exception.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Forward declaring type: TimeZoneNotFoundException
class TimeZoneNotFoundException;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::TimeZoneNotFoundException);
DEFINE_IL2CPP_ARG_TYPE(::System::TimeZoneNotFoundException*, "System", "TimeZoneNotFoundException");
// Type namespace: System
namespace System {
// Size: 0x88
#pragma pack(push, 1)
// Autogenerated type: System.TimeZoneNotFoundException
// [TokenAttribute] Offset: FFFFFFFF
// [TypeForwardedFromAttribute] Offset: 11A8E4C
class TimeZoneNotFoundException : public ::System::Exception {
public:
// public System.Void .ctor(System.String message, System.Exception innerException)
// Offset: 0x297E0F0
// Implemented from: System.Exception
// Base method: System.Void Exception::.ctor(System.String message, System.Exception innerException)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TimeZoneNotFoundException* New_ctor(::StringW message, ::System::Exception* innerException) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::TimeZoneNotFoundException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TimeZoneNotFoundException*, creationType>(message, innerException)));
}
// protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x297E170
// Implemented from: System.Exception
// Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TimeZoneNotFoundException* New_ctor(::System::Runtime::Serialization::SerializationInfo* info, ::System::Runtime::Serialization::StreamingContext context) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::TimeZoneNotFoundException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TimeZoneNotFoundException*, creationType>(info, context)));
}
// public System.Void .ctor()
// Offset: 0x297E200
// Implemented from: System.Exception
// Base method: System.Void Exception::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TimeZoneNotFoundException* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::TimeZoneNotFoundException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TimeZoneNotFoundException*, creationType>()));
}
}; // System.TimeZoneNotFoundException
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::TimeZoneNotFoundException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::TimeZoneNotFoundException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::TimeZoneNotFoundException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead! | c++ | code | 4,567 | 706 |
/****************************************************************************
* Copyright � 2003-2015 Dorian C. Arnold, Philip C. Roth, Barton P. Miller *
* Detailed MRNet usage rights in "LICENSE" file. *
****************************************************************************/
#include <unordered_map>
#include <cctype>
#include <fstream>
#include "mrnet/MRNet.h"
#include "TweetAnalysis.h"
using namespace MRN;
int tweetCountFile(const char* file_path, const std::string target) {
int ans = 0;
// filestream variable file
std::ifstream file;
std::string line;
// opening file
file.open(file_path);
// extracting words from the file
while (std::getline(file, line))
{
// check if line contains target
if (line.find(target) != std::string::npos) {
ans++;
}
}
file.close();
return ans;
}
int main(int argc, char **argv)
{
Stream * stream = NULL;
PacketPtr p;
int rc, tag=0, send_val = 100;
char* recv_val = NULL;
char buffer[100];
const char* file_path_pattern = "/home/mazijun/Documents/readings/CS736/mrnet-3093918/Examples/TweetAnalysis/test-%d.txt";
Network * net = Network::CreateNetworkBE( argc, argv );
sprintf(buffer, file_path_pattern, net->get_LocalRank());
do {
rc = net->recv(&tag, p, &stream);
if( rc == -1 ) {
fprintf( stderr, "BE: Network::recv() failure\n" );
break;
}
else if( rc == 0 ) {
// a stream was closed
continue;
}
int tweet_count = 0;
switch(tag) {
case PROT_SUM:
p->unpack( "%s", &recv_val);
fprintf(stdout, "BE: receive word %s.\n", recv_val);
tweet_count = tweetCountFile(buffer, std::string(recv_val));
if( stream->send(tag, "%d", tweet_count) == -1 ) {
fprintf( stderr, "BE: stream::send(%%d) failure in PROT_SUM\n" );
tag = PROT_EXIT;
break;
}
if( stream->flush() == -1 ) {
fprintf( stderr, "BE: stream::flush() failure in PROT_SUM\n" );
break;
}
fflush(stdout);
sleep(2); // stagger sends
break;
case PROT_EXIT:
if( stream->send(tag, "%d", 0) == -1 ) {
fprintf( stderr, "BE: stream::send(%%s) failure in PROT_EXIT\n" );
break;
}
if( stream->flush( ) == -1 ) {
fprintf( stderr, "BE: stream::flush() failure in PROT_EXIT\n" );
}
break;
default:
fprintf( stderr, "BE: Unknown Protocol: %d\n", tag );
tag = PROT_EXIT;
break;
}
fflush(stderr);
} while( tag != PROT_EXIT );
if( stream != NULL ) {
while( ! stream->is_Closed() )
sleep(1);
delete stream;
}
// FE delete of the net will cause us to exit, wait for it
net->waitfor_ShutDown();
delete net;
return 0;
} | c++ | code | 3,112 | 805 |
// C:\diabpsx\PSXSRC\PAK.CPP
#include "types.h"
// address: 0x800ADDD4
// line start: 118
// line end: 235
int PAK_DoPak__FPUcPCUci(unsigned char *Dest, unsigned char *buffer, int insize) {
// register: 3
register long begin;
// register: 19
register long end;
// register: 17
register long bestlength;
// register: 20
register int offset;
// register: 23
register int bestoffset;
// register: 22
register unsigned char *theptr;
// register: 18
register unsigned char *ptr1;
// register: 5
register unsigned char *ptr2;
// register: 4
register unsigned char *ptr3;
// address: 0xFFFFFDB0
// size: 0x214
auto struct block theblock;
// register: 21
register int inpos;
}
// address: 0x8009FF00
// line start: 118
// line end: 235
int PAK_DoPak__FPUcT0i(unsigned char *Dest, unsigned char *buffer, int insize) {
// register: 3
register long begin;
// register: 19
register long end;
// register: 17
register long bestlength;
// register: 20
register int offset;
// register: 23
register int bestoffset;
// register: 22
register unsigned char *theptr;
// register: 18
register unsigned char *ptr1;
// register: 5
register unsigned char *ptr2;
// register: 4
register unsigned char *ptr3;
// address: 0xFFFFFDB0
// size: 0x214
auto struct block theblock;
// register: 21
register int inpos;
}
// address: 0x800AE014
// line start: 245
// line end: 278
int PAK_DoUnpak__FPUcPCUc(unsigned char *Dest, unsigned char *Source) {
// register: 19
register int outsize;
{
// register: 5
register unsigned char *From;
// register: 17
register int size;
// register: 3
register int ch;
}
}
// address: 0x800A0140
// line start: 245
// line end: 278
int PAK_DoUnpak__FPUcT0(unsigned char *Dest, unsigned char *Source) {
// register: 19
register int outsize;
{
// register: 5
register unsigned char *From;
// register: 17
register int size;
// register: 3
register int ch;
}
}
// address: 0x800A01E0
// line start: 55
// line end: 58
void fputc__5blockUc(struct block *this, unsigned char Val) {
}
// address: 0x8009FE18
// line start: 85
// line end: 108
void writeblock__FP5block(struct block *theblock) {
{
{
{
{
{
// register: 18
register int i;
}
}
}
}
}
} | c++ | code | 2,288 | 475 |
#include <assert.h>
#include <string>
#include <iostream>
bool pattern_match(const std::string& lhs, const std::string& rhs)
{
std::cout << std::endl;
std::cout << "pattern_match(" << lhs << ", " << rhs << ")\n";
bool negate = false;
bool mismatched = false;
std::string::const_iterator seq = lhs.begin();
std::string::const_iterator seq_end = lhs.end();
std::string::const_iterator pattern = rhs.begin();
std::string::const_iterator pattern_end = rhs.end();
while (seq != seq_end && pattern != pattern_end) {
std::cout << "seq = " << *seq << ", pattern = " << *pattern << "\n";
std::string::const_iterator seq_tmp;
switch (*pattern) {
case '?':
break;
case '*':
// if * is the last pattern, return true
if (++pattern == pattern_end) return true;
while (*seq != *pattern && seq != seq_end) ++seq;
// if seq reaches to the end without matching pattern
if (seq == seq_end) return false;
break;
case '[':
negate = false;
mismatched = false;
if (*(++pattern) == '!') {
negate = true;
++pattern;
}
if (*(pattern+1) == '-') {
// range matching
char c_start = *pattern; ++pattern;
//assert(*pattern == '-');
char c_end = *(++pattern); ++pattern;
//assert(*pattern == ']');
// swap c_start and c_end if c_start is larger
if (c_start > c_end) {
char tmp = c_start;
c_end = c_start;
c_start = tmp;
}
mismatched = (c_start <= *seq && *seq <= c_end) ? negate : !negate;
if (mismatched) return false;
} else {
// literal matching
while (*pattern != ']') {
if (*seq == *pattern) {
mismatched = negate;
break;
}
++pattern;
}
if (mismatched) return false;
while (*pattern != ']') ++pattern;
}
break;
case '{':
seq_tmp = seq;
mismatched = true;
while (*(++pattern) != '}') {
// this assumes that there's no sequence like "{,a}" where ',' is
// follows immediately after '{', which is illegal.
if (*pattern == ',') {
mismatched = false;
break;
} else if (*seq != *pattern) {
// fast forward to the next ',' or '}'
while (*(++pattern) != ',' && *pattern != '}');
if (*pattern == '}') return false;
// redo seq matching
seq = seq_tmp;
mismatched = true;
} else {
// matched
++seq;
mismatched = false;
}
}
if (mismatched) return false;
while (*pattern != '}') ++pattern;
--seq;
break;
default: // non-special character
if (*seq != *pattern) return false;
break;
}
++seq; ++pattern;
}
if (seq == seq_end && pattern == pattern_end) return true;
else return false;
}
int main()
{
std::string seq = "/abc/d";
std::string pattern;
// test no special character pattern
pattern = "/abc/d";
assert(pattern_match(seq, pattern) == true);
pattern = "/ab/d";
assert(pattern_match(seq, pattern) == false);
pattern = "/abc/de";
assert(pattern_match(seq, pattern) == false);
// test ?
pattern = "/abc/?";
assert(pattern_match(seq, pattern) == true);
pattern = "/?bc/?";
assert(pattern_match(seq, pattern) == true);
pattern = "/?/d";
assert(pattern_match(seq, pattern) == false);
// test *
pattern = "/*/d";
assert(pattern_match(seq, pattern) == true);
pattern = "/*/?";
assert(pattern_match(seq, pattern) == true);
pattern = "/*/*";
assert(pattern_match(seq, pattern) == true);
pattern = "/a*c/d";
assert(pattern_match(seq, pattern) == true);
// test []
pattern = "/[abc]bc/d";
assert(pattern_match(seq, pattern) == true);
pattern = "/[!abc]bc/d";
assert(pattern_match(seq, pattern) == false);
pattern = "/abc/[d]";
assert(pattern_match(seq, pattern) == true);
pattern = "/abc/[!abc]";
assert(pattern_match(seq, pattern) == true);
pattern = "/abc/[!a-c]";
assert(pattern_match(seq, pattern) == true);
pattern = "/a[a-c]c/d";
assert(pattern_match(seq, pattern) == true);
pattern = "/[1-9]bc/d";
assert(pattern_match(seq, pattern) == false);
// test {}
pattern = "/{bed,abc,foo}/d";
assert(pattern_match(seq, pattern) == true);
pattern = "/{abc,foo}/d";
assert(pattern_match(seq, pattern) == true);
pattern = "/{abcd,foo}/d";
assert(pattern_match(seq, pattern) == false);
pattern = "/abc/{a,b,d}";
assert(pattern_match(seq, pattern) == true);
pattern = "/abc/{a,b,c}";
assert(pattern_match(seq, pattern) == false);
pattern = "/a{blah,bc}/d";
assert(pattern_match(seq, pattern) == true);
} | c++ | code | 4,902 | 1,305 |
#pragma once
#include <inttypes.h>
#include <vector>
#include <string>
#include <iostream>
namespace Util::Print {
/// A tool to easily construct tables for printing to the command line
class Table {
private:
/// The number of columns
uint8_t columns;
/// The width of each column in printable characters
uint8_t columnWidth;
/// The content of each cell in each row including the header
std::vector<std::vector<std::string>> rows;
public:
Table(uint8_t columns, uint8_t columnWidth);
/// Adds a row for later serialization
void addRow(std::vector<std::string> cells);
friend std::ostream& operator << (std::ostream& os, const Table& table);
};
} | c++ | code | 812 | 157 |
#include"ac.h"
#include<cstdlib>
#include<ctime>
void stutter_filter(cv::Mat &frame) {
static cv::Mat stored;
static cv::Size stored_size;
if(stored_size != frame.size()) {
srand(static_cast<int>(time(0)));
stored = frame.clone();
stored_size = frame.size();
} else {
if(stored.empty())
stored = frame.clone();
static bool on = true;
if(on == true) {
if((rand()%15)==0) {
stored = frame.clone();
on = !on;
}
frame = stored.clone();
} else {
if((rand()%10) == 0)
on = !on;
}
}
}
extern "C" void filter(cv::Mat &frame) {
static ac::MatrixCollection<8> collection;
if(collection.empty())
srand(static_cast<unsigned int>(time(0)));
collection.shiftFrames(frame);
cv::Mat frame_copy = frame.clone();
stutter_filter(frame_copy);
int num_pixels = rand()%((frame.rows * frame.cols)/320);
for(int q = 0; q < num_pixels; ++q) {
int pixel_size = 16+(rand()%64);
int off_x = rand()%(frame.cols-pixel_size-1);
int off_y = rand()%(frame.rows-pixel_size-1);
int offset = rand()%(collection.size()-1);
for(int y = off_y; y < off_y + pixel_size; ++y) {
for(int x = off_x; x < off_x + pixel_size; ++x) {
cv::Mat &m = collection.frames[offset];
cv::Vec3b &pix = m.at<cv::Vec3b>(y, x);
cv::Vec3b &pix_copy = frame_copy.at<cv::Vec3b>(y, x);
cv::Vec3b &pixel = frame.at<cv::Vec3b>(y, x);
for(int j = 0; j < 3; ++j) {
if(pixel[j] != pix[j]) {
pixel[j] = static_cast<unsigned char>((0.5 * pixel[j]) + (0.5 * pix_copy[j]));
}
}
}
}
}
} | c++ | code | 1,887 | 527 |
// Copyright 2014 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 "mojo/edk/embedder/test_embedder.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/embedder_internal.h"
#include "mojo/edk/embedder/simple_platform_support.h"
#include "mojo/edk/system/channel_manager.h"
#include "mojo/edk/system/core.h"
#include "mojo/edk/system/handle_table.h"
namespace mojo {
namespace system {
namespace internal {
bool ShutdownCheckNoLeaks(Core* core) {
// No point in taking the lock.
const HandleTable::HandleToEntryMap& handle_to_entry_map =
core->handle_table_.handle_to_entry_map_;
if (handle_to_entry_map.empty())
return true;
for (HandleTable::HandleToEntryMap::const_iterator it =
handle_to_entry_map.begin();
it != handle_to_entry_map.end(); ++it) {
LOG(ERROR) << "Mojo embedder shutdown: Leaking handle " << (*it).first;
}
return false;
}
} // namespace internal
} // namespace system
namespace embedder {
namespace test {
void InitWithSimplePlatformSupport() {
Init(make_scoped_ptr(new SimplePlatformSupport()));
}
bool Shutdown() {
// If |InitIPCSupport()| was called, then |ShutdownIPCSupport()| must have
// been called first.
CHECK(internal::g_process_type == ProcessType::UNINITIALIZED);
CHECK(internal::g_core);
bool rv = system::internal::ShutdownCheckNoLeaks(internal::g_core);
delete internal::g_core;
internal::g_core = nullptr;
CHECK(internal::g_platform_support);
delete internal::g_platform_support;
internal::g_platform_support = nullptr;
return rv;
}
} // namespace test
} // namespace embedder
} // namespace mojo | c++ | code | 1,834 | 339 |
// Copyright (C) 2015 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
//! \addtogroup op_diff
//! @{
class op_diff
{
public:
template<typename eT>
inline static void apply_noalias(Mat<eT>& out, const Mat<eT>& X, const uword k, const uword dim);
template<typename T1>
inline static void apply(Mat<typename T1::elem_type>& out, const Op<T1,op_diff>& in);
};
class op_diff_default
{
public:
template<typename T1>
inline static void apply(Mat<typename T1::elem_type>& out, const Op<T1,op_diff_default>& in);
};
//! @} | c++ | code | 883 | 225 |
// Copyright 2014 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 <stdint.h>
#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/macros.h"
#include "media/base/test_data_util.h"
#include "media/filters/h264_parser.h"
#include "media/video/h264_poc.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
class H264POCTest : public testing::Test {
public:
H264POCTest() : sps_(), slice_hdr_() {
// Default every frame to be a reference frame.
slice_hdr_.nal_ref_idc = 1;
}
protected:
bool ComputePOC() {
return h264_poc_.ComputePicOrderCnt(&sps_, slice_hdr_, &poc_);
}
// Also sets as a reference frame and unsets IDR, which is required for
// memory management control operations to be parsed.
void SetMMCO5() {
slice_hdr_.nal_ref_idc = 1;
slice_hdr_.idr_pic_flag = false;
slice_hdr_.adaptive_ref_pic_marking_mode_flag = true;
slice_hdr_.ref_pic_marking[0].memory_mgmnt_control_operation = 6;
slice_hdr_.ref_pic_marking[1].memory_mgmnt_control_operation = 5;
slice_hdr_.ref_pic_marking[2].memory_mgmnt_control_operation = 0;
}
int32_t poc_;
H264SPS sps_;
H264SliceHeader slice_hdr_;
H264POC h264_poc_;
DISALLOW_COPY_AND_ASSIGN(H264POCTest);
};
TEST_F(H264POCTest, PicOrderCntType0) {
sps_.pic_order_cnt_type = 0;
sps_.log2_max_pic_order_cnt_lsb_minus4 = 0; // 16
// Initial IDR with POC 0.
slice_hdr_.idr_pic_flag = true;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(0, poc_);
// Ref frame with POC lsb 8.
slice_hdr_.idr_pic_flag = false;
slice_hdr_.pic_order_cnt_lsb = 8;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(8, poc_);
// Ref frame with POC lsb 0. This should be detected as wrapping, as the
// (negative) gap is at least half the maximum.
slice_hdr_.pic_order_cnt_lsb = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(16, poc_);
// Ref frame with POC lsb 9. This should be detected as negative wrapping,
// as the (positive) gap is more than half the maximum.
slice_hdr_.pic_order_cnt_lsb = 9;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(9, poc_);
}
TEST_F(H264POCTest, PicOrderCntType0_WithMMCO5) {
sps_.pic_order_cnt_type = 0;
sps_.log2_max_pic_order_cnt_lsb_minus4 = 0; // 16
// Initial IDR with POC 0.
slice_hdr_.idr_pic_flag = true;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(0, poc_);
// Skip ahead.
slice_hdr_.idr_pic_flag = false;
slice_hdr_.pic_order_cnt_lsb = 8;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(8, poc_);
slice_hdr_.pic_order_cnt_lsb = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(16, poc_);
slice_hdr_.pic_order_cnt_lsb = 8;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(24, poc_);
SetMMCO5();
slice_hdr_.pic_order_cnt_lsb = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(32, poc_);
// Due to the MMCO5 above, this is relative to 0, but also detected as
// positive wrapping.
slice_hdr_.pic_order_cnt_lsb = 8;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(24, poc_);
}
TEST_F(H264POCTest, PicOrderCntType1) {
sps_.pic_order_cnt_type = 1;
sps_.log2_max_frame_num_minus4 = 0; // 16
sps_.num_ref_frames_in_pic_order_cnt_cycle = 2;
sps_.expected_delta_per_pic_order_cnt_cycle = 3;
sps_.offset_for_ref_frame[0] = 1;
sps_.offset_for_ref_frame[1] = 2;
// Initial IDR with POC 0.
slice_hdr_.idr_pic_flag = true;
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(0, poc_);
// Ref frame.
slice_hdr_.idr_pic_flag = false;
slice_hdr_.frame_num = 1;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(1, poc_);
// Ref frame.
slice_hdr_.frame_num = 2;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(3, poc_);
// Ref frame.
slice_hdr_.frame_num = 3;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(4, poc_);
// Ref frame.
slice_hdr_.frame_num = 4;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(6, poc_);
// Ref frame, detected as wrapping (ie, this is frame 16).
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(24, poc_);
}
TEST_F(H264POCTest, PicOrderCntType1_WithMMCO5) {
sps_.pic_order_cnt_type = 1;
sps_.log2_max_frame_num_minus4 = 0; // 16
sps_.num_ref_frames_in_pic_order_cnt_cycle = 2;
sps_.expected_delta_per_pic_order_cnt_cycle = 3;
sps_.offset_for_ref_frame[0] = 1;
sps_.offset_for_ref_frame[1] = 2;
// Initial IDR with POC 0.
slice_hdr_.idr_pic_flag = true;
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(0, poc_);
// Ref frame.
slice_hdr_.idr_pic_flag = false;
slice_hdr_.frame_num = 1;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(1, poc_);
// Ref frame, detected as wrapping.
SetMMCO5();
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(24, poc_);
// Ref frame, wrapping from before has been cleared.
slice_hdr_.frame_num = 1;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(1, poc_);
}
TEST_F(H264POCTest, PicOrderCntType2) {
sps_.pic_order_cnt_type = 2;
// Initial IDR with POC 0.
slice_hdr_.idr_pic_flag = true;
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(0, poc_);
// Ref frame.
slice_hdr_.idr_pic_flag = false;
slice_hdr_.frame_num = 1;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(2, poc_);
// Ref frame.
slice_hdr_.frame_num = 2;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(4, poc_);
// Ref frame.
slice_hdr_.frame_num = 3;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(6, poc_);
// Ref frame.
slice_hdr_.frame_num = 4;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(8, poc_);
// Ref frame, detected as wrapping (ie, this is frame 16).
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(32, poc_);
}
TEST_F(H264POCTest, PicOrderCntType2_WithMMCO5) {
sps_.pic_order_cnt_type = 2;
// Initial IDR with POC 0.
slice_hdr_.idr_pic_flag = true;
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(0, poc_);
// Ref frame.
slice_hdr_.idr_pic_flag = false;
slice_hdr_.frame_num = 1;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(2, poc_);
// Ref frame, detected as wrapping.
SetMMCO5();
slice_hdr_.frame_num = 0;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(32, poc_);
// Ref frame, wrapping from before has been cleared.
slice_hdr_.frame_num = 1;
ASSERT_TRUE(ComputePOC());
ASSERT_EQ(2, poc_);
}
} // namespace media | c++ | code | 6,335 | 1,334 |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cctype>
#include <cmath>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
template <typename T> bool chmax(T &a, T& b) {if (a < b) {a = b; return true;} return false;}
template <typename T> bool chmin(T &a, T& b) {if (a > b) {a = b; return true;} return false;}
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rep3(i, m, n) for (int i = (m); i < (int)(n); ++i)
#define rrep(i, n) for (int i = (int)(n)-1; i >= 0; --i)
#define rrep3(i, m, n) for (int i = (int)(n)-1; i >= (m); --i)
#define all(x) x.begin(), x.end()
#define rall(x) x.end(), x.begin()
#define mset(x, val) memset(x, (val), sizeof(x))
#define cons(a, b) make_pair((a), (b))
#define car first
#define cdr second
#define endl '\n'
#define INF 0x7f7f7f7f7f7f7f7f
#define INFi 0x7f7f7f7f
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll solve(int wki, ll zzv, const vector<ll> & zux) {
// TODO: edit here
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll wki;
ll zzv;
cin >> wki;
vector<ll> zux(wki);
cin >> zzv;
rep (i, wki) {
cin >> zux[i];
}
auto ans = solve(wki, zzv, zux);
cout << ans << endl;
return 0;
} | c++ | code | 1,540 | 532 |
/*
* This engine was built upon
* tutorials created by: Copyright (C) 2014 Benny Bobaganoosh.
* The above tutorials served as the base on which
* this engine was developed further by Kyle Pearce.
* The game created using this engine has been entirely
* created by Kyle Pearce.
*/
#include "math3d.h"
Vector3f Vector3f::Rotate(const Quaternion& rotation) const
{
Quaternion conjugateQ = rotation.Conjugate();
Quaternion w = rotation * (*this) * conjugateQ;
Vector3f ret(w.GetX(), w.GetY(), w.GetZ());
return ret;
} | c++ | code | 528 | 121 |
/* Copyright 2021 Enjin Pte. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ENJINCPPSDK_SHAREDBALANCEFRAGMENTARGUMENTS_HPP
#define ENJINCPPSDK_SHAREDBALANCEFRAGMENTARGUMENTS_HPP
#include "enjinsdk_export.h"
#include "enjinsdk/ISerializable.hpp"
#include "enjinsdk/internal/BalanceFragmentArgumentsImpl.hpp"
#include "enjinsdk/models/AssetIdFormat.hpp"
#include "enjinsdk/models/AssetIndexFormat.hpp"
#include <string>
namespace enjin::sdk::shared {
/// \brief Fragment interface used to request certain information from balances returned by the platform.
/// \tparam T The type of the implementing class.
template<class T>
class ENJINSDK_EXPORT BalanceFragmentArguments : public serialization::ISerializable {
public:
~BalanceFragmentArguments() override = default;
[[nodiscard]] std::string serialize() const override {
return impl.serialize();
}
/// \brief Sets the desired asset ID format.
/// \param bal_id_format The ID format.
/// \return This request for chaining.
T& set_bal_id_format(models::AssetIdFormat bal_id_format) {
impl.set_bal_id_format(bal_id_format);
return dynamic_cast<T&>(*this);
}
/// \brief Sets the desired index format for non-fungible assets.
/// \param bal_index_format The index format.
/// \return This request for chaining.
T& set_bal_index_format(models::AssetIndexFormat bal_index_format) {
impl.set_bal_index_format(bal_index_format);
return dynamic_cast<T&>(*this);
}
/// \brief Sets the request to include the project UUID with the balance.
/// \return This request for chaining.
T& set_with_bal_project_uuid() {
impl.set_with_bal_project_uuid();
return dynamic_cast<T&>(*this);
}
/// \brief Sets the request to include the wallet address with balance.
/// \return This request for chaining.
T& set_with_bal_wallet_address() {
impl.set_with_bal_wallet_address();
return dynamic_cast<T&>(*this);
}
bool operator==(const BalanceFragmentArguments& rhs) const {
return impl == rhs.impl;
}
bool operator!=(const BalanceFragmentArguments& rhs) const {
return rhs != *this;
}
protected:
/// \brief Default constructor.
BalanceFragmentArguments() = default;
private:
BalanceFragmentArgumentsImpl impl;
};
}
#endif //ENJINCPPSDK_SHAREDBALANCEFRAGMENTARGUMENTS_HPP | c++ | code | 2,934 | 497 |
/*
* Copyright 2017-present Shawn Cao
*
* 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 "HashFlat.h"
#include "surface/eval/UDF.h"
namespace nebula {
namespace memory {
namespace keyed {
using Range = nebula::common::PRange;
using nebula::common::OneSlice;
using nebula::surface::eval::Aggregator;
using nebula::surface::eval::Sketch;
using nebula::type::Kind;
using nebula::type::TypeTraits;
void HashFlat::init() {
ops_.reserve(numColumns_);
keys_.reserve(numColumns_);
values_.reserve(numColumns_);
for (size_t i = 0; i < numColumns_; ++i) {
// every column may have its own operations
ops_.emplace_back(genComparator(i), genHasher(i), genCopier(i));
if (!isAggregate(i)) {
keys_.push_back(i);
} else {
values_.push_back(i);
}
}
// reserve a memory chunk to store hash values
if (keys_.size() > 0) {
keyHash_ = std::make_unique<OneSlice>(sizeof(size_t) * keys_.size());
// optimization - if the keys are all primmitive (non-strings), and index are continous
// we can just hash the memory chunk (row.offset+col-offset, total-size)
size_t last = keys_.at(0) - 1;
optimal_ = true;
keyWidth_ = 0;
for (auto index : keys_) {
Kind k = cops_.at(index).kind;
keyWidth_ += cops_.at(index).width;
if (index != last + 1 || k >= Kind::VARCHAR) {
optimal_ = false;
break;
}
// assign last for next check
last = index;
}
}
}
Comparator HashFlat::genComparator(size_t i) noexcept {
// only need for key
if (isAggregate(i)) {
return {};
}
#define PREPARE_AND_NULLCHECK() \
const auto& row1Props = rows_[row1]; \
const auto& row2Props = rows_[row2]; \
auto row1Offset = row1Props.offset; \
auto row2Offset = row2Props.offset; \
const auto& colProps1 = row1Props.colProps.at(i); \
const auto& colProps2 = row2Props.colProps.at(i); \
if (colProps1.isNull != colProps2.isNull) { \
return -1; \
} \
if (colProps1.isNull) { \
return 0; \
}
#define TYPE_COMPARE(KIND, TYPE) \
case Kind::KIND: { \
return [this, i](size_t row1, size_t row2) -> int { \
PREPARE_AND_NULLCHECK() \
return main_->slice.compare<TYPE>(row1Offset + colProps1.offset, row2Offset + colProps2.offset); \
}; \
}
// fetch value
Kind k = cops_.at(i).kind;
// we only support primitive types for keys
switch (k) {
TYPE_COMPARE(BOOLEAN, bool)
TYPE_COMPARE(TINYINT, int8_t)
TYPE_COMPARE(SMALLINT, int16_t)
TYPE_COMPARE(INTEGER, int32_t)
TYPE_COMPARE(BIGINT, int64_t)
TYPE_COMPARE(REAL, int32_t)
TYPE_COMPARE(DOUBLE, int64_t)
TYPE_COMPARE(INT128, int128_t)
case Kind::VARCHAR: {
// read the real data from data_
// TODO(cao) - we don't need convert strings from bytes for hash
// instead, slice should be able to compare two byte range
return [this, i](size_t row1, size_t row2) -> int {
PREPARE_AND_NULLCHECK()
// offset and length of each
auto r1 = Range::make(main_->slice, row1Offset + colProps1.offset);
auto r2 = Range::make(main_->slice, row2Offset + colProps2.offset);
// length has to be the same
if (r1.size != r2.size) {
return r1.size - r2.size;
}
return data_->slice.compare(r1.offset, r2.offset, r1.size);
};
}
default:
return [i](size_t, size_t) -> int {
LOG(ERROR) << "Compare a non-supported column: " << i;
return 0;
};
}
#undef PREPARE_AND_NULLCHECK
#undef TYPE_COMPARE
}
Hasher HashFlat::genHasher(size_t i) noexcept {
// only need for key
if (isAggregate(i)) {
return {};
}
#define PREPARE_AND_NULL() \
const auto& rowProps = rows_.at(row); \
auto rowOffset = rowProps.offset; \
const auto& colProps = rowProps.colProps.at(i); \
if (colProps.isNull) { \
return 0L; \
}
#define TYPE_HASH(KIND, TYPE) \
case Kind::KIND: { \
return [this, i](size_t row) -> size_t { \
PREPARE_AND_NULL() \
return main_->slice.hash<TYPE>(rowOffset + colProps.offset); \
}; \
}
// fetch value
Kind k = cops_.at(i).kind;
switch (k) {
TYPE_HASH(BOOLEAN, bool)
TYPE_HASH(TINYINT, int8_t)
TYPE_HASH(SMALLINT, int16_t)
TYPE_HASH(INTEGER, int32_t)
TYPE_HASH(BIGINT, int64_t)
TYPE_HASH(REAL, int32_t)
TYPE_HASH(DOUBLE, int64_t)
TYPE_HASH(INT128, int128_t)
case Kind::VARCHAR: {
// read 4 bytes offset and 4 bytes length
return [this, i](size_t row) -> size_t {
PREPARE_AND_NULL()
auto so = rowOffset + colProps.offset;
auto r = Range::make(main_->slice, so);
// read the real data from data_
// TODO(cao) - we don't need convert strings from bytes for hash
// instead, slice should be able to hash the range[offset, len] much cheaper
if (r.size == 0) {
return 0L;
}
return data_->slice.hash(r.offset, r.size);
};
}
default:
return [i](size_t) -> size_t {
LOG(ERROR) << "Hash a non-supported column: " << i;
return 0;
};
}
#undef PREPARE_AND_NULL
#undef TYPE_HASH
}
// TODO(cao): I spent a couple of days trying to nail down which GCC optimization
// causing the SIGSEGV on the returned function from this method
// CMakeList.txt has more details in the problem.
// So now, we disable optimizations higher than level 1 on this method
// we may dig more in the future to understand this problem better. (CLANG need no this)
Copier HashFlat::genCopier(size_t i) noexcept {
// only need for value
if (!isAggregate(i)) {
return {};
}
const auto& f = fields_.at(i);
const auto ot = f->outputType();
const auto it = f->inputType();
// below provides a template to write core logic for all input / output type combinations
#define LOGIC_BY_IO(O, I) \
case Kind::I: return bind<Kind::O, Kind::I>(i);
ITERATE_BY_IO(ot, it)
#undef LOGIC_BY_IO
// no supported combination found
return {};
}
std::pair<size_t, size_t> HashFlat::optimalKeys(size_t row) const noexcept {
const auto& rowProps = rows_.at(row);
// starting offset of all sequential keys = row offset + first key offset
auto offset = rowProps.offset + rowProps.colProps.at(0).offset;
auto length = keyWidth_;
// remove nulls
for (auto index : keys_) {
const auto& colProps = rowProps.colProps.at(index);
if (colProps.isNull) {
length -= cops_.at(index).width;
}
}
return { offset, length };
}
// compute hash value of given row and column list
// The function has very similar logic as row accessor, we inline it for perf
size_t HashFlat::hash(size_t rowId) const {
// if optimal, let's figure out offset and length of the key bytes
if (LIKELY(optimal_)) {
auto kp = optimalKeys(rowId);
auto ptr = main_->slice.ptr();
// just hash the key set
return nebula::common::Hasher::hash64(ptr + kp.first, kp.second);
}
// hash on every column and write value into keyHash_ chunk
if (LIKELY(keyHash_ != nullptr)) {
size_t* ptr = (size_t*)keyHash_->ptr();
auto len = keyHash_->size();
std::memset(ptr, 0, len);
for (size_t i = 0, size = keys_.size(); i < size; ++i) {
*(ptr + i) = ops_.at(keys_.at(i)).hasher(rowId);
}
return nebula::common::Hasher::hash64(ptr, len);
}
return 0;
}
// check if two rows are equal to each other on given columns
bool HashFlat::equal(size_t row1, size_t row2) const {
// if optimal, let's figure out offset and length of the key bytes
if (LIKELY(optimal_)) {
auto kp1 = optimalKeys(row1);
auto kp2 = optimalKeys(row2);
// if length equals - return false
if (kp1.second != kp2.second) {
return false;
}
auto ptr = main_->slice.ptr();
return std::memcmp(ptr + kp1.first, ptr + kp2.first, kp1.second) == 0;
}
for (auto index : keys_) {
if (ops_.at(index).comparator(row1, row2) != 0) {
return false;
}
}
return true;
}
bool HashFlat::update(const nebula::surface::RowData& row) {
// add a new row to the buffer may be expensive
// if there are object values to be created such as customized aggregation
// to have consistent way - we're taking this approach
this->add(row);
auto newRow = getRows() - 1;
auto hValue = hash(newRow);
Key key{ *this, newRow, hValue };
auto itr = rowKeys_.find(key);
if (itr != rowKeys_.end()) {
// copy the new row data into target for non-keys
auto oldRow = std::get<1>(*itr);
for (size_t i : values_) {
ops_.at(i).copier(newRow, oldRow);
}
// rollback the new added row
rollback();
return true;
}
// resume all values population and add a new row key
rowKeys_.insert(key);
// since this is a new row, create aggregator for all its value fields
auto& rowProps = rows_.at(newRow);
for (size_t i : values_) {
auto& sketch = rowProps.colProps.at(i).sketch;
if (sketch == nullptr) {
sketch = cops_.at(i).sketcher();
// since this is the first time sketch created, merge its own value
ops_.at(i).copier(newRow, newRow);
}
}
return false;
}
} // namespace keyed
} // namespace memory
} // namespace nebula | c++ | code | 10,519 | 2,314 |
#include <Common/ErrorCodes.h>
#include <chrono>
/** Previously, these constants were located in one enum.
* But in this case there is a problem: when you add a new constant, you need to recompile
* all translation units that use at least one constant (almost the whole project).
* Therefore it is made so that definitions of constants are located here, in one file,
* and their declaration are in different files, at the place of use.
*
* Later it was converted to the lookup table, to provide:
* - errorCodeToName()
* - system.errors table
*/
#define APPLY_FOR_ERROR_CODES(M) \
M(0, OK) \
M(1, UNSUPPORTED_METHOD) \
M(2, UNSUPPORTED_PARAMETER) \
M(3, UNEXPECTED_END_OF_FILE) \
M(4, EXPECTED_END_OF_FILE) \
M(6, CANNOT_PARSE_TEXT) \
M(7, INCORRECT_NUMBER_OF_COLUMNS) \
M(8, THERE_IS_NO_COLUMN) \
M(9, SIZES_OF_COLUMNS_DOESNT_MATCH) \
M(10, NOT_FOUND_COLUMN_IN_BLOCK) \
M(11, POSITION_OUT_OF_BOUND) \
M(12, PARAMETER_OUT_OF_BOUND) \
M(13, SIZES_OF_COLUMNS_IN_TUPLE_DOESNT_MATCH) \
M(15, DUPLICATE_COLUMN) \
M(16, NO_SUCH_COLUMN_IN_TABLE) \
M(17, DELIMITER_IN_STRING_LITERAL_DOESNT_MATCH) \
M(18, CANNOT_INSERT_ELEMENT_INTO_CONSTANT_COLUMN) \
M(19, SIZE_OF_FIXED_STRING_DOESNT_MATCH) \
M(20, NUMBER_OF_COLUMNS_DOESNT_MATCH) \
M(21, CANNOT_READ_ALL_DATA_FROM_TAB_SEPARATED_INPUT) \
M(22, CANNOT_PARSE_ALL_VALUE_FROM_TAB_SEPARATED_INPUT) \
M(23, CANNOT_READ_FROM_ISTREAM) \
M(24, CANNOT_WRITE_TO_OSTREAM) \
M(25, CANNOT_PARSE_ESCAPE_SEQUENCE) \
M(26, CANNOT_PARSE_QUOTED_STRING) \
M(27, CANNOT_PARSE_INPUT_ASSERTION_FAILED) \
M(28, CANNOT_PRINT_FLOAT_OR_DOUBLE_NUMBER) \
M(29, CANNOT_PRINT_INTEGER) \
M(30, CANNOT_READ_SIZE_OF_COMPRESSED_CHUNK) \
M(31, CANNOT_READ_COMPRESSED_CHUNK) \
M(32, ATTEMPT_TO_READ_AFTER_EOF) \
M(33, CANNOT_READ_ALL_DATA) \
M(34, TOO_MANY_ARGUMENTS_FOR_FUNCTION) \
M(35, TOO_FEW_ARGUMENTS_FOR_FUNCTION) \
M(36, BAD_ARGUMENTS) \
M(37, UNKNOWN_ELEMENT_IN_AST) \
M(38, CANNOT_PARSE_DATE) \
M(39, TOO_LARGE_SIZE_COMPRESSED) \
M(40, CHECKSUM_DOESNT_MATCH) \
M(41, CANNOT_PARSE_DATETIME) \
M(42, NUMBER_OF_ARGUMENTS_DOESNT_MATCH) \
M(43, ILLEGAL_TYPE_OF_ARGUMENT) \
M(44, ILLEGAL_COLUMN) \
M(45, ILLEGAL_NUMBER_OF_RESULT_COLUMNS) \
M(46, UNKNOWN_FUNCTION) \
M(47, UNKNOWN_IDENTIFIER) \
M(48, NOT_IMPLEMENTED) \
M(49, LOGICAL_ERROR) \
M(50, UNKNOWN_TYPE) \
M(51, EMPTY_LIST_OF_COLUMNS_QUERIED) \
M(52, COLUMN_QUERIED_MORE_THAN_ONCE) \
M(53, TYPE_MISMATCH) \
M(54, STORAGE_DOESNT_ALLOW_PARAMETERS) \
M(55, STORAGE_REQUIRES_PARAMETER) \
M(56, UNKNOWN_STORAGE) \
M(57, TABLE_ALREADY_EXISTS) \
M(58, TABLE_METADATA_ALREADY_EXISTS) \
M(59, ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER) \
M(60, UNKNOWN_TABLE) \
M(61, ONLY_FILTER_COLUMN_IN_BLOCK) \
M(62, SYNTAX_ERROR) \
M(63, UNKNOWN_AGGREGATE_FUNCTION) \
M(64, CANNOT_READ_AGGREGATE_FUNCTION_FROM_TEXT) \
M(65, CANNOT_WRITE_AGGREGATE_FUNCTION_AS_TEXT) \
M(66, NOT_A_COLUMN) \
M(67, ILLEGAL_KEY_OF_AGGREGATION) \
M(68, CANNOT_GET_SIZE_OF_FIELD) \
M(69, ARGUMENT_OUT_OF_BOUND) \
M(70, CANNOT_CONVERT_TYPE) \
M(71, CANNOT_WRITE_AFTER_END_OF_BUFFER) \
M(72, CANNOT_PARSE_NUMBER) \
M(73, UNKNOWN_FORMAT) \
M(74, CANNOT_READ_FROM_FILE_DESCRIPTOR) \
M(75, CANNOT_WRITE_TO_FILE_DESCRIPTOR) \
M(76, CANNOT_OPEN_FILE) \
M(77, CANNOT_CLOSE_FILE) \
M(78, UNKNOWN_TYPE_OF_QUERY) \
M(79, INCORRECT_FILE_NAME) \
M(80, INCORRECT_QUERY) \
M(81, UNKNOWN_DATABASE) \
M(82, DATABASE_ALREADY_EXISTS) \
M(83, DIRECTORY_DOESNT_EXIST) \
M(84, DIRECTORY_ALREADY_EXISTS) \
M(85, FORMAT_IS_NOT_SUITABLE_FOR_INPUT) \
M(86, RECEIVED_ERROR_FROM_REMOTE_IO_SERVER) \
M(87, CANNOT_SEEK_THROUGH_FILE) \
M(88, CANNOT_TRUNCATE_FILE) \
M(89, UNKNOWN_COMPRESSION_METHOD) \
M(90, EMPTY_LIST_OF_COLUMNS_PASSED) \
M(91, SIZES_OF_MARKS_FILES_ARE_INCONSISTENT) \
M(92, EMPTY_DATA_PASSED) \
M(93, UNKNOWN_AGGREGATED_DATA_VARIANT) \
M(94, CANNOT_MERGE_DIFFERENT_AGGREGATED_DATA_VARIANTS) \
M(95, CANNOT_READ_FROM_SOCKET) \
M(96, CANNOT_WRITE_TO_SOCKET) \
M(97, CANNOT_READ_ALL_DATA_FROM_CHUNKED_INPUT) \
M(98, CANNOT_WRITE_TO_EMPTY_BLOCK_OUTPUT_STREAM) \
M(99, UNKNOWN_PACKET_FROM_CLIENT) \
M(100, UNKNOWN_PACKET_FROM_SERVER) \
M(101, UNEXPECTED_PACKET_FROM_CLIENT) \
M(102, UNEXPECTED_PACKET_FROM_SERVER) \
M(103, RECEIVED_DATA_FOR_WRONG_QUERY_ID) \
M(104, TOO_SMALL_BUFFER_SIZE) \
M(105, CANNOT_READ_HISTORY) \
M(106, CANNOT_APPEND_HISTORY) \
M(107, FILE_DOESNT_EXIST) \
M(108, NO_DATA_TO_INSERT) \
M(109, CANNOT_BLOCK_SIGNAL) \
M(110, CANNOT_UNBLOCK_SIGNAL) \
M(111, CANNOT_MANIPULATE_SIGSET) \
M(112, CANNOT_WAIT_FOR_SIGNAL) \
M(113, THERE_IS_NO_SESSION) \
M(114, CANNOT_CLOCK_GETTIME) \
M(115, UNKNOWN_SETTING) \
M(116, THERE_IS_NO_DEFAULT_VALUE) \
M(117, INCORRECT_DATA) \
M(119, ENGINE_REQUIRED) \
M(120, CANNOT_INSERT_VALUE_OF_DIFFERENT_SIZE_INTO_TUPLE) \
M(121, UNSUPPORTED_JOIN_KEYS) \
M(122, INCOMPATIBLE_COLUMNS) \
M(123, UNKNOWN_TYPE_OF_AST_NODE) \
M(124, INCORRECT_ELEMENT_OF_SET) \
M(125, INCORRECT_RESULT_OF_SCALAR_SUBQUERY) \
M(126, CANNOT_GET_RETURN_TYPE) \
M(127, ILLEGAL_INDEX) \
M(128, TOO_LARGE_ARRAY_SIZE) \
M(129, FUNCTION_IS_SPECIAL) \
M(130, CANNOT_READ_ARRAY_FROM_TEXT) \
M(131, TOO_LARGE_STRING_SIZE) \
M(133, AGGREGATE_FUNCTION_DOESNT_ALLOW_PARAMETERS) \
M(134, PARAMETERS_TO_AGGREGATE_FUNCTIONS_MUST_BE_LITERALS) \
M(135, ZERO_ARRAY_OR_TUPLE_INDEX) \
M(137, UNKNOWN_ELEMENT_IN_CONFIG) \
M(138, EXCESSIVE_ELEMENT_IN_CONFIG) \
M(139, NO_ELEMENTS_IN_CONFIG) \
M(140, ALL_REQUESTED_COLUMNS_ARE_MISSING) \
M(141, SAMPLING_NOT_SUPPORTED) \
M(142, NOT_FOUND_NODE) \
M(143, FOUND_MORE_THAN_ONE_NODE) \
M(144, FIRST_DATE_IS_BIGGER_THAN_LAST_DATE) \
M(145, UNKNOWN_OVERFLOW_MODE) \
M(146, QUERY_SECTION_DOESNT_MAKE_SENSE) \
M(147, NOT_FOUND_FUNCTION_ELEMENT_FOR_AGGREGATE) \
M(148, NOT_FOUND_RELATION_ELEMENT_FOR_CONDITION) \
M(149, NOT_FOUND_RHS_ELEMENT_FOR_CONDITION) \
M(150, EMPTY_LIST_OF_ATTRIBUTES_PASSED) \
M(151, INDEX_OF_COLUMN_IN_SORT_CLAUSE_IS_OUT_OF_RANGE) \
M(152, UNKNOWN_DIRECTION_OF_SORTING) \
M(153, ILLEGAL_DIVISION) \
M(154, AGGREGATE_FUNCTION_NOT_APPLICABLE) \
M(155, UNKNOWN_RELATION) \
M(156, DICTIONARIES_WAS_NOT_LOADED) \
M(157, ILLEGAL_OVERFLOW_MODE) \
M(158, TOO_MANY_ROWS) \
M(159, TIMEOUT_EXCEEDED) \
M(160, TOO_SLOW) \
M(161, TOO_MANY_COLUMNS) \
M(162, TOO_DEEP_SUBQUERIES) \
M(163, TOO_DEEP_PIPELINE) \
M(164, READONLY) \
M(165, TOO_MANY_TEMPORARY_COLUMNS) \
M(166, TOO_MANY_TEMPORARY_NON_CONST_COLUMNS) \
M(167, TOO_DEEP_AST) \
M(168, TOO_BIG_AST) \
M(169, BAD_TYPE_OF_FIELD) \
M(170, BAD_GET) \
M(172, CANNOT_CREATE_DIRECTORY) \
M(173, CANNOT_ALLOCATE_MEMORY) \
M(174, CYCLIC_ALIASES) \
M(176, CHUNK_NOT_FOUND) \
M(177, DUPLICATE_CHUNK_NAME) \
M(178, MULTIPLE_ALIASES_FOR_EXPRESSION) \
M(179, MULTIPLE_EXPRESSIONS_FOR_ALIAS) \
M(180, THERE_IS_NO_PROFILE) \
M(181, ILLEGAL_FINAL) \
M(182, ILLEGAL_PREWHERE) \
M(183, UNEXPECTED_EXPRESSION) \
M(184, ILLEGAL_AGGREGATION) \
M(185, UNSUPPORTED_MYISAM_BLOCK_TYPE) \
M(186, UNSUPPORTED_COLLATION_LOCALE) \
M(187, COLLATION_COMPARISON_FAILED) \
M(188, UNKNOWN_ACTION) \
M(189, TABLE_MUST_NOT_BE_CREATED_MANUALLY) \
M(190, SIZES_OF_ARRAYS_DOESNT_MATCH) \
M(191, SET_SIZE_LIMIT_EXCEEDED) \
M(192, UNKNOWN_USER) \
M(193, WRONG_PASSWORD) \
M(194, REQUIRED_PASSWORD) \
M(195, IP_ADDRESS_NOT_ALLOWED) \
M(196, UNKNOWN_ADDRESS_PATTERN_TYPE) \
M(197, SERVER_REVISION_IS_TOO_OLD) \
M(198, DNS_ERROR) \
M(199, UNKNOWN_QUOTA) \
M(200, QUOTA_DOESNT_ALLOW_KEYS) \
M(201, QUOTA_EXPIRED) \
M(202, TOO_MANY_SIMULTANEOUS_QUERIES) \
M(203, NO_FREE_CONNECTION) \
M(204, CANNOT_FSYNC) \
M(205, NESTED_TYPE_TOO_DEEP) \
M(206, ALIAS_REQUIRED) \
M(207, AMBIGUOUS_IDENTIFIER) \
M(208, EMPTY_NESTED_TABLE) \
M(209, SOCKET_TIMEOUT) \
M(210, NETWORK_ERROR) \
M(211, EMPTY_QUERY) \
M(212, UNKNOWN_LOAD_BALANCING) \
M(213, UNKNOWN_TOTALS_MODE) \
M(214, CANNOT_STATVFS) \
M(215, NOT_AN_AGGREGATE) \
M(216, QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING) \
M(217, CLIENT_HAS_CONNECTED_TO_WRONG_PORT) \
M(218, TABLE_IS_DROPPED) \
M(219, DATABASE_NOT_EMPTY) \
M(220, DUPLICATE_INTERSERVER_IO_ENDPOINT) \
M(221, NO_SUCH_INTERSERVER_IO_ENDPOINT) \
M(222, ADDING_REPLICA_TO_NON_EMPTY_TABLE) \
M(223, UNEXPECTED_AST_STRUCTURE) \
M(224, REPLICA_IS_ALREADY_ACTIVE) \
M(225, NO_ZOOKEEPER) \
M(226, NO_FILE_IN_DATA_PART) \
M(227, UNEXPECTED_FILE_IN_DATA_PART) \
M(228, BAD_SIZE_OF_FILE_IN_DATA_PART) \
M(229, QUERY_IS_TOO_LARGE) \
M(230, NOT_FOUND_EXPECTED_DATA_PART) \
M(231, TOO_MANY_UNEXPECTED_DATA_PARTS) \
M(232, NO_SUCH_DATA_PART) \
M(233, BAD_DATA_PART_NAME) \
M(234, NO_REPLICA_HAS_PART) \
M(235, DUPLICATE_DATA_PART) \
M(236, ABORTED) \
M(237, NO_REPLICA_NAME_GIVEN) \
M(238, FORMAT_VERSION_TOO_OLD) \
M(239, CANNOT_MUNMAP) \
M(240, CANNOT_MREMAP) \
M(241, MEMORY_LIMIT_EXCEEDED) \
M(242, TABLE_IS_READ_ONLY) \
M(243, NOT_ENOUGH_SPACE) \
M(244, UNEXPECTED_ZOOKEEPER_ERROR) \
M(246, CORRUPTED_DATA) \
M(247, INCORRECT_MARK) \
M(248, INVALID_PARTITION_VALUE) \
M(250, NOT_ENOUGH_BLOCK_NUMBERS) \
M(251, NO_SUCH_REPLICA) \
M(252, TOO_MANY_PARTS) \
M(253, REPLICA_IS_ALREADY_EXIST) \
M(254, NO_ACTIVE_REPLICAS) \
M(255, TOO_MANY_RETRIES_TO_FETCH_PARTS) \
M(256, PARTITION_ALREADY_EXISTS) \
M(257, PARTITION_DOESNT_EXIST) \
M(258, UNION_ALL_RESULT_STRUCTURES_MISMATCH) \
M(260, CLIENT_OUTPUT_FORMAT_SPECIFIED) \
M(261, UNKNOWN_BLOCK_INFO_FIELD) \
M(262, BAD_COLLATION) \
M(263, CANNOT_COMPILE_CODE) \
M(264, INCOMPATIBLE_TYPE_OF_JOIN) \
M(265, NO_AVAILABLE_REPLICA) \
M(266, MISMATCH_REPLICAS_DATA_SOURCES) \
M(267, STORAGE_DOESNT_SUPPORT_PARALLEL_REPLICAS) \
M(268, CPUID_ERROR) \
M(269, INFINITE_LOOP) \
M(270, CANNOT_COMPRESS) \
M(271, CANNOT_DECOMPRESS) \
M(272, CANNOT_IO_SUBMIT) \
M(273, CANNOT_IO_GETEVENTS) \
M(274, AIO_READ_ERROR) \
M(275, AIO_WRITE_ERROR) \
M(277, INDEX_NOT_USED) \
M(279, ALL_CONNECTION_TRIES_FAILED) \
M(280, NO_AVAILABLE_DATA) \
M(281, DICTIONARY_IS_EMPTY) \
M(282, INCORRECT_INDEX) \
M(283, UNKNOWN_DISTRIBUTED_PRODUCT_MODE) \
M(284, WRONG_GLOBAL_SUBQUERY) \
M(285, TOO_FEW_LIVE_REPLICAS) \
M(286, UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE) \
M(287, UNKNOWN_FORMAT_VERSION) \
M(288, DISTRIBUTED_IN_JOIN_SUBQUERY_DENIED) \
M(289, REPLICA_IS_NOT_IN_QUORUM) \
M(290, LIMIT_EXCEEDED) \
M(291, DATABASE_ACCESS_DENIED) \
M(293, MONGODB_CANNOT_AUTHENTICATE) \
M(294, INVALID_BLOCK_EXTRA_INFO) \
M(295, RECEIVED_EMPTY_DATA) \
M(296, NO_REMOTE_SHARD_FOUND) \
M(297, SHARD_HAS_NO_CONNECTIONS) \
M(298, CANNOT_PIPE) \
M(299, CANNOT_FORK) \
M(300, CANNOT_DLSYM) \
M(301, CANNOT_CREATE_CHILD_PROCESS) \
M(302, CHILD_WAS_NOT_EXITED_NORMALLY) \
M(303, CANNOT_SELECT) \
M(304, CANNOT_WAITPID) \
M(305, TABLE_WAS_NOT_DROPPED) \
M(306, TOO_DEEP_RECURSION) \
M(307, TOO_MANY_BYTES) \
M(308, UNEXPECTED_NODE_IN_ZOOKEEPER) \
M(309, FUNCTION_CANNOT_HAVE_PARAMETERS) \
M(317, INVALID_SHARD_WEIGHT) \
M(318, INVALID_CONFIG_PARAMETER) \
M(319, UNKNOWN_STATUS_OF_INSERT) \
M(321, VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) \
M(335, BARRIER_TIMEOUT) \
M(336, UNKNOWN_DATABASE_ENGINE) \
M(337, DDL_GUARD_IS_ACTIVE) \
M(341, UNFINISHED) \
M(342, METADATA_MISMATCH) \
M(344, SUPPORT_IS_DISABLED) \
M(345, TABLE_DIFFERS_TOO_MUCH) \
M(346, CANNOT_CONVERT_CHARSET) \
M(347, CANNOT_LOAD_CONFIG) \
M(349, CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN) \
M(350, INCOMPATIBLE_SOURCE_TABLES) \
M(351, AMBIGUOUS_TABLE_NAME) \
M(352, AMBIGUOUS_COLUMN_NAME) \
M(353, INDEX_OF_POSITIONAL_ARGUMENT_IS_OUT_OF_RANGE) \
M(354, ZLIB_INFLATE_FAILED) \
M(355, ZLIB_DEFLATE_FAILED) \
M(356, BAD_LAMBDA) \
M(357, RESERVED_IDENTIFIER_NAME) \
M(358, INTO_OUTFILE_NOT_ALLOWED) \
M(359, TABLE_SIZE_EXCEEDS_MAX_DROP_SIZE_LIMIT) \
M(360, CANNOT_CREATE_CHARSET_CONVERTER) \
M(361, SEEK_POSITION_OUT_OF_BOUND) \
M(362, CURRENT_WRITE_BUFFER_IS_EXHAUSTED) \
M(363, CANNOT_CREATE_IO_BUFFER) \
M(364, RECEIVED_ERROR_TOO_MANY_REQUESTS) \
M(366, SIZES_OF_NESTED_COLUMNS_ARE_INCONSISTENT) \
M(367, TOO_MANY_FETCHES) \
M(369, ALL_REPLICAS_ARE_STALE) \
M(370, DATA_TYPE_CANNOT_BE_USED_IN_TABLES) \
M(371, INCONSISTENT_CLUSTER_DEFINITION) \
M(372, SESSION_NOT_FOUND) \
M(373, SESSION_IS_LOCKED) \
M(374, INVALID_SESSION_TIMEOUT) \
M(375, CANNOT_DLOPEN) \
M(376, CANNOT_PARSE_UUID) \
M(377, ILLEGAL_SYNTAX_FOR_DATA_TYPE) \
M(378, DATA_TYPE_CANNOT_HAVE_ARGUMENTS) \
M(379, UNKNOWN_STATUS_OF_DISTRIBUTED_DDL_TASK) \
M(380, CANNOT_KILL) \
M(381, HTTP_LENGTH_REQUIRED) \
M(382, CANNOT_LOAD_CATBOOST_MODEL) \
M(383, CANNOT_APPLY_CATBOOST_MODEL) \
M(384, PART_IS_TEMPORARILY_LOCKED) \
M(385, MULTIPLE_STREAMS_REQUIRED) \
M(386, NO_COMMON_TYPE) \
M(387, DICTIONARY_ALREADY_EXISTS) \
M(388, CANNOT_ASSIGN_OPTIMIZE) \
M(389, INSERT_WAS_DEDUPLICATED) \
M(390, CANNOT_GET_CREATE_TABLE_QUERY) \
M(391, EXTERNAL_LIBRARY_ERROR) \
M(392, QUERY_IS_PROHIBITED) \
M(393, THERE_IS_NO_QUERY) \
M(394, QUERY_WAS_CANCELLED) \
M(395, FUNCTION_THROW_IF_VALUE_IS_NON_ZERO) \
M(396, TOO_MANY_ROWS_OR_BYTES) \
M(397, QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW) \
M(398, UNKNOWN_MUTATION_COMMAND) \
M(399, FORMAT_IS_NOT_SUITABLE_FOR_OUTPUT) \
M(400, CANNOT_STAT) \
M(401, FEATURE_IS_NOT_ENABLED_AT_BUILD_TIME) \
M(402, CANNOT_IOSETUP) \
M(403, INVALID_JOIN_ON_EXPRESSION) \
M(404, BAD_ODBC_CONNECTION_STRING) \
M(405, PARTITION_SIZE_EXCEEDS_MAX_DROP_SIZE_LIMIT) \
M(406, TOP_AND_LIMIT_TOGETHER) \
M(407, DECIMAL_OVERFLOW) \
M(408, BAD_REQUEST_PARAMETER) \
M(409, EXTERNAL_EXECUTABLE_NOT_FOUND) \
M(410, EXTERNAL_SERVER_IS_NOT_RESPONDING) \
M(411, PTHREAD_ERROR) \
M(412, NETLINK_ERROR) \
M(413, CANNOT_SET_SIGNAL_HANDLER) \
M(415, ALL_REPLICAS_LOST) \
M(416, REPLICA_STATUS_CHANGED) \
M(417, EXPECTED_ALL_OR_ANY) \
M(418, UNKNOWN_JOIN) \
M(419, MULTIPLE_ASSIGNMENTS_TO_COLUMN) \
M(420, CANNOT_UPDATE_COLUMN) \
M(421, CANNOT_ADD_DIFFERENT_AGGREGATE_STATES) \
M(422, UNSUPPORTED_URI_SCHEME) \
M(423, CANNOT_GETTIMEOFDAY) \
M(424, CANNOT_LINK) \
M(425, SYSTEM_ERROR) \
M(427, CANNOT_COMPILE_REGEXP) \
M(428, UNKNOWN_LOG_LEVEL) \
M(429, FAILED_TO_GETPWUID) \
M(430, MISMATCHING_USERS_FOR_PROCESS_AND_DATA) \
M(431, ILLEGAL_SYNTAX_FOR_CODEC_TYPE) \
M(432, UNKNOWN_CODEC) \
M(433, ILLEGAL_CODEC_PARAMETER) \
M(434, CANNOT_PARSE_PROTOBUF_SCHEMA) \
M(435, NO_COLUMN_SERIALIZED_TO_REQUIRED_PROTOBUF_FIELD) \
M(436, PROTOBUF_BAD_CAST) \
M(437, PROTOBUF_FIELD_NOT_REPEATED) \
M(438, DATA_TYPE_CANNOT_BE_PROMOTED) \
M(439, CANNOT_SCHEDULE_TASK) \
M(440, INVALID_LIMIT_EXPRESSION) \
M(441, CANNOT_PARSE_DOMAIN_VALUE_FROM_STRING) \
M(442, BAD_DATABASE_FOR_TEMPORARY_TABLE) \
M(443, NO_COLUMNS_SERIALIZED_TO_PROTOBUF_FIELDS) \
M(444, UNKNOWN_PROTOBUF_FORMAT) \
M(445, CANNOT_MPROTECT) \
M(446, FUNCTION_NOT_ALLOWED) \
M(447, HYPERSCAN_CANNOT_SCAN_TEXT) \
M(448, BROTLI_READ_FAILED) \
M(449, BROTLI_WRITE_FAILED) \
M(450, BAD_TTL_EXPRESSION) \
M(451, BAD_TTL_FILE) \
M(452, SETTING_CONSTRAINT_VIOLATION) \
M(453, MYSQL_CLIENT_INSUFFICIENT_CAPABILITIES) \
M(454, OPENSSL_ERROR) \
M(455, SUSPICIOUS_TYPE_FOR_LOW_CARDINALITY) \
M(456, UNKNOWN_QUERY_PARAMETER) \
M(457, BAD_QUERY_PARAMETER) \
M(458, CANNOT_UNLINK) \
M(459, CANNOT_SET_THREAD_PRIORITY) \
M(460, CANNOT_CREATE_TIMER) \
M(461, CANNOT_SET_TIMER_PERIOD) \
M(462, CANNOT_DELETE_TIMER) \
M(463, CANNOT_FCNTL) \
M(464, CANNOT_PARSE_ELF) \
M(465, CANNOT_PARSE_DWARF) \
M(466, INSECURE_PATH) \
M(467, CANNOT_PARSE_BOOL) \
M(468, CANNOT_PTHREAD_ATTR) \
M(469, VIOLATED_CONSTRAINT) \
M(470, QUERY_IS_NOT_SUPPORTED_IN_LIVE_VIEW) \
M(471, INVALID_SETTING_VALUE) \
M(472, READONLY_SETTING) \
M(473, DEADLOCK_AVOIDED) \
M(474, INVALID_TEMPLATE_FORMAT) \
M(475, INVALID_WITH_FILL_EXPRESSION) \
M(476, WITH_TIES_WITHOUT_ORDER_BY) \
M(477, INVALID_USAGE_OF_INPUT) \
M(478, UNKNOWN_POLICY) \
M(479, UNKNOWN_DISK) \
M(480, UNKNOWN_PROTOCOL) \
M(481, PATH_ACCESS_DENIED) \
M(482, DICTIONARY_ACCESS_DENIED) \
M(483, TOO_MANY_REDIRECTS) \
M(484, INTERNAL_REDIS_ERROR) \
M(485, SCALAR_ALREADY_EXISTS) \
M(487, CANNOT_GET_CREATE_DICTIONARY_QUERY) \
M(488, UNKNOWN_DICTIONARY) \
M(489, INCORRECT_DICTIONARY_DEFINITION) \
M(490, CANNOT_FORMAT_DATETIME) \
M(491, UNACCEPTABLE_URL) \
M(492, ACCESS_ENTITY_NOT_FOUND) \
M(493, ACCESS_ENTITY_ALREADY_EXISTS) \
M(494, ACCESS_ENTITY_FOUND_DUPLICATES) \
M(495, ACCESS_STORAGE_READONLY) \
M(496, QUOTA_REQUIRES_CLIENT_KEY) \
M(497, ACCESS_DENIED) \
M(498, LIMIT_BY_WITH_TIES_IS_NOT_SUPPORTED) \
M(499, S3_ERROR) \
M(501, CANNOT_CREATE_DATABASE) \
M(502, CANNOT_SIGQUEUE) \
M(503, AGGREGATE_FUNCTION_THROW) \
M(504, FILE_ALREADY_EXISTS) \
M(505, CANNOT_DELETE_DIRECTORY) \
M(506, UNEXPECTED_ERROR_CODE) \
M(507, UNABLE_TO_SKIP_UNUSED_SHARDS) \
M(508, UNKNOWN_ACCESS_TYPE) \
M(509, INVALID_GRANT) \
M(510, CACHE_DICTIONARY_UPDATE_FAIL) \
M(511, UNKNOWN_ROLE) \
M(512, SET_NON_GRANTED_ROLE) \
M(513, UNKNOWN_PART_TYPE) \
M(514, ACCESS_STORAGE_FOR_INSERTION_NOT_FOUND) \
M(515, INCORRECT_ACCESS_ENTITY_DEFINITION) \
M(516, AUTHENTICATION_FAILED) \
M(517, CANNOT_ASSIGN_ALTER) \
M(518, CANNOT_COMMIT_OFFSET) \
M(519, NO_REMOTE_SHARD_AVAILABLE) \
M(520, CANNOT_DETACH_DICTIONARY_AS_TABLE) \
M(521, ATOMIC_RENAME_FAIL) \
M(523, UNKNOWN_ROW_POLICY) \
M(524, ALTER_OF_COLUMN_IS_FORBIDDEN) \
M(525, INCORRECT_DISK_INDEX) \
M(526, UNKNOWN_VOLUME_TYPE) \
M(527, NO_SUITABLE_FUNCTION_IMPLEMENTATION) \
M(528, CASSANDRA_INTERNAL_ERROR) \
M(529, NOT_A_LEADER) \
M(530, CANNOT_CONNECT_RABBITMQ) \
M(531, CANNOT_FSTAT) \
M(532, LDAP_ERROR) \
M(533, INCONSISTENT_RESERVATIONS) \
M(534, NO_RESERVATIONS_PROVIDED) \
M(535, UNKNOWN_RAID_TYPE) \
M(536, CANNOT_RESTORE_FROM_FIELD_DUMP) \
M(537, ILLEGAL_MYSQL_VARIABLE) \
M(538, MYSQL_SYNTAX_ERROR) \
M(539, CANNOT_BIND_RABBITMQ_EXCHANGE) \
M(540, CANNOT_DECLARE_RABBITMQ_EXCHANGE) \
M(541, CANNOT_CREATE_RABBITMQ_QUEUE_BINDING) \
M(542, CANNOT_REMOVE_RABBITMQ_EXCHANGE) \
M(543, UNKNOWN_MYSQL_DATATYPES_SUPPORT_LEVEL) \
M(544, ROW_AND_ROWS_TOGETHER) \
M(545, FIRST_AND_NEXT_TOGETHER) \
M(546, NO_ROW_DELIMITER) \
M(547, INVALID_RAID_TYPE) \
M(548, UNKNOWN_VOLUME) \
M(549, DATA_TYPE_CANNOT_BE_USED_IN_KEY) \
M(550, CONDITIONAL_TREE_PARENT_NOT_FOUND) \
M(551, ILLEGAL_PROJECTION_MANIPULATOR) \
M(552, UNRECOGNIZED_ARGUMENTS) \
M(553, LZMA_STREAM_ENCODER_FAILED) \
M(554, LZMA_STREAM_DECODER_FAILED) \
M(555, ROCKSDB_ERROR) \
M(556, SYNC_MYSQL_USER_ACCESS_ERROR)\
M(557, UNKNOWN_UNION) \
M(558, EXPECTED_ALL_OR_DISTINCT) \
M(559, INVALID_GRPC_QUERY_INFO) \
M(560, ZS | c++ | code | 20,000 | 3,729 |
/// (c) Ben Jones 2019 - present
#include "ExitStatement.hpp"
#include "expressions/evaluator/ExpressionEvaluator.hpp"
#include "evaluator/StatementEvaluator.hpp"
#include <utility>
namespace arrow {
ExitStatement::ExitStatement(long const lineNumber,
std::shared_ptr<ArrowlessStatement> statement)
: Statement(lineNumber)
, m_statement(std::move(statement))
{
}
Token ExitStatement::getToken() const
{
return m_statement->getToken();
}
std::shared_ptr<Expression> ExitStatement::getExpression() const
{
return m_statement->getExpression();
}
std::string ExitStatement::toString() const
{
return m_statement->toString();
}
std::shared_ptr<StatementEvaluator> ExitStatement::getEvaluator() const
{
struct ExitStatementEvaluator : public StatementEvaluator
{
ExitStatementEvaluator(ExitStatement statement)
: m_statement(std::move(statement))
{
}
StatementResult evaluate(Environment & environment) const override
{
return StatementResult::Exit;
}
private:
ExitStatement m_statement;
};
return std::make_shared<ExitStatementEvaluator>(*this);
}
} | c++ | code | 1,332 | 209 |
#include "GraphicsDevice.h"
#include "AccelerationStructure.h"
#include "scene/SimplePolygonMesh.h"
#include "VkrayBookUtility.h"
void SimplePolygonMesh::Create(VkGraphicsDevice& device, const CreateInfo& createInfo, MaterialManager& materialManager)
{
auto hostMemProps = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
auto usageForRT = \
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | \
VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
VkBufferUsageFlags usageVB = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
usageVB |= usageForRT;
auto vbSize = createInfo.vbSize;
vertexBuffer = device->CreateBuffer(vbSize, usageVB, hostMemProps);
device->WriteToBuffer(vertexBuffer, createInfo.srcVertices, vbSize);
VkBufferUsageFlags usageIB = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
usageIB |= usageForRT;
auto ibSize = createInfo.ibSize;
indexBuffer = device->CreateBuffer(ibSize, usageIB, hostMemProps);
device->WriteToBuffer(indexBuffer, createInfo.srcIndices, ibSize);
indexCount = createInfo.indexCount;
vertexCount = createInfo.vertexCount;
vertexStride = createInfo.stride;
m_material = createInfo.material;
m_materialIndex = materialManager.AddMaterial(m_material);
}
void SimplePolygonMesh::BuildAS(VkGraphicsDevice& device, VkBuildAccelerationStructureFlagsKHR buildFlags)
{
AccelerationStructure::Input blasInput;
blasInput.asGeometry = GetAccelerationStructureGeometry();
blasInput.asBuildRangeInfo = GetAccelerationStructureBuildRangeInfo();
m_blas.BuildAS(device,
VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR,
blasInput,
buildFlags);
m_blas.DestroyScratchBuffer(device);
m_asInstance.accelerationStructureReference = m_blas.GetDeviceAddress();
}
std::vector<VkAccelerationStructureGeometryKHR> SimplePolygonMesh::GetAccelerationStructureGeometry(int frameIndex)
{
VkAccelerationStructureGeometryKHR asGeometry{
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR
};
asGeometry.flags = m_geometryFlags;
asGeometry.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR;
// VkAccelerationStructureGeometryTrianglesDataKHR
auto& triangles = asGeometry.geometry.triangles;
triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR;
triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT;
triangles.vertexData.deviceAddress = vertexBuffer.GetDeviceAddress();
triangles.maxVertex = vertexCount;
triangles.vertexStride = vertexStride;
triangles.indexType = VK_INDEX_TYPE_UINT32;
triangles.indexData.deviceAddress = indexBuffer.GetDeviceAddress();
return { asGeometry };
}
std::vector<VkAccelerationStructureBuildRangeInfoKHR> SimplePolygonMesh::GetAccelerationStructureBuildRangeInfo()
{
VkAccelerationStructureBuildRangeInfoKHR asBuildRangeInfo{};
asBuildRangeInfo.primitiveCount = indexCount / 3;
asBuildRangeInfo.primitiveOffset = 0;
asBuildRangeInfo.firstVertex = 0;
asBuildRangeInfo.transformOffset = 0;
return { asBuildRangeInfo };
}
std::vector<SceneObject::SceneObjectParameter> SimplePolygonMesh::GetSceneObjectParameters()
{
SceneObjectParameter objParam{};
objParam.blasMatrixIndex = 0;
objParam.materialIndex = m_materialIndex;
objParam.vertexPosition = GetDeviceAddressVB();
objParam.vertexNormal = 0;
objParam.vertexTexcoord = 0;
objParam.indexBuffer = GetDeviceAddressIB();
return { objParam };
} | c++ | code | 3,613 | 466 |
/*
* Copyright 2020 The Magma Authors.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
* 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 <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "lte/gateway/c/core/oai/tasks/nas5g/include/ies/M5GGprsTimer3.h"
#include "lte/gateway/c/core/oai/tasks/nas5g/include/M5GCommonDefs.h"
namespace magma5g {
GPRSTimer3Msg::GPRSTimer3Msg(){};
GPRSTimer3Msg::~GPRSTimer3Msg(){};
int GPRSTimer3Msg::DecodeGPRSTimer3Msg(GPRSTimer3Msg* gprstimer, uint8_t iei,
uint8_t* buffer, uint32_t len) {
int decoded = 0;
if (iei > 0) {
CHECK_IEI_DECODER(iei, *buffer);
decoded++;
}
gprstimer->unit = (*(buffer + decoded) >> 5) & 0x7;
gprstimer->timervalue = *(buffer + decoded) & 0x1f;
decoded++;
return decoded;
};
int GPRSTimer3Msg::EncodeGPRSTimer3Msg(GPRSTimer3Msg* gprstimer, uint8_t iei,
uint8_t* buffer, uint32_t len) {
uint32_t encoded = 0;
/*
* Checking IEI and pointer
*/
CHECK_PDU_POINTER_AND_LENGTH_ENCODER(buffer, GPRS_TIMER3_MINIMUM_LENGTH, len);
if (iei > 0) {
*buffer = iei;
encoded++;
}
*(buffer + encoded) = gprstimer->len;
encoded++;
*(buffer + encoded) =
0x00 | ((gprstimer->unit & 0x7) << 5) | (gprstimer->timervalue & 0x1f);
encoded++;
return encoded;
};
} // namespace magma5g | c++ | code | 1,749 | 347 |
// Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_wsdlconnection.h"
#include "fxjs/xfa/cjx_wsdlconnection.h"
#include "xfa/fxfa/parser/cxfa_document.h"
namespace {
const CXFA_Node::PropertyData kWsdlConnectionPropertyData[] = {
{XFA_Element::Operation, 1, 0},
{XFA_Element::WsdlAddress, 1, 0},
{XFA_Element::SoapAddress, 1, 0},
{XFA_Element::SoapAction, 1, 0},
{XFA_Element::EffectiveOutputPolicy, 1, 0},
{XFA_Element::EffectiveInputPolicy, 1, 0},
};
const CXFA_Node::AttributeData kWsdlConnectionAttributeData[] = {
{XFA_Attribute::Name, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::DataDescription, XFA_AttributeType::CData, nullptr},
};
} // namespace
CXFA_WsdlConnection::CXFA_WsdlConnection(CXFA_Document* doc,
XFA_PacketType packet)
: CXFA_Node(doc,
packet,
XFA_XDPPACKET_ConnectionSet,
XFA_ObjectType::Node,
XFA_Element::WsdlConnection,
kWsdlConnectionPropertyData,
kWsdlConnectionAttributeData,
cppgc::MakeGarbageCollected<CJX_WsdlConnection>(
doc->GetHeap()->GetAllocationHandle(),
this)) {}
CXFA_WsdlConnection::~CXFA_WsdlConnection() = default; | c++ | code | 1,522 | 251 |
#include "dvl_tortuga.h"
DVLTortugaNode::DVLTortugaNode(std::shared_ptr<ros::NodeHandle> n, int rate, int board_fd, std::string board_file):RamNode(n) {
publisher = n->advertise<geometry_msgs::TwistWithCovarianceStamped>("tortuga/dvl", 1000);
ROS_DEBUG("Set up publisher");
fd = board_fd;
file = board_file;
//intitialize all the message fields so no one gets upset if we send a message before getting good data.
msg.header.frame_id = "base_link";
msg.header.stamp = ros::Time::now();
msg.twist.twist.linear.x = 0;
msg.twist.twist.linear.y = 0;
msg.twist.twist.linear.z = 0;
msg.twist.covariance = {1e-9, 0, 0, 0, 0, 0,
0, 1e-9, 0, 0, 0, 0,
0, 0, 1e-9, 0, 0, 0,
0, 0, 0, 1e-9, 0, 0,
0, 0, 0, 0, 1e-9, 0,
0, 0, 0, 0, 0, 1e-9};
}
DVLTortugaNode::~DVLTortugaNode(){}
void DVLTortugaNode::update(){
// ros::spinOnce();
checkError(readDVLData(fd, &raw));
ROS_DEBUG("Read DVL Data");
// Raw data has a pointer to complete packet
pkt = raw.privDbgInf;
if(raw.xvel_btm == DVL_BAD_DATA || raw.yvel_btm == DVL_BAD_DATA || raw.zvel_btm == DVL_BAD_DATA){
ROS_ERROR("Bad Data, publishing last good value");
publisher.publish(msg);
}
else{
// Set all the message's data
msg.header.frame_id = "base_link";
msg.header.stamp = ros::Time::now();
msg.twist.twist.linear.x = raw.xvel_btm;
msg.twist.twist.linear.y = raw.yvel_btm;
msg.twist.twist.linear.z = raw.zvel_btm;
msg.twist.covariance = {1e-9, 0, 0, 0, 0, 0,
0, 1e-9, 0, 0, 0, 0,
0, 0, 1e-9, 0, 0, 0,
0, 0, 0, 1e-9, 0, 0,
0, 0, 0, 0, 1e-9, 0,
0, 0, 0, 0, 0, 1e-9};
publisher.publish(msg);
ROS_DEBUG("Published msg");
}
}
bool DVLTortugaNode::checkError(int e) {
switch(e) {
case ERR_NOSYNC:
ROS_ERROR("NOSYNC ERROR in node %s", file.c_str());
return true;
case ERR_TOOBIG:
ROS_ERROR("TOOBIG ERROR in node %s", file.c_str());
return true;
case ERR_CHKSUM:
ROS_ERROR("CHKSUM ERROR in node %s", file.c_str());
return true;
default:
return false;
}
} | c++ | code | 2,492 | 614 |
#ifndef BOOST_PP_IS_ITERATING
/*=============================================================================
Copyright (c) 2011 Eric Niebler
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_FUSION_VECTOR40_FWD_HPP_INCLUDED)
#define BOOST_FUSION_VECTOR40_FWD_HPP_INCLUDED
#include <boost/fusion/support/config.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <boost/fusion/container/vector/detail/cpp03/preprocessed/vector40_fwd.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/vector40_fwd.hpp")
#endif
/*=============================================================================
Copyright (c) 2011 Eric Niebler
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
This is an auto-generated file. Do not edit!
==============================================================================*/
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
namespace boost { namespace fusion
{
// expand vector31 to vector40
#define BOOST_PP_FILENAME_1 <boost/fusion/container/vector/detail/cpp03/vector40_fwd.hpp>
#define BOOST_PP_ITERATION_LIMITS (31, 40)
#include BOOST_PP_ITERATE()
}}
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES
#endif
#else
template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), typename T)>
struct BOOST_PP_CAT(vector, BOOST_PP_ITERATION());
#endif | c++ | code | 2,151 | 300 |
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
USEFORM("JvSearchFileMainFormU.cpp", JvSearchFileMainForm);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(TJvSearchFileMainForm), &JvSearchFileMainForm);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
return 0;
}
//--------------------------------------------------------------------------- | c++ | code | 1,096 | 272 |
#include "TopQuarkAnalysis/TopKinFitter/interface/TopKinFitter.h"
/// default configuration is: max iterations = 200, max deltaS = 5e-5, maxF = 1e-4
TopKinFitter::TopKinFitter(const int maxNrIter, const double maxDeltaS, const double maxF,
const double mW, const double mTop):
maxNrIter_(maxNrIter), maxDeltaS_(maxDeltaS), maxF_(maxF), mW_(mW), mTop_(mTop)
{
fitter_ = new TKinFitter("TopKinFitter", "TopKinFitter");
fitter_->setMaxNbIter(maxNrIter_);
fitter_->setMaxDeltaS(maxDeltaS_);
fitter_->setMaxF(maxF_);
fitter_->setVerbosity(0);
}
/// default destructor
TopKinFitter::~TopKinFitter()
{
delete fitter_;
}
/// convert Param to human readable form
std::string
TopKinFitter::param(const Param& param) const
{
std::string parName;
switch(param){
case kEMom : parName="EMom"; break;
case kEtEtaPhi : parName="EtEtaPhi"; break;
case kEtThetaPhi : parName="EtThetaPhi"; break;
}
return parName;
} | c++ | code | 957 | 208 |
// generated from rosidl_generator_cpp/resource/msg__traits.hpp.em
// generated code does not contain a copyright notice
#ifndef TEST_MSGS__SRV__EMPTY__RESPONSE__TRAITS_HPP_
#define TEST_MSGS__SRV__EMPTY__RESPONSE__TRAITS_HPP_
#include <stdint.h>
#include <type_traits>
namespace rosidl_generator_traits
{
#ifndef __ROSIDL_GENERATOR_CPP_TRAITS
#define __ROSIDL_GENERATOR_CPP_TRAITS
template<typename T>
struct has_fixed_size : std::false_type {};
template<typename T>
struct has_bounded_size : std::false_type {};
#endif // __ROSIDL_GENERATOR_CPP_TRAITS
#include "test_msgs/srv/empty__response__struct.hpp"
template<>
struct has_fixed_size<test_msgs::srv::Empty_Response>
: std::integral_constant<bool, true>{};
template<>
struct has_bounded_size<test_msgs::srv::Empty_Response>
: std::integral_constant<bool, true>{};
} // namespace rosidl_generator_traits
#endif // TEST_MSGS__SRV__EMPTY__RESPONSE__TRAITS_HPP_ | c++ | code | 932 | 139 |
#ifndef RHIZOME_HTML_CONTAINER_HPP
#define RHIZOME_HTML_CONTAINER_HPP
#include <vector>
#include <iostream>
#include <functional>
#include "element.hpp"
#include "h1.hpp"
#include "ul.hpp"
using std::vector;
using std::ostream;
using std::function;
namespace rhizome {
namespace html {
class Container {
protected:
vector<Element *> children;
vector<Element *> clone_children() const;
public:
Container();
virtual ~Container();
void add_child( Element *e );
Element * child_at( size_t index );
void write_children( ostream &out, size_t indent ) const;
void serialize_children( ostream &out ) const;
H1 & h1( string const &title );
//P & p( string const &cdata );
UL & ul();
UL & ul( function< void (UL &) > initialize_with );
};
}
}
#endif | c++ | code | 959 | 178 |
#include <errno.h>
#include <sys/mman.h>
#include <bits/ensure.h>
#include <mlibc/debug.hpp>
#include <mlibc/sysdeps.hpp>
int mprotect(void *pointer, size_t size, int prot) {
if(!mlibc::sys_vm_protect) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_vm_protect(pointer, size, prot); e) {
errno = e;
return -1;
}
return 0;
}
int mlock(const void *, size_t) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int mlockall(int) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int munlock(const void *, size_t) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int munlockall(void) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int posix_madvise(void *, size_t, int) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int msync(void *, size_t, int) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
void *mremap(void *pointer, size_t size, size_t new_size, int flags, ...) {
__ensure(flags == MREMAP_MAYMOVE);
void *window;
if(!mlibc::sys_vm_remap) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return (void *)-1;
}
if(int e = mlibc::sys_vm_remap(pointer, size, new_size, &window); e) {
errno = e;
return (void *)-1;
}
return window;
}
int remap_file_pages(void *, size_t, int, size_t, int) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
void *mmap(void *hint, size_t size, int prot, int flags, int fd, off_t offset) {
void *window;
if(int e = mlibc::sys_vm_map(hint, size, prot, flags, fd, offset, &window); e) {
errno = e;
return (void *)-1;
}
return window;
}
int munmap(void *pointer, size_t size) {
if(int e = mlibc::sys_vm_unmap(pointer, size); e) {
errno = e;
return -1;
}
return 0;
} | c++ | code | 1,757 | 471 |
/**
* Google's Firebase QueryFilter class, QueryFilter.cpp version 1.0.1
*
* This library supports Espressif ESP8266 and ESP32
*
* Created April 30, 2021
*
* This work is a part of Firebase ESP Client library
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FIREBASE_QUERY_FILTER_CPP
#define FIREBASE_QUERY_FILTER_CPP
#include "QueryFilter.h"
QueryFilter::QueryFilter()
{
}
QueryFilter::~QueryFilter()
{
clear();
}
QueryFilter &QueryFilter::clear()
{
std::string().swap(_orderBy);
std::string().swap(_limitToFirst);
std::string().swap(_limitToLast);
std::string().swap(_startAt);
std::string().swap(_endAt);
std::string().swap(_equalTo);
return *this;
}
QueryFilter &QueryFilter::orderBy(const String &val)
{
appendP(_orderBy, fb_esp_pgm_str_3, true);
_orderBy += val.c_str();
appendP(_orderBy, fb_esp_pgm_str_3);
return *this;
}
QueryFilter &QueryFilter::limitToFirst(int val)
{
char *num = intStr(val);
_limitToFirst = num;
delS(num);
return *this;
}
QueryFilter &QueryFilter::limitToLast(int val)
{
char *num = intStr(val);
_limitToLast = num;
delS(num);
return *this;
}
QueryFilter &QueryFilter::startAt(float val)
{
char *num = floatStr(val);
_startAt = num;
delS(num);
return *this;
}
QueryFilter &QueryFilter::endAt(float val)
{
char *num = floatStr(val);
_endAt = num;
delS(num);
return *this;
}
QueryFilter &QueryFilter::startAt(const String &val)
{
appendP(_startAt, fb_esp_pgm_str_3, true);
_startAt += val.c_str();
appendP(_startAt, fb_esp_pgm_str_3);
return *this;
}
QueryFilter &QueryFilter::endAt(const String &val)
{
appendP(_endAt, fb_esp_pgm_str_3, true);
_startAt += val.c_str();
appendP(_endAt, fb_esp_pgm_str_3);
return *this;
}
QueryFilter &QueryFilter::equalTo(int val)
{
char *num = intStr(val);
_equalTo = num;
delS(num);
return *this;
}
QueryFilter &QueryFilter::equalTo(const String &val)
{
appendP(_equalTo, fb_esp_pgm_str_3, true);
_equalTo += val.c_str();
appendP(_equalTo, fb_esp_pgm_str_3);
return *this;
}
char *QueryFilter::strP(PGM_P pgm)
{
size_t len = strlen_P(pgm) + 5;
char *buf = newS(len);
strcpy_P(buf, pgm);
buf[strlen_P(pgm)] = 0;
return buf;
}
char *QueryFilter::newS(size_t len)
{
char *p = new char[len];
memset(p, 0, len);
return p;
}
void QueryFilter::appendP(std::string &buf, PGM_P p, bool empty)
{
if (empty)
buf.clear();
char *b = strP(p);
buf += b;
delS(b);
}
void QueryFilter::delS(char *p)
{
if (p != nullptr)
delete[] p;
}
char *QueryFilter::floatStr(float value)
{
char *buf = newS(36);
dtostrf(value, 7, 9, buf);
return buf;
}
char *QueryFilter::intStr(int value)
{
char *buf = newS(36);
itoa(value, buf, 10);
return buf;
}
#endif | c++ | code | 4,045 | 974 |
auto SH2::Recompiler::pool(u32 address) -> Pool* {
auto& pool = pools[address >> 8 & 0xffffff];
if(!pool) pool = (Pool*)allocator.acquire(sizeof(Pool));
return pool;
}
auto SH2::Recompiler::block(u32 address) -> Block* {
if(auto block = pool(address)->blocks[address >> 1 & 0x7f]) return block;
auto block = emit(address);
return pool(address)->blocks[address >> 1 & 0x7f] = block;
}
alwaysinline auto SH2::Recompiler::emitInstruction(u16 opcode) -> bool {
#define op(id, name, ...) \
case id: \
call(&SH2::name, &self, ##__VA_ARGS__); \
return 0;
#define br(id, name, ...) \
case id: \
call(&SH2::name, &self, ##__VA_ARGS__); \
return 1;
#include "decoder.hpp"
#undef op
#undef br
return 0;
}
auto SH2::Recompiler::emit(u32 address) -> Block* {
if(unlikely(allocator.available() < 1_MiB)) {
print("SH2 allocator flush\n");
allocator.release(bump_allocator::zero_fill);
reset();
}
auto block = (Block*)allocator.acquire(sizeof(Block));
block->code = allocator.acquire();
bind({block->code, allocator.available()});
bool hasBranched = 0;
while(true) {
u16 instruction = self.readWord(address);
bool branched = emitInstruction(instruction);
mov(rax, mem64(&self.CCR));
inc(rax);
mov(mem64(&self.CCR), rax);
call(&SH2::instructionEpilogue, &self);
address += 2;
if(hasBranched || (address & 0xfe) == 0) break; //block boundary
hasBranched = branched;
test(rax, rax);
jz(imm8(1));
ret();
}
ret();
allocator.reserve(size());
return block;
} | c++ | code | 1,580 | 461 |
// Copyright (c) 2021 PaddlePaddle 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 "core/types.h"
#include "operation/resize_nearest.h"
#include "utility/debug.h"
#include "utility/hints.h"
#include "utility/logging.h"
#include "utility/modeling.h"
#include "utility/utility.h"
namespace nnadapter {
namespace operation {
void CopyShapeDimensionTypeToOutput(core::Operand* shape_operand,
core::Operand* input_operand,
core::Operand* output_operand) {
NNAdapterOperandDimensionType shape_dims;
if (IsConstantOperand(shape_operand)) {
shape_dims.dynamic_count = 0;
if (shape_operand->type.precision == NNADAPTER_INT32) {
shape_dims.count = shape_operand->length / sizeof(int32_t);
memcpy(shape_dims.data,
shape_operand->buffer,
shape_dims.count * sizeof(int32_t));
} else if (shape_operand->type.precision == NNADAPTER_INT64) {
shape_dims.count = shape_operand->length / sizeof(int64_t);
auto shape_data = reinterpret_cast<int64_t*>(shape_operand->buffer);
for (uint32_t i = 0; i < shape_dims.count; i++) {
shape_dims.data[i] = static_cast<int32_t>(shape_data[i]);
}
} else {
NNADAPTER_LOG(FATAL) << "Unsupported precision: "
<< OperandPrecisionCodeToString(
shape_operand->type.precision);
}
} else if (IsTemporaryShapeOperand(shape_operand)) {
auto& temporary_shape = *(GetTemporaryShape(shape_operand));
NNADAPTER_CHECK(temporary_shape.data);
NNADAPTER_CHECK(temporary_shape.data[0]);
memcpy(
&shape_dims, &temporary_shape, sizeof(NNAdapterOperandDimensionType));
} else {
NNADAPTER_LOG(FATAL) << "Unsupported shape lifetime: "
<< OperandLifetimeCodeToString(
shape_operand->type.lifetime);
}
memcpy(output_operand->type.dimensions.data + 2,
shape_dims.data,
shape_dims.count * sizeof(int32_t));
for (uint32_t i = 0; i < input_operand->type.dimensions.dynamic_count; i++) {
if (shape_dims.dynamic_count > 0) {
memcpy(output_operand->type.dimensions.dynamic_data[i] + 2,
shape_dims.dynamic_data[i],
shape_dims.count * sizeof(int32_t));
} else {
memcpy(output_operand->type.dimensions.dynamic_data[i] + 2,
shape_dims.data,
shape_dims.count * sizeof(int32_t));
}
}
}
bool ValidateResize(const core::Operation* operation) { return false; }
int PrepareResize(core::Operation* operation) {
auto& input_operands = operation->input_operands;
auto& output_operands = operation->output_operands;
auto input_count = input_operands.size();
auto output_count = output_operands.size();
NNADAPTER_CHECK_GE(input_count, 4);
NNADAPTER_CHECK_EQ(output_count, 1);
/* Input */
auto input_operand = input_operands[0];
NNADAPTER_VLOG(5) << "input: " << OperandToString(input_operand);
/* Shape */
auto shape_operand = input_operands[1];
if (shape_operand == nullptr) {
NNADAPTER_VLOG(5) << "Shape is null, please use scales.";
} else {
NNADAPTER_VLOG(5) << "shape: " << OperandToString(shape_operand);
}
/* Scales */
auto scales_operand = input_operands[2];
if (scales_operand == nullptr) {
NNADAPTER_VLOG(5) << "Scales is null, please use shape.";
} else {
NNADAPTER_VLOG(5) << "scales: " << OperandToString(scales_operand);
}
NNADAPTER_CHECK(shape_operand != nullptr || scales_operand != nullptr)
<< "shape_operand and scales_operand should not both be null.";
/* Output */
auto* output_operand = output_operands[0];
NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
// Infer the shape and type of output operands
CopyOperandTypeExceptQuantParams(&output_operand->type, input_operand->type);
if (scales_operand != nullptr) {
std::vector<float> scales;
if (IsConstantOperand(scales_operand)) {
auto scales_size = scales_operand->length / sizeof(float);
scales.resize(scales_size);
memcpy(scales.data(), scales_operand->buffer, scales_operand->length);
} else {
NNADAPTER_LOG(FATAL) << "Unsupported scales lifetime: "
<< OperandLifetimeCodeToString(
scales_operand->type.lifetime);
}
if (scales[0] > 0 && scales[1] > 0) {
auto infer_output_shape = [&](int32_t* input_dimensions,
int32_t* output_dimensions) {
for (size_t i = 0; i < scales.size(); i++) {
output_dimensions[i + 2] =
input_dimensions[i + 2] == NNADAPTER_UNKNOWN
? NNADAPTER_UNKNOWN
: static_cast<int32_t>(
static_cast<float>(input_dimensions[i + 2]) *
scales[i]);
}
};
infer_output_shape(input_operand->type.dimensions.data,
output_operand->type.dimensions.data);
for (uint32_t i = 0; i < input_operand->type.dimensions.dynamic_count;
i++) {
infer_output_shape(input_operand->type.dimensions.dynamic_data[i],
output_operand->type.dimensions.dynamic_data[i]);
}
} else {
CopyShapeDimensionTypeToOutput(
shape_operand, input_operand, output_operand);
}
} else {
CopyShapeDimensionTypeToOutput(
shape_operand, input_operand, output_operand);
}
output_operand->type.lifetime = NNADAPTER_TEMPORARY_VARIABLE;
NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
return NNADAPTER_NO_ERROR;
}
int ExecuteResize(core::Operation* operation) {
return NNADAPTER_FEATURE_NOT_SUPPORTED;
}
} // namespace operation
} // namespace nnadapter | c++ | code | 6,372 | 1,216 |
#include "core/modules/codegen/codegen-x64.h"
namespace zz {
namespace x64 {
void CodeGen::JmpBranch(addr_t address) {
TurboAssembler *turbo_assembler_ = reinterpret_cast<TurboAssembler *>(this->assembler_);
#define _ turbo_assembler_->
#define __ turbo_assembler_->GetCodeBuffer()->
dword offset = (dword)(address - turbo_assembler_->CurrentIP());
// RIP-relative addressing
__ Emit8(0xFF);
__ Emit8(0x25);
__ Emit32(0x0);
__ Emit64(address);
}
} // namespace x64
} // namespace zz | c++ | code | 505 | 102 |
/*
* (C) Copyright 2020 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/filters/obsfunctions/SymmCldImpactIR.h"
#include <algorithm>
#include <cmath>
#include <set>
#include <string>
#include <vector>
#include "ioda/ObsDataVector.h"
#include "oops/util/IntSetParser.h"
#include "oops/util/missingValues.h"
#include "ufo/filters/Variable.h"
#include "ufo/utils/Constants.h"
namespace ufo {
static ObsFunctionMaker<SymmCldImpactIR> makerSCIIR_("SymmCldImpactIR");
// -----------------------------------------------------------------------------
SymmCldImpactIR::SymmCldImpactIR(const eckit::LocalConfiguration config)
: invars_(), channels_() {
// Initialize options
options_.deserialize(config);
// Get channels from options
std::string chlist = options_.chlist;
std::set<int> channelset = oops::parseIntSet(chlist);
std::copy(channelset.begin(), channelset.end(), std::back_inserter(channels_));
// Include required variables from ObsDiag
invars_ += Variable("brightness_temperature_assuming_clear_sky@ObsDiag", channels_);
}
// -----------------------------------------------------------------------------
SymmCldImpactIR::~SymmCldImpactIR() {}
// -----------------------------------------------------------------------------
void SymmCldImpactIR::compute(const ObsFilterData & in,
ioda::ObsDataVector<float> & SCI) const {
const float missing = util::missingValue(missing);
// Get dimensions
size_t nlocs = in.nlocs();
// Allocate vectors common across channels
std::vector<float> clr(nlocs);
std::vector<float> bak(nlocs);
std::vector<float> obs(nlocs);
std::vector<float> bias(nlocs);
float Cmod, Cobs;
for (size_t ich = 0; ich < SCI.nvars(); ++ich) {
// Get channel-specific clr, bak, obs, and bias
in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag", channels_)[ich], clr);
in.get(Variable("brightness_temperature@HofX", channels_)[ich], bak);
in.get(Variable("brightness_temperature@ObsValue", channels_)[ich], obs);
if (in.has(Variable("brightness_temperature@ObsBiasData", channels_)[ich])) {
in.get(Variable("brightness_temperature@ObsBiasData", channels_)[ich], bias);
} else {
std::fill(bias.begin(), bias.end(), 0.0f);
}
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
if (clr[iloc] != missing && bak[iloc] != missing &&
obs[iloc] != missing && bias[iloc] != missing) {
// Temporarily account for ZERO clear-sky BT output from CRTM
// TODO(JJG): change CRTM clear-sky behavior
if (clr[iloc] > -1.0f && clr[iloc] < 1.0f) clr[iloc] = bak[iloc];
// HofX contains bias correction; subtracting it here
Cmod = std::abs(clr[iloc] - bak[iloc] + bias[iloc]);
Cobs = std::abs(clr[iloc] - obs[iloc] + bias[iloc]);
SCI[ich][iloc] = 0.5f * (Cmod + Cobs);
} else {
SCI[ich][iloc] = missing;
}
}
}
}
// -----------------------------------------------------------------------------
const ufo::Variables & SymmCldImpactIR::requiredVariables() const {
return invars_;
}
// -----------------------------------------------------------------------------
} // namespace ufo | c++ | code | 3,349 | 903 |
#include "catch.hpp"
#include "QuEST.h"
#include "utilities.hpp"
#include <random>
/** Prepares a density matrix in the debug state, and the reference QMatrix
*/
#define PREPARE_TEST(qureg, ref) \
Qureg qureg = createDensityQureg(NUM_QUBITS, QUEST_ENV); \
initDebugState(qureg); \
QMatrix ref = toQMatrix(qureg);
/* allows concise use of Contains in catch's REQUIRE_THROWS_WITH */
using Catch::Matchers::Contains;
/** @sa mixDamping
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixDamping", "[decoherence]" ) {
PREPARE_TEST(qureg, ref);
SECTION( "correctness" ) {
int target = GENERATE( range(0,NUM_QUBITS) );
qreal prob = getRandomReal(0, 1);
mixDamping(qureg, target, prob);
// ref -> kraus0 ref kraus0^dagger + kraus1 ref kraus1^dagger
QMatrix kraus0{{1,0},{0,sqrt(1-prob)}};
QMatrix rho0 = ref;
applyReferenceOp(rho0, target, kraus0);
QMatrix kraus1{{0,sqrt(prob)},{0,0}};
QMatrix rho1 = ref;
applyReferenceOp(rho1, target, kraus1);
ref = rho0 + rho1;
REQUIRE( areEqual(qureg, ref) );
}
SECTION( "validation ") {
SECTION( "qubit index" ) {
int target = GENERATE( -1, NUM_QUBITS );
REQUIRE_THROWS_WITH( mixDamping(qureg, target, 0), Contains("Invalid target") );
}
SECTION( "probability" ) {
REQUIRE_THROWS_WITH( mixDamping(qureg, 0, -.1), Contains("Probabilities") );
REQUIRE_THROWS_WITH( mixDamping(qureg, 0, 1.1), Contains("Probabilities") );
}
SECTION( "density-matrix" ) {
Qureg vec = createQureg(NUM_QUBITS, QUEST_ENV);
REQUIRE_THROWS_WITH( mixDamping(vec, 0, 0), Contains("density matrices") );
destroyQureg(vec, QUEST_ENV);
}
}
destroyQureg(qureg, QUEST_ENV);
}
/** @sa mixDensityMatrix
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixDensityMatrix", "[decoherence]" ) {
Qureg qureg1 = createDensityQureg(NUM_QUBITS, QUEST_ENV);
Qureg qureg2 = createDensityQureg(NUM_QUBITS, QUEST_ENV);
initDebugState(qureg1);
initDebugState(qureg2);
QMatrix ref1 = toQMatrix(qureg1);
QMatrix ref2 = toQMatrix(qureg2);
SECTION( "correctness" ) {
// test p in {0, 1} and 10 random values in (0,1)
qreal prob = GENERATE( 0., 1., take(10, random(0.,1.)) );
mixDensityMatrix(qureg1, prob, qureg2);
// ensure target qureg modified correctly
ref1 = (1-prob)*ref1 + (prob)*ref2;
REQUIRE( areEqual(qureg1, ref1) );
// enure other qureg was not modified
REQUIRE( areEqual(qureg2, ref2) );
}
SECTION( "input validation" ) {
SECTION( "probabilities") {
qreal prob = GENERATE( -0.1, 1.1 );
REQUIRE_THROWS_WITH( mixDensityMatrix(qureg1, prob, qureg2), Contains("Probabilities") );
}
SECTION( "density matrices" ) {
// one is statevec
Qureg state1 = createQureg(qureg1.numQubitsRepresented, QUEST_ENV);
REQUIRE_THROWS_WITH( mixDensityMatrix(qureg1, 0, state1), Contains("density matrices") );
REQUIRE_THROWS_WITH( mixDensityMatrix(state1, 0, qureg1), Contains("density matrices") );
// both are statevec
Qureg state2 = createQureg(qureg1.numQubitsRepresented, QUEST_ENV);
REQUIRE_THROWS_WITH( mixDensityMatrix(state1, 0, state2), Contains("density matrices") );
destroyQureg(state1, QUEST_ENV);
destroyQureg(state2, QUEST_ENV);
}
SECTION( "matching dimensions" ) {
Qureg qureg3 = createDensityQureg(1 + qureg1.numQubitsRepresented, QUEST_ENV);
REQUIRE_THROWS_WITH( mixDensityMatrix(qureg1, 0, qureg3), Contains("Dimensions") );
REQUIRE_THROWS_WITH( mixDensityMatrix(qureg3, 0, qureg1), Contains("Dimensions") );
destroyQureg(qureg3, QUEST_ENV);
}
}
destroyQureg(qureg1, QUEST_ENV);
destroyQureg(qureg2, QUEST_ENV);
}
/** @sa mixDephasing
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixDephasing", "[decoherence]" ) {
PREPARE_TEST(qureg, ref);
SECTION( "correctness " ) {
int target = GENERATE( range(0,NUM_QUBITS) );
qreal prob = getRandomReal(0, 1/2.);
mixDephasing(qureg, target, prob);
// ref -> (1 - prob) ref + prob Z ref Z
QMatrix phaseRef = ref;
applyReferenceOp(phaseRef, target, QMatrix{{1,0},{0,-1}}); // Z ref Z
ref = ((1 - prob) * ref) + (prob * phaseRef);
REQUIRE( areEqual(qureg, ref) );
}
SECTION( "validation ") {
SECTION( "qubit index" ) {
int target = GENERATE( -1, NUM_QUBITS );
REQUIRE_THROWS_WITH( mixDephasing(qureg, target, 0), Contains("Invalid target") );
}
SECTION( "probability" ) {
REQUIRE_THROWS_WITH( mixDephasing(qureg, 0, -.1), Contains("Probabilities") );
REQUIRE_THROWS_WITH( mixDephasing(qureg, 0, .6), Contains("probability") && Contains("cannot exceed 1/2") );
}
SECTION( "density-matrix" ) {
Qureg vec = createQureg(NUM_QUBITS, QUEST_ENV);
REQUIRE_THROWS_WITH( mixDephasing(vec, 0, 0), Contains("density matrices") );
destroyQureg(vec, QUEST_ENV);
}
}
destroyQureg(qureg, QUEST_ENV);
}
/** @sa mixDepolarising
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixDepolarising", "[decoherence]" ) {
PREPARE_TEST(qureg, ref);
SECTION( "correctness " ) {
int target = GENERATE( range(0,NUM_QUBITS) );
qreal prob = getRandomReal(0, 3/4.);
mixDepolarising(qureg, target, prob);
QMatrix xRef = ref;
applyReferenceOp(xRef, target, QMatrix{{0,1},{1,0}}); // X ref X
QMatrix yRef = ref;
applyReferenceOp(yRef, target, QMatrix{{0,-qcomp(0,1)},{qcomp(0,1),0}}); // Y ref Y
QMatrix zRef = ref;
applyReferenceOp(zRef, target, QMatrix{{1,0},{0,-1}}); // Z ref Z
ref = ((1 - prob) * ref) + ((prob/3.) * ( xRef + yRef + zRef));
REQUIRE( areEqual(qureg, ref) );
}
SECTION( "validation ") {
SECTION( "qubit index" ) {
int target = GENERATE( -1, NUM_QUBITS );
REQUIRE_THROWS_WITH( mixDepolarising(qureg, target, 0), Contains("Invalid target") );
}
SECTION( "probability" ) {
REQUIRE_THROWS_WITH( mixDepolarising(qureg, 0, -.1), Contains("Probabilities") );
REQUIRE_THROWS_WITH( mixDepolarising(qureg, 0, .76), Contains("probability") && Contains("cannot exceed 3/4") );
}
SECTION( "density-matrix" ) {
Qureg vec = createQureg(NUM_QUBITS, QUEST_ENV);
REQUIRE_THROWS_WITH( mixDepolarising(vec, 0, 0), Contains("density matrices") );
destroyQureg(vec, QUEST_ENV);
}
}
destroyQureg(qureg, QUEST_ENV);
}
/** @sa mixMultiQubitKrausMap
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixMultiQubitKrausMap", "[decoherence]" ) {
PREPARE_TEST(qureg, ref);
// figure out max-num (inclusive) targs allowed by hardware backend
// (each node must contain as 2^(2*numTargs) amps)
int maxNumTargs = calcLog2(qureg.numAmpsPerChunk) / 2;
SECTION( "correctness" ) {
/* note that this function incurs a stack overhead when numTargs < 4,
* and a heap overhead when numTargs >= 4
*/
int numTargs = GENERATE_COPY( range(1,maxNumTargs+1) ); // inclusive upper bound
// note this is very expensive to try every arrangement (2 min runtime for numTargs=5 alone)
int* targs = GENERATE_COPY( sublists(range(0,NUM_QUBITS), numTargs) );
// try the min and max number of operators, and 2 random numbers
// (there are way too many to try all!)
int maxNumOps = (2*numTargs)*(2*numTargs);
int numOps = GENERATE_COPY( 1, maxNumOps, take(2,random(1,maxNumOps)) );
// use a new random map
std::vector<QMatrix> matrs = getRandomKrausMap(numTargs, numOps);
// create map in QuEST datatypes
ComplexMatrixN ops[numOps];
for (int i=0; i<numOps; i++) {
ops[i] = createComplexMatrixN(numTargs);
toComplexMatrixN(matrs[i], ops[i]);
}
mixMultiQubitKrausMap(qureg, targs, numTargs, ops, numOps);
// set ref -> K_i ref K_i^dagger
QMatrix matrRefs[numOps];
for (int i=0; i<numOps; i++) {
matrRefs[i] = ref;
applyReferenceOp(matrRefs[i], targs, numTargs, matrs[i]);
}
ref = getZeroMatrix(ref.size());
for (int i=0; i<numOps; i++)
ref += matrRefs[i];
REQUIRE( areEqual(qureg, ref, 1E2*REAL_EPS) );
// cleanup QuEST datatypes
for (int i=0; i<numOps; i++)
destroyComplexMatrixN(ops[i]);
}
SECTION( "input validation" ) {
SECTION( "repetition of target" ) {
// make valid targets
int targs[NUM_QUBITS];
for (int i=0; i<NUM_QUBITS; i++)
targs[i] = i;
// duplicate one
int badInd = GENERATE( range(0,NUM_QUBITS) );
int copyInd = GENERATE_COPY( filter([=](int i){ return i!=badInd; }, range(0,NUM_QUBITS)) );
targs[badInd] = targs[copyInd];
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, NUM_QUBITS, NULL, 1), Contains("target qubits") && Contains("unique") );
}
SECTION( "qubit indices" ) {
// make valid targets
int targs[NUM_QUBITS];
for (int i=0; i<NUM_QUBITS; i++)
targs[i] = i;
// make one invalid
targs[GENERATE( range(0,NUM_QUBITS) )] = GENERATE( -1, NUM_QUBITS );
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, NUM_QUBITS, NULL, 1), Contains("Invalid target qubit") );
}
SECTION( "number of operators" ) {
int numTargs = GENERATE_COPY( range(1,maxNumTargs+1) );
int maxNumOps = (2*numTargs)*(2*numTargs);
int numOps = GENERATE_REF( -1, 0, maxNumOps + 1 );
// make valid targets to avoid triggering target validation
int targs[numTargs];
for (int i=0; i<numTargs; i++)
targs[i] = i;
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, numTargs, NULL, numOps), Contains("operators may be specified") );
}
SECTION( "initialisation of operators" ) {
/* compilers don't auto-initialise to NULL; the below circumstance
* only really occurs when 'malloc' returns NULL in createComplexMatrixN,
* which actually triggers its own validation. Hence this test is useless
* currently.
*/
int numTargs = NUM_QUBITS;
int numOps = (2*numTargs)*(2*numTargs);
// no need to initialise ops, but set their attribs correct to avoid triggering other validation
ComplexMatrixN ops[numOps];
for (int i=0; i<numOps; i++)
ops[i].numQubits = numTargs;
// make one of the max-ops explicitly NULL
ops[GENERATE_COPY( range(0,numTargs) )].real = NULL;
// make valid targets to avoid triggering target validation
int targs[numTargs];
for (int i=0; i<numTargs; i++)
targs[i] = i;
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, numTargs, ops, numOps), Contains("ComplexMatrixN") && Contains("created") );
}
SECTION( "dimension of operators" ) {
// make valid (dimension-wise) max-qubits Kraus map
int numTargs = NUM_QUBITS;
int numOps = (2*numTargs)*(2*numTargs);
ComplexMatrixN ops[numOps];
for (int i=0; i<numOps; i++)
ops[i] = createComplexMatrixN(numTargs);
// make one have wrong-dimensions
int badInd = GENERATE_COPY( range(0,numTargs) );
destroyComplexMatrixN(ops[badInd]);
ops[badInd] = createComplexMatrixN(numTargs - 1);
// make valid targets to avoid triggering target validation
int targs[numTargs];
for (int i=0; i<numTargs; i++)
targs[i] = i;
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, numTargs, ops, numOps), Contains("same number of qubits") );
for (int i=0; i<numOps; i++)
destroyComplexMatrixN(ops[i]);
}
SECTION( "trace preserving" ) {
int numTargs = GENERATE_COPY( range(1,maxNumTargs+1) );
int maxNumOps = (2*numTargs) * (2*numTargs);
int numOps = GENERATE_COPY( 1, 2, maxNumOps );
// generate a valid map
std::vector<QMatrix> matrs = getRandomKrausMap(numTargs, numOps);
ComplexMatrixN ops[numOps];
for (int i=0; i<numOps; i++) {
ops[i] = createComplexMatrixN(numTargs);
toComplexMatrixN(matrs[i], ops[i]);
}
// make only one invalid
ops[GENERATE_REF( range(0,numOps) )].real[0][0] = 0;
// make valid targets to avoid triggering target validation
int targs[numTargs];
for (int i=0; i<numTargs; i++)
targs[i] = i;
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, numTargs, ops, numOps), Contains("trace preserving") );
for (int i=0; i<numOps; i++)
destroyComplexMatrixN(ops[i]);
}
SECTION( "density-matrix" ) {
Qureg statevec = createQureg(NUM_QUBITS, QUEST_ENV);
// make valid targets to avoid triggering target validation
int targs[NUM_QUBITS];
for (int i=0; i<NUM_QUBITS; i++)
targs[i] = i;
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(statevec, targs, NUM_QUBITS, NULL, 1), Contains("valid only for density matrices") );
destroyQureg(statevec, QUEST_ENV);
}
SECTION( "operator fits in node" ) {
// each node requires (2 numTargs)^2 amplitudes
int minAmps = (2*NUM_QUBITS) * (2*NUM_QUBITS);
// make valid targets to avoid triggering target validation
int targs[NUM_QUBITS];
for (int i=0; i<NUM_QUBITS; i++)
targs[i] = i;
// make a simple Identity map
ComplexMatrixN ops[] = {createComplexMatrixN(NUM_QUBITS)};
for (int i=0; i<(1<<NUM_QUBITS); i++)
ops[0].real[i][i] = 1;
// fake a smaller qureg
qureg.numAmpsPerChunk = minAmps - 1;
REQUIRE_THROWS_WITH( mixMultiQubitKrausMap(qureg, targs, NUM_QUBITS, ops, 1), Contains("targets too many qubits") && Contains("cannot all fit") );
destroyComplexMatrixN(ops[0]);
}
}
destroyQureg(qureg, QUEST_ENV);
}
/** @sa mixPauli
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixPauli", "[decoherence]" ) {
PREPARE_TEST(qureg, ref);
SECTION( "correctness" ) {
int target = GENERATE( range(0,NUM_QUBITS) );
// randomly generate valid pauli-error probabilities
qreal probs[3];
qreal max0 = 1/2.; // satisfies p1 < 1 - py
probs[0] = getRandomReal(0, max0);
qreal max1 = (max0 - probs[0])/2.; // p2 can use half of p1's "unused space"
probs[1] = getRandomReal(0, max1);
qreal max2 = (max1 - probs[1])/2.; // p3 can use half of p2's "unused space"
probs[2] = getRandomReal(0, max2);
// uniformly randomly assign probs (bound to target)
int inds[3] = {0,1,2};
std::shuffle(inds,inds+3, std::default_random_engine(1E5 * target));
qreal probX = probs[inds[0]]; // seed:target shows no variation
qreal probY = probs[inds[1]];
qreal probZ = probs[inds[2]];
mixPauli(qureg, target, probX, probY, probZ);
QMatrix xRef = ref;
applyReferenceOp(xRef, target, QMatrix{{0,1},{1,0}}); // X ref X
QMatrix yRef = ref;
applyReferenceOp(yRef, target, QMatrix{{0,-qcomp(0,1)},{qcomp(0,1),0}}); // Y ref Y
QMatrix zRef = ref;
applyReferenceOp(zRef, target, QMatrix{{1,0},{0,-1}}); // Z ref Z
ref = ((1 - probX - probY - probZ) * ref) +
(probX * xRef) + (probY * yRef) + (probZ * zRef);
REQUIRE( areEqual(qureg, ref) );
}
SECTION( "input validation" ) {
SECTION( "qubit index" ) {
int target = GENERATE( -1, NUM_QUBITS );
REQUIRE_THROWS_WITH( mixPauli(qureg, target, 0, 0, 0), Contains("Invalid target") );
}
SECTION( "probability" ) {
int target = 0;
// probs clearly must be in [0, 1]
REQUIRE_THROWS_WITH( mixPauli(qureg, target, -.1, 0, 0), Contains("Probabilities") );
REQUIRE_THROWS_WITH( mixPauli(qureg, target, 0, -.1, 0), Contains("Probabilities") );
REQUIRE_THROWS_WITH( mixPauli(qureg, target, 0, 0, -.1), Contains("Probabilities") );
// max single-non-zero-prob is 0.5
REQUIRE_THROWS_WITH( mixPauli(qureg, target, .6, 0, 0), Contains("cannot exceed the probability") );
REQUIRE_THROWS_WITH( mixPauli(qureg, target, 0, .6, 0), Contains("cannot exceed the probability") );
REQUIRE_THROWS_WITH( mixPauli(qureg, target, 0, 0, .6), Contains("cannot exceed the probability") );
// must satisfy px, py, pz < 1 - px - py - pz
REQUIRE_THROWS_WITH( mixPauli(qureg, target, .3, .3, .3), Contains("cannot exceed the probability") );
}
SECTION( "density-matrix" ) {
Qureg vec = createQureg(NUM_QUBITS, QUEST_ENV);
REQUIRE_THROWS_WITH( mixPauli(vec, 0, 0, 0, 0), Contains("density matrices") );
destroyQureg(vec, QUEST_ENV);
}
}
destroyQureg(qureg, QUEST_ENV);
}
/** @sa mixKrausMap
* @ingroup unittest
* @author Tyson Jones
*/
TEST_CASE( "mixKrausMap", "[decoherence]" ) {
PREPARE_TEST(qureg, ref);
SECTION( "correctness" ) {
int target = GENERATE( range(0,NUM_QUBITS) );
int numOps = GENERATE( range(1,5) ); // max 4 inclusive
std::vector<QMatrix> matrs = getRandomKrausMap(1, numOps);
ComplexMatrix2 ops[numOps];
for (int i=0; i<numOps; i++)
ops[i] = toComplexMatrix2(matrs[i]);
mixKrausMap(qureg, target, ops, numOps);
// set ref -> K_i ref K_i^dagger
QMatrix matrRefs[numOps];
for (int i=0; i<numOps; i++) {
matrRefs[i] = ref;
applyReferenceOp(matrRefs[i], target, mat | c++ | code | 20,000 | 4,169 |
//===- PPCBoolRetToInt.cpp - Convert bool literals to i32 if they are returned ==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements converting i1 values to i32 if they could be more
// profitably allocated as GPRs rather than CRs. This pass will become totally
// unnecessary if Register Bank Allocation and Global Instruction Selection ever
// go upstream.
//
// Presently, the pass converts i1 Constants, and Arguments to i32 if the
// transitive closure of their uses includes only PHINodes, CallInsts, and
// ReturnInsts. The rational is that arguments are generally passed and returned
// in GPRs rather than CRs, so casting them to i32 at the LLVM IR level will
// actually save casts at the Machine Instruction level.
//
// It might be useful to expand this pass to add bit-wise operations to the list
// of safe transitive closure types. Also, we miss some opportunities when LLVM
// represents logical AND and OR operations with control flow rather than data
// flow. For example by lowering the expression: return (A && B && C)
//
// as: return A ? true : B && C.
//
// There's code in SimplifyCFG that code be used to turn control flow in data
// flow using SelectInsts. Selects are slow on some architectures (P7/P8), so
// this probably isn't good in general, but for the special case of i1, the
// Selects could be further lowered to bit operations that are fast everywhere.
//
//===----------------------------------------------------------------------===//
#include "PPC.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Pass.h"
using namespace llvm;
namespace {
#define DEBUG_TYPE "bool-ret-to-int"
STATISTIC(NumBoolRetPromotion,
"Number of times a bool feeding a RetInst was promoted to an int");
STATISTIC(NumBoolCallPromotion,
"Number of times a bool feeding a CallInst was promoted to an int");
STATISTIC(NumBoolToIntPromotion,
"Total number of times a bool was promoted to an int");
class PPCBoolRetToInt : public FunctionPass {
static SmallPtrSet<Value *, 8> findAllDefs(Value *V) {
SmallPtrSet<Value *, 8> Defs;
SmallVector<Value *, 8> WorkList;
WorkList.push_back(V);
Defs.insert(V);
while (!WorkList.empty()) {
Value *Curr = WorkList.back();
WorkList.pop_back();
if (User *CurrUser = dyn_cast<User>(Curr))
for (auto &Op : CurrUser->operands())
if (Defs.insert(Op).second)
WorkList.push_back(Op);
}
return Defs;
}
// Translate a i1 value to an equivalent i32 value:
static Value *translate(Value *V) {
Type *Int32Ty = Type::getInt32Ty(V->getContext());
if (Constant *C = dyn_cast<Constant>(V))
return ConstantExpr::getZExt(C, Int32Ty);
if (PHINode *P = dyn_cast<PHINode>(V)) {
// Temporarily set the operands to 0. We'll fix this later in
// runOnUse.
Value *Zero = Constant::getNullValue(Int32Ty);
PHINode *Q =
PHINode::Create(Int32Ty, P->getNumIncomingValues(), P->getName(), P);
for (unsigned i = 0; i < P->getNumOperands(); ++i)
Q->addIncoming(Zero, P->getIncomingBlock(i));
return Q;
}
Argument *A = dyn_cast<Argument>(V);
Instruction *I = dyn_cast<Instruction>(V);
assert((A || I) && "Unknown value type");
auto InstPt =
A ? &*A->getParent()->getEntryBlock().begin() : I->getNextNode();
return new ZExtInst(V, Int32Ty, "", InstPt);
}
typedef SmallPtrSet<const PHINode *, 8> PHINodeSet;
// A PHINode is Promotable if:
// 1. Its type is i1 AND
// 2. All of its uses are ReturnInt, CallInst, PHINode, or DbgInfoIntrinsic
// AND
// 3. All of its operands are Constant or Argument or
// CallInst or PHINode AND
// 4. All of its PHINode uses are Promotable AND
// 5. All of its PHINode operands are Promotable
static PHINodeSet getPromotablePHINodes(const Function &F) {
PHINodeSet Promotable;
// Condition 1
for (auto &BB : F)
for (auto &I : BB)
if (const PHINode *P = dyn_cast<PHINode>(&I))
if (P->getType()->isIntegerTy(1))
Promotable.insert(P);
SmallVector<const PHINode *, 8> ToRemove;
for (const auto &P : Promotable) {
// Condition 2 and 3
auto IsValidUser = [] (const Value *V) -> bool {
return isa<ReturnInst>(V) || isa<CallInst>(V) || isa<PHINode>(V) ||
isa<DbgInfoIntrinsic>(V);
};
auto IsValidOperand = [] (const Value *V) -> bool {
return isa<Constant>(V) || isa<Argument>(V) || isa<CallInst>(V) ||
isa<PHINode>(V);
};
const auto &Users = P->users();
const auto &Operands = P->operands();
if (!std::all_of(Users.begin(), Users.end(), IsValidUser) ||
!std::all_of(Operands.begin(), Operands.end(), IsValidOperand))
ToRemove.push_back(P);
}
// Iterate to convergence
auto IsPromotable = [&Promotable] (const Value *V) -> bool {
const PHINode *Phi = dyn_cast<PHINode>(V);
return !Phi || Promotable.count(Phi);
};
while (!ToRemove.empty()) {
for (auto &User : ToRemove)
Promotable.erase(User);
ToRemove.clear();
for (const auto &P : Promotable) {
// Condition 4 and 5
const auto &Users = P->users();
const auto &Operands = P->operands();
if (!std::all_of(Users.begin(), Users.end(), IsPromotable) ||
!std::all_of(Operands.begin(), Operands.end(), IsPromotable))
ToRemove.push_back(P);
}
}
return Promotable;
}
typedef DenseMap<Value *, Value *> B2IMap;
public:
static char ID;
PPCBoolRetToInt() : FunctionPass(ID) {
initializePPCBoolRetToIntPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) {
PHINodeSet PromotablePHINodes = getPromotablePHINodes(F);
B2IMap Bool2IntMap;
bool Changed = false;
for (auto &BB : F) {
for (auto &I : BB) {
if (ReturnInst *R = dyn_cast<ReturnInst>(&I))
if (F.getReturnType()->isIntegerTy(1))
Changed |=
runOnUse(R->getOperandUse(0), PromotablePHINodes, Bool2IntMap);
if (CallInst *CI = dyn_cast<CallInst>(&I))
for (auto &U : CI->operands())
if (U->getType()->isIntegerTy(1))
Changed |= runOnUse(U, PromotablePHINodes, Bool2IntMap);
}
}
return Changed;
}
static bool runOnUse(Use &U, const PHINodeSet &PromotablePHINodes,
B2IMap &BoolToIntMap) {
auto Defs = findAllDefs(U);
// If the values are all Constants or Arguments, don't bother
if (!std::any_of(Defs.begin(), Defs.end(), isa<Instruction, Value *>))
return false;
// Presently, we only know how to handle PHINode, Constant, and Arguments.
// Potentially, bitwise operations (AND, OR, XOR, NOT) and sign extension
// could also be handled in the future.
for (const auto &V : Defs)
if (!isa<PHINode>(V) && !isa<Constant>(V) && !isa<Argument>(V))
return false;
for (const auto &V : Defs)
if (const PHINode *P = dyn_cast<PHINode>(V))
if (!PromotablePHINodes.count(P))
return false;
if (isa<ReturnInst>(U.getUser()))
++NumBoolRetPromotion;
if (isa<CallInst>(U.getUser()))
++NumBoolCallPromotion;
++NumBoolToIntPromotion;
for (const auto &V : Defs)
if (!BoolToIntMap.count(V))
BoolToIntMap[V] = translate(V);
// Replace the operands of the translated instructions. There were set to
// zero in the translate function.
for (auto &Pair : BoolToIntMap) {
User *First = dyn_cast<User>(Pair.first);
User *Second = dyn_cast<User>(Pair.second);
assert((!First || Second) && "translated from user to non-user!?");
if (First)
for (unsigned i = 0; i < First->getNumOperands(); ++i)
Second->setOperand(i, BoolToIntMap[First->getOperand(i)]);
}
Value *IntRetVal = BoolToIntMap[U];
Type *Int1Ty = Type::getInt1Ty(U->getContext());
Instruction *I = cast<Instruction>(U.getUser());
Value *BackToBool = new TruncInst(IntRetVal, Int1Ty, "backToBool", I);
U.set(BackToBool);
return true;
}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<DominatorTreeWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
};
}
char PPCBoolRetToInt::ID = 0;
INITIALIZE_PASS(PPCBoolRetToInt, "bool-ret-to-int",
"Convert i1 constants to i32 if they are returned",
false, false)
FunctionPass *llvm::createPPCBoolRetToIntPass() { return new PPCBoolRetToInt(); } | c++ | code | 9,019 | 2,145 |
#include "stdafx.h"
#include "poltergeist.h"
#include "../../../PhysicsShell.h"
#include "../../../level.h"
#include "../../../material_manager.h"
#include "../../../level_debug.h"
CPolterSpecialAbility::CPolterSpecialAbility(CPoltergeist *polter)
{
m_object = polter;
m_particles_object = 0;
m_particles_object_electro = 0;
}
CPolterSpecialAbility::~CPolterSpecialAbility()
{
CParticlesObject::Destroy (m_particles_object);
CParticlesObject::Destroy (m_particles_object_electro);
}
void CPolterSpecialAbility::load(LPCSTR section)
{
m_particles_hidden = pSettings->r_string(section,"Particles_Hidden");
m_particles_damage = pSettings->r_string(section,"Particles_Damage");
m_particles_death = pSettings->r_string(section,"Particles_Death");
m_particles_idle = pSettings->r_string(section,"Particles_Idle");
m_sound_base.create (pSettings->r_string(section,"Sound_Idle"), st_Effect, SOUND_TYPE_MONSTER_TALKING);
m_last_hit_frame = 0;
}
void CPolterSpecialAbility::update_schedule()
{
if ( m_object->g_Alive() && m_object->is_hidden() ) {
if (!m_sound_base._feedback()) m_sound_base.play_at_pos(m_object, m_object->Position());
else m_sound_base.set_position(m_object->Position());
}
}
void CPolterSpecialAbility::on_hide()
{
VERIFY(m_particles_object == 0);
if (!m_object->g_Alive())
return;
Fvector center;
m_object->Center( center );
m_particles_object = m_object->PlayParticles( m_particles_hidden, center, Fvector().set( 0.f, 0.1f, 0.f ), false );
m_particles_object_electro = m_object->PlayParticles( m_particles_idle, center, Fvector().set( 0.f, 0.1f, 0.f ), false );
}
void CPolterSpecialAbility::on_show()
{
if (m_particles_object) CParticlesObject::Destroy(m_particles_object);
if (m_particles_object_electro) CParticlesObject::Destroy(m_particles_object_electro);
m_sound_base.stop();
}
void CPolterSpecialAbility::update_frame()
{
Fvector center;
m_object->Center( center );
Fmatrix xform = m_object->XFORM();
xform.translate_over( center );
if ( m_particles_object ) m_particles_object->SetXFORM( xform );
if ( m_particles_object_electro ) m_particles_object_electro->SetXFORM( xform );
}
void CPolterSpecialAbility::on_die()
{
Fvector particles_position = m_object->m_current_position;
particles_position.y += m_object->target_height;
m_object->PlayParticles (m_particles_death, particles_position, Fvector().set(0.0f,1.0f,0.0f), TRUE, FALSE);
CParticlesObject::Destroy (m_particles_object_electro);
CParticlesObject::Destroy (m_particles_object);
m_sound_base.stop();
}
void CPolterSpecialAbility::on_hit(SHit* pHDS)
{
if (m_object->g_Alive() && (pHDS->hit_type == ALife::eHitTypeFireWound) && (Device.dwFrame != m_last_hit_frame)) {
if(BI_NONE != pHDS->bone()) {
//вычислить координаты попадания
IKinematics* V = smart_cast<IKinematics*>(m_object->Visual());
Fvector start_pos = pHDS->bone_space_position();
Fmatrix& m_bone = V->LL_GetBoneInstance(pHDS->bone()).mTransform;
m_bone.transform_tiny (start_pos);
m_object->XFORM().transform_tiny (start_pos);
m_object->PlayParticles(m_particles_damage, start_pos, Fvector().set(0.f,1.f,0.f));
}
}
m_last_hit_frame = Device.dwFrame;
}
//////////////////////////////////////////////////////////////////////////
// Other
//////////////////////////////////////////////////////////////////////////
#define IMPULSE 10.f
#define IMPULSE_RADIUS 5.f
#define TRACE_DISTANCE 10.f
#define TRACE_ATTEMPT_COUNT 3
void CPoltergeist::PhysicalImpulse (const Fvector &position)
{
m_nearest.clear ();
Level().ObjectSpace.GetNearest (m_nearest,position, IMPULSE_RADIUS, NULL);
if (m_nearest.empty()) return;
u32 index = Random.randI ((u32)m_nearest.size());
CPhysicsShellHolder *obj = smart_cast<CPhysicsShellHolder *>(m_nearest[index]);
if (!obj || !obj->m_pPhysicsShell) return;
Fvector dir;
dir.sub(obj->Position(), position);
dir.normalize();
CPhysicsElement* E=obj->m_pPhysicsShell->get_ElementByStoreOrder(u16(Random.randI(obj->m_pPhysicsShell->get_ElementsNumber())));
E->applyImpulse(dir,IMPULSE * E->getMass());
}
#pragma warning(push)
#pragma warning(disable: 4267)
void CPoltergeist::StrangeSounds(const Fvector &position)
{
if (m_strange_sound._feedback()) return;
for (u32 i = 0; i < TRACE_ATTEMPT_COUNT; i++)
{
Fvector dir;
dir.random_dir();
collide::rq_result l_rq;
if (Level().ObjectSpace.RayPick(position, dir, TRACE_DISTANCE, collide::rqtStatic, l_rq, nullptr))
{
if (l_rq.range < TRACE_DISTANCE)
{
// Получить пару материалов
CDB::TRI* pTri = Level().ObjectSpace.GetStaticTris() + l_rq.element;
SGameMtlPair* mtl_pair = GMLib.GetMaterialPair(material().self_material_idx(),pTri->material);
if (!mtl_pair) continue;
// Играть звук
if (!mtl_pair->CollideSounds.empty())
{
CLONE_MTL_SOUND(m_strange_sound, mtl_pair, CollideSounds);
Fvector pos;
pos.mad(position, dir, ((l_rq.range - 0.1f > 0) ? l_rq.range - 0.1f : l_rq.range));
m_strange_sound.play_at_pos(this,pos);
return;
}
}
}
}
}
#pragma warning(pop) | c++ | code | 5,121 | 1,105 |
// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/matrix_game.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace matrix_game {
namespace {
// Check the utilities to see if the game is constant-sum or identical
// (cooperative).
GameType::Utility GetUtilityType(const std::vector<double>& row_player_utils,
const std::vector<double>& col_player_utils) {
double util_sum = 0;
// Assume both are true until proven otherwise.
bool constant_sum = true;
bool identical = true;
for (int i = 0; i < row_player_utils.size(); ++i) {
if (i == 0) {
util_sum = row_player_utils[i] + col_player_utils[i];
} else {
if (constant_sum &&
!Near(row_player_utils[i] + col_player_utils[i], util_sum)) {
constant_sum = false;
}
}
if (identical && row_player_utils[i] != col_player_utils[i]) {
identical = false;
}
}
if (constant_sum && Near(util_sum, 0.0)) {
return GameType::Utility::kZeroSum;
} else if (constant_sum) {
return GameType::Utility::kConstantSum;
} else if (identical) {
return GameType::Utility::kIdentical;
} else {
return GameType::Utility::kGeneralSum;
}
}
} // namespace
MatrixState::MatrixState(std::shared_ptr<const Game> game)
: NFGState(game),
matrix_game_(static_cast<const MatrixGame*>(game.get())) {}
std::string MatrixState::ToString() const {
std::string result = "";
absl::StrAppend(&result, "Terminal? ", IsTerminal() ? "true" : "false", "\n");
if (IsTerminal()) {
absl::StrAppend(&result, "History: ", HistoryString(), "\n");
absl::StrAppend(&result, "Returns: ", absl::StrJoin(Returns(), ","), "\n");
}
absl::StrAppend(&result, "Row actions: ");
for (auto move : LegalActions(0)) {
absl::StrAppend(&result, ActionToString(0, move), " ");
}
absl::StrAppend(&result, "\nCol actions: ");
for (auto move : LegalActions(1)) {
absl::StrAppend(&result, ActionToString(1, move), " ");
}
absl::StrAppend(&result, "\nUtility matrix:\n");
for (int r = 0; r < matrix_game_->NumRows(); r++) {
for (int c = 0; c < matrix_game_->NumCols(); c++) {
absl::StrAppend(&result, matrix_game_->RowUtility(r, c), ",",
matrix_game_->ColUtility(r, c), " ");
}
absl::StrAppend(&result, "\n");
}
return result;
}
std::unique_ptr<State> MatrixGame::NewInitialState() const {
return std::unique_ptr<State>(new MatrixState(shared_from_this()));
}
std::vector<double> FlattenMatrix(
const std::vector<std::vector<double>>& matrix_rows) {
std::vector<double> utilities;
int total_size = 0;
int row_size = -1;
int i = 0;
for (int r = 0; r < matrix_rows.size(); ++r) {
if (row_size < 0) {
row_size = matrix_rows[r].size();
}
SPIEL_CHECK_GT(row_size, 0);
SPIEL_CHECK_EQ(row_size, matrix_rows[r].size());
total_size += row_size;
utilities.resize(total_size, 0);
for (int c = 0; c < matrix_rows[r].size(); ++c) {
utilities[i] = matrix_rows[r][c];
++i;
}
}
return utilities;
}
std::shared_ptr<const MatrixGame> CreateMatrixGame(
const std::vector<std::vector<double>>& row_player_utils,
const std::vector<std::vector<double>>& col_player_utils) {
SPIEL_CHECK_GT(row_player_utils.size(), 0);
int num_rows = row_player_utils.size();
int num_columns = row_player_utils[0].size();
std::vector<std::string> row_names(num_rows);
std::vector<std::string> col_names(num_columns);
for (int i = 0; i < num_rows; ++i) {
row_names[i] = absl::StrCat("row", i);
}
for (int i = 0; i < num_columns; ++i) {
col_names[i] = absl::StrCat("col", i);
}
return CreateMatrixGame("short_name", "Long Name", row_names, col_names,
row_player_utils, col_player_utils);
}
// Create a matrix game with the specified utilities and row/column names.
// Utilities must be in row-major form.
std::shared_ptr<const MatrixGame> CreateMatrixGame(
const std::string& short_name, const std::string& long_name,
const std::vector<std::string>& row_names,
const std::vector<std::string>& col_names,
const std::vector<std::vector<double>>& row_player_utils,
const std::vector<std::vector<double>>& col_player_utils) {
int rows = row_names.size();
int columns = col_names.size();
std::vector<double> flat_row_utils = FlattenMatrix(row_player_utils);
std::vector<double> flat_col_utils = FlattenMatrix(col_player_utils);
SPIEL_CHECK_EQ(flat_row_utils.size(), rows * columns);
SPIEL_CHECK_EQ(flat_col_utils.size(), rows * columns);
// Detect the utility type from the utilities.
GameType::Utility utility = GetUtilityType(flat_row_utils, flat_col_utils);
GameType game_type{
/*short_name=*/short_name,
/*long_name=*/long_name,
GameType::Dynamics::kSimultaneous,
GameType::ChanceMode::kDeterministic,
GameType::Information::kOneShot,
utility,
GameType::RewardModel::kTerminal,
/*max_num_players=*/2,
/*min_num_players=*/2,
/*provides_information_state_string=*/true,
/*provides_information_state_tensor=*/true,
/*parameter_specification=*/{} // no parameters
};
return std::shared_ptr<const MatrixGame>(new MatrixGame(
game_type, {}, row_names, col_names, flat_row_utils, flat_col_utils));
}
} // namespace matrix_game
} // namespace open_spiel | c++ | code | 6,047 | 1,478 |
#pragma once
#include <steem/chain/database.hpp>
/*
* This file provides with() functions which modify the database
* temporarily, then restore it. These functions are mostly internal
* implementation detail of the database.
*
* Essentially, we want to be able to use "finally" to restore the
* database regardless of whether an exception is thrown or not, but there
* is no "finally" in C++. Instead, C++ requires us to create a struct
* and put the finally block in a destructor. Aagh!
*/
namespace steem { namespace chain { namespace detail {
/**
* Class used to help the with_skip_flags implementation.
* It must be defined in this header because it must be
* available to the with_skip_flags implementation,
* which is a template and therefore must also be defined
* in this header.
*/
struct skip_flags_restorer
{
skip_flags_restorer( node_property_object& npo, uint32_t old_skip_flags )
: _npo( npo ), _old_skip_flags( old_skip_flags )
{}
~skip_flags_restorer()
{
_npo.skip_flags = _old_skip_flags;
}
node_property_object& _npo;
uint32_t _old_skip_flags; // initialized in ctor
};
/**
* Class used to help the without_pending_transactions
* implementation.
*
* TODO: Change the name of this class to better reflect the fact
* that it restores popped transactions as well as pending transactions.
*/
struct pending_transactions_restorer
{
pending_transactions_restorer( database& db, const std::vector<signed_transaction>&& pending_transactions )
: _db(db), _pending_transactions( std::move(pending_transactions) )
{
_db.clear_pending();
}
~pending_transactions_restorer()
{
for( const auto& tx : _db._popped_tx )
{
try {
if( !_db.is_known_transaction( tx.id() ) ) {
// since push_transaction() takes a signed_transaction,
// the operation_results field will be ignored.
_db._push_transaction( tx );
}
} catch ( const fc::exception& ) {
}
}
_db._popped_tx.clear();
for( const signed_transaction& tx : _pending_transactions )
{
try
{
if( !_db.is_known_transaction( tx.id() ) ) {
// since push_transaction() takes a signed_transaction,
// the operation_results field will be ignored.
_db._push_transaction( tx );
}
}
catch( const transaction_exception& e )
{
dlog( "Pending transaction became invalid after switching to block ${b} ${n} ${t}",
("b", _db.head_block_id())("n", _db.head_block_num())("t", _db.head_block_time()) );
dlog( "The invalid transaction caused exception ${e}", ("e", e.to_detail_string()) );
dlog( "${t}", ("t", tx) );
}
catch( const fc::exception& e )
{
/*
dlog( "Pending transaction became invalid after switching to block ${b} ${n} ${t}",
("b", _db.head_block_id())("n", _db.head_block_num())("t", _db.head_block_time()) );
dlog( "The invalid pending transaction caused exception ${e}", ("e", e.to_detail_string() ) );
dlog( "${t}", ("t", tx) );
*/
}
}
}
database& _db;
std::vector< signed_transaction > _pending_transactions;
};
/**
* Set the skip_flags to the given value, call callback,
* then reset skip_flags to their previous value after
* callback is done.
*/
template< typename Lambda >
void with_skip_flags(
database& db,
uint32_t skip_flags,
Lambda callback )
{
node_property_object& npo = db.node_properties();
skip_flags_restorer restorer( npo, npo.skip_flags );
npo.skip_flags = skip_flags;
callback();
return;
}
/**
* Empty pending_transactions, call callback,
* then reset pending_transactions after callback is done.
*
* Pending transactions which no longer validate will be culled.
*/
template< typename Lambda >
void without_pending_transactions(
database& db,
const std::vector<signed_transaction>&& pending_transactions,
Lambda callback )
{
pending_transactions_restorer restorer( db, std::move(pending_transactions) );
callback();
return;
}
} } } // steem::chain::detail | c++ | code | 4,300 | 850 |
/*
* Copyright (C) 2021 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include <imgui.h>
#include <reshade.hpp>
#include <mutex>
#include <vector>
#include <unordered_map>
#include <algorithm>
static bool s_disable_intz = false;
static std::mutex s_mutex;
#ifdef BUILTIN_ADDON
#include "ini_file.hpp"
#endif
using namespace reshade::api;
struct draw_stats
{
uint32_t vertices = 0;
uint32_t drawcalls = 0;
float last_viewport[6] = {};
};
struct clear_stats : public draw_stats
{
bool rect = false;
};
struct depth_stencil_info
{
draw_stats total_stats;
draw_stats current_stats; // Stats since last clear operation
std::vector<clear_stats> clears;
bool copied_during_frame = false;
};
struct depth_stencil_hash
{
inline size_t operator()(resource value) const
{
// Simply use the handle (which is usually a pointer) as hash value (with some bits shaved off due to pointer alignment)
return static_cast<size_t>(value.handle >> 4);
}
};
struct state_tracking
{
static constexpr uint8_t GUID[16] = { 0x43, 0x31, 0x9e, 0x83, 0x38, 0x7c, 0x44, 0x8e, 0x88, 0x1c, 0x7e, 0x68, 0xfc, 0x2e, 0x52, 0xc4 };
draw_stats best_copy_stats;
bool first_empty_stats = true;
bool has_indirect_drawcalls = false;
resource current_depth_stencil = { 0 };
float current_viewport[6] = {};
std::unordered_map<resource, depth_stencil_info, depth_stencil_hash> counters_per_used_depth_stencil;
state_tracking()
{
// Reserve some space upfront to avoid rehashing during command recording
counters_per_used_depth_stencil.reserve(32);
}
void reset()
{
reset_on_present();
current_depth_stencil = { 0 };
}
void reset_on_present()
{
best_copy_stats = { 0, 0 };
first_empty_stats = true;
has_indirect_drawcalls = false;
counters_per_used_depth_stencil.clear();
}
void merge(const state_tracking &source)
{
// Executing a command list in a different command list inherits state
current_depth_stencil = source.current_depth_stencil;
if (first_empty_stats)
first_empty_stats = source.first_empty_stats;
has_indirect_drawcalls |= source.has_indirect_drawcalls;
if (source.best_copy_stats.vertices > best_copy_stats.vertices)
best_copy_stats = source.best_copy_stats;
if (source.counters_per_used_depth_stencil.empty())
return;
counters_per_used_depth_stencil.reserve(source.counters_per_used_depth_stencil.size());
for (const auto &[depth_stencil_handle, snapshot] : source.counters_per_used_depth_stencil)
{
depth_stencil_info &target_snapshot = counters_per_used_depth_stencil[depth_stencil_handle];
target_snapshot.total_stats.vertices += snapshot.total_stats.vertices;
target_snapshot.total_stats.drawcalls += snapshot.total_stats.drawcalls;
target_snapshot.current_stats.vertices += snapshot.current_stats.vertices;
target_snapshot.current_stats.drawcalls += snapshot.current_stats.drawcalls;
target_snapshot.clears.insert(target_snapshot.clears.end(), snapshot.clears.begin(), snapshot.clears.end());
target_snapshot.copied_during_frame |= snapshot.copied_during_frame;
}
}
};
struct state_tracking_context
{
static constexpr uint8_t GUID[16] = { 0x7c, 0x63, 0x63, 0xc7, 0xf9, 0x4e, 0x43, 0x7a, 0x91, 0x60, 0x14, 0x17, 0x82, 0xc4, 0x4a, 0x98 };
// Enable or disable the creation of backup copies at clear operations on the selected depth-stencil
bool preserve_depth_buffers = false;
// Enable or disable the aspect ratio check from 'check_aspect_ratio' in the detection heuristic
bool use_aspect_ratio_heuristics = true;
// Set to zero for automatic detection, otherwise will use the clear operation at the specific index within a frame
size_t force_clear_index = 0;
// Stats of the previous frame for the selected depth-stencil
draw_stats previous_stats = {};
// A resource used as target for a backup copy for the selected depth-stencil
resource backup_texture = { 0 };
// The depth-stencil that is currently selected as being the main depth target
// Any clear operations on it are subject for special handling (backup copy or replacement)
resource selected_depth_stencil = { 0 };
// Resource used to override automatic depth-stencil selection
resource override_depth_stencil = { 0 };
// The current shader resource view bound to shaders
// This can be created from either the original depth-stencil of the application (if it supports shader access), or from the backup resource, or from one of the replacement resources
resource_view selected_shader_resource = { 0 };
// List of resources that were deleted this frame
std::vector<resource> destroyed_resources;
// List of all encountered depth-stencils of the last frame
std::vector<std::pair<resource, depth_stencil_info>> current_depth_stencil_list;
std::unordered_map<resource, unsigned int, depth_stencil_hash> display_count_per_depth_stencil;
// Checks whether the aspect ratio of the two sets of dimensions is similar or not
bool check_aspect_ratio(float width_to_check, float height_to_check, uint32_t width, uint32_t height) const
{
if (width_to_check == 0.0f || height_to_check == 0.0f)
return true;
const float w = static_cast<float>(width);
const float w_ratio = w / width_to_check;
const float h = static_cast<float>(height);
const float h_ratio = h / height_to_check;
const float aspect_ratio = (w / h) - (static_cast<float>(width_to_check) / height_to_check);
return std::fabs(aspect_ratio) <= 0.1f && w_ratio <= 1.85f && h_ratio <= 1.85f && w_ratio >= 0.5f && h_ratio >= 0.5f;
}
// Update the backup texture to match the requested dimensions
void update_backup_texture(device *device, resource_desc desc)
{
if (backup_texture != 0)
{
const resource_desc existing_desc = device->get_resource_desc(backup_texture);
if (desc.texture.width == existing_desc.texture.width && desc.texture.height == existing_desc.texture.height && desc.texture.format == existing_desc.texture.format)
return; // Texture already matches dimensions, so can re-use
device->wait_idle(); // Texture may still be in use on device, so wait for all operations to finish before destroying it
device->destroy_resource(backup_texture);
backup_texture = { 0 };
}
desc.type = resource_type::texture_2d;
desc.heap = memory_heap::gpu_only;
desc.usage = resource_usage::shader_resource | resource_usage::copy_dest;
if (device->get_api() == device_api::d3d9)
desc.texture.format = format::r32_float; // D3DFMT_R32F, since INTZ does not support D3DUSAGE_RENDERTARGET which is required for copying
else if (device->get_api() != device_api::vulkan) // Use depth format as-is in Vulkan, since those are valid for shader resource views there
desc.texture.format = format_to_typeless(desc.texture.format);
if (!device->create_resource(desc, nullptr, resource_usage::copy_dest, &backup_texture))
reshade::log_message(1, "Failed to create backup depth-stencil texture!");
}
};
static void clear_depth_impl(command_list *cmd_list, state_tracking &state, const state_tracking_context &device_state, resource depth_stencil, bool fullscreen_draw_call)
{
if (depth_stencil == 0 || device_state.backup_texture == 0 || depth_stencil != device_state.selected_depth_stencil)
return;
depth_stencil_info &counters = state.counters_per_used_depth_stencil[depth_stencil];
// Update stats with data from previous frame
if (!fullscreen_draw_call && counters.current_stats.drawcalls == 0 && state.first_empty_stats)
{
counters.current_stats = device_state.previous_stats;
state.first_empty_stats = false;
}
// Ignore clears when there was no meaningful workload
if (counters.current_stats.drawcalls == 0)
return;
// Skip clears when last viewport only affected a subset of the depth-stencil
if (const resource_desc desc = cmd_list->get_device()->get_resource_desc(depth_stencil);
!device_state.check_aspect_ratio(counters.current_stats.last_viewport[2], counters.current_stats.last_viewport[3], desc.texture.width, desc.texture.height))
{
counters.current_stats = { 0, 0 };
return;
}
counters.clears.push_back({ counters.current_stats, fullscreen_draw_call });
// Make a backup copy of the depth texture before it is cleared
if (device_state.force_clear_index == 0 ?
// If clear index override is set to zero, always copy any suitable buffers
// Use greater equals operator here to handle case where the same scene is first rendered into a shadow map and then for real (e.g. Mirror's Edge)
fullscreen_draw_call || counters.current_stats.vertices >= state.best_copy_stats.vertices :
// This is not really correct, since clears may accumulate over multiple command lists, but it's unlikely that the same depth-stencil is used in more than one
counters.clears.size() == device_state.force_clear_index)
{
// Since clears from fullscreen draw calls are selected based on their order (last one wins), their stats are ignored for the regular clear heuristic
if (!fullscreen_draw_call)
state.best_copy_stats = counters.current_stats;
// A resource has to be in this state for a clear operation, so can assume it here
cmd_list->barrier(depth_stencil, resource_usage::depth_stencil_write, resource_usage::copy_source);
cmd_list->copy_resource(depth_stencil, device_state.backup_texture);
cmd_list->barrier(depth_stencil, resource_usage::copy_source, resource_usage::depth_stencil_write);
counters.copied_during_frame = true;
}
// Reset draw call stats for clears
counters.current_stats = { 0, 0 };
}
static void update_effect_runtime(effect_runtime *runtime)
{
device *const device = runtime->get_device();
const state_tracking_context &device_state = device->get_private_data<state_tracking_context>(state_tracking_context::GUID);
// TODO: This only works reliably if there is a single effect runtime (swap chain).
// With multiple presenting swap chains it can happen that not all effect runtimes are updated after the selected depth-stencil resource changed (or worse the backup texture was updated).
runtime->update_texture_bindings("DEPTH", device_state.selected_shader_resource);
runtime->enumerate_uniform_variables(nullptr, [&device_state](effect_runtime *runtime, auto variable) {
const char *const source = runtime->get_uniform_annotation(variable, "source");
if (source != nullptr && strcmp(source, "bufready_depth") == 0)
{
const bool bufready_depth_value = (device_state.selected_shader_resource != 0);
runtime->set_uniform_data(variable, &bufready_depth_value, 1);
}
});
}
static void on_init_device(device *device)
{
state_tracking_context &device_state = device->create_private_data<state_tracking_context>(state_tracking_context::GUID);
#ifdef BUILTIN_ADDON
const ini_file &config = reshade::global_config();
config.get("DEPTH", "DisableINTZ", s_disable_intz);
config.get("DEPTH", "DepthCopyBeforeClears", device_state.preserve_depth_buffers);
config.get("DEPTH", "DepthCopyAtClearIndex", device_state.force_clear_index);
config.get("DEPTH", "UseAspectRatioHeuristics", device_state.use_aspect_ratio_heuristics);
#endif
if (device_state.force_clear_index == std::numeric_limits<uint32_t>::max())
device_state.force_clear_index = 0;
}
static void on_init_queue_or_command_list(api_object *queue_or_cmd_list)
{
queue_or_cmd_list->create_private_data<state_tracking>(state_tracking::GUID);
}
static void on_destroy_device(device *device)
{
state_tracking_context &device_state = device->get_private_data<state_tracking_context>(state_tracking_context::GUID);
if (device_state.backup_texture != 0)
device->destroy_resource(device_state.backup_texture);
if (device_state.selected_shader_resource != 0)
device->destroy_resource_view(device_state.selected_shader_resource);
device->destroy_private_data<state_tracking_context>(state_tracking_context::GUID);
}
static void on_destroy_queue_or_command_list(api_object *queue_or_cmd_list)
{
queue_or_cmd_list->destroy_private_data<state_tracking>(state_tracking::GUID);
}
static bool on_create_resource(device *device, resource_desc &desc, subresource_data *, resource_usage)
{
if (desc.type != resource_type::surface && desc.type != resource_type::texture_2d)
return false; // Skip resources that are not 2D textures
if (desc.texture.samples != 1 || (desc.usage & resource_usage::depth_stencil) == resource_usage::undefined)
return false; // Skip MSAA textures and resources that are not used for depth-stencil views
switch (device->get_api())
{
case device_api::d3d9:
if (s_disable_intz)
return false;
desc.texture.format = format::intz;
desc.usage |= resource_usage::shader_resource;
break;
case device_api::d3d10:
case device_api::d3d11:
// Allow shader access to images that are used as depth-stencil attachments
desc.texture.format = format_to_typeless(desc.texture.format);
desc.usage |= resource_usage::shader_resource;
break;
case device_api::d3d12:
case device_api::vulkan:
// D3D12 and Vulkan always use backup texture, but need to be able to copy to it
desc.usage |= resource_usage::copy_source;
break;
}
return true;
}
static bool on_create_resource_view(device *device, resource resource, resource_usage usage_type, resource_view_desc &desc)
{
// A view cannot be created with a typeless format (which was set in 'on_create_resource' above), so fix it in case defaults are used
if ((device->get_api() != device_api::d3d10 && device->get_api() != device_api::d3d11) || desc.format != format::unknown)
return false;
const resource_desc texture_desc = device->get_resource_desc(resource);
// Only non-MSAA textures where modified, so skip all others
if (texture_desc.texture.samples != 1 || (texture_desc.usage & resource_usage::depth_stencil) == resource_usage::undefined)
return false;
switch (usage_type)
{
case resource_usage::depth_stencil:
desc.format = format_to_depth_stencil_typed(texture_desc.texture.format);
break;
case resource_usage::shader_resource:
desc.format = format_to_default_typed(texture_desc.texture.format);
break;
}
// Only need to set the rest of the fields if the application did not pass in a valid description already
if (desc.type == resource_view_type::unknown)
{
desc.type = texture_desc.texture.depth_or_layers > 1 ? resource_view_type::texture_2d_array : resource_view_type::texture_2d;
desc.texture.first_level = 0;
desc.texture.level_count = (usage_type == resource_usage::shader_resource) ? 0xFFFFFFFF : 1;
desc.texture.first_layer = 0;
desc.texture.layer_count = (usage_type == resource_usage::shader_resource) ? 0xFFFFFFFF : 1;
}
return true;
}
static void on_destroy_resource(device *device, resource resource)
{
state_tracking_context &device_state = device->get_private_data<state_tracking_context>(state_tracking_context::GUID);
// In some cases the 'destroy_device' event may be called before all resources have been destroyed
// The state tracking context would have been destroyed already in that case, so return early if it does not exist
if (&device_state == nullptr)
return;
std::lock_guard<std::mutex> lock(s_mutex);
device_state.destroyed_resources.push_back(resource);
}
static bool on_draw(command_list *cmd_list, uint32_t vertices, uint32_t instances, uint32_t, uint32_t)
{
auto &state = cmd_list->get_private_data<state_tracking>(state_tracking::GUID);
if (state.current_depth_stencil == 0)
return false; // This is a draw call with no depth-stencil bound
#if 0
// Check if this draw call likely represets a fullscreen rectangle (one or two triangles), which would clear the depth-stencil
const state_tracking_context &device_state = cmd_list->get_device()->get_data<state_tracking_context>(state_tracking_context::GUID);
if (device_state.preserve_depth_buffers && (vertices == 3 || vertices == 6))
{
// TODO: Check pipeline state (cull mode none, depth test enabled, depth write enabled, depth compare function always)
clear_depth_impl(cmd_list, state, device_state, state.current_depth_stencil, true);
return false;
}
#endif
depth_stencil_info &counters = state.counters_per_used_depth_stencil[state.current_depth_stencil];
counters.total_stats.vertices += vertices * instances;
counters.total_stats.drawcalls += 1;
counters.current_stats.vertices += vertices * instances;
counters.current_stats.drawcalls += 1;
std::memcpy(counters.current_stats.last_viewport, state.current_viewport, 6 * sizeof(float));
return false;
}
static bool on_draw_indexed(command_list *cmd_list, uint32_t indices, uint32_t instances, uint32_t, int32_t, uint32_t)
{
on_draw(cmd_list, indices, instances, 0, 0);
return false;
}
static bool on_draw_indirect(command_list *cmd_list, indirect_command type, resource, uint64_t, uint32_t draw_count, uint32_t)
{
if (type == indirect_command::dispatch)
return false;
for (uint32_t i = 0; i < draw_count; ++i)
on_draw(cmd_list, 0, 0, 0, 0);
auto &state = cmd_list->get_private_data<state_tracking>(state_tracking::GUID);
state.has_indirect_drawcalls = true;
return false;
}
static void on_bind_viewport(command_list *cmd_list, uint32_t first, uint32_t count, const float *viewport)
{
if (first != 0 || count == 0)
return; // Only interested in the main viewport
auto &state = cmd_list->get_private_data<state_tracking>(state_tracking::GUID);
std::memcpy(state.current_viewport, viewport, 6 * sizeof(float));
}
static void on_begin_render_pass(command_list *cmd_list, render_pass, framebuffer fbo)
{
device *const device = cmd_list->get_device();
auto &state = cmd_list->get_private_data<state_tracking>(state_tracking::GUID);
resource depth_stencil = { 0 };
const resource_view depth_stencil_view = device->get_framebuffer_attachment(fbo, attachment_type::depth, 0);
if (depth_stencil_view.handle != 0)
depth_stencil = device->get_resource_from_view(depth_stencil_view);
// Make a backup of the depth texture before it is used differently, since in D3D12 or Vulkan the underlying memory may be aliased to a different resource, so cannot just access it at the end of the frame
if (depth_stencil != state.current_depth_stencil && state.current_depth_stencil != 0 && (device->get_api() == device_api::d3d12 || device->get_api() == device_api::vulkan))
clear_depth_impl(cmd_list, state, device->get_private_data<state_tracking_context>(state_tracking_context::GUID), state.current_depth_stencil, true);
state.current_depth_stencil = depth_stencil;
}
static void on_bind_depth_stencil(command_list *cmd_list, uint32_t, const resource_view *, resource_view depth_stencil_view)
{
device *const device = cmd_list->get_device();
auto &state = cmd_list->get_private_data<state_tracking>(state_tracking::GUID);
resource depth_stencil = { 0 };
if (depth_stencil_view.handle != 0)
depth_stencil = device->get_resource_from_view(depth_stencil_view);
// Make a backup of the depth texture before it is used differently, since in D3D12 or Vulkan the underlying memory may be aliased to a different resource, so cannot just access it at the end of the frame
if (depth_stencil != state.current_depth_stencil && state.current_depth_stencil != 0 && (device->get_api() == device_api::d3d12 || device->get_api() == device_api::vulkan))
clear_depth_impl(cmd_list, state, device->get_private_data<state_tracking_context>(state_tracking_context::GUID), state.current_depth_stencil, true);
state.current_depth_stencil = depth_stencil;
}
static bool on_clear_depth_stencil_attachment(command_list *cmd_list, attachment_type flags, const float[4], float, uint8_t, uint32_t, const int32_t *)
{
device *const device = cmd_list->get_device();
const state_tracking_context &device_state = device->get_private_data<state_tracking_context>(state_tracking_context::GUID);
// Ignore clears that do not affect the depth buffer (stencil clears)
if ((flags & attachment_type::depth) == attachment_type::depth &&
device_state.preserve_depth_buffers &&
// Cannot preserve depth buffers here in Vulkan though, since it is not valid to issue copy commands | c++ | code | 19,999 | 3,910 |
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
bool isAdditiveNumber(string num) {
if (num == "")
return false;
int len = num.size();
for (int i = 1; i < len; i++) // 用双指针i, j分别作为substr{n-2}和substr{n-1}的开始位置
{
for (int j = i + 1; j < len; j++)
{
string s1 = num.substr(0, i); // substr[0, i]
string s2 = num.substr(i, j - i); // substr[i, j]
if ((s1.size() > 1 && s1[0] == '0') || (s2.size() > 1 && s2[0] == '0'))
continue; // 出现开头是字符0的情况, 不处理
auto preNum = stoll(s1);
auto curNum = stoll(s2);
auto nextNum = preNum + curNum;
auto combinedStr = s1 + s2 + to_string(nextNum);
while (combinedStr.size() < num.size()) // 继续前移
{
preNum = curNum;
curNum = nextNum;
nextNum = preNum + curNum; // 迭代地使用递推关系
combinedStr += to_string(nextNum);
}
if (combinedStr == num)
return true;
}
}
return false;
}
};
// Test
int main()
{
Solution sol;
string s = "199100199";
auto res = sol.isAdditiveNumber(s);
cout << (res == true ? "True" : "False") << endl;
return 0;
} | c++ | code | 1,525 | 340 |
/******************************************************************************
*
* Copyright (c) 2017, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms of
* the Apache License 2.0. The full license can be found in the LICENSE file.
*
*/
#include <perspective/first.h>
#include <perspective/base.h>
#include <perspective/pool.h>
#include <perspective/update_task.h>
#include <perspective/compat.h>
#include <perspective/env_vars.h>
#ifdef PSP_ENABLE_PYTHON
#include <thread>
#endif
#include <chrono>
namespace perspective {
t_updctx::t_updctx() {}
t_updctx::t_updctx(t_uindex gnode_id, const std::string& ctx)
: m_gnode_id(gnode_id)
, m_ctx(ctx) {}
#if defined PSP_ENABLE_WASM
t_val
empty_callback() {
t_val callback = t_val::global("Object").new_();
callback.set("_update_callback", t_val::global("Function").new_());
return callback;
}
t_pool::t_pool()
: m_update_delegate(empty_callback())
, m_sleep(0) {
m_run.clear();
}
#elif defined PSP_ENABLE_PYTHON
t_val
empty_callback() {
return py::none();
}
t_pool::t_pool()
: m_update_delegate(empty_callback())
, m_event_loop_thread_id(std::thread::id())
, m_sleep(0) {
m_run.clear();
}
#else
t_pool::t_pool()
: m_sleep(0) {
m_run.clear();
}
#endif
t_pool::~t_pool() {}
void
t_pool::init() {
if (t_env::log_progress()) {
std::cout << "t_pool.init " << std::endl;
}
m_run.test_and_set(std::memory_order_acquire);
m_data_remaining.store(false);
std::thread t(&t_pool::_process, this);
set_thread_name(t, "psp_pool_thread");
t.detach();
}
t_uindex
t_pool::register_gnode(t_gnode* node) {
std::lock_guard<std::mutex> lg(m_mtx);
m_gnodes.push_back(node);
t_uindex id = m_gnodes.size() - 1;
node->set_id(id);
node->set_pool_cleanup([this, id]() { this->m_gnodes[id] = 0; });
#ifdef PSP_ENABLE_PYTHON
if (m_event_loop_thread_id != std::thread::id()) {
node->set_event_loop_thread_id(m_event_loop_thread_id);
}
#endif
if (t_env::log_progress()) {
std::cout << "t_pool.register_gnode node => " << node << " rv => " << id << std::endl;
}
return id;
}
void
t_pool::unregister_gnode(t_uindex idx) {
std::lock_guard<std::mutex> lgxo(m_mtx);
if (t_env::log_progress()) {
std::cout << "t_pool.unregister_gnode idx => " << idx << std::endl;
}
m_gnodes[idx] = 0;
}
void
t_pool::send(t_uindex gnode_id, t_uindex port_id, const t_data_table& table) {
{
std::lock_guard<std::mutex> lg(m_mtx);
m_data_remaining.store(true);
if (m_gnodes[gnode_id]) {
m_gnodes[gnode_id]->send(port_id, table);
}
if (t_env::log_progress()) {
std::cout << "t_pool.send gnode_id => " << gnode_id << " port_id => " << port_id
<< " tbl_size => " << table.size() << std::endl;
}
if (t_env::log_data_pool_send()) {
std::cout << "t_pool.send" << std::endl;
table.pprint();
}
}
}
#ifdef PSP_ENABLE_PYTHON
void t_pool::set_event_loop() {
m_event_loop_thread_id = std::this_thread::get_id();
for (auto node : m_gnodes) {
node->set_event_loop_thread_id(m_event_loop_thread_id);
}
}
std::thread::id t_pool::get_event_loop_thread_id() const {
return m_event_loop_thread_id;
}
#endif
void
t_pool::_process() {
auto work_to_do = m_data_remaining.load();
if (work_to_do) {
t_update_task task(*this);
task.run();
}
}
void
t_pool::stop() {
m_run.clear(std::memory_order_release);
_process();
if (t_env::log_progress()) {
std::cout << "t_pool.stop" << std::endl;
}
}
void
t_pool::set_sleep(t_uindex ms) {
m_sleep.store(ms);
if (t_env::log_progress()) {
std::cout << "t_pool.set_sleep ms => " << ms << std::endl;
}
}
std::vector<t_stree*>
t_pool::get_trees() {
std::vector<t_stree*> rval;
for (auto& g : m_gnodes) {
if (!g)
continue;
auto trees = g->get_trees();
rval.insert(std::end(rval), std::begin(trees), std::end(trees));
}
if (t_env::log_progress()) {
std::cout << "t_pool.get_trees: "
<< " rv => " << rval << std::endl;
}
return rval;
}
#ifdef PSP_ENABLE_WASM
void
t_pool::register_context(
t_uindex gnode_id, const std::string& name, t_ctx_type type, std::int32_t ptr) {
std::lock_guard<std::mutex> lg(m_mtx);
if (!validate_gnode_id(gnode_id))
return;
m_gnodes[gnode_id]->_register_context(name, type, ptr);
}
#else
void
t_pool::register_context(
t_uindex gnode_id, const std::string& name, t_ctx_type type, std::int64_t ptr) {
std::lock_guard<std::mutex> lg(m_mtx);
if (!validate_gnode_id(gnode_id))
return;
m_gnodes[gnode_id]->_register_context(name, type, ptr);
}
#endif
#if defined PSP_ENABLE_WASM || defined PSP_ENABLE_PYTHON
void
t_pool::set_update_delegate(t_val ud) {
m_update_delegate = ud;
}
#endif
void
t_pool::notify_userspace(t_uindex port_id) {
#if defined PSP_ENABLE_WASM
m_update_delegate.call<void>("_update_callback", port_id);
#elif PSP_ENABLE_PYTHON
if (!m_update_delegate.is_none()) {
m_update_delegate.attr("_update_callback")(port_id);
}
#endif
}
void
t_pool::unregister_context(t_uindex gnode_id, const std::string& name) {
std::lock_guard<std::mutex> lg(m_mtx);
if (t_env::log_progress()) {
std::cout << repr() << " << t_pool.unregister_context: "
<< " gnode_id => " << gnode_id << " name => " << name << std::endl;
}
if (!validate_gnode_id(gnode_id))
return;
m_gnodes[gnode_id]->_unregister_context(name);
}
bool
t_pool::get_data_remaining() const {
auto data = m_data_remaining.load();
return data;
}
std::vector<t_tscalar>
t_pool::get_row_data_pkeys(t_uindex gnode_id, const std::vector<t_tscalar>& pkeys) {
std::lock_guard<std::mutex> lg(m_mtx);
if (!validate_gnode_id(gnode_id))
return std::vector<t_tscalar>();
auto rv = m_gnodes[gnode_id]->get_row_data_pkeys(pkeys);
if (t_env::log_progress()) {
std::cout << "t_pool.get_row_data_pkeys: "
<< " gnode_id => " << gnode_id << " pkeys => " << pkeys << " rv => " << rv
<< std::endl;
}
return rv;
}
std::vector<t_updctx>
t_pool::get_contexts_last_updated() {
std::lock_guard<std::mutex> lg(m_mtx);
std::vector<t_updctx> rval;
for (t_uindex idx = 0, loop_end = m_gnodes.size(); idx < loop_end; ++idx) {
if (!m_gnodes[idx])
continue;
auto updated_contexts = m_gnodes[idx]->get_contexts_last_updated();
auto gnode_id = m_gnodes[idx]->get_id();
for (const auto& ctx_name : updated_contexts) {
if (t_env::log_progress()) {
std::cout << "t_pool.get_contexts_last_updated: "
<< " gnode_id => " << gnode_id << " ctx_name => " << ctx_name
<< std::endl;
}
rval.push_back(t_updctx(gnode_id, ctx_name));
}
}
return rval;
}
bool
t_pool::validate_gnode_id(t_uindex gnode_id) const {
return m_gnodes[gnode_id] && gnode_id < m_gnodes.size();
}
std::string
t_pool::repr() const {
std::stringstream ss;
ss << "t_pool<" << this << ">";
return ss.str();
}
void
t_pool::pprint_registered() const {
auto self = repr();
for (t_uindex idx = 0, loop_end = m_gnodes.size(); idx < loop_end; ++idx) {
if (!m_gnodes[idx])
continue;
auto gnode_id = m_gnodes[idx]->get_id();
auto ctxnames = m_gnodes[idx]->get_registered_contexts();
for (const auto& cname : ctxnames) {
std::cout << self << " gnode_id => " << gnode_id << " ctxname => " << cname
<< std::endl;
}
}
}
t_uindex
t_pool::epoch() const {
return m_epoch.load();
}
void
t_pool::inc_epoch() {
++m_epoch;
}
std::vector<t_uindex>
t_pool::get_gnodes_last_updated() {
std::lock_guard<std::mutex> lg(m_mtx);
std::vector<t_uindex> rv;
for (t_uindex idx = 0, loop_end = m_gnodes.size(); idx < loop_end; ++idx) {
if (!m_gnodes[idx] || !m_gnodes[idx]->was_updated())
continue;
rv.push_back(idx);
m_gnodes[idx]->clear_updated();
}
return rv;
}
t_gnode*
t_pool::get_gnode(t_uindex idx) {
std::lock_guard<std::mutex> lg(m_mtx);
PSP_VERBOSE_ASSERT(idx < m_gnodes.size() && m_gnodes[idx], "Bad gnode encountered");
return m_gnodes[idx];
}
} // end namespace perspective | c++ | code | 8,708 | 2,217 |
/*
* Copyright (C) 2016 Intel Corporation. All Rights Reserved.
*
* 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, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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 "i965_config_test.h"
namespace AVC {
namespace Decode {
VAStatus ProfileNotSupported()
{
return VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
}
VAStatus EntrypointNotSupported()
{
return VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
}
// H264*NotSupported functions report properly if profile is not supported or
// only entrypoint is not supported
VAStatus H264NotSupported()
{
I965TestEnvironment *env(I965TestEnvironment::instance());
EXPECT_PTR(env);
struct i965_driver_data *i965(*env);
EXPECT_PTR(i965);
if (!HAS_H264_ENCODING(i965)
&& !HAS_LP_H264_ENCODING(i965))
return ProfileNotSupported();
return EntrypointNotSupported();
}
VAStatus H264MVCNotSupported()
{
I965TestEnvironment *env(I965TestEnvironment::instance());
EXPECT_PTR(env);
struct i965_driver_data *i965(*env);
EXPECT_PTR(i965);
if (!HAS_H264_MVC_ENCODING(i965))
return ProfileNotSupported();
return EntrypointNotSupported();
}
VAStatus HasDecodeSupport()
{
I965TestEnvironment *env(I965TestEnvironment::instance());
EXPECT_PTR(env);
struct i965_driver_data *i965(*env);
EXPECT_PTR(i965);
if (HAS_H264_DECODING(i965))
return VA_STATUS_SUCCESS;
return H264NotSupported();
}
VAStatus HasMVCDecodeSupport()
{
I965TestEnvironment *env(I965TestEnvironment::instance());
EXPECT_PTR(env);
struct i965_driver_data *i965(*env);
EXPECT_PTR(i965);
if (HAS_H264_MVC_DECODING_PROFILE(i965, VAProfileH264MultiviewHigh))
return VA_STATUS_SUCCESS;
return H264MVCNotSupported();
}
VAStatus HasStereoCDecodeSupport()
{
I965TestEnvironment *env(I965TestEnvironment::instance());
EXPECT_PTR(env);
struct i965_driver_data *i965(*env);
EXPECT_PTR(i965);
if (HAS_H264_MVC_DECODING_PROFILE(i965, VAProfileH264StereoHigh))
return VA_STATUS_SUCCESS;
return H264MVCNotSupported();
}
static const std::vector<ConfigTestInput> inputs = {
{ VAProfileH264ConstrainedBaseline, VAEntrypointVLD, &HasDecodeSupport },
{ VAProfileH264Main, VAEntrypointVLD, &HasDecodeSupport },
{ VAProfileH264High, VAEntrypointVLD, &HasDecodeSupport },
{ VAProfileH264MultiviewHigh, VAEntrypointVLD,
&HasMVCDecodeSupport },
{ VAProfileH264StereoHigh, VAEntrypointVLD,
&HasStereoCDecodeSupport },
};
INSTANTIATE_TEST_CASE_P(
AVCDecode, I965ConfigTest, ::testing::ValuesIn(inputs));
} // namespace Decode
} // namespace AVC | c++ | code | 3,662 | 647 |
#pragma once
#include <cmath> // isfinite
#include <cstdint> // uint8_t
#include <functional> // function
#include <string> // string
#include <utility> // move
#include <vector> // vector
#include "include/nlohmann/detail/exceptions.hpp"
#include "include/nlohmann/detail/input/input_adapters.hpp"
#include "include/nlohmann/detail/input/json_sax.hpp"
#include "include/nlohmann/detail/input/lexer.hpp"
#include "include/nlohmann/detail/macro_scope.hpp"
#include "include/nlohmann/detail/meta/is_sax.hpp"
#include "include/nlohmann/detail/value_t.hpp"
namespace nlohmann
{
namespace detail
{
////////////
// parser //
////////////
enum class parse_event_t : uint8_t
{
/// the parser read `{` and started to process a JSON object
object_start,
/// the parser read `}` and finished processing a JSON object
object_end,
/// the parser read `[` and started to process a JSON array
array_start,
/// the parser read `]` and finished processing a JSON array
array_end,
/// the parser read a key of a value in an object
key,
/// the parser finished reading a JSON value
value
};
template<typename BasicJsonType>
using parser_callback_t =
std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
/*!
@brief syntax analysis
This class implements a recursive descent parser.
*/
template<typename BasicJsonType, typename InputAdapterType>
class parser
{
using number_integer_t = typename BasicJsonType::number_integer_t;
using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
using number_float_t = typename BasicJsonType::number_float_t;
using string_t = typename BasicJsonType::string_t;
using lexer_t = lexer<BasicJsonType, InputAdapterType>;
using token_type = typename lexer_t::token_type;
public:
/// a parser reading from an input adapter
explicit parser(InputAdapterType&& adapter,
const parser_callback_t<BasicJsonType> cb = nullptr,
const bool allow_exceptions_ = true,
const bool skip_comments = false)
: callback(cb)
, m_lexer(std::move(adapter), skip_comments)
, allow_exceptions(allow_exceptions_)
{
// read first token
get_token();
}
/*!
@brief public parser interface
@param[in] strict whether to expect the last token to be EOF
@param[in,out] result parsed JSON value
@throw parse_error.101 in case of an unexpected token
@throw parse_error.102 if to_unicode fails or surrogate error
@throw parse_error.103 if to_unicode fails
*/
void parse(const bool strict, BasicJsonType& result)
{
if (callback)
{
json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
sax_parse_internal(&sdp);
result.assert_invariant();
// in strict mode, input must be completely read
if (strict && (get_token() != token_type::end_of_input))
{
sdp.parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::end_of_input, "value")));
}
// in case of an error, return discarded value
if (sdp.is_errored())
{
result = value_t::discarded;
return;
}
// set top-level value to null if it was discarded by the callback
// function
if (result.is_discarded())
{
result = nullptr;
}
}
else
{
json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
sax_parse_internal(&sdp);
result.assert_invariant();
// in strict mode, input must be completely read
if (strict && (get_token() != token_type::end_of_input))
{
sdp.parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::end_of_input, "value")));
}
// in case of an error, return discarded value
if (sdp.is_errored())
{
result = value_t::discarded;
return;
}
}
}
/*!
@brief public accept interface
@param[in] strict whether to expect the last token to be EOF
@return whether the input is a proper JSON text
*/
bool accept(const bool strict = true)
{
json_sax_acceptor<BasicJsonType> sax_acceptor;
return sax_parse(&sax_acceptor, strict);
}
template<typename SAX>
JSON_HEDLEY_NON_NULL(2)
bool sax_parse(SAX* sax, const bool strict = true)
{
(void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
const bool result = sax_parse_internal(sax);
// strict mode: next byte must be EOF
if (result && strict && (get_token() != token_type::end_of_input))
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::end_of_input, "value")));
}
return result;
}
private:
template<typename SAX>
JSON_HEDLEY_NON_NULL(2)
bool sax_parse_internal(SAX* sax)
{
// stack to remember the hierarchy of structured values we are parsing
// true = array; false = object
std::vector<bool> states;
// value to avoid a goto (see comment where set to true)
bool skip_to_state_evaluation = false;
while (true)
{
if (!skip_to_state_evaluation)
{
// invariant: get_token() was called before each iteration
switch (last_token)
{
case token_type::begin_object:
{
if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
{
return false;
}
// closing } -> we are done
if (get_token() == token_type::end_object)
{
if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
{
return false;
}
break;
}
// parse key
if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::value_string, "object key")));
}
if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
{
return false;
}
// parse separator (:)
if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::name_separator, "object separator")));
}
// remember we are now inside an object
states.push_back(false);
// parse values
get_token();
continue;
}
case token_type::begin_array:
{
if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
{
return false;
}
// closing ] -> we are done
if (get_token() == token_type::end_array)
{
if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
{
return false;
}
break;
}
// remember we are now inside an array
states.push_back(true);
// parse values (no need to call get_token)
continue;
}
case token_type::value_float:
{
const auto res = m_lexer.get_number_float();
if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
}
if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
{
return false;
}
break;
}
case token_type::literal_false:
{
if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
{
return false;
}
break;
}
case token_type::literal_null:
{
if (JSON_HEDLEY_UNLIKELY(!sax->null()))
{
return false;
}
break;
}
case token_type::literal_true:
{
if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
{
return false;
}
break;
}
case token_type::value_integer:
{
if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
{
return false;
}
break;
}
case token_type::value_string:
{
if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
{
return false;
}
break;
}
case token_type::value_unsigned:
{
if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
{
return false;
}
break;
}
case token_type::parse_error:
{
// using "uninitialized" to avoid "expected" message
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::uninitialized, "value")));
}
default: // the last token was unexpected
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::literal_or_value, "value")));
}
}
}
else
{
skip_to_state_evaluation = false;
}
// we reached this line after we successfully parsed a value
if (states.empty())
{
// empty stack: we reached the end of the hierarchy: done
return true;
}
if (states.back()) // array
{
// comma -> next value
if (get_token() == token_type::value_separator)
{
// parse a new value
get_token();
continue;
}
// closing ]
if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
{
if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
{
return false;
}
// We are done with this array. Before we can parse a
// new value, we need to evaluate the new state first.
// By setting skip_to_state_evaluation to false, we
// are effectively jumping to the beginning of this if.
JSON_ASSERT(!states.empty());
states.pop_back();
skip_to_state_evaluation = true;
continue;
}
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::end_array, "array")));
}
else // object
{
// comma -> next value
if (get_token() == token_type::value_separator)
{
// parse key
if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::value_string, "object key")));
}
if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
{
return false;
}
// parse separator (:)
if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
{
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::name_separator, "object separator")));
}
// parse values
get_token();
continue;
}
// closing }
if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
{
if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
{
return false;
}
// We are done with this object. Before we can parse a
// new value, we need to evaluate the new state first.
// By setting skip_to_state_evaluation to false, we
// are effectively jumping to the beginning of this if.
JSON_ASSERT(!states.empty());
states.pop_back();
skip_to_state_evaluation = true;
continue;
}
return sax->parse_error(m_lexer.get_position(),
m_lexer.get_token_string(),
parse_error::create(101, m_lexer.get_position(),
exception_message(token_type::end_object, "object")));
}
}
}
/// get next token from lexer
token_type get_token()
{
return last_token = m_lexer.scan();
}
std::string exception_message(const token_type expected, const std::string& context)
{
std::string error_msg = "syntax error ";
if (!context.empty())
{
error_msg += "while parsing " + context + " ";
}
error_msg += "- ";
if (last_token == token_type::parse_error)
{
error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
m_lexer.get_token_string() + "'";
}
else
{
error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
}
if (expected != token_type::uninitialized)
{
error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
}
return error_msg;
}
private:
/// callback function
const parser_callback_t<BasicJsonType> callback = nullptr;
/// the type of the last read token
token_type last_token = token_type::uninitialized;
/// the lexer
lexer_t m_lexer;
/// whether to throw exceptions in case of errors
const bool allow_exceptions = true;
};
} // namespace detail
} // namespace nlohmann | c++ | code | 18,670 | 2,604 |
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "gmock/gmock.h"
#include "source/spirv_target_env.h"
#include "test/unit_spirv.h"
namespace spvtools {
namespace {
using ::testing::AnyOf;
using ::testing::Eq;
using ::testing::StartsWith;
using ::testing::ValuesIn;
using TargetEnvTest = ::testing::TestWithParam<spv_target_env>;
TEST_P(TargetEnvTest, CreateContext) {
spv_target_env env = GetParam();
spv_context context = spvContextCreate(env);
ASSERT_NE(nullptr, context);
spvContextDestroy(context); // Avoid leaking
}
TEST_P(TargetEnvTest, ValidDescription) {
const char* description = spvTargetEnvDescription(GetParam());
ASSERT_NE(nullptr, description);
ASSERT_THAT(description, StartsWith("SPIR-V "));
}
TEST_P(TargetEnvTest, ValidSpirvVersion) {
auto spirv_version = spvVersionForTargetEnv(GetParam());
ASSERT_THAT(spirv_version, AnyOf(0x10000, 0x10100, 0x10200, 0x10300));
}
INSTANTIATE_TEST_SUITE_P(AllTargetEnvs, TargetEnvTest,
ValuesIn(spvtest::AllTargetEnvironments()));
TEST(GetContextTest, InvalidTargetEnvProducesNull) {
// Use a value beyond the last valid enum value.
spv_context context = spvContextCreate(static_cast<spv_target_env>(30));
EXPECT_EQ(context, nullptr);
}
// A test case for parsing an environment string.
struct ParseCase {
const char* input;
bool success; // Expect to successfully parse?
spv_target_env env; // The parsed environment, if successful.
};
using TargetParseTest = ::testing::TestWithParam<ParseCase>;
TEST_P(TargetParseTest, Samples) {
spv_target_env env;
bool parsed = spvParseTargetEnv(GetParam().input, &env);
EXPECT_THAT(parsed, Eq(GetParam().success));
if (parsed) {
EXPECT_THAT(env, Eq(GetParam().env));
}
}
INSTANTIATE_TEST_SUITE_P(
TargetParsing, TargetParseTest,
ValuesIn(std::vector<ParseCase>{
{"spv1.0", true, SPV_ENV_UNIVERSAL_1_0},
{"spv1.1", true, SPV_ENV_UNIVERSAL_1_1},
{"spv1.2", true, SPV_ENV_UNIVERSAL_1_2},
{"spv1.3", true, SPV_ENV_UNIVERSAL_1_3},
{"vulkan1.0", true, SPV_ENV_VULKAN_1_0},
{"vulkan1.1", true, SPV_ENV_VULKAN_1_1},
{"vulkan1.2", true, SPV_ENV_VULKAN_1_2},
{"opencl2.1", true, SPV_ENV_OPENCL_2_1},
{"opencl2.2", true, SPV_ENV_OPENCL_2_2},
{"opengl4.0", true, SPV_ENV_OPENGL_4_0},
{"opengl4.1", true, SPV_ENV_OPENGL_4_1},
{"opengl4.2", true, SPV_ENV_OPENGL_4_2},
{"opengl4.3", true, SPV_ENV_OPENGL_4_3},
{"opengl4.5", true, SPV_ENV_OPENGL_4_5},
{"opencl1.2", true, SPV_ENV_OPENCL_1_2},
{"opencl1.2embedded", true, SPV_ENV_OPENCL_EMBEDDED_1_2},
{"opencl2.0", true, SPV_ENV_OPENCL_2_0},
{"opencl2.0embedded", true, SPV_ENV_OPENCL_EMBEDDED_2_0},
{"opencl2.1embedded", true, SPV_ENV_OPENCL_EMBEDDED_2_1},
{"opencl2.2embedded", true, SPV_ENV_OPENCL_EMBEDDED_2_2},
{"opencl2.3", false, SPV_ENV_UNIVERSAL_1_0},
{"opencl3.0", false, SPV_ENV_UNIVERSAL_1_0},
{"vulkan1.9", false, SPV_ENV_UNIVERSAL_1_0},
{"vulkan2.0", false, SPV_ENV_UNIVERSAL_1_0},
{nullptr, false, SPV_ENV_UNIVERSAL_1_0},
{"", false, SPV_ENV_UNIVERSAL_1_0},
{"abc", false, SPV_ENV_UNIVERSAL_1_0},
}));
// A test case for parsing an environment string.
struct ParseVulkanCase {
uint32_t vulkan;
uint32_t spirv;
bool success; // Expect to successfully parse?
spv_target_env env; // The parsed environment, if successful.
};
using TargetParseVulkanTest = ::testing::TestWithParam<ParseVulkanCase>;
TEST_P(TargetParseVulkanTest, Samples) {
spv_target_env env;
bool parsed = spvParseVulkanEnv(GetParam().vulkan, GetParam().spirv, &env);
EXPECT_THAT(parsed, Eq(GetParam().success));
if (parsed) {
EXPECT_THAT(env, Eq(GetParam().env));
}
}
#define VK(MAJ, MIN) ((MAJ << 22) | (MIN << 12))
#define SPV(MAJ, MIN) ((MAJ << 16) | (MIN << 8))
INSTANTIATE_TEST_SUITE_P(
TargetVulkanParsing, TargetParseVulkanTest,
ValuesIn(std::vector<ParseVulkanCase>{
// Vulkan 1.0 cases
{VK(1, 0), SPV(1, 0), true, SPV_ENV_VULKAN_1_0},
{VK(1, 0), SPV(1, 1), true, SPV_ENV_VULKAN_1_1},
{VK(1, 0), SPV(1, 2), true, SPV_ENV_VULKAN_1_1},
{VK(1, 0), SPV(1, 3), true, SPV_ENV_VULKAN_1_1},
{VK(1, 0), SPV(1, 4), true, SPV_ENV_VULKAN_1_1_SPIRV_1_4},
{VK(1, 0), SPV(1, 5), true, SPV_ENV_VULKAN_1_2},
{VK(1, 0), SPV(1, 6), true, SPV_ENV_VULKAN_1_3},
{VK(1, 0), SPV(1, 7), false, SPV_ENV_UNIVERSAL_1_0},
// Vulkan 1.1 cases
{VK(1, 1), SPV(1, 0), true, SPV_ENV_VULKAN_1_1},
{VK(1, 1), SPV(1, 1), true, SPV_ENV_VULKAN_1_1},
{VK(1, 1), SPV(1, 2), true, SPV_ENV_VULKAN_1_1},
{VK(1, 1), SPV(1, 3), true, SPV_ENV_VULKAN_1_1},
{VK(1, 1), SPV(1, 4), true, SPV_ENV_VULKAN_1_1_SPIRV_1_4},
{VK(1, 1), SPV(1, 5), true, SPV_ENV_VULKAN_1_2},
{VK(1, 1), SPV(1, 6), true, SPV_ENV_VULKAN_1_3},
{VK(1, 1), SPV(1, 7), false, SPV_ENV_UNIVERSAL_1_0},
// Vulkan 1.2 cases
{VK(1, 2), SPV(1, 0), true, SPV_ENV_VULKAN_1_2},
{VK(1, 2), SPV(1, 1), true, SPV_ENV_VULKAN_1_2},
{VK(1, 2), SPV(1, 2), true, SPV_ENV_VULKAN_1_2},
{VK(1, 2), SPV(1, 3), true, SPV_ENV_VULKAN_1_2},
{VK(1, 2), SPV(1, 4), true, SPV_ENV_VULKAN_1_2},
{VK(1, 2), SPV(1, 5), true, SPV_ENV_VULKAN_1_2},
{VK(1, 2), SPV(1, 6), true, SPV_ENV_VULKAN_1_3},
{VK(1, 2), SPV(1, 7), false, SPV_ENV_UNIVERSAL_1_0},
// Vulkan 1.3 cases
{VK(1, 3), SPV(1, 0), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 1), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 2), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 3), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 4), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 5), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 6), true, SPV_ENV_VULKAN_1_3},
{VK(1, 3), SPV(1, 7), false, SPV_ENV_UNIVERSAL_1_0},
// Vulkan 2.0 cases
{VK(2, 0), SPV(1, 0), false, SPV_ENV_UNIVERSAL_1_0},
// Vulkan 99.0 cases
{VK(99, 0), SPV(1, 0), false, SPV_ENV_UNIVERSAL_1_0},
}));
} // namespace
} // namespace spvtools | c++ | code | 6,815 | 1,650 |
#include "image_browser.hpp"
void image_browser::AddFullRow(const image_browser::ImageRow& row, bool first_row){
html_writer::OpenRow();
size_t i = 0;
for (const auto& item : row){
image_browser::ScoredImage si = item;
html_writer::AddImage(std::get<0>(si), std::get<1>(si), (i==0&&first_row));
i+=1;
}
html_writer::CloseRow();
}
void image_browser::CreateImageBrowser(const std::string& title, const std::string& stylesheet,
const std::vector<image_browser::ImageRow>& rows){
html_writer::OpenDocument();
html_writer::AddTitle(title);
html_writer::AddCSSStyle(stylesheet);
html_writer::OpenBody();
size_t i = 0;
for (const auto& row : rows){
AddFullRow(row, i==0);
i+=1;
}
html_writer::CloseBody();
html_writer::CloseDocument();
} | c++ | code | 805 | 212 |
#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_writer.h>
#include <library/cpp/unittest/registar.h>
#include <util/stream/str.h>
using namespace NJson;
class TReformatCallbacks: public TJsonCallbacks {
TJsonWriter& Writer;
public:
TReformatCallbacks(TJsonWriter& writer)
: Writer(writer)
{
}
bool OnBoolean(bool val) override {
Writer.Write(val);
return true;
}
bool OnInteger(long long val) override {
Writer.Write(val);
return true;
}
bool OnUInteger(unsigned long long val) override {
Writer.Write(val);
return true;
}
bool OnString(const TStringBuf& val) override {
Writer.Write(val);
return true;
}
bool OnDouble(double val) override {
Writer.Write(val);
return true;
}
bool OnOpenArray() override {
Writer.OpenArray();
return true;
}
bool OnCloseArray() override {
Writer.CloseArray();
return true;
}
bool OnOpenMap() override {
Writer.OpenArray();
return true;
}
bool OnCloseMap() override {
Writer.CloseArray();
return true;
}
bool OnMapKey(const TStringBuf& val) override {
Writer.Write(val);
return true;
}
};
Y_UNIT_TEST_SUITE(TJsonReaderTest) {
Y_UNIT_TEST(JsonReformatTest) {
TString data = "{\"null value\": null, \"intkey\": 10, \"double key\": 11.11, \"string key\": \"string\", \"array\": [1,2,3,\"TString\"], \"bool key\": true}";
TString result1, result2;
{
TStringStream in;
in << data;
TStringStream out;
TJsonWriter writer(&out, false);
TReformatCallbacks cb(writer);
ReadJson(&in, &cb);
writer.Flush();
result1 = out.Str();
}
{
TStringStream in;
in << result1;
TStringStream out;
TJsonWriter writer(&out, false);
TReformatCallbacks cb(writer);
ReadJson(&in, &cb);
writer.Flush();
result2 = out.Str();
}
UNIT_ASSERT_VALUES_EQUAL(result1, result2);
}
Y_UNIT_TEST(TJsonEscapedApostrophe) {
TString jsonString = "{ \"foo\" : \"bar\\'buzz\" }";
{
TStringStream in;
in << jsonString;
TStringStream out;
TJsonWriter writer(&out, false);
TReformatCallbacks cb(writer);
UNIT_ASSERT(!ReadJson(&in, &cb));
}
{
TStringStream in;
in << jsonString;
TStringStream out;
TJsonWriter writer(&out, false);
TReformatCallbacks cb(writer);
UNIT_ASSERT(ReadJson(&in, false, true, &cb));
writer.Flush();
UNIT_ASSERT_EQUAL(out.Str(), "[\"foo\",\"bar'buzz\"]");
}
}
Y_UNIT_TEST(TJsonTreeTest) {
TString data = "{\"intkey\": 10, \"double key\": 11.11, \"null value\":null, \"string key\": \"string\", \"array\": [1,2,3,\"TString\"], \"bool key\": true}";
TStringStream in;
in << data;
TJsonValue value;
ReadJsonTree(&in, &value);
UNIT_ASSERT_VALUES_EQUAL(value["intkey"].GetInteger(), 10);
UNIT_ASSERT_DOUBLES_EQUAL(value["double key"].GetDouble(), 11.11, 0.001);
UNIT_ASSERT_VALUES_EQUAL(value["bool key"].GetBoolean(), true);
UNIT_ASSERT_VALUES_EQUAL(value["string key"].GetString(), TString("string"));
UNIT_ASSERT_VALUES_EQUAL(value["array"][0].GetInteger(), 1);
UNIT_ASSERT_VALUES_EQUAL(value["array"][1].GetInteger(), 2);
UNIT_ASSERT_VALUES_EQUAL(value["array"][2].GetInteger(), 3);
UNIT_ASSERT_VALUES_EQUAL(value["array"][3].GetString(), TString("TString"));
UNIT_ASSERT(value["null value"].IsNull());
// AsString
UNIT_ASSERT_VALUES_EQUAL(value["intkey"].GetStringRobust(), "10");
UNIT_ASSERT_VALUES_EQUAL(value["double key"].GetStringRobust(), "11.11");
UNIT_ASSERT_VALUES_EQUAL(value["bool key"].GetStringRobust(), "true");
UNIT_ASSERT_VALUES_EQUAL(value["string key"].GetStringRobust(), "string");
UNIT_ASSERT_VALUES_EQUAL(value["array"].GetStringRobust(), "[1,2,3,\"TString\"]");
UNIT_ASSERT_VALUES_EQUAL(value["null value"].GetStringRobust(), "null");
const TJsonValue::TArray* array;
UNIT_ASSERT(GetArrayPointer(value, "array", &array));
UNIT_ASSERT_VALUES_EQUAL(value["array"].GetArray().size(), array->size());
UNIT_ASSERT_VALUES_EQUAL(value["array"][0].GetInteger(), (*array)[0].GetInteger());
UNIT_ASSERT_VALUES_EQUAL(value["array"][1].GetInteger(), (*array)[1].GetInteger());
UNIT_ASSERT_VALUES_EQUAL(value["array"][2].GetInteger(), (*array)[2].GetInteger());
UNIT_ASSERT_VALUES_EQUAL(value["array"][3].GetString(), (*array)[3].GetString());
}
Y_UNIT_TEST(TJsonRomaTest) {
TString data = "{\"test\": [ {\"name\": \"A\"} ]}";
TStringStream in;
in << data;
TJsonValue value;
ReadJsonTree(&in, &value);
UNIT_ASSERT_VALUES_EQUAL(value["test"][0]["name"].GetString(), TString("A"));
}
Y_UNIT_TEST(TJsonReadTreeWithComments) {
{
TString leadingCommentData = "{ // \"test\" : 1 \n}";
{
// No comments allowed
TStringStream in;
in << leadingCommentData;
TJsonValue value;
UNIT_ASSERT(!ReadJsonTree(&in, false, &value));
}
{
// Comments allowed
TStringStream in;
in << leadingCommentData;
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, true, &value));
UNIT_ASSERT(!value.Has("test"));
}
}
{
TString trailingCommentData = "{ \"test1\" : 1 // \"test2\" : 2 \n }";
{
// No comments allowed
TStringStream in;
in << trailingCommentData;
TJsonValue value;
UNIT_ASSERT(!ReadJsonTree(&in, false, &value));
}
{
// Comments allowed
TStringStream in;
in << trailingCommentData;
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, true, &value));
UNIT_ASSERT(value.Has("test1"));
UNIT_ASSERT_EQUAL(value["test1"].GetInteger(), 1);
UNIT_ASSERT(!value.Has("test2"));
}
}
}
Y_UNIT_TEST(TJsonSignedIntegerTest) {
{
TStringStream in;
in << "{ \"test\" : " << Min<i64>() << " }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsInteger());
UNIT_ASSERT(!value["test"].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"].GetInteger(), Min<i64>());
UNIT_ASSERT_EQUAL(value["test"].GetIntegerRobust(), Min<i64>());
} // Min<i64>()
{
TStringStream in;
in << "{ \"test\" : " << Max<i64>() + 1ull << " }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(!value["test"].IsInteger());
UNIT_ASSERT(value["test"].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"].GetIntegerRobust(), (i64)(Max<i64>() + 1ull));
} // Max<i64>() + 1
}
Y_UNIT_TEST(TJsonUnsignedIntegerTest) {
{
TStringStream in;
in << "{ \"test\" : 1 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsInteger());
UNIT_ASSERT(value["test"].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"].GetInteger(), 1);
UNIT_ASSERT_EQUAL(value["test"].GetIntegerRobust(), 1);
UNIT_ASSERT_EQUAL(value["test"].GetUInteger(), 1);
UNIT_ASSERT_EQUAL(value["test"].GetUIntegerRobust(), 1);
} // 1
{
TStringStream in;
in << "{ \"test\" : -1 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsInteger());
UNIT_ASSERT(!value["test"].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"].GetInteger(), -1);
UNIT_ASSERT_EQUAL(value["test"].GetIntegerRobust(), -1);
UNIT_ASSERT_EQUAL(value["test"].GetUInteger(), 0);
UNIT_ASSERT_EQUAL(value["test"].GetUIntegerRobust(), static_cast<unsigned long long>(-1));
} // -1
{
TStringStream in;
in << "{ \"test\" : 18446744073709551615 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(!value["test"].IsInteger());
UNIT_ASSERT(value["test"].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"].GetInteger(), 0);
UNIT_ASSERT_EQUAL(value["test"].GetIntegerRobust(), static_cast<long long>(18446744073709551615ull));
UNIT_ASSERT_EQUAL(value["test"].GetUInteger(), 18446744073709551615ull);
UNIT_ASSERT_EQUAL(value["test"].GetUIntegerRobust(), 18446744073709551615ull);
} // 18446744073709551615
{
TStringStream in;
in << "{ \"test\" : 1.1 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(!value["test"].IsInteger());
UNIT_ASSERT(!value["test"].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"].GetInteger(), 0);
UNIT_ASSERT_EQUAL(value["test"].GetIntegerRobust(), static_cast<long long>(1.1));
UNIT_ASSERT_EQUAL(value["test"].GetUInteger(), 0);
UNIT_ASSERT_EQUAL(value["test"].GetUIntegerRobust(), static_cast<unsigned long long>(1.1));
} // 1.1
{
TStringStream in;
in << "{ \"test\" : [1, 18446744073709551615] }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsArray());
UNIT_ASSERT_EQUAL(value["test"].GetArray().size(), 2);
UNIT_ASSERT(value["test"][0].IsInteger());
UNIT_ASSERT(value["test"][0].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"][0].GetInteger(), 1);
UNIT_ASSERT_EQUAL(value["test"][0].GetUInteger(), 1);
UNIT_ASSERT(!value["test"][1].IsInteger());
UNIT_ASSERT(value["test"][1].IsUInteger());
UNIT_ASSERT_EQUAL(value["test"][1].GetUInteger(), 18446744073709551615ull);
}
} // TJsonUnsignedIntegerTest
Y_UNIT_TEST(TJsonDoubleTest) {
{
TStringStream in;
in << "{ \"test\" : 1.0 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsDouble());
UNIT_ASSERT_EQUAL(value["test"].GetDouble(), 1.0);
UNIT_ASSERT_EQUAL(value["test"].GetDoubleRobust(), 1.0);
} // 1.0
{
TStringStream in;
in << "{ \"test\" : 1 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsDouble());
UNIT_ASSERT_EQUAL(value["test"].GetDouble(), 1.0);
UNIT_ASSERT_EQUAL(value["test"].GetDoubleRobust(), 1.0);
} // 1
{
TStringStream in;
in << "{ \"test\" : -1 }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(value["test"].IsDouble());
UNIT_ASSERT_EQUAL(value["test"].GetDouble(), -1.0);
UNIT_ASSERT_EQUAL(value["test"].GetDoubleRobust(), -1.0);
} // -1
{
TStringStream in;
in << "{ \"test\" : " << Max<ui64>() << " }";
TJsonValue value;
UNIT_ASSERT(ReadJsonTree(&in, &value));
UNIT_ASSERT(value.Has("test"));
UNIT_ASSERT(!value["test"].IsDouble());
UNIT_ASSERT_EQUAL(value["test"].GetDouble(), 0.0);
UNIT_ASSERT_EQUAL(value["test"].GetDoubleRobust(), static_cast<double>(Max<ui64>()));
} // Max<ui64>()
} // TJsonDoubleTest
Y_UNIT_TEST(TJsonInvalidTest) {
{
// No exceptions mode.
TStringStream in;
in << "{ \"test\" : }";
TJsonValue value;
UNIT_ASSERT(!ReadJsonTree(&in, &value));
}
{
// Exception throwing mode.
TStringStream in;
in << "{ \"test\" : }";
TJsonValue value;
UNIT_ASSERT_EXCEPTION(ReadJsonTree(&in, &value, true), TJsonException);
}
}
Y_UNIT_TEST(TJsonMemoryLeakTest) {
// after https://clubs.at.yandex-team.ru/stackoverflow/3691
TString s = ".";
NJson::TJsonValue json;
try {
TStringInput in(s);
NJson::ReadJsonTree(&in, &json, true);
} catch (...) {
}
} // TJsonMemoryLeakTest
Y_UNIT_TEST(TJsonDuplicateKeysWithNullValuesTest) {
const TString json = "{\"\":null,\"\":\"\"}";
TStringInput in(json);
NJson::TJsonValue v;
UNIT_ASSERT(ReadJsonTree(&in, &v));
UNIT_ASSERT(v.IsMap());
UNIT_ASSERT_VALUES_EQUAL(1, v.GetMap().size());
UNIT_ASSERT_VALUES_EQUAL("", v.GetMap().begin()->first);
UNIT_ASSERT(v.GetMap().begin()->second.IsString());
UNIT_ASSERT_VALUES_EQUAL("", v.GetMap().begin()->second.GetString());
}
}
static const TString YANDEX_STREAMING_JSON("{\"a\":1}//d{\"b\":2}");
Y_UNIT_TEST_SUITE(TCompareReadJsonFast) {
Y_UNIT_TEST(NoEndl) {
NJson::TJsonValue parsed;
bool success = NJson::ReadJsonTree(YANDEX_STREAMING_JSON, &parsed, false);
bool fast_success = NJson::ReadJsonFastTree(YANDEX_STREAMING_JSON, &parsed, false);
UNIT_ASSERT(success == fast_success);
}
Y_UNIT_TEST(WithEndl) {
NJson::TJsonValue parsed1;
NJson::TJsonValue parsed2;
bool success = NJson::ReadJsonTree(YANDEX_STREAMING_JSON + "\n", &parsed1, false);
bool fast_success = NJson::ReadJsonFastTree(YANDEX_STREAMING_JSON + "\n", &parsed2, false);
UNIT_ASSERT_VALUES_EQUAL(success, fast_success);
}
Y_UNIT_TEST(NoQuotes) {
TString streamingJson = "{a:1}";
NJson::TJsonValue parsed;
bool success = NJson::ReadJsonTree(streamingJson, &parsed, false);
bool fast_success = NJson::ReadJsonFastTree(streamingJson, &parsed, false);
UNIT_ASSERT(success != fast_success);
}
} | c++ | code | 15,297 | 3,440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.