text
stringlengths 5
1.04M
|
|---|
// Copyright (c) 2007-2011 Hartmut Kaiser
// Copyright (c) 2011 Bryce Adelstein-Lelbach
//
// 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(HPX_ECFE19F9_A826_4AE1_AC7C_33DC5714CF0B)
#define HPX_ECFE19F9_A826_4AE1_AC7C_33DC5714CF0B
#include <hpx/include/components.hpp>
#include "stubs/simple_accumulator.hpp"
namespace examples
{
///////////////////////////////////////////////////////////////////////////
/// Client for the \a server::simple_accumulator component.
class simple_accumulator
: public hpx::components::client_base<
simple_accumulator, stubs::simple_accumulator
>
{
typedef hpx::components::client_base<
simple_accumulator, stubs::simple_accumulator
> base_type;
typedef base_type::argument_type argument_type;
public:
/// Default construct an empty client side representation (not
/// connected to any existing component).
simple_accumulator()
{}
/// Create a client side representation for the existing
/// \a server::simple_accumulator instance with the given GID.
simple_accumulator(hpx::future<hpx::naming::id_type> && gid)
: base_type(std::move(gid))
{}
///////////////////////////////////////////////////////////////////////
/// Reset the accumulator's value to 0.
///
/// \note This function has fire-and-forget semantics. It will not wait
/// for the action to be executed. Instead, it will return
/// immediately after the action has has been dispatched.
void reset_non_blocking()
{
HPX_ASSERT(this->get_id());
this->base_type::reset_non_blocking(this->get_id());
}
/// Reset the accumulator's value to 0.
///
/// \note This function is fully synchronous.
void reset_sync()
{
HPX_ASSERT(this->get_id());
this->base_type::reset_sync(this->get_id());
}
///////////////////////////////////////////////////////////////////////
/// Add \p arg to the accumulator's value.
///
/// \note This function has fire-and-forget semantics. It will not wait
/// for the action to be executed. Instead, it will return
/// immediately after the action has has been dispatched.
void add_non_blocking(argument_type arg)
{
HPX_ASSERT(this->get_id());
this->base_type::add_non_blocking(this->get_id(), arg);
}
/// Add \p arg to the accumulator's value.
///
/// \note This function is fully synchronous.
void add_sync(argument_type arg)
{
HPX_ASSERT(this->get_id());
this->base_type::add_sync(this->get_id(), arg);
}
///////////////////////////////////////////////////////////////////////
/// Asynchronously query the current value of the accumulator.
///
/// \returns This function returns an \a hpx::lcos::future. When the
/// value of this computation is needed, the get() method of
/// the future should be called. If the value is available,
/// get() will return immediately; otherwise, it will block
/// until the value is ready.
hpx::lcos::future<argument_type> query_async()
{
HPX_ASSERT(this->get_id());
return this->base_type::query_async(this->get_id());
}
/// Query the current value of the accumulator.
///
/// \note This function is fully synchronous.
argument_type query_sync()
{
HPX_ASSERT(this->get_id());
return this->base_type::query_sync(this->get_id());
}
};
}
#endif
|
//==============================================================================
///
/// File: ScriptingStringSwitcher.cpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Scripting/ScriptingStringSwitcher.hpp"
#include "DT3Core/System/Factory.hpp"
#include "DT3Core/System/Profiler.hpp"
#include "DT3Core/Types/FileBuffer/ArchiveData.hpp"
#include "DT3Core/Types/FileBuffer/Archive.hpp"
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Register with object factory
//==============================================================================
IMPLEMENT_FACTORY_CREATION_SCRIPT(ScriptingStringSwitcher,"Switches",NULL)
IMPLEMENT_PLUG_NODE(ScriptingStringSwitcher)
IMPLEMENT_PLUG_INFO_INDEX(_in1)
IMPLEMENT_PLUG_INFO_INDEX(_in_string1)
IMPLEMENT_PLUG_INFO_INDEX(_in2)
IMPLEMENT_PLUG_INFO_INDEX(_in_string2)
IMPLEMENT_PLUG_INFO_INDEX(_in3)
IMPLEMENT_PLUG_INFO_INDEX(_in_string3)
IMPLEMENT_PLUG_INFO_INDEX(_in4)
IMPLEMENT_PLUG_INFO_INDEX(_in_string4)
IMPLEMENT_PLUG_INFO_INDEX(_in5)
IMPLEMENT_PLUG_INFO_INDEX(_in_string5)
IMPLEMENT_PLUG_INFO_INDEX(_in6)
IMPLEMENT_PLUG_INFO_INDEX(_in_string6)
IMPLEMENT_PLUG_INFO_INDEX(_in7)
IMPLEMENT_PLUG_INFO_INDEX(_in_string7)
IMPLEMENT_PLUG_INFO_INDEX(_in8)
IMPLEMENT_PLUG_INFO_INDEX(_in_string8)
IMPLEMENT_PLUG_INFO_INDEX(_in9)
IMPLEMENT_PLUG_INFO_INDEX(_in_string9)
IMPLEMENT_PLUG_INFO_INDEX(_in10)
IMPLEMENT_PLUG_INFO_INDEX(_in_string10)
IMPLEMENT_PLUG_INFO_INDEX(_in11)
IMPLEMENT_PLUG_INFO_INDEX(_in_string11)
IMPLEMENT_PLUG_INFO_INDEX(_in12)
IMPLEMENT_PLUG_INFO_INDEX(_in_string12)
IMPLEMENT_PLUG_INFO_INDEX(_in13)
IMPLEMENT_PLUG_INFO_INDEX(_in_string13)
IMPLEMENT_PLUG_INFO_INDEX(_in14)
IMPLEMENT_PLUG_INFO_INDEX(_in_string14)
IMPLEMENT_PLUG_INFO_INDEX(_in15)
IMPLEMENT_PLUG_INFO_INDEX(_in_string15)
IMPLEMENT_PLUG_INFO_INDEX(_in16)
IMPLEMENT_PLUG_INFO_INDEX(_in_string16)
IMPLEMENT_PLUG_INFO_INDEX(_out)
//==============================================================================
//==============================================================================
BEGIN_IMPLEMENT_PLUGS(ScriptingStringSwitcher)
PLUG_INIT(_in1,"In_1")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string1,"String_1")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in2,"In_2")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string2,"String_2")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in3,"In_3")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string3,"String_3")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in4,"In_4")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string4,"String_4")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in5,"In_5")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string5,"String_5")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in6,"In_6")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string6,"String_6")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in7,"In_7")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string7,"String_7")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in8,"In_8")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string8,"String_8")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in9,"In_9")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string9,"String_9")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in10,"In_10")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string10,"String_10")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in11,"In_11")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string11,"String_11")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in12,"In_12")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string12,"String_12")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in13,"In_13")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string13,"String_13")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in14,"In_14")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string14,"String_14")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in15,"In_15")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string15,"String_15")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in16,"In_16")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_in_string16,"String_16")
.set_input(true)
.affects(PLUG_INFO_INDEX(_out));
PLUG_INIT(_out,"Out")
.set_output(true);
END_IMPLEMENT_PLUGS
//==============================================================================
/// Standard class constructors/destructors
//==============================================================================
ScriptingStringSwitcher::ScriptingStringSwitcher (void)
: _in1 (PLUG_INFO_INDEX(_in1), false),
_in_string1 (PLUG_INFO_INDEX(_in_string1)),
_in2 (PLUG_INFO_INDEX(_in2), false),
_in_string2 (PLUG_INFO_INDEX(_in_string2)),
_in3 (PLUG_INFO_INDEX(_in3), false),
_in_string3 (PLUG_INFO_INDEX(_in_string3)),
_in4 (PLUG_INFO_INDEX(_in4), false),
_in_string4 (PLUG_INFO_INDEX(_in_string4)),
_in5 (PLUG_INFO_INDEX(_in5), false),
_in_string5 (PLUG_INFO_INDEX(_in_string5)),
_in6 (PLUG_INFO_INDEX(_in6), false),
_in_string6 (PLUG_INFO_INDEX(_in_string6)),
_in7 (PLUG_INFO_INDEX(_in7), false),
_in_string7 (PLUG_INFO_INDEX(_in_string7)),
_in8 (PLUG_INFO_INDEX(_in8), false),
_in_string8 (PLUG_INFO_INDEX(_in_string8)),
_in9 (PLUG_INFO_INDEX(_in9), false),
_in_string9 (PLUG_INFO_INDEX(_in_string9)),
_in10 (PLUG_INFO_INDEX(_in10), false),
_in_string10 (PLUG_INFO_INDEX(_in_string10)),
_in11 (PLUG_INFO_INDEX(_in11), false),
_in_string11 (PLUG_INFO_INDEX(_in_string11)),
_in12 (PLUG_INFO_INDEX(_in12), false),
_in_string12 (PLUG_INFO_INDEX(_in_string12)),
_in13 (PLUG_INFO_INDEX(_in13), false),
_in_string13 (PLUG_INFO_INDEX(_in_string13)),
_in14 (PLUG_INFO_INDEX(_in14), false),
_in_string14 (PLUG_INFO_INDEX(_in_string14)),
_in15 (PLUG_INFO_INDEX(_in15), false),
_in_string15 (PLUG_INFO_INDEX(_in_string15)),
_in16 (PLUG_INFO_INDEX(_in16), false),
_in_string16 (PLUG_INFO_INDEX(_in_string16)),
_buffer_output (false),
_out (PLUG_INFO_INDEX(_out))
{
}
ScriptingStringSwitcher::ScriptingStringSwitcher (const ScriptingStringSwitcher &rhs)
: ScriptingBase (rhs),
_in1 (rhs._in1),
_in_string1 (rhs._in_string1),
_in2 (rhs._in2),
_in_string2 (rhs._in_string2),
_in3 (rhs._in3),
_in_string3 (rhs._in_string3),
_in4 (rhs._in4),
_in_string4 (rhs._in_string4),
_in5 (rhs._in5),
_in_string5 (rhs._in_string5),
_in6 (rhs._in6),
_in_string6 (rhs._in_string6),
_in7 (rhs._in7),
_in_string7 (rhs._in_string7),
_in8 (rhs._in8),
_in_string8 (rhs._in_string8),
_in9 (rhs._in9),
_in_string9 (rhs._in_string9),
_in10 (rhs._in10),
_in_string10 (rhs._in_string10),
_in11 (rhs._in11),
_in_string11 (rhs._in_string11),
_in12 (rhs._in12),
_in_string12 (rhs._in_string12),
_in13 (rhs._in13),
_in_string13 (rhs._in_string13),
_in14 (rhs._in14),
_in_string14 (rhs._in_string14),
_in15 (rhs._in15),
_in_string15 (rhs._in_string15),
_in16 (rhs._in16),
_in_string16 (rhs._in_string16),
_buffer_output (rhs._buffer_output),
_out (rhs._out)
{
}
ScriptingStringSwitcher & ScriptingStringSwitcher::operator = (const ScriptingStringSwitcher &rhs)
{
// Make sure we are not assigning the class to itself
if (&rhs != this) {
ScriptingBase::operator = (rhs);
_in1 = rhs._in1;
_in_string1 = rhs._in_string1;
_in2 = rhs._in2;
_in_string2 = rhs._in_string2;
_in3 = rhs._in3;
_in_string3 = rhs._in_string3;
_in4 = rhs._in4;
_in_string4 = rhs._in_string4;
_in5 = rhs._in5;
_in_string5 = rhs._in_string5;
_in6 = rhs._in6;
_in_string6 = rhs._in_string6;
_in7 = rhs._in7;
_in_string7 = rhs._in_string7;
_in8 = rhs._in8;
_in_string8 = rhs._in_string8;
_in9 = rhs._in9;
_in_string9 = rhs._in_string9;
_in10 = rhs._in10;
_in_string10 = rhs._in_string10;
_in11 = rhs._in11;
_in_string11 = rhs._in_string11;
_in12 = rhs._in12;
_in_string12 = rhs._in_string12;
_in13 = rhs._in13;
_in_string13 = rhs._in_string13;
_in14 = rhs._in14;
_in_string14 = rhs._in_string14;
_in15 = rhs._in15;
_in_string15 = rhs._in_string15;
_in16 = rhs._in16;
_in_string16 = rhs._in_string16;
_buffer_output = rhs._buffer_output;
_out = rhs._out;
}
return (*this);
}
ScriptingStringSwitcher::~ScriptingStringSwitcher (void)
{
}
//==============================================================================
//==============================================================================
void ScriptingStringSwitcher::initialize (void)
{
ScriptingBase::initialize();
}
//==============================================================================
//==============================================================================
void ScriptingStringSwitcher::archive (const std::shared_ptr<Archive> &archive)
{
ScriptingBase::archive(archive);
archive->push_domain (class_id ());
*archive << ARCHIVE_PLUG(_in1, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string1, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in2, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string2, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in3, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string3, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in4, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string4, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in5, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string5, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in6, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string6, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in7, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string7, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in8, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string8, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in9, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string9, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in10, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string10, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in11, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string11, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in12, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string12, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in13, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string13, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in14, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string14, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in15, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string15, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in16, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_in_string16, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_DATA(_buffer_output, DATA_PERSISTENT | DATA_SETTABLE);
*archive << ARCHIVE_PLUG(_out, DATA_PERSISTENT);
archive->pop_domain ();
}
//==============================================================================
//==============================================================================
DTboolean ScriptingStringSwitcher::compute (const PlugBase *plug)
{
PROFILER(SCRIPTING);
if (super_type::compute(plug)) return true;
if (plug == &_out) {
if (_in16) _out = _in_string16;
else if (_in15) _out = _in_string15;
else if (_in14) _out = _in_string14;
else if (_in13) _out = _in_string13;
else if (_in12) _out = _in_string12;
else if (_in11) _out = _in_string11;
else if (_in10) _out = _in_string10;
else if (_in9) _out = _in_string9;
else if (_in8) _out = _in_string8;
else if (_in7) _out = _in_string7;
else if (_in6) _out = _in_string6;
else if (_in5) _out = _in_string5;
else if (_in4) _out = _in_string4;
else if (_in3) _out = _in_string3;
else if (_in2) _out = _in_string2;
else if (_in1) _out = _in_string1;
else if (!_buffer_output) _out = "";
_out.set_clean();
return true;
}
return false;
}
//==============================================================================
//==============================================================================
} // DT3
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// REQUIRES: modules-build
// WARNING: This test was generated by 'generate_private_header_tests.py'
// and should not be edited manually.
// expected-error@*:* {{use of private header from outside its module: '__memory/concepts.h'}}
#include <__memory/concepts.h>
|
/* Copyright (C) 2020 European Spallation Source, ERIC. See LICENSE file */
//===----------------------------------------------------------------------===//
///
/// \file MainWindow.cpp
///
//===----------------------------------------------------------------------===//
#include "ui_MainWindow.h"
#include <MainWindow.h>
#include <string.h>
MainWindow::MainWindow(Configuration &Config, QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), mConfig(Config) {
ui->setupUi(this);
if (strcmp(Config.Plot.PlotType.c_str(), "tof") == 0) {
TOF = true;
}
if (!TOF) {
// Always create the XY plot
Plot2DXY = new Custom2DPlot(mConfig, 0);
ui->gridLayout->addWidget(Plot2DXY, 0, 0, 1, 1);
// If detector is 3D, also create XZ and YZ
if (Config.Geometry.ZDim > 1) {
Plot2DXZ = new Custom2DPlot(mConfig, 1);
ui->gridLayout->addWidget(Plot2DXZ, 0, 1, 1, 1);
Plot2DYZ = new Custom2DPlot(mConfig, 2);
ui->gridLayout->addWidget(Plot2DYZ, 0, 2, 1, 1);
}
} else {
PlotTOF = new CustomTofPlot(mConfig);
ui->gridLayout->addWidget(PlotTOF, 0, 0, 1, 1);
}
ui->lblDescriptionText->setText(mConfig.Plot.PlotTitle.c_str());
ui->lblEventRateText->setText("0");
connect(ui->pushButtonQuit, SIGNAL(clicked()), this,
SLOT(handleExitButton()));
connect(ui->pushButtonClear, SIGNAL(clicked()), this,
SLOT(handleClearButton()));
connect(ui->pushButtonLog, SIGNAL(clicked()), this, SLOT(handleLogButton()));
connect(ui->pushButtonGradient, SIGNAL(clicked()), this,
SLOT(handleGradientButton()));
connect(ui->pushButtonInvert, SIGNAL(clicked()), this,
SLOT(handleInvertButton()));
connect(ui->pushButtonAutoScale, SIGNAL(clicked()), this,
SLOT(handleAutoScaleButton()));
updateGradientLabel();
updateAutoScaleLabel();
show();
startKafkaConsumerThread();
}
MainWindow::~MainWindow() { delete ui; }
void MainWindow::startKafkaConsumerThread() {
KafkaConsumerThread = new WorkerThread(mConfig);
qRegisterMetaType<int>("uint64_t&");
connect(KafkaConsumerThread, &WorkerThread::resultReady, this,
&MainWindow::handleKafkaData);
KafkaConsumerThread->start();
}
// SLOT
void MainWindow::handleKafkaData(int EventRate) {
ui->lblEventRateText->setText(QString::number(EventRate));
ui->lblDiscardedPixelsText->setText(
QString::number(KafkaConsumerThread->consumer()->PixelDiscard));
KafkaConsumerThread->mutex.lock();
if (!TOF) {
Plot2DXY->addData(KafkaConsumerThread->consumer()->mHistogramPlot);
if (mConfig.Geometry.ZDim > 1) {
Plot2DXZ->addData(KafkaConsumerThread->consumer()->mHistogramPlot);
Plot2DYZ->addData(KafkaConsumerThread->consumer()->mHistogramPlot);
}
} else {
PlotTOF->addData(KafkaConsumerThread->consumer()->mHistogramTofPlot);
}
KafkaConsumerThread->mutex.unlock();
}
// SLOT
void MainWindow::handleExitButton() { QApplication::quit(); }
void MainWindow::handleClearButton() {
if (!TOF) {
Plot2DXY->clearDetectorImage();
if (mConfig.Geometry.ZDim > 1) {
Plot2DXZ->clearDetectorImage();
Plot2DYZ->clearDetectorImage();
}
} else {
PlotTOF->clearDetectorImage();
}
}
void MainWindow::updateGradientLabel() {
// Gradient button and lables are not relevant for TOF so we hide them
if (TOF) {
ui->pushButtonGradient->setVisible(false);
ui->pushButtonInvert->setVisible(false);
ui->lblGradientText->setVisible(false);
ui->lblGradient->setVisible(false);
return;
}
if (mConfig.Plot.InvertGradient)
ui->lblGradientText->setText(
QString::fromStdString(mConfig.Plot.ColorGradient + " (I)"));
else
ui->lblGradientText->setText(
QString::fromStdString(mConfig.Plot.ColorGradient));
}
void MainWindow::updateAutoScaleLabel() {
// AutoScale button and lables are not relevant for TOF so we hide them
if (not TOF) {
ui->pushButtonAutoScale->setVisible(false);
ui->lblAutoScaleText->setVisible(false);
ui->lblAutoScale->setVisible(false);
return;
}
if (mConfig.TOF.AutoScale)
ui->lblAutoScaleText->setText(QString::fromStdString("on"));
else
ui->lblAutoScaleText->setText(QString::fromStdString("off"));
}
// toggle the log scale flag
void MainWindow::handleLogButton() {
mConfig.Plot.LogScale = not mConfig.Plot.LogScale;
}
// toggle the invert gradient flag
void MainWindow::handleInvertButton() {
if (TOF)
return;
mConfig.Plot.InvertGradient = not mConfig.Plot.InvertGradient;
updateGradientLabel();
}
// toggle the auto scale button
void MainWindow::handleAutoScaleButton() {
if (not TOF)
return;
mConfig.TOF.AutoScale = not mConfig.TOF.AutoScale;
updateAutoScaleLabel();
}
void MainWindow::handleGradientButton() {
if (TOF) {
return;
}
mConfig.Plot.ColorGradient =
Plot2DXY->getNextColorGradient(mConfig.Plot.ColorGradient);
updateGradientLabel();
}
|
#pragma once
#ifndef _PYTHON_SEQUENCE_ITERATOR_HPP
#define _PYTHON_SEQUENCE_ITERATOR_HPP
#include "converters.hpp"
#include "core_reflection/object_handle.hpp"
#include "core_variant/collection.hpp"
#include "wg_pyscript/py_script_object.hpp"
#include <type_traits>
namespace wgt
{
namespace PythonType
{
/**
* This class wraps a PyScript::ScriptSequence or ScriptList or ScriptTuple
* with the Collection system's interface.
*/
template <typename T>
class SequenceIterator final : public CollectionIteratorImplBase
{
public:
static const bool is_supported = std::is_convertible<T, PyScript::ScriptSequence>::value;
static_assert(is_supported, "T must inherit from a PyScript::ScriptSequence type");
typedef T container_type;
typedef typename container_type::size_type key_type;
typedef Variant value_type;
typedef SequenceIterator<T> this_type;
SequenceIterator(const ObjectHandle& containerHandle, const container_type& container, key_type index,
const Converters& typeConverters);
const container_type& container() const;
/**
* Get the index into the list.
* As an int, not as a Variant like the key() method.
*
* In Python if you pass in a negative index,
* Python adds the length of the sequence to the index.
* E.g. list[-1] gets the last item in the list
* For this implementation, negative indexes should be checked and
* converted to a positive one in the range start-end.
*/
key_type rawIndex() const;
virtual const TypeId& keyType() const override;
virtual const TypeId& valueType() const override;
virtual Variant key() const override;
virtual Variant value() const override;
virtual bool setValue(const Variant& value) const override;
virtual void inc( size_t advAmount ) override;
virtual bool equals(const CollectionIteratorImplBase& that) const override;
virtual CollectionIteratorImplPtr clone() const override;
private:
ObjectHandle containerHandle_;
container_type container_;
key_type index_;
const Converters& typeConverters_;
};
} // namespace PythonType
} // end namespace wgt
#endif // _PYTHON_SEQUENCE_ITERATOR_HPP
|
/*
EngineAll.cpp
Written by Matthew Fisher
See EngineAll.h for a defintion of all files included here.
*/
//All source files include Main.h
#include "Main.h"
#include "EngineAll\Core\Stdhdr.cpp"
#include "EngineAll\Core\UnicodeString.cpp"
#include "EngineAll\Core\String.cpp"
#include "EngineAll\Core\OutputDataStream.cpp"
#include "EngineAll\Core\InputDataStream.cpp"
#include "EngineALl\Networking\Pipe.cpp"
#include "EngineAll\Math\RGBColor.cpp"
#include "EngineAll\Math\SpaceVector.cpp"
#include "EngineAll\Math\Line3D.cpp"
#include "EngineAll\Math\LineSegment2D.cpp"
#include "EngineAll\Math\LineSegment3D.cpp"
#include "EngineAll\Math\Plane.cpp"
#include "EngineAll\Math\Intersect.cpp"
#include "EngineAll\Math\Matrix4.cpp"
#include "EngineAll\Multithreading\Thread.cpp"
#include "EngineAll\Graphics Objects\ColorSpaces.cpp"
#include "EngineAll\Graphics Objects\Bitmap.cpp"
#include "EngineAll\Graphics Objects\ZBuffer.cpp"
#include "EngineAll\Graphics Objects\MatrixController.cpp"
#include "EngineAll\Graphics Objects\Camera.cpp"
#include "EngineAll\Graphics Objects\PrimitiveRender.cpp"
#include "EngineAll\Graphics Objects\MeshVertex.cpp"
#include "EngineAll\Graphics Objects\Clipper.cpp"
#include "EngineAll\Graphics Objects\Viewport.cpp"
#include "EngineAll\Graphics Objects\KDTree3.cpp"
#include "EngineAll\Graphics Objects\KDTreeN.cpp"
#include "EngineAll\Graphics Objects\PointSet.cpp"
#include "EngineAll\Graphics Objects\RayIntersectorBruteForce.cpp"
#include "EngineAll\Graphics Objects\RayIntersectorKDTree.cpp"
#include "EngineAll\Simple Mesh\BaseMesh.cpp"
#include "EngineAll\Simple Mesh\D3D9Mesh.cpp"
#include "EngineAll\Simple Mesh\D3D10Mesh.cpp"
#include "EngineAll\Simple Mesh\Mesh.cpp"
#include "EngineAll\Complex Mesh\Triangle.cpp"
#include "EngineAll\Complex Mesh\FullEdge.cpp"
#include "EngineAll\Complex Mesh\Vertex.cpp"
#include "EngineAll\Complex Mesh\ComplexMesh.cpp"
#include "EngineAll\D3DObjects\D3D9RenderTargetTexture.cpp"
#include "EngineAll\D3DObjects\D3D9RenderTargetSurface.cpp"
#include "EngineAll\D3DObjects\D3D9VertexDeclaration.cpp"
#include "EngineAll\D3DObjects\D3D9PixelShader.cpp"
#include "EngineAll\D3DObjects\D3D9VertexShader.cpp"
#include "EngineAll\D3DObjects\D3D9PersistentMesh.cpp"
#include "EngineAll\D3DObjects\D3D9Font.cpp"
#include "EngineAll\D3DObjects\D3D10Effect.cpp"
#include "EngineAll\Textures\BaseTexture.cpp"
#include "EngineAll\Textures\D3D9Texture.cpp"
#include "EngineAll\Textures\D3D10Texture.cpp"
#include "EngineAll\Textures\OpenGLTexture.cpp"
#include "EngineAll\Textures\GenericTexture.cpp"
#include "EngineAll\Graphics Devices\GraphicsDevice.cpp"
#include "EngineAll\Graphics Devices\D3D9GraphicsDevice.cpp"
#include "EngineAll\Graphics Devices\D3D10GraphicsDevice.cpp"
#include "EngineAll\Graphics Devices\OpenGLGraphicsDevice.cpp"
#include "EngineAll\Graphics Devices\SoftwareGraphicsDevice.cpp"
#include "EngineAll\Utility\MovieExporter.cpp"
#include "EngineAll\Utility\AudioCapture.cpp"
#include "EngineAll\Utility\VideoCompressor.cpp"
#include "EngineAll\Utility\Indicator.cpp"
#include "EngineAll\Utility\FileCollection.cpp"
#include "EngineAll\Utility\ParameterFile.cpp"
#include "EngineAll\Utility\UVAtlas.cpp"
#include "EngineAll\Utility\FrameTimer.cpp"
#include "EngineAll\Utility\Profiler.cpp"
#include "EngineAll\Utility\Directory.cpp"
#include "EngineAll\Utility\MenuInterface.cpp"
#include "EngineAll\Utility\Console.cpp"
#include "EngineAll\Windows Controller\InputManager.cpp"
#include "EngineAll\Windows Controller\EventHandler.cpp"
#include "EngineAll\Windows Controller\WindowManager.cpp"
#include "EngineAll\Windows Controller\WindowObjects.cpp"
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_IMGCODECS_HPP
#define OPENCV_IMGCODECS_HPP
#include "opencv2/core.hpp"
/**
@defgroup imgcodecs Image file reading and writing
@{
@defgroup imgcodecs_c C API
@defgroup imgcodecs_ios iOS glue
@}
*/
//////////////////////////////// image codec ////////////////////////////////
namespace cv
{
//! @addtogroup imgcodecs
//! @{
//! Imread flags
enum ImreadModes {
IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image.
IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image.
IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format.
IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image.
IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2.
IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2.
IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4.
IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4.
IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8.
IMREAD_REDUCED_COLOR_8 = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8.
IMREAD_IGNORE_ORIENTATION = 128 //!< If set, do not rotate the image according to EXIF's orientation flag.
};
//! Imwrite flags
enum ImwriteFlags {
IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95.
IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False.
IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False.
IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart.
IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is 0 - don't use.
IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is 0 - don't use.
IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. If specified, strategy is changed to IMWRITE_PNG_STRATEGY_DEFAULT (Z_DEFAULT_STRATEGY). Default value is 1 (best speed setting).
IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_RLE.
IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0.
IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1.
IMWRITE_WEBP_QUALITY = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used.
IMWRITE_PAM_TUPLETYPE = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format
};
//! Imwrite PNG specific flags used to tune the compression algorithm.
/** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage.
- The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY.
- IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data.
- The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately.
- IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
*/
enum ImwritePNGFlags {
IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data.
IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better.
IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match).
IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding).
IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
};
//! Imwrite PAM specific tupletype flags used to define the 'TUPETYPE' field of a PAM file.
enum ImwritePAMFlags {
IMWRITE_PAM_FORMAT_NULL = 0,
IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1,
IMWRITE_PAM_FORMAT_GRAYSCALE = 2,
IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3,
IMWRITE_PAM_FORMAT_RGB = 4,
IMWRITE_PAM_FORMAT_RGB_ALPHA = 5,
};
/** @brief Loads an image from a file.
@anchor imread
The function imread loads an image from the specified file and returns it. If the image cannot be
read (because of missing file, improper permissions, unsupported or invalid format), the function
returns an empty matrix ( Mat::data==NULL ).
Currently, the following file formats are supported:
- Windows bitmaps - \*.bmp, \*.dib (always supported)
- JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Notes* section)
- JPEG 2000 files - \*.jp2 (see the *Notes* section)
- Portable Network Graphics - \*.png (see the *Notes* section)
- WebP - \*.webp (see the *Notes* section)
- Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported)
- Sun rasters - \*.sr, \*.ras (always supported)
- TIFF files - \*.tiff, \*.tif (see the *Notes* section)
- OpenEXR Image files - \*.exr (see the *Notes* section)
- Radiance HDR - \*.hdr, \*.pic (always supported)
- Raster and Vector geospatial data supported by Gdal (see the *Notes* section)
@note
- The function determines the type of an image by the content, not by the file extension.
- In the case of color images, the decoded images will have the channels stored in **B G R** order.
- On Microsoft Windows\* OS and MacOSX\*, the codecs shipped with an OpenCV image (libjpeg,
libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs,
and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware
that currently these native image loaders give images with different pixel values because of
the color management embedded into MacOSX.
- On Linux\*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for
codecs supplied with an OS image. Install the relevant packages (do not forget the development
files, for example, "libjpeg-dev", in Debian\* and Ubuntu\*) to get the codec support or turn
on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake.
- In the case you set *WITH_GDAL* flag to true in CMake and @ref IMREAD_LOAD_GDAL to load the image,
then [GDAL](http://www.gdal.org) driver will be used in order to decode the image by supporting
the following formats: [Raster](http://www.gdal.org/formats_list.html),
[Vector](http://www.gdal.org/ogr_formats.html).
- If EXIF information are embedded in the image file, the EXIF orientation will be taken into account
and thus the image will be rotated accordingly except if the flag @ref IMREAD_IGNORE_ORIENTATION is passed.
@param filename Name of file to be loaded.
@param flags Flag that can take values of cv::ImreadModes
*/
CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR );
/** @brief Loads a multi-page image from a file.
The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects.
@param filename Name of file to be loaded.
@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR.
@param mats A vector of Mat objects holding each page, if more than one.
@sa cv::imread
*/
CV_EXPORTS_W bool imreadmulti(const String& filename, std::vector<Mat>& mats, int flags = IMREAD_ANYCOLOR);
/** @brief Saves an image to a specified file.
The function imwrite saves the image to the specified file. The image format is chosen based on the
filename extension (see cv::imread for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U)
in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images
can be saved using this function. If the format, depth or channel order is different, use
Mat::convertTo , and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O
functions to save the image to XML or YAML format.
It is possible to store PNG images with an alpha channel using this function. To do this, create
8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels
should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535.
The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom
compression parameters :
@code
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void createAlphaMat(Mat &mat)
{
CV_Assert(mat.channels() == 4);
for (int i = 0; i < mat.rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
Vec4b& bgra = mat.at<Vec4b>(i, j);
bgra[0] = UCHAR_MAX; // Blue
bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green
bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red
bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha
}
}
}
int main(int argv, char **argc)
{
// Create mat with alpha channel
Mat mat(480, 640, CV_8UC4);
createAlphaMat(mat);
vector<int> compression_params;
compression_params.push_back(IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
try {
imwrite("alpha.png", mat, compression_params);
}
catch (cv::Exception& ex) {
fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
return 1;
}
fprintf(stdout, "Saved PNG file with alpha data.\n");
return 0;
}
@endcode
@param filename Name of the file.
@param img Image to be saved.
@param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags
*/
CV_EXPORTS_W bool imwrite( const String& filename, InputArray img,
const std::vector<int>& params = std::vector<int>());
/** @brief Reads an image from a buffer in memory.
The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or
contains invalid data, the function returns an empty matrix ( Mat::data==NULL ).
See cv::imread for the list of supported formats and flags description.
@note In the case of color images, the decoded images will have the channels stored in **B G R** order.
@param buf Input array or vector of bytes.
@param flags The same flags as in cv::imread, see cv::ImreadModes.
*/
CV_EXPORTS_W Mat imdecode( InputArray buf, int flags );
/** @overload
@param buf
@param flags
@param dst The optional output placeholder for the decoded matrix. It can save the image
reallocations when the function is called repeatedly for images of the same size.
*/
CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst);
/** @brief Encodes an image into a memory buffer.
The function imencode compresses the image and stores it in the memory buffer that is resized to fit the
result. See cv::imwrite for the list of supported formats and flags description.
@param ext File extension that defines the output format.
@param img Image to be written.
@param buf Output buffer resized to fit the compressed image.
@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags.
*/
CV_EXPORTS_W bool imencode( const String& ext, InputArray img,
CV_OUT std::vector<uchar>& buf,
const std::vector<int>& params = std::vector<int>());
//! @} imgcodecs
} // cv
#endif //OPENCV_IMGCODECS_HPP
|
#include <iostream>
#include <algorithm>
#include <string>
#include <bitset>
//#define CONTENT 16895
////14-5
//#define BUFFER 16384
//#define LOOK 34
//
//#define DISTANCE 14//2^14=16384
//#define LENGTH 5//2^5+2=34
//14-4
#define BUFFER 16384
#define LOOK 6
#define DISTANCE 14//2^14=16384
#define LENGTH 2//2^5+2=34
//15-3 is the best, with 5 useless '0' at the front
using namespace std;
string content;
int main()
{
freopen("article.txt", "rb", stdin);
//freopen("test.txt", "rb", stdin);
freopen("feature14-2.txt", "wb", stdout);
//freopen("chartest.txt", "wb", stdout);
unsigned char c;
string s;
while (~scanf("%c", &c))
content += c;
int ci, bi;//content index, buffer index
int tci, tbi;//temp content index, temp buffer index
int ml, md;//max length, max distance
int l;
int i, j;
int eight;
int length;
length = content.size();
cout << 0;
cout << bitset<8>(content[0]);
//cout << 0 << " " << content[0] << endl;
for (ci = 1; ci < length; ci += ml)
{
//find the longest match
md = ml = 0;
for (bi = ci - 1; bi >= 0 && bi >= ci - BUFFER; bi--)
{
l = 0;
for (tbi = bi, tci = ci; ; )
{
//cout << "tci: " << tci << endl;
if (l >= LOOK || tci >= length)
{
ml = l;
md = ci - bi;
l = 0;
break;
}
if (content[tci] == content[tbi])
{
l++;
tci++;
tbi++;
}
else
{
if (l > ml)
{
ml = l;
md = ci - bi;
}
//cout << "out: " << tbi << " " << tci << endl;
break;
}
}
}
//when decoding, transform back to (ml + 3)
if (ml - 3< 0)//so that ml is [0, 15)
{
ml = 1;
cout << 0;
cout << bitset<8>(content[ci]);
//cout << 0 << " " << content[ci] << endl;
}
else
{
cout << 1;
cout << bitset<DISTANCE>(md);
cout << bitset<LENGTH>(ml - 3);
//cout << " " << md << " " << ml << endl;
}
}
}
|
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Tests for death tests.
#include "gtest/gtest-death-test.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
#if GTEST_HAS_DEATH_TEST
# if GTEST_OS_WINDOWS
# include <direct.h> // For chdir().
# else
# include <unistd.h>
# include <sys/wait.h> // For waitpid.
# endif // GTEST_OS_WINDOWS
# include <limits.h>
# include <signal.h>
# include <stdio.h>
# if GTEST_OS_LINUX
# include <sys/time.h>
# endif // GTEST_OS_LINUX
# include "gtest/gtest-spi.h"
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
# define GTEST_IMPLEMENTATION_ 1
# include "src/gtest-internal-inl.h"
# undef GTEST_IMPLEMENTATION_
namespace posix = ::testing::internal::posix;
using testing::Message;
using testing::internal::DeathTest;
using testing::internal::DeathTestFactory;
using testing::internal::FilePath;
using testing::internal::GetLastErrnoDescription;
using testing::internal::GetUnitTestImpl;
using testing::internal::InDeathTestChild;
using testing::internal::ParseNaturalNumber;
namespace testing {
namespace internal {
// A helper class whose objects replace the death test factory for a
// single UnitTest object during their lifetimes.
class ReplaceDeathTestFactory {
public:
explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
: unit_test_impl_(GetUnitTestImpl()) {
old_factory_ = unit_test_impl_->death_test_factory_.release();
unit_test_impl_->death_test_factory_.reset(new_factory);
}
~ReplaceDeathTestFactory() {
unit_test_impl_->death_test_factory_.release();
unit_test_impl_->death_test_factory_.reset(old_factory_);
}
private:
// Prevents copying ReplaceDeathTestFactory objects.
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
void operator=(const ReplaceDeathTestFactory&);
UnitTestImpl* unit_test_impl_;
DeathTestFactory* old_factory_;
};
} // namespace internal
} // namespace testing
void DieWithMessage(const ::std::string& message) {
fprintf(stderr, "%s", message.c_str());
fflush(stderr); // Make sure the text is printed before the process exits.
// We call _exit() instead of exit(), as the former is a direct
// system call and thus safer in the presence of threads. exit()
// will invoke user-defined exit-hooks, which may do dangerous
// things that conflict with death tests.
//
// Some compilers can recognize that _exit() never returns and issue the
// 'unreachable code' warning for code following this function, unless
// fooled by a fake condition.
if (AlwaysTrue())
_exit(1);
}
void DieInside(const ::std::string& function) {
DieWithMessage("death inside " + function + "().");
}
// Tests that death tests work.
class TestForDeathTest : public testing::Test {
protected:
TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
virtual ~TestForDeathTest() {
posix::ChDir(original_dir_.c_str());
}
// A static member function that's expected to die.
static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
// A method of the test fixture that may die.
void MemberFunction() {
if (should_die_)
DieInside("MemberFunction");
}
// True iff MemberFunction() should die.
bool should_die_;
const FilePath original_dir_;
};
// A class with a member function that may die.
class MayDie {
public:
explicit MayDie(bool should_die) : should_die_(should_die) {}
// A member function that may die.
void MemberFunction() const {
if (should_die_)
DieInside("MayDie::MemberFunction");
}
private:
// True iff MemberFunction() should die.
bool should_die_;
};
// A global function that's expected to die.
void GlobalFunction() { DieInside("GlobalFunction"); }
// A non-void function that's expected to die.
int NonVoidFunction() {
DieInside("NonVoidFunction");
return 1;
}
// A unary function that may die.
void DieIf(bool should_die) {
if (should_die)
DieInside("DieIf");
}
// A binary function that may die.
bool DieIfLessThan(int x, int y) {
if (x < y) {
DieInside("DieIfLessThan");
}
return true;
}
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
void DeathTestSubroutine() {
EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
}
// Death in dbg, not opt.
int DieInDebugElse12(int* sideeffect) {
if (sideeffect) *sideeffect = 12;
# ifndef NDEBUG
DieInside("DieInDebugElse12");
# endif // NDEBUG
return 12;
}
# if GTEST_OS_WINDOWS
// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
// On Windows, the process's exit code is the same as its exit status,
// so the predicate just compares the its input with its parameter.
EXPECT_TRUE(testing::ExitedWithCode(0)(0));
EXPECT_TRUE(testing::ExitedWithCode(1)(1));
EXPECT_TRUE(testing::ExitedWithCode(42)(42));
EXPECT_FALSE(testing::ExitedWithCode(0)(1));
EXPECT_FALSE(testing::ExitedWithCode(1)(0));
}
# else
// Returns the exit status of a process that calls _exit(2) with a
// given exit code. This is a helper function for the
// ExitStatusPredicateTest test suite.
static int NormalExitStatus(int exit_code) {
pid_t child_pid = fork();
if (child_pid == 0) {
_exit(exit_code);
}
int status;
waitpid(child_pid, &status, 0);
return status;
}
// Returns the exit status of a process that raises a given signal.
// If the signal does not cause the process to die, then it returns
// instead the exit status of a process that exits normally with exit
// code 1. This is a helper function for the ExitStatusPredicateTest
// test suite.
static int KilledExitStatus(int signum) {
pid_t child_pid = fork();
if (child_pid == 0) {
raise(signum);
_exit(1);
}
int status;
waitpid(child_pid, &status, 0);
return status;
}
// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
const int status0 = NormalExitStatus(0);
const int status1 = NormalExitStatus(1);
const int status42 = NormalExitStatus(42);
const testing::ExitedWithCode pred0(0);
const testing::ExitedWithCode pred1(1);
const testing::ExitedWithCode pred42(42);
EXPECT_PRED1(pred0, status0);
EXPECT_PRED1(pred1, status1);
EXPECT_PRED1(pred42, status42);
EXPECT_FALSE(pred0(status1));
EXPECT_FALSE(pred42(status0));
EXPECT_FALSE(pred1(status42));
}
// Tests the KilledBySignal predicate.
TEST(ExitStatusPredicateTest, KilledBySignal) {
const int status_segv = KilledExitStatus(SIGSEGV);
const int status_kill = KilledExitStatus(SIGKILL);
const testing::KilledBySignal pred_segv(SIGSEGV);
const testing::KilledBySignal pred_kill(SIGKILL);
EXPECT_PRED1(pred_segv, status_segv);
EXPECT_PRED1(pred_kill, status_kill);
EXPECT_FALSE(pred_segv(status_kill));
EXPECT_FALSE(pred_kill(status_segv));
}
# endif // GTEST_OS_WINDOWS
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
TEST_F(TestForDeathTest, SingleStatement) {
if (AlwaysFalse())
// This would fail if executed; this is a compilation test only
ASSERT_DEATH(return, "");
if (AlwaysTrue())
EXPECT_DEATH(_exit(1), "");
else
// This empty "else" branch is meant to ensure that EXPECT_DEATH
// doesn't expand into an "if" statement without an "else"
;
if (AlwaysFalse())
ASSERT_DEATH(return, "") << "did not die";
if (AlwaysFalse())
;
else
EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
}
void DieWithEmbeddedNul() {
fprintf(stderr, "Hello%cmy null world.\n", '\0');
fflush(stderr);
_exit(1);
}
# if GTEST_USES_PCRE
// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
// message has a NUL character in it.
TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
// TODO(wan@google.com): <regex.h> doesn't support matching strings
// with embedded NUL characters - find a way to workaround it.
EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
}
# endif // GTEST_USES_PCRE
// Tests that death test macros expand to code which interacts well with switch
// statements.
TEST_F(TestForDeathTest, SwitchStatement) {
// Microsoft compiler usually complains about switch statements without
// case labels. We suppress that warning for this test.
# ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4065)
# endif // _MSC_VER
switch (0)
default:
ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
switch (0)
case 0:
EXPECT_DEATH(_exit(1), "") << "exit in switch case";
# ifdef _MSC_VER
# pragma warning(pop)
# endif // _MSC_VER
}
// Tests that a static member function can be used in a "fast" style
// death test.
TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
testing::GTEST_FLAG(death_test_style) = "fast";
ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
}
// Tests that a method of the test fixture can be used in a "fast"
// style death test.
TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
testing::GTEST_FLAG(death_test_style) = "fast";
should_die_ = true;
EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
}
void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
// Tests that death tests work even if the current directory has been
// changed.
TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
testing::GTEST_FLAG(death_test_style) = "fast";
ChangeToRootDir();
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ChangeToRootDir();
ASSERT_DEATH(_exit(1), "");
}
# if GTEST_OS_LINUX
void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() {
struct itimerval timer;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 1;
timer.it_value = timer.it_interval;
ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
struct sigaction signal_action;
memset(&signal_action, 0, sizeof(signal_action));
sigemptyset(&signal_action.sa_mask);
signal_action.sa_sigaction = SigprofAction;
signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
}
// Disables ITIMER_PROF timer and ignores SIGPROF signal.
void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
struct itimerval timer;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
timer.it_value = timer.it_interval;
ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
struct sigaction signal_action;
memset(&signal_action, 0, sizeof(signal_action));
sigemptyset(&signal_action.sa_mask);
signal_action.sa_handler = SIG_IGN;
ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
}
// Tests that death tests work when SIGPROF handler and timer are set.
TEST_F(TestForDeathTest, FastSigprofActionSet) {
testing::GTEST_FLAG(death_test_style) = "fast";
SetSigprofActionAndTimer();
EXPECT_DEATH(_exit(1), "");
struct sigaction old_signal_action;
DisableSigprofActionAndTimer(&old_signal_action);
EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
}
TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
SetSigprofActionAndTimer();
EXPECT_DEATH(_exit(1), "");
struct sigaction old_signal_action;
DisableSigprofActionAndTimer(&old_signal_action);
EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
}
# endif // GTEST_OS_LINUX
// Repeats a representative sample of death tests in the "threadsafe" style:
TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
}
TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
should_die_ = true;
EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
}
TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
for (int i = 0; i < 3; ++i)
EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
}
TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
ChangeToRootDir();
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ChangeToRootDir();
ASSERT_DEATH(_exit(1), "");
}
TEST_F(TestForDeathTest, MixedStyles) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
EXPECT_DEATH(_exit(1), "");
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_DEATH(_exit(1), "");
}
# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
namespace {
bool pthread_flag;
void SetPthreadFlag() {
pthread_flag = true;
}
} // namespace
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
if (!testing::GTEST_FLAG(death_test_use_fork)) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
pthread_flag = false;
ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
ASSERT_DEATH(_exit(1), "");
ASSERT_FALSE(pthread_flag);
}
}
# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
// Tests that a method of another class can be used in a death test.
TEST_F(TestForDeathTest, MethodOfAnotherClass) {
const MayDie x(true);
ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
}
// Tests that a global function can be used in a death test.
TEST_F(TestForDeathTest, GlobalFunction) {
EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
}
// Tests that any value convertible to an RE works as a second
// argument to EXPECT_DEATH.
TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
static const char regex_c_str[] = "GlobalFunction";
EXPECT_DEATH(GlobalFunction(), regex_c_str);
const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex);
# if GTEST_HAS_GLOBAL_STRING
const string regex_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_str);
# endif // GTEST_HAS_GLOBAL_STRING
const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str);
}
// Tests that a non-void function can be used in a death test.
TEST_F(TestForDeathTest, NonVoidFunction) {
ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
}
// Tests that functions that take parameter(s) can be used in a death test.
TEST_F(TestForDeathTest, FunctionWithParameter) {
EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
}
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) {
DeathTestSubroutine();
}
// Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) {
for (int i = 0; i < 5; i++) {
EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
}
}
// Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) {
EXPECT_DEATH({ // NOLINT
const int x = 2;
const int y = x + 1;
DieIfLessThan(x, y);
},
"DieIfLessThan");
}
// Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
"failed to die");
}
// Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
}, "died but not with expected error");
}
// On exit, *aborted will be true iff the EXPECT_DEATH() statement
// aborted the function.
void ExpectDeathTestHelper(bool* aborted) {
*aborted = true;
EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
*aborted = false;
}
// Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
"failed to die");
EXPECT_FALSE(aborted);
}
// Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) {
static bool aborted;
EXPECT_FATAL_FAILURE({ // NOLINT
aborted = true;
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
aborted = false;
}, "failed to die");
EXPECT_TRUE(aborted);
}
// Tests that EXPECT_DEATH evaluates the arguments exactly once.
TEST_F(TestForDeathTest, SingleEvaluation) {
int x = 3;
EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
const char* regex = "DieIf";
const char* regex_save = regex;
EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
EXPECT_EQ(regex_save + 1, regex);
}
// Tests that run-away death tests are reported as failures.
TEST_F(TestForDeathTest, RunawayIsFailure) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
"failed to die.");
}
// Tests that death tests report executing 'return' in the statement as
// failure.
TEST_F(TestForDeathTest, ReturnIsFailure) {
EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
"illegal return in test statement.");
}
// Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it:
// 1. Asserts on death.
// 2. Has no side effect.
//
// And in opt mode, it:
// 1. Has side effects but does not assert.
TEST_F(TestForDeathTest, TestExpectDebugDeath) {
int sideeffect = 0;
EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
<< "Must accept a streamed message";
# ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect);
# else
// Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect);
# endif
}
// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it:
// 1. Asserts on death.
// 2. Has no side effect.
//
// And in opt mode, it:
// 1. Has side effects but does not assert.
TEST_F(TestForDeathTest, TestAssertDebugDeath) {
int sideeffect = 0;
ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
<< "Must accept a streamed message";
# ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect);
# else
// Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect);
# endif
}
# ifndef NDEBUG
void ExpectDebugDeathHelper(bool* aborted) {
*aborted = true;
EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
*aborted = false;
}
# if GTEST_OS_WINDOWS
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
printf("This test should be considered failing if it shows "
"any pop-up dialogs.\n");
fflush(stdout);
EXPECT_DEATH({
testing::GTEST_FLAG(catch_exceptions) = false;
abort();
}, "");
}
# endif // GTEST_OS_WINDOWS
// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
// the function.
TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
EXPECT_FALSE(aborted);
}
void AssertDebugDeathHelper(bool* aborted) {
*aborted = true;
ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
*aborted = false;
}
// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
// failure.
TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
static bool aborted;
aborted = false;
EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
EXPECT_TRUE(aborted);
}
# endif // _NDEBUG
// Tests the *_EXIT family of macros, using a variety of predicates.
static void TestExitMacros() {
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
# if GTEST_OS_WINDOWS
// Of all signals effects on the process exit code, only those of SIGABRT
// are documented on Windows.
// See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
# else
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
<< "This failure is expected, too.";
}, "This failure is expected, too.");
# endif // GTEST_OS_WINDOWS
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
<< "This failure is expected.";
}, "This failure is expected.");
}
TEST_F(TestForDeathTest, ExitMacros) {
TestExitMacros();
}
TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
testing::GTEST_FLAG(death_test_use_fork) = true;
TestExitMacros();
}
TEST_F(TestForDeathTest, InvalidStyle) {
testing::GTEST_FLAG(death_test_style) = "rococo";
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
}, "This failure is expected.");
}
TEST_F(TestForDeathTest, DeathTestFailedOutput) {
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("death\n"),
"expected message"),
"Actual msg:\n"
"[ DEATH ] death\n");
}
TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH({
fprintf(stderr, "returning\n");
fflush(stderr);
return;
}, ""),
" Result: illegal return in test statement.\n"
" Error msg:\n"
"[ DEATH ] returning\n");
}
TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
testing::ExitedWithCode(3),
"expected message"),
" Result: died but not with expected exit code:\n"
" Exited with exit status 1\n"
"Actual msg:\n"
"[ DEATH ] exiting with rc 1\n");
}
TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
"line 1\nxyz\nline 3\n"),
"Actual msg:\n"
"[ DEATH ] line 1\n"
"[ DEATH ] line 2\n"
"[ DEATH ] line 3\n");
}
TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
"line 1\nline 2\nline 3\n");
}
// A DeathTestFactory that returns MockDeathTests.
class MockDeathTestFactory : public DeathTestFactory {
public:
MockDeathTestFactory();
virtual bool Create(const char* statement,
const ::testing::internal::RE* regex,
const char* file, int line, DeathTest** test);
// Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role,
int status, bool passed);
// Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; }
int WaitCalls() const { return wait_calls_; }
int PassedCalls() const { return passed_args_.size(); }
bool PassedArgument(int n) const { return passed_args_[n]; }
int AbortCalls() const { return abort_args_.size(); }
DeathTest::AbortReason AbortArgument(int n) const {
return abort_args_[n];
}
bool TestDeleted() const { return test_deleted_; }
private:
friend class MockDeathTest;
// If true, Create will return a MockDeathTest; otherwise it returns
// NULL.
bool create_;
// The value a MockDeathTest will return from its AssumeRole method.
DeathTest::TestRole role_;
// The value a MockDeathTest will return from its Wait method.
int status_;
// The value a MockDeathTest will return from its Passed method.
bool passed_;
// Number of times AssumeRole was called.
int assume_role_calls_;
// Number of times Wait was called.
int wait_calls_;
// The arguments to the calls to Passed since the last call to
// SetParameters.
std::vector<bool> passed_args_;
// The arguments to the calls to Abort since the last call to
// SetParameters.
std::vector<DeathTest::AbortReason> abort_args_;
// True if the last MockDeathTest returned by Create has been
// deleted.
bool test_deleted_;
};
// A DeathTest implementation useful in testing. It returns values set
// at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory
// object.
class MockDeathTest : public DeathTest {
public:
MockDeathTest(MockDeathTestFactory *parent,
TestRole role, int status, bool passed) :
parent_(parent), role_(role), status_(status), passed_(passed) {
}
virtual ~MockDeathTest() {
parent_->test_deleted_ = true;
}
virtual TestRole AssumeRole() {
++parent_->assume_role_calls_;
return role_;
}
virtual int Wait() {
++parent_->wait_calls_;
return status_;
}
virtual bool Passed(bool exit_status_ok) {
parent_->passed_args_.push_back(exit_status_ok);
return passed_;
}
virtual void Abort(AbortReason reason) {
parent_->abort_args_.push_back(reason);
}
private:
MockDeathTestFactory* const parent_;
const TestRole role_;
const int status_;
const bool passed_;
};
// MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory()
: create_(true),
role_(DeathTest::OVERSEE_TEST),
status_(0),
passed_(true),
assume_role_calls_(0),
wait_calls_(0),
passed_args_(),
abort_args_() {
}
// Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create,
DeathTest::TestRole role,
int status, bool passed) {
create_ = create;
role_ = role;
status_ = status;
passed_ = passed;
assume_role_calls_ = 0;
wait_calls_ = 0;
passed_args_.clear();
abort_args_.clear();
}
// Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true.
bool MockDeathTestFactory::Create(const char* /*statement*/,
const ::testing::internal::RE* /*regex*/,
const char* /*file*/,
int /*line*/,
DeathTest** test) {
test_deleted_ = false;
if (create_) {
*test = new MockDeathTest(this, role_, status_, passed_);
} else {
*test = NULL;
}
return true;
}
// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
// It installs a MockDeathTestFactory that is used for the duration
// of the test case.
class MacroLogicDeathTest : public testing::Test {
protected:
static testing::internal::ReplaceDeathTestFactory* replacer_;
static MockDeathTestFactory* factory_;
static void SetUpTestCase() {
factory_ = new MockDeathTestFactory;
replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
}
static void TearDownTestCase() {
delete replacer_;
replacer_ = NULL;
delete factory_;
factory_ = NULL;
}
// Runs a death test that breaks the rules by returning. Such a death
// test cannot be run directly from a test routine that uses a
// MockDeathTest, or the remainder of the routine will not be executed.
static void RunReturningDeathTest(bool* flag) {
ASSERT_DEATH({ // NOLINT
*flag = true;
return;
}, "");
}
};
testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
= NULL;
MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
// Test that nothing happens when the factory doesn't return a DeathTest:
TEST_F(MacroLogicDeathTest, NothingHappens) {
bool flag = false;
factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
EXPECT_DEATH(flag = true, "");
EXPECT_FALSE(flag);
EXPECT_EQ(0, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
EXPECT_EQ(0, factory_->PassedCalls());
EXPECT_EQ(0, factory_->AbortCalls());
EXPECT_FALSE(factory_->TestDeleted());
}
// Test that the parent process doesn't run the death test code,
// and that the Passed method returns false when the (simulated)
// child process exits with status 0:
TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
bool flag = false;
factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
EXPECT_DEATH(flag = true, "");
EXPECT_FALSE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(1, factory_->WaitCalls());
ASSERT_EQ(1, factory_->PassedCalls());
EXPECT_FALSE(factory_->PassedArgument(0));
EXPECT_EQ(0, factory_->AbortCalls());
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that the Passed method was given the argument "true" when
// the (simulated) child process exits with status 1:
TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
bool flag = false;
factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
EXPECT_DEATH(flag = true, "");
EXPECT_FALSE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(1, factory_->WaitCalls());
ASSERT_EQ(1, factory_->PassedCalls());
EXPECT_TRUE(factory_->PassedArgument(0));
EXPECT_EQ(0, factory_->AbortCalls());
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that the (simulated) child process executes the death test
// code, and is aborted with the correct AbortReason if it
// executes a return statement.
TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
bool flag = false;
factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
RunReturningDeathTest(&flag);
EXPECT_TRUE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
EXPECT_EQ(0, factory_->PassedCalls());
EXPECT_EQ(1, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(0));
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that the (simulated) child process is aborted with the
// correct AbortReason if it does not die.
TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
bool flag = false;
factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
EXPECT_DEATH(flag = true, "");
EXPECT_TRUE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
EXPECT_EQ(0, factory_->PassedCalls());
// This time there are two calls to Abort: one since the test didn't
// die, and another from the ReturnSentinel when it's destroyed. The
// sentinel normally isn't destroyed if a test doesn't die, since
// _exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest.
ASSERT_EQ(2, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(1));
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that a successful death test does not register a successful
// test part.
TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
EXPECT_DEATH(_exit(1), "");
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
TEST(StreamingAssertionsDeathTest, DeathTest) {
EXPECT_DEATH(_exit(1), "") << "unexpected failure";
ASSERT_DEATH(_exit(1), "") << "unexpected failure";
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(_exit(0), "") << "expected failure";
}, "expected failure");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_DEATH(_exit(0), "") << "expected failure";
}, "expected failure");
}
// Tests that GetLastErrnoDescription returns an empty string when the
// last error is 0 and non-empty string when it is non-zero.
TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
errno = ENOENT;
EXPECT_STRNE("", GetLastErrnoDescription().c_str());
errno = 0;
EXPECT_STREQ("", GetLastErrnoDescription().c_str());
}
# if GTEST_OS_WINDOWS
TEST(AutoHandleTest, AutoHandleWorks) {
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
// Tests that the AutoHandle is correctly initialized with a handle.
testing::internal::AutoHandle auto_handle(handle);
EXPECT_EQ(handle, auto_handle.Get());
// Tests that Reset assigns INVALID_HANDLE_VALUE.
// Note that this cannot verify whether the original handle is closed.
auto_handle.Reset();
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
// Tests that Reset assigns the new handle.
// Note that this cannot verify whether the original handle is closed.
handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
auto_handle.Reset(handle);
EXPECT_EQ(handle, auto_handle.Get());
// Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
testing::internal::AutoHandle auto_handle2;
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
}
# endif // GTEST_OS_WINDOWS
# if GTEST_OS_WINDOWS
typedef unsigned __int64 BiggestParsable;
typedef signed __int64 BiggestSignedParsable;
# else
typedef unsigned long long BiggestParsable;
typedef signed long long BiggestSignedParsable;
# endif // GTEST_OS_WINDOWS
// We cannot use std::numeric_limits<T>::max() as it clashes with the
// max() macro defined by <windows.h>.
const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
BiggestParsable result = 0;
// Rejects non-numbers.
EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
// Rejects numbers with whitespace prefix.
EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
// Rejects negative numbers.
EXPECT_FALSE(ParseNaturalNumber("-123", &result));
// Rejects numbers starting with a plus sign.
EXPECT_FALSE(ParseNaturalNumber("+123", &result));
errno = 0;
}
TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
BiggestParsable result = 0;
EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
signed char char_result = 0;
EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
errno = 0;
}
TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
BiggestParsable result = 0;
result = 0;
ASSERT_TRUE(ParseNaturalNumber("123", &result));
EXPECT_EQ(123U, result);
// Check 0 as an edge case.
result = 1;
ASSERT_TRUE(ParseNaturalNumber("0", &result));
EXPECT_EQ(0U, result);
result = 1;
ASSERT_TRUE(ParseNaturalNumber("00000", &result));
EXPECT_EQ(0U, result);
}
TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
Message msg;
msg << kBiggestParsableMax;
BiggestParsable result = 0;
EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
EXPECT_EQ(kBiggestParsableMax, result);
Message msg2;
msg2 << kBiggestSignedParsableMax;
BiggestSignedParsable signed_result = 0;
EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
Message msg3;
msg3 << INT_MAX;
int int_result = 0;
EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
EXPECT_EQ(INT_MAX, int_result);
Message msg4;
msg4 << UINT_MAX;
unsigned int uint_result = 0;
EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
EXPECT_EQ(UINT_MAX, uint_result);
}
TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
short short_result = 0;
ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
EXPECT_EQ(123, short_result);
signed char char_result = 0;
ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
EXPECT_EQ(123, char_result);
}
# if GTEST_OS_WINDOWS
TEST(EnvironmentTest, HandleFitsIntoSizeT) {
// TODO(vladl@google.com): Remove this test after this condition is verified
// in a static assertion in gtest-death-test.cc in the function
// GetStatusFileDescriptor.
ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
}
# endif // GTEST_OS_WINDOWS
// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
// failures when death tests are available on the system.
TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
"death inside CondDeathTestExpectMacro");
ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
"death inside CondDeathTestAssertMacro");
// Empty statement will not crash, which must trigger a failure.
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
}
#else
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;
// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
// defined but do not trigger failures when death tests are not available on
// the system.
TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
// Empty statement will not crash, but that should not trigger a failure
// when death tests are not supported.
CaptureStderr();
EXPECT_DEATH_IF_SUPPORTED(;, "");
std::string output = GetCapturedStderr();
ASSERT_TRUE(NULL != strstr(output.c_str(),
"Death tests are not supported on this platform"));
ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
// The streamed message should not be printed as there is no test failure.
CaptureStderr();
EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
output = GetCapturedStderr();
ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
CaptureStderr();
ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
output = GetCapturedStderr();
ASSERT_TRUE(NULL != strstr(output.c_str(),
"Death tests are not supported on this platform"));
ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
CaptureStderr();
ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
output = GetCapturedStderr();
ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
}
void FuncWithAssert(int* n) {
ASSERT_DEATH_IF_SUPPORTED(return;, "");
(*n)++;
}
// Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
// function (as ASSERT_DEATH does) if death tests are not supported.
TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
int n = 0;
FuncWithAssert(&n);
EXPECT_EQ(1, n);
}
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
fflush(stderr);
_exit(1);
}, "Inside");
}
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
fflush(stderr);
_exit(1);
}, "Inside");
}
#endif // GTEST_HAS_DEATH_TEST
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
//
// The syntax should work whether death tests are available or not.
TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
if (AlwaysFalse())
// This would fail if executed; this is a compilation test only
ASSERT_DEATH_IF_SUPPORTED(return, "");
if (AlwaysTrue())
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
else
// This empty "else" branch is meant to ensure that EXPECT_DEATH
// doesn't expand into an "if" statement without an "else"
; // NOLINT
if (AlwaysFalse())
ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
if (AlwaysFalse())
; // NOLINT
else
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
}
// Tests that conditional death test macros expand to code which interacts
// well with switch statements.
TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
// Microsoft compiler usually complains about switch statements without
// case labels. We suppress that warning for this test.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4065)
#endif // _MSC_VER
switch (0)
default:
ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
<< "exit in default switch handler";
switch (0)
case 0:
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
#ifdef _MSC_VER
# pragma warning(pop)
#endif // _MSC_VER
}
// Tests that a test case whose name ends with "DeathTest" works fine
// on Windows.
TEST(NotADeathTest, Test) {
SUCCEED();
}
|
/*
* Copyright (c) 2014-2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#if defined(MBED_CONF_NANOSTACK_CONFIGURATION) && DEVICE_SPI && DEVICE_INTERRUPTIN && DEVICE_I2C && defined(MBED_CONF_RTOS_PRESENT)
#include "platform/arm_hal_interrupt.h"
#include "nanostack/platform/arm_hal_phy.h"
#include "ns_types.h"
#include "NanostackRfPhyAtmel.h"
#include "randLIB.h"
#include "AT86RFReg.h"
#include "nanostack/platform/arm_hal_phy.h"
#include "mbed_trace.h"
#include "mbed_toolchain.h"
#include "DigitalIn.h"
#include "DigitalOut.h"
#include "InterruptIn.h"
#include "SPI.h"
#include "inttypes.h"
#include "Timeout.h"
#define TRACE_GROUP "AtRF"
/*Worst case sensitivity*/
#define RF_DEFAULT_SENSITIVITY -88
/*Run calibration every 5 minutes*/
#define RF_CALIBRATION_INTERVAL 6000000
/*Wait ACK for 2.5ms*/
#define RF_ACK_WAIT_DEFAULT_TIMEOUT 50
/*Base CCA backoff (50us units) - substitutes for Inter-Frame Spacing*/
#define RF_CCA_BASE_BACKOFF 13 /* 650us */
/*CCA random backoff (50us units)*/
#define RF_CCA_RANDOM_BACKOFF 51 /* 2550us */
#define RF_MTU 127
#define RF_PHY_MODE OQPSK_SIN_250
/*Radio RX and TX state definitions*/
#define RFF_ON 0x01
#define RFF_RX 0x02
#define RFF_TX 0x04
#define RFF_CCA 0x08
namespace {
typedef enum {
RF_MODE_NORMAL = 0,
RF_MODE_SNIFFER = 1,
RF_MODE_ED = 2
} rf_mode_t;
/*Atmel RF Part Type*/
typedef enum {
ATMEL_UNKNOW_DEV = 0,
ATMEL_AT86RF212,
ATMEL_AT86RF231, // No longer supported (doesn't give ED+status on frame read)
ATMEL_AT86RF233
} rf_trx_part_e;
/*Atmel RF states*/
typedef enum {
NOP = 0x00,
BUSY_RX = 0x01,
BUSY_TX = 0x02,
RF_TX_START = 0x02,
FORCE_TRX_OFF = 0x03,
FORCE_PLL_ON = 0x04,
RX_ON = 0x06,
TRX_OFF = 0x08,
PLL_ON = 0x09,
BUSY_RX_AACK = 0x11,
SLEEP = 0x0F,
RX_AACK_ON = 0x16,
TX_ARET_ON = 0x19,
STATE_TRANSITION_IN_PROGRESS = 0x1F
} rf_trx_states_t;
} // anonymous namespace
static const uint8_t *rf_tx_data; // Points to Nanostack's buffer
static uint8_t rf_tx_length;
/*ACK wait duration changes depending on data rate*/
static uint16_t rf_ack_wait_duration = RF_ACK_WAIT_DEFAULT_TIMEOUT;
static int8_t rf_sensitivity = RF_DEFAULT_SENSITIVITY;
static rf_mode_t rf_mode = RF_MODE_NORMAL;
static uint8_t radio_tx_power = 0x00; // Default to +4dBm
static uint8_t rf_phy_channel = 12;
static uint8_t rf_tuned = 1;
static uint8_t rf_use_antenna_diversity = 0;
static int16_t expected_ack_sequence = -1;
static uint8_t rf_rx_mode = 0;
static uint8_t rf_flags = 0;
static int8_t rf_radio_driver_id = -1;
static phy_device_driver_s device_driver;
static uint8_t mac_tx_handle = 0;
static uint8_t xah_ctrl_1;
/* Channel configurations for 2.4 and sub-GHz */
static const phy_rf_channel_configuration_s phy_24ghz = {.channel_0_center_frequency = 2405000000U, .channel_spacing = 5000000U, .datarate = 250000U, .number_of_channels = 16U, .modulation = M_OQPSK};
static const phy_rf_channel_configuration_s phy_subghz = {.channel_0_center_frequency = 868300000U, .channel_spacing = 2000000U, .datarate = 250000U, .number_of_channels = 11U, .modulation = M_OQPSK};
static const phy_device_channel_page_s phy_channel_pages[] = {
{ CHANNEL_PAGE_0, &phy_24ghz},
{ CHANNEL_PAGE_2, &phy_subghz},
{ CHANNEL_PAGE_0, NULL}
};
/**
* RF output power write
*
* \brief TX power has to be set before network start.
*
* \param power
* AT86RF233
* 0 = 4 dBm
* 1 = 3.7 dBm
* 2 = 3.4 dBm
* 3 = 3 dBm
* 4 = 2.5 dBm
* 5 = 2 dBm
* 6 = 1 dBm
* 7 = 0 dBm
* 8 = -1 dBm
* 9 = -2 dBm
* 10 = -3 dBm
* 11 = -4 dBm
* 12 = -6 dBm
* 13 = -8 dBm
* 14 = -12 dBm
* 15 = -17 dBm
*
* AT86RF212B
* See datasheet for TX power settings
*
* \return 0, Supported Value
* \return -1, Not Supported Value
*/
static rf_trx_part_e rf_radio_type_read(void);
static void rf_ack_wait_timer_start(uint16_t slots);
static void rf_handle_cca_ed_done(uint8_t full_trx_status);
static void rf_handle_tx_end(rf_trx_states_t trx_status);
static void rf_handle_rx_end(rf_trx_states_t trx_status);
static void rf_on(void);
static void rf_give_up_on_ack(void);
static void rf_receive(rf_trx_states_t trx_status = STATE_TRANSITION_IN_PROGRESS);
static rf_trx_states_t rf_poll_trx_state_change(rf_trx_states_t trx_state);
static void rf_init(void);
static int8_t rf_device_register(const uint8_t *mac_addr);
static void rf_device_unregister(void);
static int8_t rf_start_cca(uint8_t *data_ptr, uint16_t data_length, uint8_t tx_handle, data_protocol_e data_protocol);
static void rf_cca_abort(void);
static void rf_calibration_cb(void);
static void rf_init_phy_mode(void);
static void rf_ack_wait_timer_interrupt(void);
static void rf_calibration_timer_interrupt(void);
static void rf_calibration_timer_start(uint32_t slots);
static void rf_cca_timer_interrupt(void);
static void rf_cca_timer_start(uint32_t slots);
static uint8_t rf_scale_lqi(int8_t rssi);
static int8_t rf_interface_state_control(phy_interface_state_e new_state, uint8_t rf_channel);
static int8_t rf_extension(phy_extension_type_e extension_type, uint8_t *data_ptr);
static int8_t rf_address_write(phy_address_type_e address_type, uint8_t *address_ptr);
static void rf_if_cca_timer_start(uint32_t slots);
static void rf_if_enable_promiscuous_mode(void);
static void rf_if_lock(void);
static void rf_if_unlock(void);
static uint8_t rf_if_read_rnd(void);
static void rf_if_calibration_timer_start(uint32_t slots);
static void rf_if_interrupt_handler(void);
static void rf_if_ack_wait_timer_start(uint16_t slots);
static void rf_if_ack_wait_timer_stop(void);
static void rf_if_ack_pending_ctrl(uint8_t state);
static void rf_if_calibration(void);
static uint8_t rf_if_read_register(uint8_t addr);
static void rf_if_set_bit(uint8_t addr, uint8_t bit, uint8_t bit_mask);
static void rf_if_clear_bit(uint8_t addr, uint8_t bit);
static void rf_if_write_register(uint8_t addr, uint8_t data);
static void rf_if_reset_radio(void);
static void rf_if_enable_ant_div(void);
static void rf_if_disable_ant_div(void);
static void rf_if_enable_slptr(void);
static void rf_if_disable_slptr(void);
static void rf_if_write_antenna_diversity_settings(void);
static void rf_if_write_set_tx_power_register(uint8_t value);
static void rf_if_write_rf_settings(void);
static rf_trx_states_t rf_if_read_trx_state(void);
static uint16_t rf_if_read_packet(uint8_t data[RF_MTU], uint8_t *lqi_out, uint8_t *ed_out, bool *crc_good);
static void rf_if_write_short_addr_registers(uint8_t *short_address);
static uint8_t rf_if_last_acked_pending(void);
static void rf_if_write_pan_id_registers(uint8_t *pan_id);
static void rf_if_write_ieee_addr_registers(uint8_t *address);
static void rf_if_write_frame_buffer(const uint8_t *ptr, uint8_t length);
static rf_trx_states_t rf_if_change_trx_state(rf_trx_states_t trx_state);
static void rf_if_start_cca_process(void);
static int8_t rf_if_scale_rssi(uint8_t ed_level);
static void rf_if_set_channel_register(uint8_t channel);
static void rf_if_enable_promiscuous_mode(void);
static void rf_if_disable_promiscuous_mode(void);
static uint8_t rf_if_read_part_num(void);
static void rf_if_enable_irq(void);
static void rf_if_disable_irq(void);
static void rf_if_spi_exchange_n(const void *tx, size_t tx_len, void *rx, size_t rx_len);
static inline rf_trx_states_t rf_if_trx_status_from_full(uint8_t full_trx_status)
{
return (rf_trx_states_t)(full_trx_status & 0x1F);
}
#ifdef MBED_CONF_RTOS_PRESENT
#include "rtos.h"
using namespace mbed;
using namespace rtos;
static void rf_if_irq_task_process_irq();
#define SIG_RADIO 1
#define SIG_TIMER_ACK 2
#define SIG_TIMER_CAL 4
#define SIG_TIMER_CCA 8
#define SIG_TIMERS (SIG_TIMER_ACK|SIG_TIMER_CAL|SIG_TIMER_CCA)
#define SIG_ALL (SIG_RADIO|SIG_TIMERS)
#endif
// HW pins to RF chip
class UnlockedSPI : public SPI {
public:
UnlockedSPI(PinName mosi, PinName miso, PinName sclk) :
SPI(mosi, miso, sclk) { }
virtual void lock() { }
virtual void unlock() { }
};
class RFBits {
public:
RFBits(PinName spi_mosi, PinName spi_miso,
PinName spi_sclk, PinName spi_cs,
PinName spi_rst, PinName spi_slp, PinName spi_irq);
UnlockedSPI spi;
DigitalOut CS;
DigitalOut RST;
DigitalOut SLP_TR;
InterruptIn IRQ;
Timeout ack_timer;
Timeout cal_timer;
Timeout cca_timer;
#ifdef MBED_CONF_RTOS_PRESENT
Thread irq_thread;
Mutex mutex;
void rf_if_irq_task();
#endif
};
RFBits::RFBits(PinName spi_mosi, PinName spi_miso,
PinName spi_sclk, PinName spi_cs,
PinName spi_rst, PinName spi_slp, PinName spi_irq)
: spi(spi_mosi, spi_miso, spi_sclk),
CS(spi_cs),
RST(spi_rst),
SLP_TR(spi_slp),
IRQ(spi_irq)
#ifdef MBED_CONF_RTOS_PRESENT
, irq_thread(osPriorityRealtime, MBED_CONF_ATMEL_RF_IRQ_THREAD_STACK_SIZE, NULL, "atmel_irq_thread")
#endif
{
#ifdef MBED_CONF_RTOS_PRESENT
irq_thread.start(mbed::callback(this, &RFBits::rf_if_irq_task));
#endif
}
static RFBits *rf;
static uint8_t rf_part_num = 0;
/*TODO: RSSI Base value setting*/
static int8_t rf_rssi_base_val = -91;
static void rf_if_lock(void)
{
platform_enter_critical();
}
static void rf_if_unlock(void)
{
platform_exit_critical();
}
#ifdef MBED_CONF_RTOS_PRESENT
static void rf_if_cca_timer_signal(void)
{
rf->irq_thread.flags_set(SIG_TIMER_CCA);
}
static void rf_if_cal_timer_signal(void)
{
rf->irq_thread.flags_set(SIG_TIMER_CAL);
}
static void rf_if_ack_timer_signal(void)
{
rf->irq_thread.flags_set(SIG_TIMER_ACK);
}
#endif
// t1 = 180ns, SEL falling edge to MISO active [SPI setup assumed slow enough to not need manual delay]
#define CS_SELECT() {rf->CS = 0; /* delay_ns(180); */}
// t9 = 250ns, last clock to SEL rising edge, t8 = 250ns, SPI idle time between consecutive access
#define CS_RELEASE() {wait_ns(250); rf->CS = 1; wait_ns(250);}
/*
* \brief Read connected radio part.
*
* This function only return valid information when rf_init() is called
*
* \return
*/
static rf_trx_part_e rf_radio_type_read(void)
{
rf_trx_part_e ret_val = ATMEL_UNKNOW_DEV;
switch (rf_part_num) {
case PART_AT86RF212:
ret_val = ATMEL_AT86RF212;
break;
case PART_AT86RF233:
ret_val = ATMEL_AT86RF233;
break;
default:
break;
}
return ret_val;
}
/*
* \brief Function starts the ACK wait timeout.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_if_ack_wait_timer_start(uint16_t slots)
{
#ifdef MBED_CONF_RTOS_PRESENT
rf->ack_timer.attach_us(rf_if_ack_timer_signal, slots * 50);
#else
rf->ack_timer.attach_us(rf_ack_wait_timer_interrupt, slots * 50);
#endif
}
/*
* \brief Function starts the calibration interval.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_if_calibration_timer_start(uint32_t slots)
{
#ifdef MBED_CONF_RTOS_PRESENT
rf->cal_timer.attach_us(rf_if_cal_timer_signal, slots * 50);
#else
rf->cal_timer.attach_us(rf_calibration_timer_interrupt, slots * 50);
#endif
}
/*
* \brief Function starts the CCA interval.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_if_cca_timer_start(uint32_t slots)
{
#ifdef MBED_CONF_RTOS_PRESENT
rf->cca_timer.attach_us(rf_if_cca_timer_signal, slots * 50);
#else
rf->cca_timer.attach_us(rf_cca_timer_interrupt, slots * 50);
#endif
}
/*
* \brief Function stops the CCA interval.
*
* \return none
*/
static void rf_if_cca_timer_stop(void)
{
rf->cca_timer.detach();
}
/*
* \brief Function stops the ACK wait timeout.
*
* \param none
*
* \return none
*/
static void rf_if_ack_wait_timer_stop(void)
{
rf->ack_timer.detach();
}
/*
* \brief Function sets bit(s) in given RF register.
*
* \param addr Address of the register to set
* \param bit Bit(s) to set
* \param bit_mask Masks the field inside the register
*
* \return none
*/
static void rf_if_set_bit(uint8_t addr, uint8_t bit, uint8_t bit_mask)
{
uint8_t reg = rf_if_read_register(addr);
reg &= ~bit_mask;
reg |= bit;
rf_if_write_register(addr, reg);
}
/*
* \brief Function clears bit(s) in given RF register.
*
* \param addr Address of the register to clear
* \param bit Bit(s) to clear
*
* \return none
*/
static void rf_if_clear_bit(uint8_t addr, uint8_t bit)
{
rf_if_set_bit(addr, 0, bit);
}
/*
* \brief Function writes register in RF.
*
* \param addr Address on the RF
* \param data Written data
*
* \return none
*/
static void rf_if_write_register(uint8_t addr, uint8_t data)
{
const uint8_t tx[2] = { static_cast<uint8_t>(0xC0 | addr), data };
uint8_t rx[2];
CS_SELECT();
rf_if_spi_exchange_n(tx, 2, rx, 2);
CS_RELEASE();
}
/*
* \brief Function reads RF register, and also outputs PHY_STATUS
*
* \param addr Address on the RF
* \param[out] status_out Pointer to store PHY_STATUS
*
* \return Read register data
*/
static uint8_t rf_if_read_register_with_status(uint8_t addr, uint8_t *status_out)
{
const uint8_t tx[1] = { static_cast<uint8_t>(0x80 | addr) };
uint8_t rx[2];
CS_SELECT();
rf_if_spi_exchange_n(tx, 1, rx, 2);
CS_RELEASE();
if (status_out) {
*status_out = rx[0];
}
return rx[1];
}
/*
* \brief Function reads RF register.
*
* \param addr Address on the RF
*
* \return Read register data
*/
static uint8_t rf_if_read_register(uint8_t addr)
{
return rf_if_read_register_with_status(addr, NULL);
}
/*
* \brief Function resets the RF.
*
* \param none
*
* \return none
*/
static void rf_if_reset_radio(void)
{
#if MBED_CONF_ATMEL_RF_USE_SPI_SPACING_API
rf->spi.frequency(MBED_CONF_ATMEL_RF_FULL_SPI_SPEED);
int spacing = rf->spi.write_spacing(MBED_CONF_ATMEL_RF_FULL_SPI_SPEED_BYTE_SPACING);
if (spacing < MBED_CONF_ATMEL_RF_FULL_SPI_SPEED_BYTE_SPACING) {
rf->spi.frequency(MBED_CONF_ATMEL_RF_LOW_SPI_SPEED);
rf->spi.write_spacing(0);
}
#elif MBED_CONF_ATMEL_RF_ASSUME_SPACED_SPI
rf->spi.frequency(MBED_CONF_ATMEL_RF_FULL_SPI_SPEED);
#else
rf->spi.frequency(MBED_CONF_ATMEL_RF_LOW_SPI_SPEED);
#endif
rf->IRQ.rise(0);
rf->RST = 1;
wait_ms(1);
rf->RST = 0;
wait_ms(10);
CS_RELEASE();
rf->SLP_TR = 0;
wait_ms(10);
rf->RST = 1;
wait_ms(10);
rf->IRQ.rise(&rf_if_interrupt_handler);
}
/*
* \brief Function enables the promiscuous mode.
*
* \param none
*
* \return none
*/
static void rf_if_enable_promiscuous_mode(void)
{
if (!(xah_ctrl_1 & AACK_PROM_MODE)) {
/*Set AACK_PROM_MODE to enable the promiscuous mode*/
rf_if_write_register(XAH_CTRL_1, xah_ctrl_1 |= AACK_PROM_MODE);
}
}
/*
* \brief Function disable the promiscuous mode.
*
* \param none
*
* \return none
*/
static void rf_if_disable_promiscuous_mode(void)
{
if (xah_ctrl_1 & AACK_PROM_MODE) {
/*Clear AACK_PROM_MODE to disable the promiscuous mode*/
rf_if_write_register(XAH_CTRL_1, xah_ctrl_1 &= ~AACK_PROM_MODE);
}
}
/*
* \brief Function enables the Antenna diversity usage.
*
* \param none
*
* \return none
*/
static void rf_if_enable_ant_div(void)
{
/*Set ANT_EXT_SW_EN to enable controlling of antenna diversity*/
rf_if_set_bit(ANT_DIV, ANT_EXT_SW_EN, ANT_EXT_SW_EN);
}
/*
* \brief Function disables the Antenna diversity usage.
*
* \param none
*
* \return none
*/
static void rf_if_disable_ant_div(void)
{
rf_if_clear_bit(ANT_DIV, ANT_EXT_SW_EN);
}
/*
* \brief Function sets the SLP TR pin.
*
* \param none
*
* \return none
*/
static void rf_if_enable_slptr(void)
{
rf->SLP_TR = 1;
}
/*
* \brief Function clears the SLP TR pin.
*
* \param none
*
* \return none
*/
static void rf_if_disable_slptr(void)
{
rf->SLP_TR = 0;
}
/*
* \brief Function writes the antenna diversity settings.
*
* \param none
*
* \return none
*/
static void rf_if_write_antenna_diversity_settings(void)
{
/*Recommended setting of PDT_THRES is 3 when antenna diversity is used*/
rf_if_set_bit(RX_CTRL, 0x03, 0x0f);
rf_if_write_register(ANT_DIV, ANT_DIV_EN | ANT_EXT_SW_EN | ANT_CTRL_DEFAULT);
}
/*
* \brief Function writes the TX output power register.
*
* \param value Given register value
*
* \return none
*/
static void rf_if_write_set_tx_power_register(uint8_t value)
{
rf_if_write_register(PHY_TX_PWR, value);
}
/*
* \brief Function returns the RF part number.
*
* \param none
*
* \return part number
*/
static uint8_t rf_if_read_part_num(void)
{
return rf_if_read_register(PART_NUM);
}
/*
* \brief Function writes the RF settings and initialises SPI interface.
*
* \param none
*
* \return none
*/
static void rf_if_write_rf_settings(void)
{
/*Reset RF module*/
rf_if_reset_radio();
rf_part_num = rf_if_read_part_num();
rf_if_write_register(XAH_CTRL_0, 0);
/* Auto CRC on, IRQ status shows unmasked only, TRX_STATUS output on all accesses */
rf_if_write_register(TRX_CTRL_1, TX_AUTO_CRC_ON | SPI_CMD_MODE_TRX_STATUS);
rf_if_write_register(IRQ_MASK, CCA_ED_DONE | TRX_END | TRX_UR);
xah_ctrl_1 = rf_if_read_register(XAH_CTRL_1);
/*Read transceiver PART_NUM*/
rf_part_num = rf_if_read_register(PART_NUM);
/*Sub-GHz RF settings*/
if (rf_part_num == PART_AT86RF212) {
/*GC_TX_OFFS mode-dependent setting - OQPSK*/
rf_if_write_register(RF_CTRL_0, 0x32);
if (rf_if_read_register(VERSION_NUM) == VERSION_AT86RF212B) {
/*TX Output Power setting - 0 dBm North American Band*/
rf_if_write_register(PHY_TX_PWR, 0x03);
} else {
/*TX Output Power setting - 0 dBm North American Band*/
rf_if_write_register(PHY_TX_PWR, 0x24);
}
/*PHY Mode: IEEE 802.15.4-2006/2011 - OQPSK-SIN-250*/
rf_if_write_register(TRX_CTRL_2, RX_SAFE_MODE | RF_PHY_MODE);
/*Based on receiver Characteristics. See AT86RF212B Datasheet where RSSI BASE VALUE in range -97 - -100 dBm*/
rf_rssi_base_val = -98;
}
/*2.4GHz RF settings*/
else {
#if 0
/* Disable power saving functions for now - can only impact reliability,
* and don't have any users demanding it. */
/*Set RPC register*/
rf_if_write_register(TRX_RPC, RX_RPC_CTRL | RX_RPC_EN | PLL_RPC_EN | XAH_TX_RPC_EN | IPAN_RPC_EN | TRX_RPC_RSVD_1);
#endif
/*PHY Mode: IEEE 802.15.4 - Data Rate 250 kb/s*/
rf_if_write_register(TRX_CTRL_2, RX_SAFE_MODE);
rf_rssi_base_val = -91;
}
}
/*
* \brief Function returns the RF state
*
* \param none
*
* \return RF state
*/
static rf_trx_states_t rf_if_read_trx_state(void)
{
return rf_if_trx_status_from_full(rf_if_read_register(TRX_STATUS));
}
/*
* \brief Function reads packet buffer.
*
* \param data_out Output buffer
* \param lqi_out LQI output
* \param ed_out ED output
* \param crc_good CRC good indication
*
* \return PSDU length [0..RF_MTU]
*/
static uint16_t rf_if_read_packet(uint8_t data_out[RF_MTU], uint8_t *lqi_out, uint8_t *ed_out, bool *crc_good)
{
CS_SELECT();
const uint8_t tx[1] = { 0x20 };
uint8_t rx[3];
rf_if_spi_exchange_n(tx, 1, rx, 2);
uint8_t len = rx[1] & 0x7F;
rf_if_spi_exchange_n(NULL, 0, data_out, len);
rf_if_spi_exchange_n(NULL, 0, rx, 3);
*lqi_out = rx[0];
*ed_out = rx[1];
*crc_good = rx[2] & 0x80;
CS_RELEASE();
return len;
}
/*
* \brief Function writes RF short address registers
*
* \param short_address Given short address
*
* \return none
*/
static void rf_if_write_short_addr_registers(uint8_t *short_address)
{
rf_if_write_register(SHORT_ADDR_1, *short_address++);
rf_if_write_register(SHORT_ADDR_0, *short_address);
}
/*
* \brief Function sets the frame pending in ACK message
*
* \param state Given frame pending state
*
* \return none
*/
static void rf_if_ack_pending_ctrl(uint8_t state)
{
rf_if_lock();
if (state) {
rf_if_set_bit(CSMA_SEED_1, (1 << AACK_SET_PD), (1 << AACK_SET_PD));
} else {
rf_if_clear_bit(CSMA_SEED_1, (1 << AACK_SET_PD));
}
rf_if_unlock();
}
/*
* \brief Function returns the state of frame pending control
*
* \param none
*
* \return Frame pending state
*/
static uint8_t rf_if_last_acked_pending(void)
{
uint8_t last_acked_data_pending;
rf_if_lock();
if (rf_if_read_register(CSMA_SEED_1) & (1 << AACK_SET_PD)) {
last_acked_data_pending = 1;
} else {
last_acked_data_pending = 0;
}
rf_if_unlock();
return last_acked_data_pending;
}
/*
* \brief Function calibrates the RF part.
*
* \param none
*
* \return none
*/
static void rf_if_calibration(void)
{
rf_if_set_bit(FTN_CTRL, FTN_START, FTN_START);
/*Wait while calibration is running*/
while (rf_if_read_register(FTN_CTRL) & FTN_START);
}
/*
* \brief Function writes RF PAN Id registers
*
* \param pan_id Given PAN Id
*
* \return none
*/
static void rf_if_write_pan_id_registers(uint8_t *pan_id)
{
rf_if_write_register(PAN_ID_1, *pan_id++);
rf_if_write_register(PAN_ID_0, *pan_id);
}
/*
* \brief Function writes RF IEEE Address registers
*
* \param address Given IEEE Address
*
* \return none
*/
static void rf_if_write_ieee_addr_registers(uint8_t *address)
{
uint8_t i;
uint8_t temp = IEEE_ADDR_0;
for (i = 0; i < 8; i++) {
rf_if_write_register(temp++, address[7 - i]);
}
}
/*
* \brief Function writes data in RF frame buffer.
*
* \param ptr Pointer to data (PSDU, except FCS)
* \param length Pointer to length (PSDU length, minus 2 for FCS)
*
* \return none
*/
static void rf_if_write_frame_buffer(const uint8_t *ptr, uint8_t length)
{
const uint8_t cmd[2] = { 0x60, static_cast<uint8_t>(length + 2) };
CS_SELECT();
rf_if_spi_exchange_n(cmd, 2, NULL, 0);
rf_if_spi_exchange_n(ptr, length, NULL, 0);
CS_RELEASE();
}
/*
* \brief Function returns 8-bit random value.
*
* \param none
*
* \return random value
*/
static uint8_t rf_if_read_rnd(void)
{
uint8_t temp;
uint8_t tmp_rpc_val = 0;
/*RPC must be disabled while reading the random number*/
if (rf_part_num == PART_AT86RF233) {
tmp_rpc_val = rf_if_read_register(TRX_RPC);
rf_if_write_register(TRX_RPC, RX_RPC_CTRL | TRX_RPC_RSVD_1);
}
wait_ms(1);
temp = ((rf_if_read_register(PHY_RSSI) >> 5) << 6);
wait_ms(1);
temp |= ((rf_if_read_register(PHY_RSSI) >> 5) << 4);
wait_ms(1);
temp |= ((rf_if_read_register(PHY_RSSI) >> 5) << 2);
wait_ms(1);
temp |= ((rf_if_read_register(PHY_RSSI) >> 5));
wait_ms(1);
if (rf_part_num == PART_AT86RF233) {
rf_if_write_register(TRX_RPC, tmp_rpc_val);
}
return temp;
}
/*
* \brief Function changes the state of the RF.
*
* \param trx_state Given RF state
*
* \return none
*/
static rf_trx_states_t rf_if_change_trx_state(rf_trx_states_t trx_state)
{
rf_if_write_register(TRX_STATE, trx_state);
/*Wait while not in desired state*/
return rf_poll_trx_state_change(trx_state);
}
/*
* \brief Function starts the CCA process
*
* \param none
*
* \return none
*/
static void rf_if_start_cca_process(void)
{
rf_if_write_register(PHY_CC_CCA, CCA_REQUEST | CCA_MODE_3A | rf_phy_channel);
}
/*
* \brief Function scales RSSI
*
* \param ed_level ED level read from chip
*
* \return appropriately scaled RSSI dBm
*/
static int8_t rf_if_scale_rssi(uint8_t ed_level)
{
if (rf_part_num == PART_AT86RF212) {
/* Data sheet says to multiply by 1.03 - this is 1.03125, rounding down */
ed_level += ed_level >> 5;
}
return rf_rssi_base_val + ed_level;
}
/*
* \brief Function sets the RF channel field
*
* \param Given channel
*
* \return none
*/
static void rf_if_set_channel_register(uint8_t channel)
{
rf_if_set_bit(PHY_CC_CCA, channel, CCA_CHANNEL_MASK);
}
/*
* \brief Function enables RF irq pin interrupts in RF interface.
*
* \param none
*
* \return none
*/
static void rf_if_enable_irq(void)
{
rf->IRQ.enable_irq();
}
/*
* \brief Function disables RF irq pin interrupts in RF interface.
*
* \param none
*
* \return none
*/
static void rf_if_disable_irq(void)
{
rf->IRQ.disable_irq();
}
#ifdef MBED_CONF_RTOS_PRESENT
static void rf_if_interrupt_handler(void)
{
rf->irq_thread.flags_set(SIG_RADIO);
}
// Started during construction of rf, so variable
// rf isn't set at the start. Uses 'this' instead.
void RFBits::rf_if_irq_task(void)
{
for (;;) {
uint32_t flags = ThisThread::flags_wait_any(SIG_ALL);
rf_if_lock();
if (flags & SIG_RADIO) {
rf_if_irq_task_process_irq();
}
if (flags & SIG_TIMER_ACK) {
rf_ack_wait_timer_interrupt();
}
if (flags & SIG_TIMER_CCA) {
rf_cca_timer_interrupt();
}
if (flags & SIG_TIMER_CAL) {
rf_calibration_timer_interrupt();
}
rf_if_unlock();
}
}
static void rf_if_irq_task_process_irq(void)
#else
/*
* \brief Function is a RF interrupt vector. End of frame in RX and TX are handled here as well as CCA process interrupt.
*
* \param none
*
* \return none
*/
static void rf_if_interrupt_handler(void)
#endif
{
uint8_t irq_status, full_trx_status;
/*Read and clear interrupt flag, and pick up trx_status*/
irq_status = rf_if_read_register_with_status(IRQ_STATUS, &full_trx_status);
/*Frame end interrupt (RX and TX)*/
if (irq_status & TRX_END) {
rf_trx_states_t trx_status = rf_if_trx_status_from_full(full_trx_status);
if (rf_flags & RFF_TX) {
rf_handle_tx_end(trx_status);
} else if (rf_flags & RFF_RX) {
rf_handle_rx_end(trx_status);
} else {
//something went really wrong
}
}
if (irq_status & CCA_ED_DONE) {
rf_handle_cca_ed_done(full_trx_status);
}
if (irq_status & TRX_UR) {
// Here some counter could be used to monitor the under run occurrence count.
// Do not print anything here!
}
}
/*
* \brief Function writes/read data in SPI interface
*/
static void rf_if_spi_exchange_n(const void *tx, size_t tx_len, void *rx, size_t rx_len)
{
#if 1
rf->spi.write(static_cast<const char *>(tx), tx_len,
static_cast<char *>(rx), rx_len);
#else
const uint8_t *txb = static_cast<const uint8_t *>(tx);
uint8_t *rxb = static_cast<uint8_t *>(rx);
while (tx_len > 0 || rx_len > 0) {
uint8_t b;
if (tx_len) {
tx_len--;
b = *txb++;
} else {
b = 0xFF;
}
b = rf->spi.write(b);
if (rx_len) {
rx_len--;
*rxb++ = b;
}
}
#endif
}
/*
* \brief Function sets given RF flag on.
*
* \param x Given RF flag
*
* \return none
*/
static void rf_flags_set(uint8_t x)
{
rf_flags |= x;
}
/*
* \brief Function clears given RF flag on.
*
* \param x Given RF flag
*
* \return none
*/
static void rf_flags_clear(uint8_t x)
{
rf_flags &= ~x;
}
/*
* \brief Function checks if given RF flag is on.
*
* \param x Given RF flag
*
* \return states of the given flags
*/
static uint8_t rf_flags_check(uint8_t x)
{
return (rf_flags & x);
}
/*
* \brief Function clears all RF flags.
*
* \param none
*
* \return none
*/
static void rf_flags_reset(void)
{
rf_flags = 0;
}
/*
* \brief Function initialises and registers the RF driver.
*
* \param none
*
* \return rf_radio_driver_id Driver ID given by NET library
*/
static int8_t rf_device_register(const uint8_t *mac_addr)
{
rf_trx_part_e radio_type;
rf_init();
radio_type = rf_radio_type_read();
if (radio_type != ATMEL_UNKNOW_DEV) {
/*Set pointer to MAC address*/
device_driver.PHY_MAC = (uint8_t *)mac_addr;
device_driver.driver_description = (char *)"ATMEL_MAC";
//Create setup Used Radio chips
if (radio_type == ATMEL_AT86RF212) {
device_driver.link_type = PHY_LINK_15_4_SUBGHZ_TYPE;
} else {
device_driver.link_type = PHY_LINK_15_4_2_4GHZ_TYPE;
}
device_driver.phy_channel_pages = phy_channel_pages;
/*Maximum size of payload is 127*/
device_driver.phy_MTU = 127;
/*No header in PHY*/
device_driver.phy_header_length = 0;
/*No tail in PHY*/
device_driver.phy_tail_length = 0;
/*Set address write function*/
device_driver.address_write = &rf_address_write;
/*Set RF extension function*/
device_driver.extension = &rf_extension;
/*Set RF state control function*/
device_driver.state_control = &rf_interface_state_control;
/*Set transmit function*/
device_driver.tx = &rf_start_cca;
/*NULLIFY rx and tx_done callbacks*/
device_driver.phy_rx_cb = NULL;
device_driver.phy_tx_done_cb = NULL;
/*Register device driver*/
rf_radio_driver_id = arm_net_phy_register(&device_driver);
} else {
rf_if_disable_irq();
}
return rf_radio_driver_id;
}
/*
* \brief Function unregisters the RF driver.
*
* \param none
*
* \return none
*/
static void rf_device_unregister()
{
if (rf_radio_driver_id >= 0) {
arm_net_phy_unregister(rf_radio_driver_id);
rf_radio_driver_id = -1;
}
}
/*
* \brief Function is a call back for ACK wait timeout.
*
* \param none
*
* \return none
*/
static void rf_ack_wait_timer_interrupt(void)
{
rf_if_lock();
rf_give_up_on_ack();
rf_if_unlock();
}
/*
* \brief Function is a call back for calibration interval timer.
*
* \param none
*
* \return none
*/
static void rf_calibration_timer_interrupt(void)
{
/*Calibrate RF*/
rf_calibration_cb();
/*Start new calibration timeout*/
rf_calibration_timer_start(RF_CALIBRATION_INTERVAL);
}
/*
* \brief Function is a call back for cca interval timer.
*
* \param none
*
* \return none
*/
static void rf_cca_timer_interrupt(void)
{
rf_flags_set(RFF_CCA);
/*Start CCA process*/
rf_if_start_cca_process();
}
/*
* \brief Function starts the ACK wait timeout.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_ack_wait_timer_start(uint16_t slots)
{
rf_if_ack_wait_timer_start(slots);
}
/*
* \brief Function starts the calibration interval.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_calibration_timer_start(uint32_t slots)
{
rf_if_calibration_timer_start(slots);
}
/*
* \brief Function starts the CCA backoff.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_cca_timer_start(uint32_t slots)
{
rf_if_cca_timer_start(slots);
}
/*
* \brief Function stops the CCA backoff.
*
* \return none
*/
static void rf_cca_timer_stop(void)
{
rf_if_cca_timer_stop();
}
/*
* \brief Function writes various RF settings in startup.
*
* \param none
*
* \return none
*/
static void rf_write_settings(void)
{
rf_if_lock();
rf_if_write_rf_settings();
/*Set output power*/
rf_if_write_set_tx_power_register(radio_tx_power);
/*Initialise Antenna Diversity*/
if (rf_use_antenna_diversity) {
rf_if_write_antenna_diversity_settings();
}
rf_if_unlock();
}
/*
* \brief Function writes 16-bit address in RF address filter.
*
* \param short_address Given short address
*
* \return none
*/
static void rf_set_short_adr(uint8_t *short_address)
{
rf_if_lock();
/*Wake up RF if sleeping*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
}
/*Write address filter registers*/
rf_if_write_short_addr_registers(short_address);
/*RF back to sleep*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_enable_slptr();
}
rf_if_unlock();
}
/*
* \brief Function writes PAN Id in RF PAN Id filter.
*
* \param pan_id Given PAN Id
*
* \return none
*/
static void rf_set_pan_id(uint8_t *pan_id)
{
rf_if_lock();
/*Wake up RF if sleeping*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
}
/*Write address filter registers*/
rf_if_write_pan_id_registers(pan_id);
/*RF back to sleep*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_enable_slptr();
}
rf_if_unlock();
}
/*
* \brief Function writes 64-bit address in RF address filter.
*
* \param address Given 64-bit address
*
* \return none
*/
static void rf_set_address(uint8_t *address)
{
rf_if_lock();
/*Wake up RF if sleeping*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
}
/*Write address filter registers*/
rf_if_write_ieee_addr_registers(address);
/*RF back to sleep*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_enable_slptr();
}
rf_if_unlock();
}
/*
* \brief Function sets the RF channel.
*
* \param ch New channel
*
* \return none
*/
static void rf_channel_set(uint8_t ch)
{
rf_if_lock();
rf_phy_channel = ch;
if (ch < 0x1f) {
rf_if_set_channel_register(ch);
}
rf_if_unlock();
}
/*
* \brief Function initialises the radio driver and resets the radio.
*
* \param none
*
* \return none
*/
static void rf_init(void)
{
rf_if_lock();
/*Write RF settings*/
rf_write_settings();
/*Initialise PHY mode*/
rf_init_phy_mode();
/*Clear RF flags*/
rf_flags_reset();
/*Set RF in TRX OFF state*/
rf_if_change_trx_state(TRX_OFF);
/*Set RF in PLL_ON state*/
rf_trx_states_t trx_status = rf_if_change_trx_state(PLL_ON);
/*Start receiver*/
rf_receive(trx_status);
/*Read randomness, and add to seed*/
randLIB_add_seed(rf_if_read_rnd());
/*Start RF calibration timer*/
rf_calibration_timer_start(RF_CALIBRATION_INTERVAL);
rf_if_unlock();
}
/**
* \brief Function gets called when MAC is setting radio off.
*
* \param none
*
* \return none
*/
static void rf_off(void)
{
if (rf_flags_check(RFF_ON)) {
rf_if_lock();
rf_cca_abort();
uint16_t while_counter = 0;
/*Wait while receiving*/
while (rf_if_read_trx_state() == BUSY_RX_AACK) {
while_counter++;
if (while_counter == 0xffff) {
break;
}
}
/*RF state change: RX_AACK_ON->PLL_ON->TRX_OFF->SLEEP*/
if (rf_if_read_trx_state() == RX_AACK_ON) {
rf_if_change_trx_state(PLL_ON);
}
rf_if_change_trx_state(TRX_OFF);
rf_if_enable_slptr();
/*Disable Antenna Diversity*/
if (rf_use_antenna_diversity) {
rf_if_disable_ant_div();
}
rf_if_unlock();
}
/*Clears all flags*/
rf_flags_reset();
}
/*
* \brief Function polls the RF state until it has changed to desired state.
*
* \param trx_state RF state
*
* \return none
*/
static rf_trx_states_t rf_poll_trx_state_change(rf_trx_states_t trx_state)
{
uint16_t while_counter = 0;
if (trx_state == FORCE_PLL_ON) {
trx_state = PLL_ON;
} else if (trx_state == FORCE_TRX_OFF) {
trx_state = TRX_OFF;
}
rf_trx_states_t state_out;
while ((state_out = rf_if_read_trx_state()) != trx_state) {
while_counter++;
if (while_counter == 0x1ff) {
break;
}
}
return state_out;
}
/*
* \brief Function polls the RF state until it is no longer transitioning.
*
* \param trx_state RF state
*
* \return none
*/
static rf_trx_states_t rf_poll_for_state(void)
{
rf_trx_states_t state_out;
while ((state_out = rf_if_read_trx_state()) == STATE_TRANSITION_IN_PROGRESS) {
}
return state_out;
}
/*
* \brief Function starts the CCA process before starting data transmission and copies the data to RF TX FIFO.
*
* \param data_ptr Pointer to TX data (excluding FCS)
* \param data_length Length of the TX data (excluding FCS)
* \param tx_handle Handle to transmission
* \return 0 Success
* \return -1 Busy
*/
static int8_t rf_start_cca(uint8_t *data_ptr, uint16_t data_length, uint8_t tx_handle, data_protocol_e data_protocol)
{
(void)data_protocol;
rf_if_lock();
/*Check if transmitter is busy*/
rf_trx_states_t trx_state = rf_if_read_trx_state();
if (trx_state == BUSY_RX || trx_state == BUSY_RX_AACK || data_length > RF_MTU - 2) {
rf_if_unlock();
/*Return busy*/
return -1;
} else {
rf_give_up_on_ack();
/*Nanostack has a static TX buffer, which will remain valid until we*/
/*generate a callback, so we just note the pointer for reading later.*/
rf_tx_data = data_ptr;
rf_tx_length = data_length;
/*Start CCA timeout*/
rf_cca_timer_start(RF_CCA_BASE_BACKOFF + randLIB_get_random_in_range(0, RF_CCA_RANDOM_BACKOFF));
/*Store TX handle*/
mac_tx_handle = tx_handle;
rf_if_unlock();
}
/*Return success*/
return 0;
}
/*
* \brief Function aborts CCA process.
*
* \param none
*
* \return none
*/
static void rf_cca_abort(void)
{
rf_cca_timer_stop();
rf_flags_clear(RFF_CCA);
}
/*
* \brief Function starts the transmission of the frame.
*
* \param none
*
* \return none
*/
static bool rf_start_tx()
{
/* Attempt change to PLL_ON */
rf_if_write_register(TRX_STATE, PLL_ON);
// It appears that if radio is busy, rather than ignoring the state change,
// the state change happens when it stops being busy - eg
// after address match fail or finishing reception. If this happens, we do
// not want to transmit - our channel clear check is stale (either someone is
// still transmitting, or it's a long time since we checked). So wait for the
// PLL_ON change and then go to receive mode without trying to transmit.
rf_trx_states_t state = rf_poll_for_state();
int poll_count = 0;
while (state != PLL_ON) {
/* Change didn't work (yet) - must be busy - assume it will eventually change */
state = rf_poll_for_state();
poll_count++;
}
rf_flags_clear(RFF_RX);
// Check whether we saw any delay in the PLL_ON transition.
if (poll_count > 0) {
// let's get back to the receiving state.
rf_receive(state);
return false;
}
rf_flags_set(RFF_TX);
/*RF state change: SLP_TR pulse triggers PLL_ON->BUSY_TX*/
rf_if_enable_slptr();
/*Chip permits us to write frame buffer while it is transmitting*/
/*As long as first byte of data is in within 176us of TX start, we're good */
rf_if_write_frame_buffer(rf_tx_data, rf_tx_length);
rf_if_disable_slptr();
return true;
}
/*
* \brief Function sets the RF in RX state.
*
* \param none
*
* \return none
*/
static void rf_receive(rf_trx_states_t trx_status)
{
uint16_t while_counter = 0;
if (rf_flags_check(RFF_ON) == 0) {
rf_on();
rf_channel_set(rf_phy_channel);
trx_status = TRX_OFF;
}
/*If not yet in RX state set it*/
if (rf_flags_check(RFF_RX) == 0) {
/*Wait while receiving data. Just making sure, usually this shouldn't happen. */
while (trx_status == BUSY_RX || trx_status == BUSY_RX_AACK || trx_status == STATE_TRANSITION_IN_PROGRESS) {
while_counter++;
if (while_counter == 0xffff) {
break;
}
trx_status = rf_if_read_trx_state();
}
if ((rf_mode == RF_MODE_SNIFFER) || (rf_mode == RF_MODE_ED)) {
if (trx_status != RX_ON) {
trx_status = rf_if_change_trx_state(RX_ON);
}
} else {
/*ACK is always received in promiscuous mode to bypass address filters*/
if (rf_rx_mode) {
rf_rx_mode = 0;
rf_if_enable_promiscuous_mode();
} else {
rf_if_disable_promiscuous_mode();
}
if (trx_status != RX_AACK_ON) {
trx_status = rf_if_change_trx_state(RX_AACK_ON);
}
}
/*If calibration timer was unable to calibrate the RF, run calibration now*/
if (!rf_tuned) {
/*Start calibration. This can be done in states TRX_OFF, PLL_ON or in any receive state*/
rf_if_calibration();
/*RF is tuned now*/
rf_tuned = 1;
}
rf_flags_set(RFF_RX);
}
}
/*
* \brief Function calibrates the radio.
*
* \param none
*
* \return none
*/
static void rf_calibration_cb(void)
{
/*clear tuned flag to start tuning in rf_receive*/
rf_tuned = 0;
/*If RF is in default receive state, start calibration*/
if (rf_if_read_trx_state() == RX_AACK_ON) {
rf_if_lock();
/*Set RF in PLL_ON state*/
rf_if_change_trx_state(PLL_ON);
/*Set RF in TRX_OFF state to start PLL tuning*/
rf_if_change_trx_state(TRX_OFF);
/*Set RF in RX_ON state to calibrate*/
rf_trx_states_t trx_status = rf_if_change_trx_state(RX_ON);
/*Calibrate FTN*/
rf_if_calibration();
/*RF is tuned now*/
rf_tuned = 1;
/*Back to default receive state*/
rf_flags_clear(RFF_RX);
rf_receive(trx_status);
rf_if_unlock();
}
}
/*
* \brief Function sets RF_ON flag when radio is powered.
*
* \param none
*
* \return none
*/
static void rf_on(void)
{
/*Set RFF_ON flag*/
if (rf_flags_check(RFF_ON) == 0) {
rf_if_lock();
rf_flags_set(RFF_ON);
/*Enable Antenna diversity*/
if (rf_use_antenna_diversity)
/*Set ANT_EXT_SW_EN to enable controlling of antenna diversity*/
{
rf_if_enable_ant_div();
}
/*Wake up from sleep state*/
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
rf_if_unlock();
}
}
/*
* \brief Abandon waiting for an ack frame
* \return none
*/
static void rf_give_up_on_ack(void)
{
if (expected_ack_sequence == -1) {
return;
}
rf_if_disable_promiscuous_mode();
rf_if_ack_wait_timer_stop();
expected_ack_sequence = -1;
if (device_driver.phy_tx_done_cb) {
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, PHY_LINK_TX_FAIL, 0, 0);
}
}
/*
* \brief Function handles the received ACK frame.
*
* \param seq_number Sequence number of received ACK
* \param data_pending Pending bit state in received ACK
*
* \return none
*/
static void rf_handle_ack(uint8_t seq_number, uint8_t data_pending)
{
phy_link_tx_status_e phy_status;
/*Received ACK sequence must be equal with transmitted packet sequence*/
if (expected_ack_sequence == seq_number) {
rf_if_disable_promiscuous_mode();
rf_if_ack_wait_timer_stop();
expected_ack_sequence = -1;
/*When data pending bit in ACK frame is set, inform NET library*/
if (data_pending) {
phy_status = PHY_LINK_TX_DONE_PENDING;
} else {
phy_status = PHY_LINK_TX_DONE;
}
/*Call PHY TX Done API*/
if (device_driver.phy_tx_done_cb) {
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, phy_status, 0, 0);
}
} else {
rf_give_up_on_ack();
}
}
/*
* \brief Function is a call back for RX end interrupt.
*
* \param none
*
* \return none
*/
static void rf_handle_rx_end(rf_trx_states_t trx_status)
{
/*Frame received interrupt*/
if (!rf_flags_check(RFF_RX)) {
return;
}
static uint8_t rf_buffer[RF_MTU];
uint8_t rf_lqi, rf_ed;
int8_t rf_rssi;
bool crc_good;
/*Read received packet*/
uint8_t len = rf_if_read_packet(rf_buffer, &rf_lqi, &rf_ed, &crc_good);
if (len < 5 || !crc_good) {
rf_give_up_on_ack();
return;
}
/* Convert raw ED to dBm value (chip-dependent) */
rf_rssi = rf_if_scale_rssi(rf_ed);
/* Create a virtual LQI using received RSSI, forgetting actual HW LQI */
/* (should be done through PHY_EXTENSION_CONVERT_SIGNAL_INFO) */
rf_lqi = rf_scale_lqi(rf_rssi);
/*Handle received ACK*/
if ((rf_buffer[0] & 0x07) == 0x02 && rf_mode != RF_MODE_SNIFFER) {
/*Check if data is pending*/
bool pending = (rf_buffer[0] & 0x10);
/*Send sequence number in ACK handler*/
rf_handle_ack(rf_buffer[2], pending);
} else {
rf_give_up_on_ack();
if (device_driver.phy_rx_cb) {
device_driver.phy_rx_cb(rf_buffer, len - 2, rf_lqi, rf_rssi, rf_radio_driver_id);
}
}
}
/*
* \brief Function is called when MAC is shutting down the radio.
*
* \param none
*
* \return none
*/
static void rf_shutdown(void)
{
/*Call RF OFF*/
rf_off();
}
/*
* \brief Function is a call back for TX end interrupt.
*
* \param none
*
* \return none
*/
static void rf_handle_tx_end(rf_trx_states_t trx_status)
{
rf_rx_mode = 0;
/*If ACK is needed for this transmission*/
if ((rf_tx_data[0] & 0x20) && rf_flags_check(RFF_TX)) {
expected_ack_sequence = rf_tx_data[2];
rf_ack_wait_timer_start(rf_ack_wait_duration);
rf_rx_mode = 1;
}
rf_flags_clear(RFF_TX);
/*Start receiver*/
rf_receive(trx_status);
/*Call PHY TX Done API*/
if (device_driver.phy_tx_done_cb) {
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, PHY_LINK_TX_SUCCESS, 0, 0);
}
}
/*
* \brief Function is a call back for CCA ED done interrupt.
*
* \param none
*
* \return none
*/
static void rf_handle_cca_ed_done(uint8_t full_trx_status)
{
if (!rf_flags_check(RFF_CCA)) {
return;
}
rf_flags_clear(RFF_CCA);
bool success = false;
/*Check the result of CCA process*/
if ((full_trx_status & CCA_STATUS) && rf_if_trx_status_from_full(full_trx_status) == RX_AACK_ON) {
success = rf_start_tx();
}
if (!success) {
/*Send CCA fail notification*/
if (device_driver.phy_tx_done_cb) {
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, PHY_LINK_CCA_FAIL, 0, 0);
}
}
}
/*
* \brief Function gives the control of RF states to MAC.
*
* \param new_state RF state
* \param rf_channel RF channel
*
* \return 0 Success
*/
static int8_t rf_interface_state_control(phy_interface_state_e new_state, uint8_t rf_channel)
{
int8_t ret_val = 0;
switch (new_state) {
/*Reset PHY driver and set to idle*/
case PHY_INTERFACE_RESET:
break;
/*Disable PHY Interface driver*/
case PHY_INTERFACE_DOWN:
rf_shutdown();
break;
/*Enable PHY Interface driver*/
case PHY_INTERFACE_UP:
rf_if_lock();
rf_mode = RF_MODE_NORMAL;
rf_channel_set(rf_channel);
rf_receive();
rf_if_enable_irq();
rf_if_unlock();
break;
/*Enable wireless interface ED scan mode*/
case PHY_INTERFACE_RX_ENERGY_STATE:
rf_mode = RF_MODE_ED;
rf_channel_set(rf_channel);
rf_receive();
rf_if_disable_irq();
// Read status to clear pending flags.
rf_if_read_register(IRQ_STATUS);
// ED can be initiated by writing arbitrary value to PHY_ED_LEVEL
rf_if_write_register(PHY_ED_LEVEL, 0xff);
break;
case PHY_INTERFACE_SNIFFER_STATE: /**< Enable Sniffer state */
rf_mode = RF_MODE_SNIFFER;
rf_channel_set(rf_channel);
rf_flags_clear(RFF_RX);
rf_receive();
rf_if_enable_irq();
break;
}
return ret_val;
}
/*
* \brief Function controls the ACK pending, channel setting and energy detection.
*
* \param extension_type Type of control
* \param data_ptr Data from NET library
*
* \return 0 Success
*/
static int8_t rf_extension(phy_extension_type_e extension_type, uint8_t *data_ptr)
{
switch (extension_type) {
/*Control MAC pending bit for Indirect data transmission*/
case PHY_EXTENSION_CTRL_PENDING_BIT:
if (*data_ptr) {
rf_if_ack_pending_ctrl(1);
} else {
rf_if_ack_pending_ctrl(0);
}
break;
/*Return frame pending status*/
case PHY_EXTENSION_READ_LAST_ACK_PENDING_STATUS:
*data_ptr = rf_if_last_acked_pending();
break;
/*Set channel*/
case PHY_EXTENSION_SET_CHANNEL:
break;
/*Read energy on the channel*/
case PHY_EXTENSION_READ_CHANNEL_ENERGY:
// End of the ED measurement is indicated by CCA_ED_DONE
while (!(rf_if_read_register(IRQ_STATUS) & CCA_ED_DONE));
// RF input power: RSSI base level + 1[db] * PHY_ED_LEVEL
*data_ptr = rf_sensitivity + rf_if_read_register(PHY_ED_LEVEL);
// Read status to clear pending flags.
rf_if_read_register(IRQ_STATUS);
// Next ED measurement is started, next PHY_EXTENSION_READ_CHANNEL_ENERGY call will return the result.
rf_if_write_register(PHY_ED_LEVEL, 0xff);
break;
/*Read status of the link*/
case PHY_EXTENSION_READ_LINK_STATUS:
break;
default:
break;
}
return 0;
}
/*
* \brief Function sets the addresses to RF address filters.
*
* \param address_type Type of address
* \param address_ptr Pointer to given address
*
* \return 0 Success
*/
static int8_t rf_address_write(phy_address_type_e address_type, uint8_t *address_ptr)
{
int8_t ret_val = 0;
switch (address_type) {
/*Set 48-bit address*/
case PHY_MAC_48BIT:
break;
/*Set 64-bit address*/
case PHY_MAC_64BIT:
rf_set_address(address_ptr);
break;
/*Set 16-bit address*/
case PHY_MAC_16BIT:
rf_set_short_adr(address_ptr);
break;
/*Set PAN Id*/
case PHY_MAC_PANID:
rf_set_pan_id(address_ptr);
break;
}
return ret_val;
}
/*
* \brief Function initialises the ACK wait time and returns the used PHY mode.
*
* \param none
*
* \return tmp Used PHY mode
*/
static void rf_init_phy_mode(void)
{
uint8_t tmp = 0;
uint8_t part = rf_if_read_part_num();
/*Read used PHY Mode*/
tmp = rf_if_read_register(TRX_CTRL_2);
/*Set ACK wait time for used data rate*/
if (part == PART_AT86RF212) {
if ((tmp & 0x1f) == 0x00) {
rf_sensitivity = -110;
rf_ack_wait_duration = 938;
tmp = BPSK_20;
} else if ((tmp & 0x1f) == 0x04) {
rf_sensitivity = -108;
rf_ack_wait_duration = 469;
tmp = BPSK_40;
} else if ((tmp & 0x1f) == 0x14) {
rf_sensitivity = -108;
rf_ack_wait_duration = 469;
tmp = BPSK_40_ALT;
} else if ((tmp & 0x1f) == 0x08) {
rf_sensitivity = -101;
rf_ack_wait_duration = 50;
tmp = OQPSK_SIN_RC_100;
} else if ((tmp & 0x1f) == 0x09) {
rf_sensitivity = -99;
rf_ack_wait_duration = 30;
tmp = OQPSK_SIN_RC_200;
} else if ((tmp & 0x1f) == 0x18) {
rf_sensitivity = -102;
rf_ack_wait_duration = 50;
tmp = OQPSK_RC_100;
} else if ((tmp & 0x1f) == 0x19) {
rf_sensitivity = -100;
rf_ack_wait_duration = 30;
tmp = OQPSK_RC_200;
} else if ((tmp & 0x1f) == 0x0c) {
rf_sensitivity = -100;
rf_ack_wait_duration = 20;
tmp = OQPSK_SIN_250;
} else if ((tmp & 0x1f) == 0x0d) {
rf_sensitivity = -98;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_500;
} else if ((tmp & 0x1f) == 0x0f) {
rf_sensitivity = -98;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_500_ALT;
} else if ((tmp & 0x1f) == 0x1c) {
rf_sensitivity = -101;
rf_ack_wait_duration = 20;
tmp = OQPSK_RC_250;
} else if ((tmp & 0x1f) == 0x1d) {
rf_sensitivity = -99;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_500;
} else if ((tmp & 0x1f) == 0x1f) {
rf_sensitivity = -99;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_500_ALT;
} else if ((tmp & 0x3f) == 0x2A) {
rf_sensitivity = -91;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_RC_400_SCR_ON;
} else if ((tmp & 0x3f) == 0x0A) {
rf_sensitivity = -91;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_RC_400_SCR_OFF;
} else if ((tmp & 0x3f) == 0x3A) {
rf_sensitivity = -97;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_400_SCR_ON;
} else if ((tmp & 0x3f) == 0x1A) {
rf_sensitivity = -97;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_400_SCR_OFF;
} else if ((tmp & 0x3f) == 0x2E) {
rf_sensitivity = -93;
rf_ack_wait_duration = 13;
tmp = OQPSK_SIN_1000_SCR_ON;
} else if ((tmp & 0x3f) == 0x0E) {
rf_sensitivity = -93;
rf_ack_wait_duration = 13;
tmp = OQPSK_SIN_1000_SCR_OFF;
} else if ((tmp & 0x3f) == 0x3E) {
rf_sensitivity = -95;
rf_ack_wait_duration = 13;
tmp = OQPSK_RC_1000_SCR_ON;
} else if ((tmp & 0x3f) == 0x1E) {
rf_sensitivity = -95;
rf_ack_wait_duration = 13;
tmp = OQPSK_RC_1000_SCR_OFF;
}
} else {
rf_sensitivity = -101;
rf_ack_wait_duration = 20;
}
/*Board design might reduces the sensitivity*/
//rf_sensitivity += RF_SENSITIVITY_CALIBRATION;
}
static uint8_t rf_scale_lqi(int8_t rssi)
{
uint8_t scaled_lqi;
/*rssi < RF sensitivity*/
if (rssi < rf_sensitivity) {
scaled_lqi = 0;
}
/*-91 dBm < rssi < -81 dBm (AT86RF233 XPro)*/
/*-90 dBm < rssi < -80 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 10)) {
scaled_lqi = 31;
}
/*-81 dBm < rssi < -71 dBm (AT86RF233 XPro)*/
/*-80 dBm < rssi < -70 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 20)) {
scaled_lqi = 207;
}
/*-71 dBm < rssi < -61 dBm (AT86RF233 XPro)*/
/*-70 dBm < rssi < -60 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 30)) {
scaled_lqi = 255;
}
/*-61 dBm < rssi < -51 dBm (AT86RF233 XPro)*/
/*-60 dBm < rssi < -50 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 40)) {
scaled_lqi = 255;
}
/*-51 dBm < rssi < -41 dBm (AT86RF233 XPro)*/
/*-50 dBm < rssi < -40 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 50)) {
scaled_lqi = 255;
}
/*-41 dBm < rssi < -31 dBm (AT86RF233 XPro)*/
/*-40 dBm < rssi < -30 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 60)) {
scaled_lqi = 255;
}
/*-31 dBm < rssi < -21 dBm (AT86RF233 XPro)*/
/*-30 dBm < rssi < -20 dBm (AT86RF212B XPro)*/
else if (rssi < (rf_sensitivity + 70)) {
scaled_lqi = 255;
}
/*rssi > RF saturation*/
else if (rssi > (rf_sensitivity + 80)) {
scaled_lqi = 111;
}
/*-21 dBm < rssi < -11 dBm (AT86RF233 XPro)*/
/*-20 dBm < rssi < -10 dBm (AT86RF212B XPro)*/
else {
scaled_lqi = 255;
}
return scaled_lqi;
}
NanostackRfPhyAtmel::NanostackRfPhyAtmel(PinName spi_mosi, PinName spi_miso,
PinName spi_sclk, PinName spi_cs, PinName spi_rst, PinName spi_slp, PinName spi_irq,
PinName i2c_sda, PinName i2c_scl)
: _mac(i2c_sda, i2c_scl), _mac_addr(), _rf(NULL), _mac_set(false),
_spi_mosi(spi_mosi), _spi_miso(spi_miso), _spi_sclk(spi_sclk),
_spi_cs(spi_cs), _spi_rst(spi_rst), _spi_slp(spi_slp), _spi_irq(spi_irq)
{
_rf = new RFBits(_spi_mosi, _spi_miso, _spi_sclk, _spi_cs, _spi_rst, _spi_slp, _spi_irq);
}
NanostackRfPhyAtmel::~NanostackRfPhyAtmel()
{
delete _rf;
}
int8_t NanostackRfPhyAtmel::rf_register()
{
if (NULL == _rf) {
return -1;
}
rf_if_lock();
if (rf != NULL) {
rf_if_unlock();
error("Multiple registrations of NanostackRfPhyAtmel not supported");
return -1;
}
// Read the mac address if it hasn't been set by a user
rf = _rf;
if (!_mac_set) {
int ret = _mac.read_eui64((void *)_mac_addr);
if (ret < 0) {
rf = NULL;
rf_if_unlock();
return -1;
}
}
int8_t radio_id = rf_device_register(_mac_addr);
if (radio_id < 0) {
rf = NULL;
}
rf_if_unlock();
return radio_id;
}
void NanostackRfPhyAtmel::rf_unregister()
{
rf_if_lock();
if (NULL == rf) {
rf_if_unlock();
return;
}
rf_device_unregister();
rf = NULL;
rf_if_unlock();
}
void NanostackRfPhyAtmel::get_mac_address(uint8_t *mac)
{
rf_if_lock();
if (NULL == rf) {
error("NanostackRfPhyAtmel Must be registered to read mac address");
rf_if_unlock();
return;
}
memcpy((void *)mac, (void *)_mac_addr, sizeof(_mac_addr));
rf_if_unlock();
}
void NanostackRfPhyAtmel::set_mac_address(uint8_t *mac)
{
rf_if_lock();
if (NULL != rf) {
error("NanostackRfPhyAtmel cannot change mac address when running");
rf_if_unlock();
return;
}
memcpy((void *)_mac_addr, (void *)mac, sizeof(_mac_addr));
_mac_set = true;
rf_if_unlock();
}
#if MBED_CONF_ATMEL_RF_PROVIDE_DEFAULT
NanostackRfPhy &NanostackRfPhy::get_default_instance()
{
static NanostackRfPhyAtmel rf_phy(ATMEL_SPI_MOSI, ATMEL_SPI_MISO, ATMEL_SPI_SCLK, ATMEL_SPI_CS,
ATMEL_SPI_RST, ATMEL_SPI_SLP, ATMEL_SPI_IRQ, ATMEL_I2C_SDA, ATMEL_I2C_SCL);
return rf_phy;
}
#endif // MBED_CONF_ATMEL_RF_PROVIDE_DEFAULT
#endif // MBED_CONF_NANOSTACK_CONFIGURATION
|
/*******************************************************************************
Copyright (c) The Taichi Authors (2016- ). All Rights Reserved.
The use of this software is governed by the LICENSE file.
*******************************************************************************/
#include <taichi/visual/texture.h>
TC_NAMESPACE_BEGIN
// Adapted from the Java reference implementation here
// http://cs.nyu.edu/~perlin/noise/
class PerlinNoiseTexture : public Texture {
protected:
public:
void initialize(const Config &config) override {
Texture::initialize(config);
}
virtual Vector4 sample(const Vector3 &coord) const override {
return Vector4(noise(coord * 256.0_f));
}
real noise(Vector3 coord) const {
return real(noise(coord.x, coord.y, coord.z));
}
static double noise(double x, double y, double z) {
int X = (int)std::floor(x) & 255, // FIND UNIT CUBE THAT
Y = (int)std::floor(y) & 255, // CONTAINS POINT.
Z = (int)std::floor(z) & 255;
x -= std::floor(x); // FIND RELATIVE X,Y,Z
y -= std::floor(y); // OF POINT IN CUBE.
z -= std::floor(z);
const int *const p = get_p();
double u = fade(x), // COMPUTE FADE CURVES
v = fade(y), // FOR EACH OF X,Y,Z.
w = fade(z);
int A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, // HASH COORDINATES OF
B = p[X + 1] + Y, BA = p[B] + Z,
BB = p[B + 1] + Z; // THE 8 CUBE CORNERS,
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), // AND ADD
grad(p[BA], x - 1, y, z)), // BLENDED
lerp(u, grad(p[AB], x, y - 1, z), // RESULTS
grad(p[BB], x - 1, y - 1, z))), // FROM 8
lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), // CORNERS
grad(p[BA + 1], x - 1, y, z - 1)), // OF CUBE
lerp(u, grad(p[AB + 1], x, y - 1, z - 1),
grad(p[BB + 1], x - 1, y - 1, z - 1))));
}
static double fade(double t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
static double lerp(double t, double a, double b) {
return a + t * (b - a);
}
static double grad(int hash, double x, double y, double z) {
int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE
double u = h < 8 ? x : y, // INTO 12 GRADIENT DIRECTIONS.
v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
static int *get_p() {
static int p[512];
static int permutation[] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10,
23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252,
219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87,
174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48,
27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25,
63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126,
255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189,
28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70,
221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98,
108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,
251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51,
145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236,
205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66,
215, 61, 156, 180};
for (int i = 0; i < 256; i++)
p[256 + i] = p[i] = permutation[i];
return p;
}
};
TC_IMPLEMENTATION(Texture, PerlinNoiseTexture, "perlin");
TC_NAMESPACE_END
|
#pragma once
// We are using an older version of DirectX headers which causes
// "warning C4005: '...' : macro redefinition"
#pragma warning(push)
#pragma warning(disable: 4005)
#include <d3d11.h>
#include <d3dx11.h>
#pragma warning(pop)
#include <cstdint>
// Used by a scene to access necessary renderer internals
class IRenderingContext
{
public:
virtual ~IRenderingContext() {};
virtual ID3D11Device* GetDevice() const = 0;
virtual ID3D11DeviceContext* GetImmediateContext() const = 0;
virtual bool CreateVertexShader(WCHAR* szFileName,
LPCSTR szEntryPoint,
LPCSTR szShaderModel,
ID3DBlob *&pVsBlob,
ID3D11VertexShader *&pVertexShader) const = 0;
virtual bool CreatePixelShader(WCHAR* szFileName,
LPCSTR szEntryPoint,
LPCSTR szShaderModel,
ID3D11PixelShader *&pPixelShader) const = 0;
virtual bool GetWindowSize(uint32_t &width,
uint32_t &height) const = 0;
virtual bool UsesMSAA() const = 0;
virtual uint32_t GetMsaaCount() const = 0;
virtual uint32_t GetMsaaQuality() const = 0;
virtual float GetFrameAnimationTime() const = 0; // In seconds
virtual bool IsValid() const
{
return GetDevice() && GetImmediateContext();
};
};
|
/*
@ 0xCCCCCCCC
*/
#include <iostream>
#include <functional>
#include "signals.h"
void foo(int i, const int& j, int&& k)
{
std::cout << "foo" << std::endl;
}
struct Foo {
static void sfoo(int i, const int& j, int&& k)
{
std::cout << "Foo::sfoo" << std::endl;
}
void foo(int i, const int& j, int&& k)
{
s = "world";
std::cout << "Foo::foo" << std::endl;
}
std::string s = "hello";
};
int main()
{
Signal<int, const int&, int&&> s;
Slot slot = s.Connect(&foo);
s.Connect(&Foo::sfoo);
auto foo = std::make_shared<Foo>();
auto pf = foo.get();
using namespace std::placeholders;
s.Connect(std::bind(&Foo::foo, pf, _1, _2, _3), foo);
s.Emit(1, 3, 5);
slot.Disconnect();
s.Emit(5, 3, 1);
foo.reset();
s.Emit(5, 3, 1);
s.DisconnectAll();
s.Emit(3, 2, 1);
return 0;
}
|
// Copyright (c) OpenMMLab. All rights reserved.
#include "mmdeploy/core/utils/device_utils.h"
#include "mmdeploy/core/utils/formatter.h"
#include "mmdeploy/preprocess/transform/pad.h"
#include "ppl/cv/cuda/copymakeborder.h"
using namespace std;
using namespace ppl::cv::cuda;
namespace mmdeploy {
namespace cuda {
class PadImpl : public ::mmdeploy::PadImpl {
public:
explicit PadImpl(const Value& args) : ::mmdeploy::PadImpl(args) {
#if PPLCV_VERSION_MAJOR >= 0 && PPLCV_VERSION_MINOR >= 6 && PPLCV_VERSION_PATCH >= 2
map<string, ppl::cv::BorderType> border_map{{"constant", ppl::cv::BORDER_CONSTANT},
{"edge", ppl::cv::BORDER_REPLICATE},
{"reflect", ppl::cv::BORDER_REFLECT_101},
{ "symmetric",
ppl::cv::BORDER_REFLECT }};
#else
map<string, ppl::cv::BorderType> border_map{{"constant", ppl::cv::BORDER_TYPE_CONSTANT},
{"edge", ppl::cv::BORDER_TYPE_REPLICATE},
{"reflect", ppl::cv::BORDER_TYPE_REFLECT_101},
{"symmetric", ppl::cv::BORDER_TYPE_REFLECT}};
#endif
if (border_map.find(arg_.padding_mode) == border_map.end()) {
MMDEPLOY_ERROR("unsupported padding_mode '{}'", arg_.padding_mode);
throw_exception(eNotSupported);
}
padding_mode_ = border_map[arg_.padding_mode];
}
protected:
Result<Tensor> PadImage(const Tensor& img, const array<int, 4>& padding) override {
OUTCOME_TRY(auto src_tensor, MakeAvailableOnDevice(img, device_, stream_));
SyncOnScopeExit sync(stream_, src_tensor.buffer() != img.buffer(), src_tensor);
auto desc = src_tensor.desc();
int height = desc.shape[1];
int width = desc.shape[2];
int c = desc.shape[3];
auto dst_height = height + padding[1] + padding[3];
auto dst_width = width + padding[0] + padding[2];
TensorShape dst_shape{1, dst_height, dst_width, c};
TensorDesc dst_desc{device_, desc.data_type, dst_shape, ""};
Tensor dst_tensor(dst_desc);
ppl::common::RetCode ret = 0;
cudaStream_t stream = ::mmdeploy::GetNative<cudaStream_t>(stream_);
if (desc.data_type == DataType::kFLOAT) {
auto src_buffer = src_tensor.data<float>();
auto dst_buffer = dst_tensor.data<float>();
if (3 == c) {
ret = CopyMakeBorder<float, 3>(stream, height, width, width * c, src_buffer, dst_width * c,
dst_buffer, padding[1], padding[3], padding[0], padding[2],
padding_mode_, arg_.pad_val);
} else if (1 == c) {
ret = CopyMakeBorder<float, 1>(stream, height, width, width * c, src_buffer, dst_width * c,
dst_buffer, padding[1], padding[3], padding[0], padding[2],
padding_mode_, arg_.pad_val);
} else {
MMDEPLOY_ERROR("unsupported channels {}", c);
assert(0);
return Status(eNotSupported);
}
} else if (desc.data_type == DataType::kINT8) {
auto src_buffer = src_tensor.data<uint8_t>();
auto dst_buffer = dst_tensor.data<uint8_t>();
if (3 == c) {
ret = CopyMakeBorder<ppl::cv::uchar, 3>(
stream, height, width, width * c, src_buffer, dst_width * c, dst_buffer, padding[1],
padding[3], padding[0], padding[2], padding_mode_, (ppl::cv::uchar)arg_.pad_val);
} else if (1 == c) {
ret = CopyMakeBorder<ppl::cv::uchar, 1>(
stream, height, width, width * c, src_buffer, dst_width * c, dst_buffer, padding[1],
padding[3], padding[0], padding[2], padding_mode_, (ppl::cv::uchar)arg_.pad_val);
} else {
MMDEPLOY_ERROR("unsupported channels {}", c);
assert(0);
return Status(eNotSupported);
}
} else {
MMDEPLOY_ERROR("unsupported data type {}", desc.data_type);
assert(0);
return Status(eNotSupported);
}
if (ret != 0) {
MMDEPLOY_ERROR("unexpected exception happened");
assert(0);
return Status(eNotSupported);
}
return dst_tensor;
}
private:
ppl::cv::BorderType padding_mode_;
};
class PadCreator : public Creator<::mmdeploy::PadImpl> {
public:
const char* GetName() const override { return "cuda"; }
int GetVersion() const override { return 1; }
ReturnType Create(const Value& args) override { return make_unique<PadImpl>(args); }
};
} // namespace cuda
} // namespace mmdeploy
using ::mmdeploy::PadImpl;
using mmdeploy::cuda::PadCreator;
REGISTER_MODULE(PadImpl, PadCreator);
|
// Copyright Vladimir Prus 2002-2004.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ERRORS_VP_2003_01_02
#define BOOST_ERRORS_VP_2003_01_02
#include <boost/program_options/config.hpp>
#include <string>
#include <stdexcept>
#include <vector>
#if defined(BOOST_MSVC)
# pragma warning (push)
# pragma warning (disable:4275) // non dll-interface class 'std::logic_error' used as base for dll-interface class 'boost::program_options::error'
# pragma warning (disable:4251) // class 'std::vector<_Ty>' needs to have dll-interface to be used by clients of class 'boost::program_options::ambiguous_option'
#endif
namespace boost { namespace program_options {
/** Base class for all errors in the library. */
class BOOST_PROGRAM_OPTIONS_DECL error : public std::logic_error {
public:
error(const std::string& xwhat) : std::logic_error(xwhat) {}
};
class BOOST_PROGRAM_OPTIONS_DECL invalid_syntax : public error {
public:
enum kind_t {
long_not_allowed = 30,
long_adjacent_not_allowed,
short_adjacent_not_allowed,
empty_adjacent_parameter,
missing_parameter,
extra_parameter,
unrecognized_line
};
invalid_syntax(const std::string& tokens, kind_t kind);
// gcc says that throw specification on dtor is loosened
// without this line
~invalid_syntax() throw() {}
kind_t kind() const;
const std::string& tokens() const;
protected:
/** Used to convert kind_t to a related error text */
static std::string error_message(kind_t kind);
private:
// TODO: copy ctor might throw
std::string m_tokens;
kind_t m_kind;
};
/** Class thrown when option name is not recognized. */
class BOOST_PROGRAM_OPTIONS_DECL unknown_option : public error {
public:
unknown_option(const std::string& name)
: error(std::string("unknown option ").append(name)),
m_option_name(name)
{}
// gcc says that throw specification on dtor is loosened
// without this line
~unknown_option() throw() {}
const std::string& get_option_name() const throw();
private:
std::string m_option_name;
};
/** Class thrown when there's ambiguity amoung several possible options. */
class BOOST_PROGRAM_OPTIONS_DECL ambiguous_option : public error {
public:
ambiguous_option(const std::string& name,
const std::vector<std::string>& xalternatives)
: error(std::string("ambiguous option ").append(name))
, m_alternatives(xalternatives)
, m_option_name(name)
{}
~ambiguous_option() throw() {}
const std::string& get_option_name() const throw();
const std::vector<std::string>& alternatives() const throw();
private:
// TODO: copy ctor might throw
std::vector<std::string> m_alternatives;
std::string m_option_name;
};
/** Class thrown when there are several option values, but
user called a method which cannot return them all. */
class BOOST_PROGRAM_OPTIONS_DECL multiple_values : public error {
public:
multiple_values()
: error("multiple values")
, m_option_name() {}
~multiple_values() throw() {}
void set_option_name(const std::string& option);
const std::string& get_option_name() const throw();
private:
std::string m_option_name; // The name of the option which
// caused the exception.
};
/** Class thrown when there are several occurrences of an
option, but user called a method which cannot return
them all. */
class BOOST_PROGRAM_OPTIONS_DECL multiple_occurrences : public error {
public:
multiple_occurrences()
: error("multiple occurrences")
, m_option_name() {}
~multiple_occurrences() throw() {}
void set_option_name(const std::string& option);
const std::string& get_option_name() const throw();
private:
std::string m_option_name; // The name of the option which
// caused the exception.
};
/** Class thrown when value of option is incorrect. */
class BOOST_PROGRAM_OPTIONS_DECL validation_error : public error {
public:
enum kind_t {
multiple_values_not_allowed = 30,
at_least_one_value_required,
invalid_bool_value,
invalid_option_value,
invalid_option
};
validation_error(kind_t kind,
const std::string& option_value = "",
const std::string& option_name = "");
~validation_error() throw() {}
void set_option_name(const std::string& option);
const std::string& get_option_name() const throw();
const char* what() const throw();
protected:
/** Used to convert kind_t to a related error text */
static std::string error_message(kind_t kind);
private:
kind_t m_kind;
std::string m_option_name; // The name of the option which
// caused the exception.
std::string m_option_value; // Optional: value of the option m_options_name
mutable std::string m_message; // For on-demand formatting in 'what'
};
/** Class thrown if there is an invalid option value givenn */
class BOOST_PROGRAM_OPTIONS_DECL invalid_option_value
: public validation_error
{
public:
invalid_option_value(const std::string& value);
#ifndef BOOST_NO_STD_WSTRING
invalid_option_value(const std::wstring& value);
#endif
};
/** Class thrown when there are too many positional options.
This is a programming error.
*/
class BOOST_PROGRAM_OPTIONS_DECL too_many_positional_options_error : public error {
public:
too_many_positional_options_error()
: error("too many positional options")
{}
};
/** Class thrown when there are syntax errors in given command line */
class BOOST_PROGRAM_OPTIONS_DECL invalid_command_line_syntax : public invalid_syntax {
public:
invalid_command_line_syntax(const std::string& tokens, kind_t kind);
};
/** Class thrown when there are programming error related to style */
class BOOST_PROGRAM_OPTIONS_DECL invalid_command_line_style : public error {
public:
invalid_command_line_style(const std::string& msg)
: error(msg)
{}
};
/** Class thrown if config file can not be read */
class BOOST_PROGRAM_OPTIONS_DECL reading_file : public error {
public:
reading_file(const char* filename)
: error(std::string("can not read file ").append(filename))
{}
};
/** Class thrown when a required/mandatory option is missing */
class BOOST_PROGRAM_OPTIONS_DECL required_option : public error {
public:
required_option(const std::string& name)
: error(std::string("missing required option ").append(name))
, m_option_name(name)
{}
~required_option() throw() {}
const std::string& get_option_name() const throw();
private:
std::string m_option_name; // The name of the option which
// caused the exception.
};
}}
#if defined(BOOST_MSVC)
# pragma warning (pop)
#endif
#endif
|
namespace mlpack {
namespace hpt {
/*! @page hpt Hyper-Parameter Tuning
@section hptintro Introduction
\b mlpack implements a generic hyperparameter tuner that is able to tune both
continuous and discrete parameters of various different algorithms. This is an
important task---the performance of many machine learning algorithms can be
highly dependent on the hyperparameters that are chosen for that algorithm.
(One example: the choice of \f$k\f$ for a \f$k\f$-nearest-neighbors classifier.)
This hyper-parameter tuner is built on the same general concept as the
cross-validation classes (see the @ref cv "cross-validation tutorial"): given
some machine learning algorithm, some data, some performance measure, and a set
of hyperparameters, attempt to find the hyperparameter set that best optimizes
the performance measure on the given data with the given algorithm.
\b mlpack's implementation of hyperparameter tuning is flexible, and is built in
a way that supports many algorithms and many optimizers. At the time of this
writing, complex hyperparameter optimization techniques are not available, but
the hyperparameter tuner does support these, should they be implemented in the
future.
In this tutorial we will see the usage examples of the hyper-parameter tuning
module, and also more details about the \c HyperParameterTuner class.
@section hptbasic Basic Usage
The interface of the hyper-parameter tuning module is quite similar to the
interface of the @ref cv "cross-validation module". To construct a \c
HyperParameterTuner object you need to specify as template parameters what
machine learning algorithm, cross-validation strategy, performance measure, and
optimization strategy (\ref optimization::GridSearch "GridSearch" will be used by
default) you are going to use. Then, you must pass the same arguments as for
the cross-validation classes: the data and labels (or responses) to use are
given to the constructor, and the possible hyperparameter values are given to
the \c HyperParameterTuner::Optimize() method, which returns the best
algorithm configuration as a \c std::tuple<>.
Let's see some examples.
Suppose we have the following data to train and validate on.
@code
// 100-point 5-dimensional random dataset.
arma::mat data = arma::randu<arma::mat>(5, 100);
// Noisy responses retrieved by a random linear transformation of data.
arma::rowvec responses = arma::randu<arma::rowvec>(5) * data +
0.1 * arma::randn<arma::rowvec>(100);
@endcode
Given the dataset above, we can use the following code to try to find a good \c
lambda value for \ref regression::LinearRegression "LinearRegression". Here we
use \ref cv::SimpleCV "SimpleCV" instead of k-fold cross-validation to save
computation time.
@code
// Using 80% of data for training and remaining 20% for assessing MSE.
double validationSize = 0.2;
HyperParameterTuner<LinearRegression, MSE, SimpleCV> hpt(validationSize,
data, responses);
// Finding a good value for lambda from the discrete set of values 0.0, 0.001,
// 0.01, 0.1, and 1.0.
arma::vec lambdas{0.0, 0.001, 0.01, 0.1, 1.0};
double bestLambda;
std::tie(bestLambda) = hpt.Optimize(lambdas);
@endcode
In this example we have used \ref optimization::GridSearch "GridSearch" (the
default optimizer) to find a good value for the \c lambda hyper-parameter. For
that we have specified what values should be tried.
@section hptfixed Fixed Arguments
When some hyper-parameters should not be optimized, you can specify values
for them with the \c Fixed() method as in the following example of trying to
find good \c lambda1 and \c lambda2 values for \ref regression::LARS "LARS"
(least-angle regression).
@code
HyperParameterTuner<LARS, MSE, SimpleCV> hpt2(validationSize, data,
responses);
// The hyper-parameter tuner should not try to change the transposeData or
// useCholesky parameters.
bool transposeData = true;
bool useCholesky = false;
// We wish only to search for the best lambda1 and lambda2 values.
arma::vec lambda1Set{0.0, 0.001, 0.01, 0.1, 1.0};
arma::vec lambda2Set{0.0, 0.002, 0.02, 0.2, 2.0};
double bestLambda1, bestLambda2;
std::tie(bestLambda1, bestLambda2) = hpt2.Optimize(Fixed(transposeData),
Fixed(useCholesky), lambda1Set, lambda2Set);
@endcode
Note that for the call to \c hpt2.Optimize(), we have used the same order of
arguments as they appear in the corresponding \ref regression::LARS "LARS"
constructor:
@code
LARS(const arma::mat& data,
const arma::rowvec& responses,
const bool transposeData = true,
const bool useCholesky = false,
const double lambda1 = 0.0,
const double lambda2 = 0.0,
const double tolerance = 1e-16);
@endcode
@section hptgradient Gradient-Based Optimization
In some cases we may wish to optimize a hyperparameter over the space of all
possible real values, instead of providing a grid in which to search.
Alternately, we may know approximately optimal values from a grid search for
real-valued hyperparameters, but wish to further tune those values.
In this case, we can use a gradient-based optimizer for hyperparameter search.
In the following example, we try to optimize the \c lambda1 and \c lambda2
hyper-parameters for \ref regression::LARS "LARS" with the
\ref optimization::GradientDescent "GradientDescent" optimizer.
@code
HyperParameterTuner<LARS, MSE, SimpleCV, GradientDescent> hpt3(validationSize,
data, responses);
// GradientDescent can be adjusted in the following way.
hpt3.Optimizer().StepSize() = 0.1;
hpt3.Optimizer().Tolerance() = 1e-15;
// We can set up values used for calculating gradients.
hpt3.RelativeDelta() = 0.01;
hpt3.MinDelta() = 1e-10;
double initialLambda1 = 0.001;
double initialLambda2 = 0.002;
double bestGDLambda1, bestGDLambda2;
std::tie(bestGDLambda1, bestGDLambda2) = hpt3.Optimize(Fixed(transposeData),
Fixed(useCholesky), initialLambda1, initialLambda2);
@endcode
@section hpt_class The HyperParameterTuner class
The \c HyperParameterTuner class is very similar to the
\ref cv::KFoldCV "KFoldCV" and \ref cv::SimpleCV "SimpleCV" classes (see the
@ref "cross-validation tutorial" for more information on those two classes), but
there are a few important differences.
First, the \c HyperParameterTuner accepts five different hyperparameters; only
the first three of these are required:
- \c MLAlgorithm This is the algorithm to be used.
- \c Metric This is the performance measure to be used; see
@ref cvbasic_metrics for more information.
- \c CVType This is the type of cross-validation to be used for evaluating the
performance measure; this should be \ref cv::KFoldCV "KFoldCV" or
\ref cv::SimpleCV "SimpleCV".
- \c OptimizerType This is the type of optimizer to use; it can be
\c GridSearch or a gradient-based optimizer.
- \c MatType This is the type of data matrix to use. The default is
\c arma::mat. This only needs to be changed if you are specifically
using sparse data, or if you want to use a numeric type other than
\c double.
The last two template parameters are automatically inferred by the
\c HyperParameterTuner and should not need to be manually specified, unless an
unconventional data type like \c arma::fmat is being used for data points.
Typically, \ref cv::SimpleCV "SimpleCV" is a good choice for \c CVType because
it takes so much less time to compute than full \ref cv::KFoldCV "KFoldCV";
however, the disadvantage is that \ref cv::SimpleCV "SimpleCV" might give a
somewhat more noisy estimate of the performance measure on unseen test data.
The constructor for the \c HyperParameterTuner is called with exactly the same
arguments as the corresponding \c CVType that has been chosen. For more
information on that, please see the
@ref cvbasic_api "cross-validation constructor tutorial". As an example, if we
are using \ref cv::SimpleCV "SimpleCV" and wish to hold out 20\% of the dataset
as a validation set, we might construct a \c HyperParameterTuner like this:
@code
// We will use LinearRegression as the MLAlgorithm, and MSE as the performance
// measure. Our dataset is 'dataset' and the responses are 'responses'.
HyperParameterTuner<LinearRegression, MSE, SimpleCV> hpt(0.2, dataset,
responses);
@endcode
Next, we must set up the hyperparameters to be optimized. If we are doing a
grid search with the \ref optimization::GridSearch "GridSearch" optimizer (the
default), then we only need to pass a `std::vector` (for non-numeric
hyperparameters) or an `arma::vec` (for numeric hyperparameters) containing all
of the possible choices that we wish to search over.
For instance, a set of numeric values might be chosen like this, for the
\c lambda parameter (of type \c double):
@code
arma::vec lambdaSet = arma::vec("0.0 0.1 0.5 1.0");
@endcode
Similarly, a set of non-numeric values might be chosen like this, for the
\c intercept parameter:
@code
std::vector<bool> interceptSet = { false, true };
@endcode
Once all of these are set up, the \c HyperParameterTuner::Optimize() method may
be called to find the best set of hyperparameters:
@code
bool intercept;
double lambda;
std::tie(lambda, intercept) = hpt.Optimize(lambdaSet, interceptSet);
@endcode
Alternately, the \c Fixed() method (detailed in the @ref hptfixed
"Fixed arguments" section) can be used to fix the values of some parameters.
For continuous optimizers like
\ref optimization::GradientDescent "GradientDescent", a range does not need to
be specified but instead only a single value. See the
\ref hptgradient "Gradient-Based Optimization" section for more details.
@section hptfurther Further documentation
For more information on the \c HyperParameterTuner class, see the
mlpack::hpt::HyperParameterTuner class documentation and the
@ref cv "cross-validation tutorial".
*/
} // namespace hpt
} // namespace mlpack
|
/* Copyright (c) 2008-2012, Avian Contributors
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.
There is NO WARRANTY for this software. See license.txt for
details. */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "jni.h"
#include "jni-util.h"
#ifdef PLATFORM_WINDOWS
# include <windows.h>
# include <io.h>
# include <direct.h>
# include <share.h>
# define ACCESS _waccess
# define CLOSE _close
# define READ _read
# define WRITE _write
# define STAT _wstat
# define STRUCT_STAT struct _stat
# define MKDIR(path, mode) _wmkdir(path)
# define CHMOD(path, mode) _wchmod(path, mode)
# define UNLINK _wunlink
# define RENAME _wrename
# define OPEN_MASK O_BINARY
# define CHECK_X_OK R_OK
# ifdef _MSC_VER
# define S_ISREG(x) ((x) & _S_IFREG)
# define S_ISDIR(x) ((x) & _S_IFDIR)
# define S_IRUSR _S_IREAD
# define S_IWUSR _S_IWRITE
# define W_OK 2
# define R_OK 4
# else
# define OPEN _wopen
# endif
# define GET_CHARS GetStringChars
# define RELEASE_CHARS(path, chars) ReleaseStringChars(path, reinterpret_cast<const jchar*>(chars))
typedef wchar_t char_t;
#if defined(WINAPI_FAMILY)
#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#include "avian-interop.h"
#define SKIP_OPERATOR_NEW
#endif
#endif
#else // not PLATFORM_WINDOWS
# include <dirent.h>
# include <unistd.h>
# include "sys/mman.h"
# define ACCESS access
# define OPEN open
# define CLOSE close
# define READ read
# define WRITE write
# define STAT stat
# define STRUCT_STAT struct stat
# define MKDIR mkdir
# define CHMOD chmod
# define UNLINK unlink
# define RENAME rename
# define OPEN_MASK 0
# define CHECK_X_OK X_OK
# define GET_CHARS GetStringUTFChars
# define RELEASE_CHARS ReleaseStringUTFChars
typedef char char_t;
#endif // not PLATFORM_WINDOWS
#ifndef WINAPI_FAMILY
# ifndef WINAPI_PARTITION_DESKTOP
# define WINAPI_PARTITION_DESKTOP 1
# endif
# ifndef WINAPI_FAMILY_PARTITION
# define WINAPI_FAMILY_PARTITION(x) (x)
# endif
#endif // WINAPI_FAMILY
#if !defined(SKIP_OPERATOR_NEW)
inline void* operator new(size_t, void* p) throw() { return p; }
#endif
typedef const char_t* string_t;
namespace {
#ifdef _MSC_VER
inline int
OPEN(string_t path, int mask, int mode)
{
int fd;
if (_wsopen_s(&fd, path, mask, _SH_DENYNO, mode) == 0) {
return fd;
} else {
return -1;
}
}
#endif
inline bool
exists(string_t path)
{
STRUCT_STAT s;
return STAT(path, &s) == 0;
}
inline int
doOpen(JNIEnv* e, string_t path, int mask)
{
int fd = OPEN(path, mask | OPEN_MASK, S_IRUSR | S_IWUSR);
if (fd == -1) {
if (errno == ENOENT) {
throwNewErrno(e, "java/io/FileNotFoundException");
} else {
throwNewErrno(e, "java/io/IOException");
}
}
return fd;
}
inline void
doClose(JNIEnv* e, jint fd)
{
int r = CLOSE(fd);
if (r == -1) {
throwNewErrno(e, "java/io/IOException");
}
}
inline int
doRead(JNIEnv* e, jint fd, jbyte* data, jint length)
{
int r = READ(fd, data, length);
if (r > 0) {
return r;
} else if (r == 0) {
return -1;
} else {
throwNewErrno(e, "java/io/IOException");
return 0;
}
}
inline void
doWrite(JNIEnv* e, jint fd, const jbyte* data, jint length)
{
int r = WRITE(fd, data, length);
if (r != length) {
throwNewErrno(e, "java/io/IOException");
}
}
#ifdef PLATFORM_WINDOWS
class Directory {
public:
Directory(): handle(0), findNext(false) { }
virtual string_t next() {
if (handle and handle != INVALID_HANDLE_VALUE) {
if (findNext) {
if (FindNextFileW(handle, &data)) {
return data.cFileName;
}
} else {
findNext = true;
return data.cFileName;
}
}
return 0;
}
virtual void dispose() {
if (handle and handle != INVALID_HANDLE_VALUE) {
FindClose(handle);
}
free(this);
}
HANDLE handle;
WIN32_FIND_DATAW data;
bool findNext;
};
#else // not PLATFORM_WINDOWS
#endif // not PLATFORM_WINDOWS
} // namespace
inline string_t getChars(JNIEnv* e, jstring path) {
return reinterpret_cast<string_t>(e->GET_CHARS(path, 0));
}
inline void releaseChars(JNIEnv* e, jstring path, string_t chars) {
e->RELEASE_CHARS(path, chars);
}
extern "C" JNIEXPORT jstring JNICALL
Java_java_io_File_toCanonicalPath(JNIEnv* /*e*/, jclass, jstring path)
{
// todo
return path;
}
extern "C" JNIEXPORT jstring JNICALL
Java_java_io_File_toAbsolutePath(JNIEnv* e UNUSED, jclass, jstring path)
{
#ifdef PLATFORM_WINDOWS
# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
string_t chars = getChars(e, path);
if (chars) {
const unsigned BufferSize = MAX_PATH;
char_t buffer[BufferSize];
DWORD success = GetFullPathNameW(chars, BufferSize, buffer, 0);
releaseChars(e, path, chars);
if (success) {
return e->NewString
(reinterpret_cast<const jchar*>(buffer), wcslen(buffer));
}
}
return path;
# else
string_t chars = getChars(e, path);
if(chars) {
std::wstring partialPath = chars;
releaseChars(e, path, chars);
std::wstring fullPath = AvianInterop::GetFullPath(partialPath);
return e->NewString
(reinterpret_cast<const jchar*>(fullPath.c_str()), fullPath.length());
}
return path;
# endif
#else
jstring result = path;
string_t chars = getChars(e, path);
if (chars) {
if (chars[0] != '/') {
char* cwd = getcwd(NULL, 0);
if (cwd) {
unsigned size = strlen(cwd) + strlen(chars) + 2;
RUNTIME_ARRAY(char, buffer, size);
snprintf(RUNTIME_ARRAY_BODY(buffer), size, "%s/%s", cwd, chars);
result = e->NewStringUTF(RUNTIME_ARRAY_BODY(buffer));
free(cwd);
}
}
releaseChars(e, path, chars);
}
return result;
#endif
}
extern "C" JNIEXPORT jlong JNICALL
Java_java_io_File_length(JNIEnv* e, jclass, jstring path)
{
#ifdef PLATFORM_WINDOWS
// Option: without opening file
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946(v=vs.85).aspx
string_t chars = getChars(e, path);
if(chars) {
LARGE_INTEGER fileSize;
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
HANDLE file = CreateFileW
(chars, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
#else
HANDLE file = CreateFile2
(chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
#endif
releaseChars(e, path, chars);
if (file == INVALID_HANDLE_VALUE)
return 0;
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
if(!GetFileSizeEx(file, &fileSize))
{
CloseHandle(file);
return 0;
}
#else
FILE_STANDARD_INFO info;
if(!GetFileInformationByHandleEx(file, FileStandardInfo, &info, sizeof(info)))
{
CloseHandle(file);
return 0;
}
fileSize = info.EndOfFile;
#endif
CloseHandle(file);
return static_cast<jlong>(fileSize.QuadPart);
}
#else
string_t chars = getChars(e, path);
if (chars) {
STRUCT_STAT s;
int r = STAT(chars, &s);
releaseChars(e, path, chars);
if (r == 0) {
return s.st_size;
}
}
#endif
return 0;
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_File_mkdir(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
if (not exists(chars)) {
int r = ::MKDIR(chars, 0700);
if (r != 0) {
throwNewErrno(e, "java/io/IOException");
}
}
releaseChars(e, path, chars);
}
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_createNewFile(JNIEnv* e, jclass, jstring path)
{
bool result = false;
string_t chars = getChars(e, path);
if (chars) {
if (not exists(chars)) {
int fd = OPEN(chars, O_CREAT | O_WRONLY | O_EXCL, 0600);
if (fd == -1) {
if (errno != EEXIST) {
throwNewErrno(e, "java/io/IOException");
}
} else {
result = true;
doClose(e, fd);
}
}
releaseChars(e, path, chars);
}
return result;
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_File_delete(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
int r = UNLINK(chars);
if (r != 0) {
throwNewErrno(e, "java/io/IOException");
}
releaseChars(e, path, chars);
}
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_canRead(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
int r = ACCESS(chars, R_OK);
releaseChars(e, path, chars);
return (r == 0);
}
return false;
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_canWrite(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
int r = ACCESS(chars, W_OK);
releaseChars(e, path, chars);
return (r == 0);
}
return false;
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_canExecute(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
int r = ACCESS(chars, CHECK_X_OK);
releaseChars(e, path, chars);
return (r == 0);
}
return false;
}
#ifndef PLATFORM_WINDOWS
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_setExecutable(JNIEnv* e, jclass, jstring path, jboolean executable, jboolean ownerOnly)
{
string_t chars = getChars(e, path);
if(chars) {
jboolean v;
int mask;
if(ownerOnly) {
mask = S_IXUSR;
} else {
mask = S_IXUSR | S_IXGRP | S_IXOTH;
}
STRUCT_STAT s;
int r = STAT(chars, &s);
if(r == 0) {
int mode = s.st_mode;
if(executable) {
mode |= mask;
} else {
mode &= ~mask;
}
if(CHMOD(chars, mode) != 0) {
v = false;
} else {
v = true;
}
} else {
v = false;
}
releaseChars(e, path, chars);
return v;
}
return false;
}
#else // ifndef PLATFORM_WINDOWS
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_setExecutable(JNIEnv*, jclass, jstring, jboolean executable, jboolean)
{
return executable;
}
#endif
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_rename(JNIEnv* e, jclass, jstring old, jstring new_)
{
string_t oldChars = getChars(e, old);
string_t newChars = getChars(e, new_);
if (oldChars) {
bool v;
if (newChars) {
v = RENAME(oldChars, newChars) == 0;
releaseChars(e, new_, newChars);
} else {
v = false;
}
releaseChars(e, old, oldChars);
return v;
} else {
return false;
}
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_isDirectory(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
STRUCT_STAT s;
int r = STAT(chars, &s);
bool v = (r == 0 and S_ISDIR(s.st_mode));
releaseChars(e, path, chars);
return v;
} else {
return false;
}
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_isFile(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
STRUCT_STAT s;
int r = STAT(chars, &s);
bool v = (r == 0 and S_ISREG(s.st_mode));
releaseChars(e, path, chars);
return v;
} else {
return false;
}
}
extern "C" JNIEXPORT jboolean JNICALL
Java_java_io_File_exists(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
bool v = exists(chars);
releaseChars(e, path, chars);
return v;
} else {
return false;
}
}
#ifdef PLATFORM_WINDOWS
extern "C" JNIEXPORT jlong JNICALL
Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
unsigned length = wcslen(chars);
unsigned size = length * sizeof(char_t);
RUNTIME_ARRAY(char_t, buffer, length + 3);
memcpy(RUNTIME_ARRAY_BODY(buffer), chars, size);
memcpy(RUNTIME_ARRAY_BODY(buffer) + length, L"\\*", 6);
releaseChars(e, path, chars);
Directory* d = new (malloc(sizeof(Directory))) Directory;
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
d->handle = FindFirstFileW(RUNTIME_ARRAY_BODY(buffer), &(d->data));
#else
d->handle = FindFirstFileExW(RUNTIME_ARRAY_BODY(buffer), FindExInfoStandard, &(d->data), FindExSearchNameMatch, NULL, 0);
#endif
if (d->handle == INVALID_HANDLE_VALUE) {
d->dispose();
d = 0;
}
return reinterpret_cast<jlong>(d);
} else {
return 0;
}
}
extern "C" JNIEXPORT jlong JNICALL
Java_java_io_File_lastModified(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
#ifdef PLATFORM_WINDOWS
// Option: without opening file
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946(v=vs.85).aspx
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
HANDLE hFile = CreateFileW
(chars, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
#else
HANDLE hFile = CreateFile2
(chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
#endif
releaseChars(e, path, chars);
if (hFile == INVALID_HANDLE_VALUE)
return 0;
LARGE_INTEGER fileDate, filetimeToUnixEpochAdjustment;
filetimeToUnixEpochAdjustment.QuadPart = 11644473600000L * 10000L;
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
FILETIME fileLastWriteTime;
if (!GetFileTime(hFile, 0, 0, &fileLastWriteTime))
{
CloseHandle(hFile);
return 0;
}
fileDate.HighPart = fileLastWriteTime.dwHighDateTime;
fileDate.LowPart = fileLastWriteTime.dwLowDateTime;
#else
FILE_BASIC_INFO fileInfo;
if (!GetFileInformationByHandleEx(hFile, FileBasicInfo, &fileInfo, sizeof(fileInfo)))
{
CloseHandle(hFile);
return 0;
}
fileDate = fileInfo.ChangeTime;
#endif
CloseHandle(hFile);
fileDate.QuadPart -= filetimeToUnixEpochAdjustment.QuadPart;
return fileDate.QuadPart / 10000000L;
#else
struct stat fileStat;
if (stat(chars, &fileStat) == -1) {
releaseChars(e, path, chars);
return 0;
}
return (static_cast<jlong>(st.st_mtim.tv_sec) * 1000) +
(static_cast<jlong>(st.st_mtim.tv_nsec) / (1000*1000));
#endif
}
return 0;
}
extern "C" JNIEXPORT jstring JNICALL
Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle)
{
Directory* d = reinterpret_cast<Directory*>(handle);
while (true) {
string_t s = d->next();
if (s) {
if (wcscmp(s, L".") == 0 || wcscmp(s, L"..") == 0) {
// skip . or .. and try again
} else {
return e->NewString(reinterpret_cast<const jchar*>(s), wcslen(s));
}
} else {
return 0;
}
}
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_File_closeDir(JNIEnv* , jclass, jlong handle)
{
reinterpret_cast<Directory*>(handle)->dispose();
}
#else // not PLATFORM_WINDOWS
extern "C" JNIEXPORT jlong JNICALL
Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
jlong handle = reinterpret_cast<jlong>(opendir(chars));
releaseChars(e, path, chars);
return handle;
} else {
return 0;
}
}
extern "C" JNIEXPORT jstring JNICALL
Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle)
{
struct dirent * directoryEntry;
if (handle!=0) {
while (true) {
directoryEntry = readdir(reinterpret_cast<DIR*>(handle));
if (directoryEntry == NULL) {
return NULL;
} else if (strcmp(directoryEntry->d_name, ".") == 0
|| strcmp(directoryEntry->d_name, "..") == 0)
{
// skip . or .. and try again
} else {
return e->NewStringUTF(directoryEntry->d_name);
}
}
}
return NULL;
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_File_closeDir(JNIEnv* , jclass, jlong handle)
{
if (handle!=0) {
closedir(reinterpret_cast<DIR*>(handle));
}
}
#endif // not PLATFORM_WINDOWS
extern "C" JNIEXPORT jint JNICALL
Java_java_io_FileInputStream_open(JNIEnv* e, jclass, jstring path)
{
string_t chars = getChars(e, path);
if (chars) {
int fd = doOpen(e, chars, O_RDONLY);
releaseChars(e, path, chars);
return fd;
} else {
return -1;
}
}
extern "C" JNIEXPORT jint JNICALL
Java_java_io_FileInputStream_read__I(JNIEnv* e, jclass, jint fd)
{
jbyte data;
int r = doRead(e, fd, &data, 1);
if (r <= 0) {
return -1;
} else {
return data & 0xff;
}
}
extern "C" JNIEXPORT jint JNICALL
Java_java_io_FileInputStream_read__I_3BII
(JNIEnv* e, jclass, jint fd, jbyteArray b, jint offset, jint length)
{
jbyte* data = static_cast<jbyte*>(malloc(length));
if (data == 0) {
throwNew(e, "java/lang/OutOfMemoryError", 0);
return 0;
}
int r = doRead(e, fd, data, length);
e->SetByteArrayRegion(b, offset, length, data);
free(data);
return r;
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_FileInputStream_close(JNIEnv* e, jclass, jint fd)
{
doClose(e, fd);
}
extern "C" JNIEXPORT jint JNICALL
Java_java_io_FileOutputStream_open(JNIEnv* e, jclass, jstring path, jboolean append)
{
string_t chars = getChars(e, path);
if (chars) {
int fd = doOpen(e, chars, append
? (O_WRONLY | O_CREAT | O_APPEND)
: (O_WRONLY | O_CREAT | O_TRUNC));
releaseChars(e, path, chars);
return fd;
} else {
return -1;
}
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_write__II(JNIEnv* e, jclass, jint fd, jint c)
{
jbyte data = c;
doWrite(e, fd, &data, 1);
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_write__I_3BII
(JNIEnv* e, jclass, jint fd, jbyteArray b, jint offset, jint length)
{
jbyte* data = static_cast<jbyte*>(malloc(length));
if (data == 0) {
throwNew(e, "java/lang/OutOfMemoryError", 0);
return;
}
e->GetByteArrayRegion(b, offset, length, data);
if (not e->ExceptionCheck()) {
doWrite(e, fd, data, length);
}
free(data);
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_close(JNIEnv* e, jclass, jint fd)
{
doClose(e, fd);
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_RandomAccessFile_open(JNIEnv* e, jclass, jstring path,
jlongArray result)
{
string_t chars = getChars(e, path);
if (chars) {
jlong peer = 0;
jlong length = 0;
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#if defined(PLATFORM_WINDOWS)
int fd = ::_wopen(chars, O_RDONLY | OPEN_MASK);
#else
int fd = ::open((const char*)chars, O_RDONLY | OPEN_MASK);
#endif
releaseChars(e, path, chars);
if (fd == -1) {
throwNewErrno(e, "java/io/IOException");
return;
}
struct ::stat fileStats;
if(::fstat(fd, &fileStats) == -1) {
::close(fd);
throwNewErrno(e, "java/io/IOException");
return;
}
peer = fd;
length = fileStats.st_size;
#else
HANDLE hFile = CreateFile2
(chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
throwNewErrno(e, "java/io/IOException");
return;
}
FILE_STANDARD_INFO info;
if(!GetFileInformationByHandleEx(hFile, FileStandardInfo, &info, sizeof(info))) {
CloseHandle(hFile);
throwNewErrno(e, "java/io/IOException");
return;
}
peer = (jlong)hFile;
length = info.EndOfFile.QuadPart;
#endif
e->SetLongArrayRegion(result, 0, 1, &peer);
e->SetLongArrayRegion(result, 1, 1, &length);
}
}
extern "C" JNIEXPORT jint JNICALL
Java_java_io_RandomAccessFile_readBytes(JNIEnv* e, jclass, jlong peer,
jlong position, jbyteArray buffer,
int offset, int length)
{
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
int fd = (int)peer;
if(::lseek(fd, position, SEEK_SET) == -1) {
throwNewErrno(e, "java/io/IOException");
return -1;
}
uint8_t* dst = reinterpret_cast<uint8_t*>
(e->GetPrimitiveArrayCritical(buffer, 0));
int64_t bytesRead = ::read(fd, dst + offset, length);
e->ReleasePrimitiveArrayCritical(buffer, dst, 0);
if(bytesRead == -1) {
throwNewErrno(e, "java/io/IOException");
return -1;
}
#else
HANDLE hFile = (HANDLE)peer;
LARGE_INTEGER lPos;
lPos.QuadPart = position;
if(!SetFilePointerEx(hFile, lPos, nullptr, FILE_BEGIN)) {
throwNewErrno(e, "java/io/IOException");
return -1;
}
uint8_t* dst = reinterpret_cast<uint8_t*>
(e->GetPrimitiveArrayCritical(buffer, 0));
DWORD bytesRead = 0;
if(!ReadFile(hFile, dst + offset, length, &bytesRead, nullptr)) {
throwNewErrno(e, "java/io/IOException");
return -1;
}
e->ReleasePrimitiveArrayCritical(buffer, dst, 0);
#endif
return (jint)bytesRead;
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_RandomAccessFile_close(JNIEnv* /* e*/, jclass, jlong peer)
{
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
int fd = (int)peer;
::close(fd);
#else
HANDLE hFile = (HANDLE)peer;
CloseHandle(hFile);
#endif
}
|
/* Copyright 2020 Stanford, Tsinghua
*
* 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 "taso/ops.h"
#include "taso/dnnl_helper.h"
using namespace taso;
using namespace dnnl;
void Reduce::map(void)
{
// allocate tensors
size_t outputSize = sizeof(DATATYPE) * outputs[0].volume();
CHECK_NE(nullptr, outputs[0].data_ptr = malloc(outputSize));
}
void Reduce::unmap(void)
{
// clear primitives
net.clear();
// free tensors
free(outputs[0].data_ptr);
outputs[0].data_ptr = nullptr;
}
void Reduce::forward(bool block)
{
assert(false);
}
void Model::measure_reduce_cost(Reduce* reduce)
{
assert(false);
}
|
/*
* 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 <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <stdlib.h>
#include <sys/stat.h>
#include <sstream>
#include "t_generator.h"
#include "platform.h"
using std::map;
using std::ofstream;
using std::ostringstream;
using std::pair;
using std::string;
using std::stringstream;
using std::vector;
static const string endl = "\n"; // avoid ostream << std::endl flushes
/**
* Graphviz code generator
*/
class t_gv_generator : public t_generator {
public:
t_gv_generator(
t_program* program,
const std::map<std::string, std::string>& parsed_options,
const std::string& option_string)
: t_generator(program)
{
(void) parsed_options;
(void) option_string;
out_dir_base_ = "gen-gv";
std::map<std::string, std::string>::const_iterator iter;
iter = parsed_options.find("exceptions");
exception_arrows = (iter != parsed_options.end());
}
/**
* Init and end of generator
*/
void init_generator();
void close_generator();
/**
* Program-level generation functions
*/
void generate_typedef (t_typedef* ttypedef);
void generate_enum (t_enum* tenum);
void generate_const (t_const* tconst);
void generate_struct (t_struct* tstruct);
void generate_service (t_service* tservice);
protected:
/**
* Helpers
*/
void print_type(t_type* ttype, string struct_field_ref);
void print_const_value(t_const_value* tvalue);
private:
std::ofstream f_out_;
std::list<string> edges;
bool exception_arrows;
};
/**
* Init generator:
* - Adds some escaping for the Graphviz domain.
* - Create output directory and open file for writting.
* - Write the file header.
*/
void t_gv_generator::init_generator() {
escape_['{'] = "\\{";
escape_['}'] = "\\}";
// Make output directory
MKDIR(get_out_dir().c_str());
string fname = get_out_dir() + program_->get_name() + ".gv";
f_out_.open(fname.c_str());
f_out_ << "digraph \"" << escape_string(program_name_) << "\" {" << endl;
f_out_ << "node [style=filled, shape=record];" << endl;
f_out_ << "edge [arrowsize=0.5];" << endl;
f_out_ << "rankdir=LR" << endl;
}
/**
* Closes generator:
* - Print accumulated nodes connections.
* - Print footnote.
* - Closes file.
*/
void t_gv_generator::close_generator() {
// Print edges
std::list<string>::iterator iter = edges.begin();
for ( ; iter != edges.end(); iter++) {
f_out_ << (*iter) << endl;
}
// Print graph end } and close file
f_out_ << "}" << endl;
f_out_.close();
}
void t_gv_generator::generate_typedef (t_typedef* ttypedef) {
string name = ttypedef->get_name();
f_out_ << "node [fillcolor=azure];" << endl;
f_out_ << name << " [label=\"";
f_out_ << escape_string(name);
f_out_ << " :: ";
print_type(ttypedef->get_type(), name);
f_out_ << "\"];" << endl;
}
void t_gv_generator::generate_enum (t_enum* tenum) {
string name = tenum->get_name();
f_out_ << "node [fillcolor=white];" << endl;
f_out_ << name << " [label=\"enum " << escape_string(name);
vector<t_enum_value*> values = tenum->get_constants();
vector<t_enum_value*>::iterator val_iter;
for (val_iter = values.begin(); val_iter != values.end(); ++val_iter) {
f_out_ << '|' << (*val_iter)->get_name();
f_out_ << " = ";
f_out_ << (*val_iter)->get_value();
}
f_out_ << "\"];" << endl;
}
void t_gv_generator::generate_const (t_const* tconst) {
string name = tconst->get_name();
f_out_ << "node [fillcolor=aliceblue];" << endl;
f_out_ << "const_" << name << " [label=\"";
f_out_ << escape_string(name);
f_out_ << " = ";
print_const_value(tconst->get_value());
f_out_ << " :: ";
print_type(tconst->get_type(), "const_" + name);
f_out_ << "\"];" << endl;
}
void t_gv_generator::generate_struct (t_struct* tstruct) {
string name = tstruct->get_name();
if (tstruct->is_xception()) {
f_out_ << "node [fillcolor=lightpink];" << endl;
f_out_ << name << " [label=\"";
f_out_ << "exception " << escape_string(name);
} else if (tstruct->is_union()) {
f_out_ << "node [fillcolor=lightcyan];" << endl;
f_out_ << name << " [label=\"";
f_out_ << "union " << escape_string(name);
} else {
f_out_ << "node [fillcolor=beige];" << endl;
f_out_ << name << " [label=\"";
f_out_ << "struct " << escape_string(name);
}
vector<t_field*> members = tstruct->get_members();
vector<t_field*>::iterator mem_iter = members.begin();
for ( ; mem_iter != members.end(); mem_iter++) {
string field_name = (*mem_iter)->get_name();
// print port (anchor reference)
f_out_ << "|<field_" << field_name << '>';
// field name :: field type
f_out_ << (*mem_iter)->get_name();
f_out_ << " :: ";
print_type((*mem_iter)->get_type(),
name + ":field_" + field_name);
}
f_out_ << "\"];" << endl;
}
void t_gv_generator::print_type(t_type* ttype, string struct_field_ref) {
if (ttype->is_container()) {
if (ttype->is_list()) {
f_out_ << "list\\<";
print_type(((t_list*)ttype)->get_elem_type(), struct_field_ref);
f_out_ << "\\>";
} else if (ttype->is_set()) {
f_out_ << "set\\<";
print_type(((t_set*)ttype)->get_elem_type(), struct_field_ref);
f_out_ << "\\>";
} else if (ttype->is_map()) {
f_out_ << "map\\<";
print_type(((t_map*)ttype)->get_key_type(), struct_field_ref);
f_out_ << ", ";
print_type(((t_map*)ttype)->get_val_type(), struct_field_ref);
f_out_ << "\\>";
}
} else if (ttype->is_base_type()) {
f_out_ << (((t_base_type*)ttype)->is_binary() ? "binary" : ttype->get_name());
} else {
f_out_ << ttype->get_name();
edges.push_back(struct_field_ref + " -> " + ttype->get_name());
}
}
/**
* Prints out an string representation of the provided constant value
*/
void t_gv_generator::print_const_value(t_const_value* tvalue) {
bool first = true;
switch (tvalue->get_type()) {
case t_const_value::CV_INTEGER:
f_out_ << tvalue->get_integer();
break;
case t_const_value::CV_DOUBLE:
f_out_ << tvalue->get_double();
break;
case t_const_value::CV_STRING:
f_out_ << "\\\"" << get_escaped_string(tvalue) << "\\\"";
break;
case t_const_value::CV_MAP:
{
f_out_ << "\\{ ";
map<t_const_value*, t_const_value*> map_elems = tvalue->get_map();
map<t_const_value*, t_const_value*>::iterator map_iter;
for (map_iter = map_elems.begin(); map_iter != map_elems.end(); map_iter++) {
if (!first) {
f_out_ << ", ";
}
first = false;
print_const_value(map_iter->first);
f_out_ << " = ";
print_const_value(map_iter->second);
}
f_out_ << " \\}";
}
break;
case t_const_value::CV_LIST:
{
f_out_ << "\\{ ";
vector<t_const_value*> list_elems = tvalue->get_list();;
vector<t_const_value*>::iterator list_iter;
for (list_iter = list_elems.begin(); list_iter != list_elems.end(); list_iter++) {
if (!first) {
f_out_ << ", ";
}
first = false;
print_const_value(*list_iter);
}
f_out_ << " \\}";
}
break;
default:
f_out_ << "UNKNOWN";
break;
}
}
void t_gv_generator::generate_service (t_service* tservice) {
string service_name = get_service_name(tservice);
f_out_ << "subgraph cluster_" << service_name << " {" << endl;
f_out_ << "node [fillcolor=bisque];" << endl;
f_out_ << "style=dashed;" << endl;
f_out_ << "label = \"" << escape_string(service_name) << " service\";" << endl;
// TODO: service extends
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::iterator fn_iter = functions.begin();
for ( ; fn_iter != functions.end(); fn_iter++) {
string fn_name = (*fn_iter)->get_name();
f_out_ << "function_" << fn_name;
f_out_ << "[label=\"<return_type>function " << escape_string(fn_name);
f_out_ << " :: ";
print_type((*fn_iter)->get_returntype(), "function_" + fn_name + ":return_type");
vector<t_field*> args = (*fn_iter)->get_arglist()->get_members();
vector<t_field*>::iterator arg_iter = args.begin();
for ( ; arg_iter != args.end(); arg_iter++) {
f_out_ << "|<param_" << (*arg_iter)->get_name() << ">";
f_out_ << (*arg_iter)->get_name();
if ((*arg_iter)->get_value() != NULL) {
f_out_ << " = ";
print_const_value((*arg_iter)->get_value());
}
f_out_ << " :: ";
print_type((*arg_iter)->get_type(),
"function_" + fn_name + ":param_" + (*arg_iter)->get_name());
}
// end of node
f_out_ << "\"];" << endl;
// Exception edges
if (exception_arrows) {
vector<t_field*> excepts = (*fn_iter)->get_xceptions()->get_members();
vector<t_field*>::iterator ex_iter = excepts.begin();
for ( ; ex_iter != excepts.end(); ex_iter++) {
edges.push_back("function_" + fn_name + " -> " +
(*ex_iter)->get_type()->get_name() + " [color=red]");
}
}
}
f_out_ << " }" << endl;
}
THRIFT_REGISTER_GENERATOR(gv, "Graphviz",
" exceptions: Whether to draw arrows from functions to exception.\n"
)
|
#include "muduo/base/Timestamp.h"
#include <sys/time.h>
#include <stdio.h>
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
using namespace muduo;
static_assert(sizeof(Timestamp) == sizeof(int64_t),
"Timestamp is same size as int64_t");
string Timestamp::toString() const
{
char buf[32] = {0};
int64_t seconds = microSecondsSinceEpoch_ / kMicroSecondsPerSecond;
int64_t microseconds = microSecondsSinceEpoch_ % kMicroSecondsPerSecond;
snprintf(buf, sizeof(buf)-1, "%" PRId64 ".%06" PRId64 "", seconds, microseconds);
return buf;
}
string Timestamp::toFormattedString(bool showMicroseconds) const
{
char buf[64] = {0};
time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);
struct tm tm_time;
gmtime_r(&seconds, &tm_time);
if (showMicroseconds)
{
int microseconds = static_cast<int>(microSecondsSinceEpoch_ % kMicroSecondsPerSecond);
snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d",
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,
microseconds);
}
else
{
snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d",
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec);
}
return buf;
}
Timestamp Timestamp::now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t seconds = tv.tv_sec;
return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
** Source: GetFileAttributesA.c
**
** Purpose: Tests the PAL implementation of the GetFileAttributesA function by
** checking the attributes of:
** - a normal directory and file
** - a read only directory and file
** - a read write directory and file
** - a hidden directory and file
** - a read only hidden directory and file
** - a directory and a file with no attributes
** - an invalid file name
**
**
**===========================================================================*/
#include <palsuite.h>
const int TYPE_DIR = 0;
const int TYPE_FILE = 1;
/* Structure defining a test case */
typedef struct
{
char *name; /* name of the file/directory */
DWORD expectedAttribs; /* expected attributes */
HANDLE hFile; /* Handle to the file */
int isFile; /* is file (1) or dir (0) */
}TestCaseFile;
typedef struct
{
char *name; /* name of the file/directory */
DWORD expectedAttribs; /* expected attributes */
HANDLE hFile; /* Handle to the file */
int isFile; /* is file (1) or dir (0) */
}TestCaseDir;
DWORD desiredAccessFile = GENERIC_READ | GENERIC_WRITE;
DWORD shareModeFile = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
LPSECURITY_ATTRIBUTES lpAttrFile = NULL;
DWORD dwCreationDispFile = CREATE_NEW;
DWORD dwFlagsAttribFile = FILE_ATTRIBUTE_NORMAL;
HANDLE hTemplateFile = NULL;
int numFileTests = 6;
TestCaseFile gfaTestsFile[6]; /* GetFileAttributes tests list */
int numDirTests = 6;
TestCaseDir gfaTestsDir[6]; /* GetFileAttributes tests list */
BOOL CleanUpFiles()
{
DWORD dwAtt;
int i;
BOOL result = TRUE;
for (i = 0; i < numFileTests -1 ; i++ )
{
dwAtt = GetFileAttributesA(gfaTestsFile[i].name);
if( dwAtt != INVALID_FILE_ATTRIBUTES )
{
//Trace("Files iteration %d\n", i);
if(!SetFileAttributesA (gfaTestsFile[i].name, FILE_ATTRIBUTE_NORMAL))
{
result = FALSE;
Trace("ERROR:%d: Error setting attributes [%s][%d]\n", GetLastError(), gfaTestsFile[i].name, FILE_ATTRIBUTE_NORMAL);
}
if(!DeleteFileA (gfaTestsFile[i].name))
{
result = FALSE;
Trace("ERROR:%d: Error deleting file [%s][%d]\n", GetLastError(), gfaTestsFile[i].name, dwAtt);
}
}
}
// Trace("Value of result is %d\n", result);
return result;
}
BOOL SetUpFiles()
{
int i = 0;
BOOL result = TRUE;
for (i = 0; i < numFileTests -1; i++ )
{
gfaTestsFile[i].hFile = CreateFile(gfaTestsFile[i].name,
desiredAccessFile,
shareModeFile,
lpAttrFile,
dwCreationDispFile,
dwFlagsAttribFile,
hTemplateFile);
if( gfaTestsFile[i].hFile == NULL )
{
Fail("Error while creating files for iteration %d\n", i);
}
if(!SetFileAttributesA (gfaTestsFile[i].name, gfaTestsFile[i].expectedAttribs))
{
result = FALSE;
Trace("ERROR:%d: Error setting attributes [%s][%d]\n", GetLastError(), gfaTestsFile[i].name, gfaTestsFile[i].expectedAttribs);
}
}
return result;
}
BOOL CleanUpDirs()
{
DWORD dwAtt;
int i;
BOOL result = TRUE;
for (i = 0; i < numDirTests -1 ; i++ )
{
dwAtt = GetFileAttributesA(gfaTestsDir[i].name);
if( dwAtt != INVALID_FILE_ATTRIBUTES )
{
if(!SetFileAttributesA (gfaTestsDir[i].name, FILE_ATTRIBUTE_DIRECTORY))
{
result = FALSE;
Trace("ERROR:%d: Error setting attributes [%s][%d]\n", GetLastError(), gfaTestsDir[i].name, (FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_DIRECTORY));
}
if(!RemoveDirectoryA (gfaTestsDir[i].name))
{
result = FALSE;
Trace("ERROR:%d: Error deleting file [%s][%d]\n", GetLastError(), gfaTestsDir[i].name, dwAtt);
}
}
}
return result;
}
BOOL SetUpDirs()
{
int i = 0;
BOOL result = TRUE;
DWORD ret = 0;
for (i = 0; i < numDirTests - 1 ; i++ )
{
result = CreateDirectory(gfaTestsDir[i].name,
NULL);
if(!result )
{
result = FALSE;
Fail("Error while creating directory for iteration %d\n", i);
}
if(!SetFileAttributesA (gfaTestsDir[i].name, gfaTestsDir[i].expectedAttribs))
{
result = FALSE;
Trace("ERROR:%d: Error setting attributes [%s][%d]\n", GetLastError(), gfaTestsDir[i].name, gfaTestsDir[i].expectedAttribs);
}
ret = GetFileAttributesA (gfaTestsDir[i].name);
if(ret != gfaTestsDir[i].expectedAttribs)
{
result = FALSE;
Trace("ERROR: Error setting attributes [%s][%d]\n", gfaTestsDir[i].name, gfaTestsDir[i].expectedAttribs);
}
//Trace("Setup Dir setting attr [%d], returned [%d]\n", gfaTestsDir[i].expectedAttribs, ret);
}
//Trace("Setup dirs returning %d\n", result);
return result;
}
int __cdecl main(int argc, char **argv)
{
int i;
BOOL bFailed = FALSE;
DWORD result;
char * NormalDirectoryName = "normal_test_directory";
char * ReadOnlyDirectoryName = "ro_test_directory";
char * ReadWriteDirectoryName = "rw_directory";
char * HiddenDirectoryName = ".hidden_directory";
char * HiddenReadOnlyDirectoryName = ".hidden_ro_directory";
char * NoDirectoryName = "no_directory";
char * NormalFileName = "normal_test_file";
char * ReadOnlyFileName = "ro_test_file";
char * ReadWriteFileName = "rw_file";
char * HiddenFileName = ".hidden_file";
char * HiddenReadOnlyFileName = ".hidden_ro_file";
char * NotReallyAFileName = "not_really_a_file";
/* Tests on directory */
gfaTestsDir[0].name = NormalDirectoryName;
gfaTestsDir[0].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY;
gfaTestsDir[0].isFile = TYPE_DIR;
gfaTestsDir[1].name = ReadOnlyDirectoryName;
gfaTestsDir[1].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY |
FILE_ATTRIBUTE_READONLY;
gfaTestsDir[1].isFile = TYPE_DIR;
gfaTestsDir[2].name = ReadWriteDirectoryName;
gfaTestsDir[2].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY;
gfaTestsDir[2].isFile = TYPE_DIR;
gfaTestsDir[3].name = HiddenDirectoryName;
gfaTestsDir[3].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY; //|
//FILE_ATTRIBUTE_HIDDEN;
gfaTestsDir[3].isFile = TYPE_DIR;
gfaTestsDir[4].name = HiddenReadOnlyDirectoryName;
gfaTestsDir[4].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY |
FILE_ATTRIBUTE_READONLY; //|
//FILE_ATTRIBUTE_HIDDEN;
gfaTestsDir[4].isFile = TYPE_DIR;
gfaTestsDir[5].name = NoDirectoryName;
gfaTestsDir[5].expectedAttribs = INVALID_FILE_ATTRIBUTES;
gfaTestsDir[5].isFile = TYPE_DIR;
/* Tests on file */
gfaTestsFile[0].name = NormalFileName;
gfaTestsFile[0].expectedAttribs = FILE_ATTRIBUTE_NORMAL;
gfaTestsFile[0].isFile = TYPE_FILE;
gfaTestsFile[1].name = ReadOnlyFileName;
gfaTestsFile[1].expectedAttribs = FILE_ATTRIBUTE_READONLY;
gfaTestsFile[1].isFile = TYPE_FILE;
gfaTestsFile[2].name = ReadWriteFileName;
gfaTestsFile[2].expectedAttribs = FILE_ATTRIBUTE_NORMAL;
gfaTestsFile[2].isFile = TYPE_FILE;
gfaTestsFile[3].name = HiddenFileName;
gfaTestsFile[3].expectedAttribs = FILE_ATTRIBUTE_NORMAL; //FILE_ATTRIBUTE_HIDDEN;
gfaTestsFile[3].isFile = TYPE_FILE;
gfaTestsFile[4].name = HiddenReadOnlyFileName;
gfaTestsFile[4].expectedAttribs = FILE_ATTRIBUTE_READONLY; //|
//FILE_ATTRIBUTE_HIDDEN;
gfaTestsFile[4].isFile = TYPE_FILE;
gfaTestsFile[5].name = NotReallyAFileName;
gfaTestsFile[5].expectedAttribs = INVALID_FILE_ATTRIBUTES;
gfaTestsFile[5].isFile = TYPE_FILE;
/* Initialize PAL environment */
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
if(!CleanUpFiles())
{
Fail("GetFileAttributesA: Pre-Clean Up Files Failed\n");
}
if(0 == SetUpFiles())
{
Fail("GetFileAttributesA: SetUp Files Failed\n");
}
if(!CleanUpDirs())
{
Fail("GetFileAttributesA: Pre-Clean Up Directories Failed\n");
}
if(!SetUpDirs())
{
Fail("GetFileAttributesA: SetUp Directories Failed\n");
}
/*
* Go through all the test cases above,
* call GetFileAttributesA on the name and
* make sure the return value is the one expected
*/
for( i = 0; i < numFileTests; i++ )
{
result = GetFileAttributesA(gfaTestsFile[i].name);
if( result != gfaTestsFile[i].expectedAttribs )
{
bFailed = TRUE;
Trace("ERROR: GetFileAttributesA Test#%u on %s "
"returned %u instead of %u. \n",
i,
gfaTestsFile[i].name,
result,
gfaTestsFile[i].expectedAttribs);
}
}
for( i = 0; i < numDirTests; i++ )
{
result = GetFileAttributesA(gfaTestsDir[i].name);
if( result != gfaTestsDir[i].expectedAttribs )
{
bFailed = TRUE;
Trace("ERROR: GetFileAttributesA on Directories Test#%u on %s "
"returned %u instead of %u. \n",
i,
gfaTestsDir[i].name,
result,
gfaTestsDir[i].expectedAttribs);
}
}
if(!CleanUpFiles())
{
Fail("GetFileAttributesA: Post-Clean Up Files Failed\n");
}
if(!CleanUpDirs())
{
Fail("GetFileAttributesA: Post-Clean Up Directories Failed\n");
}
/* If any errors, just call Fail() */
if( bFailed )
{
Fail("");
}
PAL_Terminate();
return PASS;
}
|
/*
* The MIT License
*
* Copyright (c) 1997-2019 The 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: HyprePrecondSparseMSG.cc
//
// Hypre SparseMSG (geometric multigrid #2) preconditioner.
//--------------------------------------------------------------------------
#include <CCA/Components/Solvers/AMR/HyprePreconds/HyprePrecondSparseMSG.h>
#include <CCA/Components/Solvers/AMR/HypreDriver.h>
#include <Core/Exceptions/ProblemSetupException.h>
#include <CCA/Components/Solvers/AMR/HypreSolverParams.h>
#include <Core/Parallel/ProcessorGroup.h>
#include <Core/Util/DebugStream.h>
using namespace Uintah;
//__________________________________
// To turn on normal output
// setenv SCI_DEBUG "SOLVER_DOING_COUT:+"
static DebugStream cout_doing("SOLVER_DOING_COUT", false);
Priorities
HyprePrecondSparseMSG::initPriority(void)
//___________________________________________________________________
// Function HyprePrecondSparseMSG::initPriority~
// Set the Hypre interfaces that SparseMSG can work with. Currently, only
// the Struct interface is supported here. The vector of interfaces
// is sorted by descending priority.
//___________________________________________________________________
{
Priorities priority;
priority.push_back(HypreStruct);
return priority;
}
void
HyprePrecondSparseMSG::setup(void)
//___________________________________________________________________
// Function HyprePrecondSparseMSG::setup~
// Set up the preconditioner object. After this function call, a
// Hypre solver can use the preconditioner.
//___________________________________________________________________
{
const HypreDriver* driver = _solver->getDriver();
const HypreSolverParams* params = driver->getParams();
const HypreInterface& interface = driver->getInterface();
if (interface == HypreStruct) {
HYPRE_StructSolver precond_solver;
HYPRE_StructSparseMSGCreate(driver->getPG()->getComm(), &precond_solver);
HYPRE_StructSparseMSGSetMaxIter(precond_solver, 1);
HYPRE_StructSparseMSGSetJump(precond_solver, params->jump);
HYPRE_StructSparseMSGSetTol(precond_solver, 0.0);
HYPRE_StructSparseMSGSetZeroGuess(precond_solver);
/* weighted Jacobi = 1; red-black GS = 2 */
HYPRE_StructSparseMSGSetRelaxType(precond_solver, 1);
HYPRE_StructSparseMSGSetNumPreRelax(precond_solver, params->nPre);
HYPRE_StructSparseMSGSetNumPostRelax(precond_solver, params->nPost);
HYPRE_StructSparseMSGSetLogging(precond_solver, 0);
_precond = (HYPRE_PtrToSolverFcn)HYPRE_StructSparseMSGSolve;
_pcsetup = (HYPRE_PtrToSolverFcn)HYPRE_StructSparseMSGSetup;
_precond_solver = (HYPRE_Solver) precond_solver;
}
}
HyprePrecondSparseMSG::~HyprePrecondSparseMSG(void)
//___________________________________________________________________
// HyprePrecondSparseMSG destructor~
// Destroy the Hypre objects associated with the preconditioner.
//___________________________________________________________________
{
const HypreDriver* driver = _solver->getDriver();
const HypreInterface& interface = driver->getInterface();
if (interface == HypreStruct) {
HYPRE_StructSparseMSGDestroy((HYPRE_StructSolver) _precond_solver);
}
}
|
//*******************************************************************
// Copyright (C) 2000 ImageLinks Inc.
//
// LICENSE: LGPL see top level license.txt
//
// Author: Garrett Potts (gpotts@imagelinks.com)
//
//*************************************************************************
// $Id: ossimDateProperty.cpp 9094 2006-06-13 19:12:40Z dburken $
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <ossim/base/ossimDateProperty.h>
RTTI_DEF1(ossimDateProperty, "ossimDateProperty", ossimProperty);
ossimDateProperty::ossimDateProperty()
:ossimProperty("")
{
setDate(ossimDate());
}
ossimDateProperty::ossimDateProperty(const ossimString& name,
const ossimString& value)
:ossimProperty(name)
{
setValue(value);
}
ossimDateProperty::ossimDateProperty(const ossimString& name,
const ossimLocalTm& value)
:ossimProperty(name),
theValue(value)
{
}
ossimDateProperty::ossimDateProperty(const ossimDateProperty& src)
:ossimProperty(src),
theValue(src.theValue)
{
}
ossimObject* ossimDateProperty::dup()const
{
return new ossimDateProperty(*this);
}
void ossimDateProperty::setDate(const ossimLocalTm& localTm)
{
theValue = localTm;
}
const ossimLocalTm& ossimDateProperty::getDate()const
{
return theValue;
}
bool ossimDateProperty::setValue(const ossimString& value)
{
if(value.trim() == "")
{
theValue = ossimDate();
return true;
}
bool result = value.size() == 14;
ossimString year;
ossimString month;
ossimString day;
ossimString hour;
ossimString min;
ossimString sec;
if(value.size() == 14)
{
year = ossimString(value.begin(),
value.begin()+4);
month = ossimString(value.begin()+4,
value.begin()+6);
day = ossimString(value.begin()+6,
value.begin()+8);
hour = ossimString(value.begin()+8,
value.begin()+10);
min = ossimString(value.begin()+10,
value.begin()+12);
sec = ossimString(value.begin()+12,
value.begin()+14);
theValue.setYear(year.toUInt32());
theValue.setMonth(month.toUInt32());
theValue.setDay(day.toUInt32());
theValue.setHour(hour.toUInt32());
theValue.setMin(min.toUInt32());
theValue.setSec(sec.toUInt32());
}
return result;
}
void ossimDateProperty::valueToString(ossimString& valueResult)const
{
std::ostringstream out;
out << std::setw(4)
<< std::setfill('0')
<< theValue.getYear()
<< std::setw(2)
<< std::setfill('0')
<< theValue.getMonth()
<< std::setw(2)
<< std::setfill('0')
<< theValue.getDay()
<< std::setw(2)
<< std::setfill('0')
<< theValue.getHour()
<< std::setw(2)
<< std::setfill('0')
<< theValue.getMin()
<< std::setw(2)
<< std::setfill('0')
<< theValue.getSec();
valueResult = out.str();
}
const ossimProperty& ossimDateProperty::assign(const ossimProperty& rhs)
{
ossimProperty::assign(rhs);
ossimDateProperty* rhsPtr = PTR_CAST(ossimDateProperty, &rhs);
if(rhsPtr)
{
theValue = rhsPtr->theValue;
}
else
{
setValue(rhs.valueToString());
}
return *this;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMPEG2Writer.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkMPEG2Writer.h"
#include "vtkDataSetAttributes.h"
#include "vtkDirectory.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkErrorCode.h"
#include <vtkstd/map>
#include <vtkstd/string>
#include "mpeg2enc_config.h"
#include "mpeg2enc_global.h"
/* private prototypes */
//---------------------------------------------------------------------------
class vtkMPEG2WriterInternal
{
public:
vtkMPEG2WriterInternal();
~vtkMPEG2WriterInternal();
typedef vtkstd::map<vtkstd::string, vtkSmartPointer<vtkImageData> > StringToImageMap;
int StoreImage(const char* name, vtkImageData* id);
unsigned char* GetImagePtr(const char* name);
int RemoveImage(const char* name);
int Dim[2];
void ReadParmFile( );
void Init();
void ReadQuantMat();
MPEG2_structure* GetMPEG2Structure() { return this->Structure; }
private:
StringToImageMap ImagesMap;
MPEG2_structure* Structure;
};
//---------------------------------------------------------------------------
extern "C"
{
void vtkMPEG2WriterReportError( const char *text )
{
vtkGenericWarningMacro(<< text);
}
unsigned char* vtkMPEG2WriterInternalGetImagePtr(const char* fname,
void *mpeg2_writer_internal)
{
return (static_cast<vtkMPEG2WriterInternal*>(mpeg2_writer_internal))->GetImagePtr(fname);
}
}
//---------------------------------------------------------------------------
vtkMPEG2WriterInternal::vtkMPEG2WriterInternal()
{
this->Dim[0] = 0;
this->Dim[1] = 0;
this->Structure = new MPEG2_structure;
}
//---------------------------------------------------------------------------
vtkMPEG2WriterInternal::~vtkMPEG2WriterInternal()
{
delete this->Structure;
this->Structure = 0;
}
//---------------------------------------------------------------------------
int vtkMPEG2WriterInternal::StoreImage(const char* name, vtkImageData* iid)
{
if ( !name )
{
return 0;
}
// We need to flip the image vertically
vtkImageData* id = vtkImageData::New();
id->CopyStructure(iid);
id->SetNumberOfScalarComponents(iid->GetNumberOfScalarComponents());
vtkInformation *pipelineInfo = id->GetPipelineInformation();
if (pipelineInfo)
{
vtkInformation *scalarInfo = vtkDataObject::GetActiveFieldInformation(
pipelineInfo, vtkDataObject::FIELD_ASSOCIATION_POINTS,
vtkDataSetAttributes::SCALARS);
if (scalarInfo)
{
scalarInfo->Set(vtkDataObject::FIELD_ARRAY_TYPE(), iid->GetScalarType());
}
}
int dims[3];
id->GetDimensions(dims);
int row_length = dims[0] * id->GetNumberOfScalarComponents();
const unsigned char *src_ptr =
(const unsigned char *)iid->GetScalarPointer();
src_ptr += iid->GetNumberOfPoints() * iid->GetNumberOfScalarComponents()
- row_length;
unsigned char *dest_ptr = (unsigned char *)id->GetScalarPointer();
// We assume there is only one slice
for (int j = 0; j < dims[1]; j++)
{
memcpy(dest_ptr, src_ptr, row_length);
dest_ptr += row_length;
src_ptr -= row_length;
}
this->ImagesMap[name] = id;
id->Delete();
return 1;
}
//---------------------------------------------------------------------------
unsigned char* vtkMPEG2WriterInternal::GetImagePtr(const char* fname)
{
if ( !fname )
{
return 0;
}
vtkMPEG2WriterInternal::StringToImageMap::iterator it
= this->ImagesMap.find(fname);
if ( it == this->ImagesMap.end() )
{
return 0;
}
vtkImageData* id = it->second.GetPointer();
return static_cast<unsigned char*>(id->GetScalarPointer());
}
//---------------------------------------------------------------------------
int vtkMPEG2WriterInternal::RemoveImage(const char* fname)
{
if ( !fname )
{
return 0;
}
vtkMPEG2WriterInternal::StringToImageMap::iterator it
= this->ImagesMap.find(fname);
if ( it == this->ImagesMap.end() )
{
return 0;
}
this->ImagesMap.erase(it);
return 0;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
vtkStandardNewMacro(vtkMPEG2Writer);
//---------------------------------------------------------------------------
vtkMPEG2Writer::vtkMPEG2Writer()
{
this->Internals = 0;
this->Time = 0;
this->ActualWrittenTime = 0;
}
//---------------------------------------------------------------------------
vtkMPEG2Writer::~vtkMPEG2Writer()
{
delete this->Internals;
}
//---------------------------------------------------------------------------
void vtkMPEG2Writer::Start()
{
// Error checking
this->Error = 1;
if ( this->Internals )
{
vtkErrorMacro("Movie already started");
this->SetErrorCode(vtkGenericMovieWriter::InitError);
return;
}
if ( this->GetInput() == NULL )
{
vtkErrorMacro(<<"Write:Please specify an input!");
this->SetErrorCode(vtkGenericMovieWriter::NoInputError);
return;
}
if (!this->FileName)
{
vtkErrorMacro(<<"Write:Please specify a FileName");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return;
}
this->Internals = new vtkMPEG2WriterInternal;
this->Error = 0;
this->Time = 0;
this->ActualWrittenTime = 0;
this->Initialized = 0;
}
//---------------------------------------------------------------------------
void vtkMPEG2Writer::Write()
{
if ( !this->Internals )
{
vtkErrorMacro("Movie not started");
this->Error = 1;
this->SetErrorCode(vtkGenericMovieWriter::InitError);
return;
}
// get the data
this->GetInput()->UpdateInformation();
int *wExtent = this->GetInput()->GetWholeExtent();
this->GetInput()->SetUpdateExtent(wExtent);
this->GetInput()->Update();
int dim[4];
this->GetInput()->GetDimensions(dim);
if ( this->Internals->Dim[0] == 0 && this->Internals->Dim[1] == 0 )
{
this->Internals->Dim[0] = dim[0];
this->Internals->Dim[1] = dim[1];
}
if ( this->Internals->Dim[0] != dim[0] || this->Internals->Dim[1] != dim[1] )
{
vtkErrorMacro("Image not of the same size");
this->SetErrorCode(vtkGenericMovieWriter::ChangedResolutionError);
return;
}
if ( !this->Initialized )
{
this->Initialize();
}
MPEG2_structure* str = this->Internals->GetMPEG2Structure();
char buffer[1024];
sprintf(buffer, str->tplorg, this->Time + str->frame0);
this->Internals->StoreImage(buffer, this->GetInput());
int last = MPEG2_putseq_one(this->ActualWrittenTime, this->Time,str);
if ( last >= 0 )
{
sprintf(buffer, str->tplorg, last + str->frame0);
this->Internals->RemoveImage(buffer);
this->ActualWrittenTime ++;
}
this->Time++;
}
//---------------------------------------------------------------------------
void vtkMPEG2Writer::Initialize()
{
MPEG2_structure* str = this->Internals->GetMPEG2Structure();
str->quiet = 1;
str->report_error = vtkMPEG2WriterReportError;
str->get_image_ptr = vtkMPEG2WriterInternalGetImagePtr;
str->mpeg2_writer_internal = this->Internals;
/* read parameter file */
this->Internals->ReadParmFile();
/* read quantization matrices */
this->Internals->ReadQuantMat();
/* open output file */
if (!(str->outfile=fopen(this->FileName,"wb")))
{
sprintf(str->errortext,"Couldn't create output file %s",this->FileName);
(*(str->report_error))(str->errortext);
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
}
this->Internals->Init();
MPEG2_rc_init_seq(str); /* initialize rate control */
/* sequence header, sequence extension and sequence display extension */
MPEG2_putseqhdr(str);
if (!str->mpeg1)
{
MPEG2_putseqext(str);
MPEG2_putseqdispext(str);
}
/* optionally output some text data (description, copyright or whatever) */
if (strlen(str->id_string) > 1)
MPEG2_putuserdata(str->id_string,str);
this->Initialized = 1;
}
//---------------------------------------------------------------------------
void vtkMPEG2Writer::End()
{
MPEG2_structure* str = this->Internals->GetMPEG2Structure();
int last;
while ( (last = MPEG2_putseq_one(this->ActualWrittenTime, this->Time-1,str)) >= 0 )
{
char buffer[1024];
sprintf(buffer, str->tplorg, last + str->frame0);
this->Internals->RemoveImage(buffer);
this->ActualWrittenTime ++;
}
MPEG2_putseqend(str);
fclose(str->outfile);
if ( str->statfile )
{
fclose(str->statfile);
}
delete this->Internals;
this->Internals = 0;
}
//---------------------------------------------------------------------------
void vtkMPEG2Writer::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
void vtkMPEG2WriterInternal::Init()
{
int i, size;
static int block_count_tab[3] = {6,8,12};
MPEG2_initbits();
MPEG2_init_fdct();
MPEG2_init_idct();
/* round picture dimensions to nearest multiple of 16 or 32 */
this->Structure->mb_width = (this->Structure->horizontal_size+15)/16;
this->Structure->mb_height = this->Structure->prog_seq ? (this->Structure->vertical_size+15)/16 : 2*((this->Structure->vertical_size+31)/32);
this->Structure->mb_height2 = this->Structure->fieldpic ? this->Structure->mb_height>>1 : this->Structure->mb_height; /* for field pictures */
this->Structure->width = 16*this->Structure->mb_width;
this->Structure->height = 16*this->Structure->mb_height;
this->Structure->chrom_width = (this->Structure->chroma_format==CHROMA444) ? this->Structure->width : this->Structure->width>>1;
this->Structure->chrom_height = (this->Structure->chroma_format!=CHROMA420) ? this->Structure->height : this->Structure->height>>1;
this->Structure->height2 = this->Structure->fieldpic ? this->Structure->height>>1 : this->Structure->height;
this->Structure->width2 = this->Structure->fieldpic ? this->Structure->width<<1 : this->Structure->width;
this->Structure->chrom_width2 = this->Structure->fieldpic ? this->Structure->chrom_width<<1 : this->Structure->chrom_width;
this->Structure->block_count = block_count_tab[this->Structure->chroma_format-1];
/* clip table */
if (!(this->Structure->clp = (unsigned char *)malloc(1024)))
{
(*(this->Structure->report_error))("malloc failed\n");
}
this->Structure->clp+= 384;
for (i=-384; i<640; i++)
{
this->Structure->clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
}
for (i=0; i<3; i++)
{
size = (i==0) ? this->Structure->width*this->Structure->height :
this->Structure->chrom_width*this->Structure->chrom_height;
if (!(this->Structure->newrefframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
if (!(this->Structure->oldrefframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
if (!(this->Structure->auxframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
if (!(this->Structure->neworgframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
if (!(this->Structure->oldorgframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
if (!(this->Structure->auxorgframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
if (!(this->Structure->predframe[i] = (unsigned char *)malloc(size)))
(*(this->Structure->report_error))("malloc failed\n");
}
this->Structure->mbinfo = (struct mbinfo *)malloc(this->Structure->mb_width*this->Structure->mb_height2*sizeof(struct mbinfo));
if (!this->Structure->mbinfo)
(*(this->Structure->report_error))("malloc failed\n");
this->Structure->blocks =
(short (*)[64])malloc(this->Structure->mb_width*this->Structure->mb_height2*this->Structure->block_count*sizeof(short [64]));
if (!this->Structure->blocks)
(*(this->Structure->report_error))("malloc failed\n");
/* open statistics output file */
if (this->Structure->statname[0]=='-')
this->Structure->statfile = 0;
else if (!(this->Structure->statfile = fopen(this->Structure->statname,"w")))
{
sprintf(this->Structure->errortext,"Couldn't create statistics output file %s",this->Structure->statname);
(*(this->Structure->report_error))(this->Structure->errortext);
}
}
void vtkMPEG2WriterInternal::ReadParmFile( )
{
int i;
int h,m,s,f;
//FILE *fd;
//char line[256];
static double ratetab[8]=
{24000.0/1001.0,24.0,25.0,30000.0/1001.0,30.0,50.0,60000.0/1001.0,60.0};
/*
if (!(fd = fopen(fname,"r")))
{
sprintf(this->Structure->errortext,"Couldn't open parameter file %s",fname);
(*(this->Structure->report_error))(this->Structure->errortext);
}
fgets(this->Structure->id_string,254,fd);
fgets(line,254,fd); sscanf(line,"%s",this->Structure->tplorg);
fgets(line,254,fd); sscanf(line,"%s",this->Structure->tplref);
fgets(line,254,fd); sscanf(line,"%s",this->Structure->iqname);
fgets(line,254,fd); sscanf(line,"%s",this->Structure->niqname);
fgets(line,254,fd); sscanf(line,"%s",this->Structure->statname);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->inputtype);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->nframes);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->frame0);
fgets(line,254,fd); sscanf(line,"%d:%d:%d:%d",&h,&m,&s,&f);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->N_val);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->M_val);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->mpeg1);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->fieldpic);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->horizontal_size);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->vertical_size);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->aspectratio);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->frame_rate_code);
fgets(line,254,fd); sscanf(line,"%lf",&this->Structure->bit_rate);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->vbv_buffer_size);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->low_delay);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->constrparms);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->profile);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->level);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->prog_seq);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->chroma_format);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->video_format);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->color_primaries);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->transfer_characteristics);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->matrix_coefficients);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->display_horizontal_size);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->display_vertical_size);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->dc_prec);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->topfirst);
fgets(line,254,fd); sscanf(line,"%d %d %d",
this->Structure->frame_pred_dct_tab,this->Structure->frame_pred_dct_tab+1,this->Structure->frame_pred_dct_tab+2);
fgets(line,254,fd); sscanf(line,"%d %d %d",
this->Structure->conceal_tab,this->Structure->conceal_tab+1,this->Structure->conceal_tab+2);
fgets(line,254,fd); sscanf(line,"%d %d %d",
this->Structure->qscale_tab,this->Structure->qscale_tab+1,this->Structure->qscale_tab+2);
fgets(line,254,fd); sscanf(line,"%d %d %d",
this->Structure->intravlc_tab,this->Structure->intravlc_tab+1,this->Structure->intravlc_tab+2);
fgets(line,254,fd); sscanf(line,"%d %d %d",
this->Structure->altscan_tab,this->Structure->altscan_tab+1,this->Structure->altscan_tab+2);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->repeatfirst);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->prog_frame);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->P_val);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->reaction);
fgets(line,254,fd); sscanf(line,"%lf",&this->Structure->avg_act);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->Xi);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->Xp);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->Xb);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->d0i);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->d0p);
fgets(line,254,fd); sscanf(line,"%d",&this->Structure->d0b);
*/
strcpy(this->Structure->id_string, "vtkMPEG2Writer");
strcpy(this->Structure->tplorg, "%d");
strcpy(this->Structure->tplref, "-");
strcpy(this->Structure->iqname, "-");
strcpy(this->Structure->niqname, "-");
strcpy(this->Structure->statname, "-");
this->Structure->inputtype = T_MEMPPM;
this->Structure->nframes = 1000000;
this->Structure->frame0 = 0;
this->Structure->N_val = 21;
this->Structure->M_val = 3;
this->Structure->mpeg1 = 0;
this->Structure->fieldpic = 0;
this->Structure->horizontal_size = this->Dim[0];
this->Structure->vertical_size = this->Dim[1];
this->Structure->aspectratio = 1;
this->Structure->frame_rate_code = 5;
this->Structure->bit_rate = 5000000.0;
this->Structure->vbv_buffer_size = 112;
this->Structure->low_delay = 0;
this->Structure->constrparms = 0;
this->Structure->profile = 4;
this->Structure->level = 4;
this->Structure->prog_seq = 1;
this->Structure->chroma_format = 1;
this->Structure->video_format = 0;
this->Structure->color_primaries = 5;
this->Structure->transfer_characteristics = 5;
this->Structure->matrix_coefficients = 4;
this->Structure->display_horizontal_size = this->Dim[0];
this->Structure->display_vertical_size = this->Dim[1];
this->Structure->dc_prec = 2;
this->Structure->topfirst = 1;
this->Structure->frame_pred_dct_tab[0] = this->Structure->frame_pred_dct_tab[1] = this->Structure->frame_pred_dct_tab[2] = 0;
this->Structure->conceal_tab[0] = this->Structure->conceal_tab[1] = this->Structure->conceal_tab[2] = 0;
this->Structure->qscale_tab[0] = this->Structure->qscale_tab[1] = this->Structure->qscale_tab[2] = 1;
this->Structure->intravlc_tab[0] = 1;
this->Structure->intravlc_tab[1] = this->Structure->intravlc_tab[2] = 1;
this->Structure->altscan_tab[0] = this->Structure->altscan_tab[1] = this->Structure->altscan_tab[2] = 0;
this->Structure->repeatfirst = 0;
this->Structure->prog_frame = 0;
this->Structure->P_val = 0;
this->Structure->reaction = 0;
this->Structure->avg_act = 0;
this->Structure->Xi = 0;
this->Structure->Xp = 0;
this->Structure->Xb = 0;
this->Structure->d0i = 0;
this->Structure->d0p = 0;
this->Structure->d0b = 0;
if (this->Structure->N_val<1)
(*(this->Structure->report_error))("N must be positive");
if (this->Structure->M_val<1)
(*(this->Structure->report_error))("M must be positive");
if (this->Structure->N_val%this->Structure->M_val != 0)
(*(this->Structure->report_error))("N must be an integer multiple of M");
this->Structure->motion_data = (struct motion_data *)malloc(this->Structure->M_val*sizeof(struct motion_data));
if (!this->Structure->motion_data)
(*(this->Structure->report_error))("malloc failed\n");
this->Structure->motion_data[0].forw_hor_f_code = 2;
this->Structure->motion_data[0].forw_vert_f_code = 2;
this->Structure->motion_data[0].sxf = 11;
this->Structure->motion_data[0].syf = 11;
this->Structure->motion_data[1].forw_hor_f_code = 1;
this->Structure->motion_data[1].forw_vert_f_code = 1;
this->Structure->motion_data[1].sxf = 3;
this->Structure->motion_data[1].syf = 3;
this->Structure->motion_data[1].back_hor_f_code = 1;
this->Structure->motion_data[1].back_vert_f_code = 1;
this->Structure->motion_data[1].sxb = 7;
this->Structure->motion_data[1].syb = 7;
this->Structure->motion_data[2].forw_hor_f_code = 1;
this->Structure->motion_data[2].forw_vert_f_code = 1;
this->Structure->motion_data[2].sxf = 7;
this->Structure->motion_data[2].syf = 7;
this->Structure->motion_data[2].back_hor_f_code = 1;
this->Structure->motion_data[2].back_vert_f_code = 1;
this->Structure->motion_data[2].sxb = 3;
this->Structure->motion_data[2].syb = 3;
/*
for (i=0; i<this->Structure->M_val; i++)
{
fgets(line,254,fd);
sscanf(line,"%d %d %d %d",
&this->Structure->motion_data[i].forw_hor_f_code, &this->Structure->motion_data[i].forw_vert_f_code,
&this->Structure->motion_data[i].sxf, &this->Structure->motion_data[i].syf);
if (i!=0)
{
fgets(line,254,fd);
sscanf(line,"%d %d %d %d",
&this->Structure->motion_data[i].back_hor_f_code, &this->Structure->motion_data[i].back_vert_f_code,
&this->Structure->motion_data[i].sxb, &this->Structure->motion_data[i].syb);
}
}
fclose(fd);
*/
/* make flags boolean (x!=0 -> x=1) */
this->Structure->mpeg1 = !!this->Structure->mpeg1;
this->Structure->fieldpic = !!this->Structure->fieldpic;
this->Structure->low_delay = !!this->Structure->low_delay;
this->Structure->constrparms = !!this->Structure->constrparms;
this->Structure->prog_seq = !!this->Structure->prog_seq;
this->Structure->topfirst = !!this->Structure->topfirst;
for (i=0; i<3; i++)
{
this->Structure->frame_pred_dct_tab[i] = !!this->Structure->frame_pred_dct_tab[i];
this->Structure->conceal_tab[i] = !!this->Structure->conceal_tab[i];
this->Structure->qscale_tab[i] = !!this->Structure->qscale_tab[i];
this->Structure->intravlc_tab[i] = !!this->Structure->intravlc_tab[i];
this->Structure->altscan_tab[i] = !!this->Structure->altscan_tab[i];
}
this->Structure->repeatfirst = !!this->Structure->repeatfirst;
this->Structure->prog_frame = !!this->Structure->prog_frame;
/* make sure MPEG specific parameters are valid */
MPEG2_range_checks(this->Structure);
this->Structure->frame_rate = ratetab[this->Structure->frame_rate_code-1];
/* timecode -> frame number */
h = m = s = f = 0;
this->Structure->tc0 = h;
this->Structure->tc0 = 60*this->Structure->tc0 + m;
this->Structure->tc0 = 60*this->Structure->tc0 + s;
this->Structure->tc0 = (int)(this->Structure->frame_rate+0.5)*this->Structure->tc0 + f;
if (!this->Structure->mpeg1)
{
MPEG2_profile_and_level_checks(this->Structure);
}
else
{
/* MPEG-1 */
if (this->Structure->constrparms)
{
if (this->Structure->horizontal_size>768
|| this->Structure->vertical_size>576
|| ((this->Structure->horizontal_size+15)/16)*((this->Structure->vertical_size+15)/16)>396
|| ((this->Structure->horizontal_size+15)/16)*((this->Structure->vertical_size+15)/16)*this->Structure->frame_rate>396*25.0
|| this->Structure->frame_rate>30.0)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting constrained_parameters_flag = 0\n");
this->Structure->constrparms = 0;
}
}
if (this->Structure->constrparms)
{
for (i=0; i<this->Structure->M_val; i++)
{
if (this->Structure->motion_data[i].forw_hor_f_code>4)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting constrained_parameters_flag = 0\n");
this->Structure->constrparms = 0;
break;
}
if (this->Structure->motion_data[i].forw_vert_f_code>4)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting constrained_parameters_flag = 0\n");
this->Structure->constrparms = 0;
break;
}
if (i!=0)
{
if (this->Structure->motion_data[i].back_hor_f_code>4)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting constrained_parameters_flag = 0\n");
this->Structure->constrparms = 0;
break;
}
if (this->Structure->motion_data[i].back_vert_f_code>4)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting constrained_parameters_flag = 0\n");
this->Structure->constrparms = 0;
break;
}
}
}
}
}
/* relational checks */
if (this->Structure->mpeg1)
{
if (!this->Structure->prog_seq)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting progressive_sequence = 1\n");
this->Structure->prog_seq = 1;
}
if (this->Structure->chroma_format!=CHROMA420)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting this->Structure->chroma_format = 1 (4:2:0)\n");
this->Structure->chroma_format = CHROMA420;
}
if (this->Structure->dc_prec!=0)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting intra_dc_precision = 0\n");
this->Structure->dc_prec = 0;
}
for (i=0; i<3; i++)
if (this->Structure->qscale_tab[i])
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting this->Structure->qscale_tab[%d] = 0\n",i);
this->Structure->qscale_tab[i] = 0;
}
for (i=0; i<3; i++)
if (this->Structure->intravlc_tab[i])
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting this->Structure->intravlc_tab[%d] = 0\n",i);
this->Structure->intravlc_tab[i] = 0;
}
for (i=0; i<3; i++)
if (this->Structure->altscan_tab[i])
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting this->Structure->altscan_tab[%d] = 0\n",i);
this->Structure->altscan_tab[i] = 0;
}
}
if (!this->Structure->mpeg1 && this->Structure->constrparms)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting constrained_parameters_flag = 0\n");
this->Structure->constrparms = 0;
}
if (this->Structure->prog_seq && !this->Structure->prog_frame)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting progressive_frame = 1\n");
this->Structure->prog_frame = 1;
}
if (this->Structure->prog_frame && this->Structure->fieldpic)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting field_pictures = 0\n");
this->Structure->fieldpic = 0;
}
if (!this->Structure->prog_frame && this->Structure->repeatfirst)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting repeat_first_field = 0\n");
this->Structure->repeatfirst = 0;
}
if (this->Structure->prog_frame)
{
for (i=0; i<3; i++)
if (!this->Structure->frame_pred_dct_tab[i])
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting frame_pred_frame_dct[%d] = 1\n",i);
this->Structure->frame_pred_dct_tab[i] = 1;
}
}
if (this->Structure->prog_seq && !this->Structure->repeatfirst && this->Structure->topfirst)
{
if (!this->Structure->quiet)
fprintf(stderr,"Warning: setting top_field_first = 0\n");
this->Structure->topfirst = 0;
}
/* search windows */
for (i=0; i<this->Structure->M_val; i++)
{
if (this->Structure->motion_data[i].sxf > (4<<this->Structure->motion_data[i].forw_hor_f_code)-1)
{
if (!this->Structure->quiet)
fprintf(stderr,
"Warning: reducing forward horizontal search this->Structure->width to %d\n",
(4<<this->Structure->motion_data[i].forw_hor_f_code)-1);
this->Structure->motion_data[i].sxf = (4<<this->Structure->motion_data[i].forw_hor_f_code)-1;
}
if (this->Structure->motion_data[i].syf > (4<<this->Structure->motion_data[i].forw_vert_f_code)-1)
{
if (!this->Structure->quiet)
fprintf(stderr,
"Warning: reducing forward vertical search this->Structure->width to %d\n",
(4<<this->Structure->motion_data[i].forw_vert_f_code)-1);
this->Structure->motion_data[i].syf = (4<<this->Structure->motion_data[i].forw_vert_f_code)-1;
}
if (i!=0)
{
if (this->Structure->motion_data[i].sxb > (4<<this->Structure->motion_data[i].back_hor_f_code)-1)
{
if (!this->Structure->quiet)
fprintf(stderr,
"Warning: reducing backward horizontal search this->Structure->width to %d\n",
(4<<this->Structure->motion_data[i].back_hor_f_code)-1);
this->Structure->motion_data[i].sxb = (4<<this->Structure->motion_data[i].back_hor_f_code)-1;
}
if (this->Structure->motion_data[i].syb > (4<<this->Structure->motion_data[i].back_vert_f_code)-1)
{
if (!this->Structure->quiet)
fprintf(stderr,
"Warning: reducing backward vertical search this->Structure->width to %d\n",
(4<<this->Structure->motion_data[i].back_vert_f_code)-1);
this->Structure->motion_data[i].syb = (4<<this->Structure->motion_data[i].back_vert_f_code)-1;
}
}
}
}
void vtkMPEG2WriterInternal::ReadQuantMat()
{
int i,v;
FILE *fd;
if (this->Structure->iqname[0]=='-')
{
/* use default intra matrix */
this->Structure->load_iquant = 0;
for (i=0; i<64; i++)
this->Structure->intra_q[i] = MPEG2_default_intra_quantizer_matrix[i];
}
else
{
/* read customized intra matrix */
this->Structure->load_iquant = 1;
if (!(fd = fopen(this->Structure->iqname,"r")))
{
sprintf(this->Structure->errortext,"Couldn't open quant matrix file %s",this->Structure->iqname);
(*(this->Structure->report_error))(this->Structure->errortext);
}
for (i=0; i<64; i++)
{
fscanf(fd,"%d",&v);
if (v<1 || v>255)
(*(this->Structure->report_error))("invalid value in quant matrix");
this->Structure->intra_q[i] = v;
}
fclose(fd);
}
if (this->Structure->niqname[0]=='-')
{
/* use default non-intra matrix */
this->Structure->load_niquant = 0;
for (i=0; i<64; i++)
this->Structure->inter_q[i] = 16;
}
else
{
/* read customized non-intra matrix */
this->Structure->load_niquant = 1;
if (!(fd = fopen(this->Structure->niqname,"r")))
{
sprintf(this->Structure->errortext,"Couldn't open quant matrix file %s",this->Structure->niqname);
(*(this->Structure->report_error))(this->Structure->errortext);
}
for (i=0; i<64; i++)
{
fscanf(fd,"%d",&v);
if (v<1 || v>255)
(*(this->Structure->report_error))("invalid value in quant matrix");
this->Structure->inter_q[i] = v;
}
fclose(fd);
}
}
|
#include "k-framework.h"
kfw::core::HackManager* kfw::core::Factory::hackManager = nullptr;
kfw::core::HookManager* kfw::core::Factory::hookManager = nullptr;
kfw::core::HookManager * kfw::core::Factory::getDefaultHookManager()
{
if (hookManager == nullptr) hookManager = new HookManager();
return hookManager;
}
kfw::core::HackManager* kfw::core::Factory::getDefaultHackManager()
{
if (hackManager == nullptr) hackManager = new HackManager();
return hackManager;
}
void kfw::core::Factory::cleanup()
{
delete hackManager;
delete hookManager;
}
|
/*
* .file advanced/spectra/visualisation.cpp
* .brief Implements the canvas responsible for document visualisation
*
* @author Matus Chochlik
*
* Copyright 2012-2013 Matus Chochlik. 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 <oglplus/gl.hpp>
#include "main_frame.hpp"
#include "visualisation.hpp"
#include "coroutine.hpp"
// SpectraVisDataUploader
class SpectraVisDataUploader
: public SpectraCoroutine
{
private:
wxGLContext* gl_context;
std::shared_ptr<std::set<wxGLCanvas*>> gl_canvases;
bool SetCurrent(void);
std::shared_ptr<SpectraCalculator> spectra_calc;
std::vector<unsigned> transform_ids;
std::shared_ptr<SpectraDocument> document;
std::size_t spectrum_size;
std::size_t current_row;
std::size_t row_count;
std::size_t rows_per_load;
oglplus::Buffer& spectrum_data;
std::vector<GLfloat> data_buf;
std::size_t QuerySpectrumValues(
float* buffer,
std::size_t bufsize,
std::size_t start_row,
std::size_t end_row
);
public:
SpectraVisDataUploader(
wxGLContext* context,
const std::shared_ptr<std::set<wxGLCanvas*>>& canvases,
const std::shared_ptr<SpectraCalculator>& calc,
const std::shared_ptr<SpectraDocument>& doc,
oglplus::Buffer& spect_data
);
wxString Description(void) const;
void Cancel(void);
bool DoWork(void);
int PercentDone(void) const;
};
SpectraVisDataUploader::SpectraVisDataUploader(
wxGLContext* context,
const std::shared_ptr<std::set<wxGLCanvas*>>& canvases,
const std::shared_ptr<SpectraCalculator>& calc,
const std::shared_ptr<SpectraDocument>& doc,
oglplus::Buffer& spect_data
): gl_context(context)
, gl_canvases(canvases)
, spectra_calc(calc)
, document(doc)
, current_row(0)
, spectrum_data(spect_data)
{
assert(gl_context);
assert(gl_canvases);
assert(document);
assert(spectra_calc);
assert(spectra_calc->MaxConcurrentTransforms() > 0);
transform_ids.resize(spectra_calc->MaxConcurrentTransforms());
spectrum_size = spectra_calc->OutputSize();
row_count = document->SignalSampleCount();
rows_per_load = 256*spectra_calc->MaxConcurrentTransforms();
if(row_count < spectrum_size)
row_count = 0;
else row_count -= spectrum_size;
data_buf.resize(spectrum_size*rows_per_load);
if(SetCurrent())
{
std::vector<GLfloat> init_data(spectrum_size*row_count, 0.0f);
spectrum_data.Bind(oglplus::Buffer::Target::Texture);
oglplus::Buffer::Data(oglplus::Buffer::Target::Texture, init_data);
}
}
std::size_t SpectraVisDataUploader::QuerySpectrumValues(
float* buffer,
std::size_t bufsize,
std::size_t start_row,
std::size_t end_row
)
{
std::size_t n = end_row-start_row;
std::size_t m = transform_ids.size();
assert(bufsize >= n*spectrum_size);
std::vector<float> signal(spectra_calc->InputSize()+n-1);
document->QuerySignalSamples(
signal.data(),
signal.size(),
start_row,
end_row+spectra_calc->InputSize()-1
);
spectra_calc->BeginBatch();
for(std::size_t i=0; i!=m; ++i)
{
transform_ids[i] = spectra_calc->BeginTransform(
signal.data()+i,
spectra_calc->InputSize(),
buffer+i*spectrum_size,
spectrum_size
);
}
for(std::size_t i=0; i!=n; ++i)
{
spectra_calc->FinishTransform(
transform_ids[i%m],
buffer+i*spectrum_size,
spectrum_size
);
std::size_t j=i+m;
if(j<n)
{
transform_ids[i%m] = spectra_calc->BeginTransform(
signal.data()+j,
spectra_calc->InputSize(),
buffer+j*spectrum_size,
spectrum_size
);
}
}
spectra_calc->FinishBatch();
return n;
}
bool SpectraVisDataUploader::SetCurrent(void)
{
assert(gl_canvases);
if(gl_canvases->empty()) return false;
wxGLCanvas* gl_canvas = *gl_canvases->begin();
assert(gl_canvas);
gl_canvas->SetCurrent(*gl_context);
return true;
}
wxString SpectraVisDataUploader::Description(void) const
{
return wxGetTranslation(wxT("Uploading spectrum data to GPU"));
}
void SpectraVisDataUploader::Cancel(void)
{
current_row = row_count;
}
bool SpectraVisDataUploader::DoWork(void)
{
if((current_row < row_count) && SetCurrent())
{
spectrum_data.Bind(oglplus::Buffer::Target::Texture);
std::size_t n = rows_per_load;
if(current_row+n > row_count)
n = row_count - current_row;
this->QuerySpectrumValues(
data_buf.data(),
data_buf.size(),
current_row,
current_row+n
);
spectrum_data.Bind(oglplus::Buffer::Target::Texture);
oglplus::Buffer::SubData(
oglplus::BufferTarget::Texture,
oglplus::BufferSize::Of<GLfloat>(spectrum_size*current_row),
spectrum_size*n,
data_buf.data()
);
current_row += n;
return false;
}
return true;
}
int SpectraVisDataUploader::PercentDone(void) const
{
return int((current_row*100)/row_count);
}
// SpectraGLContext
SpectraGLContext::SpectraGLContext(
wxGLCanvas* canvas,
wxGLContext* parent_ctxt
): wxGLContext(canvas, parent_ctxt)
{
canvas->SetCurrent(*this);
}
// SpectraVisualisation
SpectraVisualisation::SpectraVisualisation(
SpectraMainFrame* frame,
wxGLCanvas* canvas,
wxGLContext* parent_ctxt,
const std::shared_ptr<SpectraCalculator>& calculator,
const std::shared_ptr<SpectraDocument>& doc
): main_frame(frame)
, selected_time(0.0f)
, selection_begin(0.0f)
, selection_end(1.0f)
, gl_context(canvas, parent_ctxt)
, gl_canvases(std::make_shared<std::set<wxGLCanvas*>>())
, document(doc)
, signal_samples_per_grid(1)
{
assert(document);
assert(calculator);
spectrum_size = calculator->OutputSize();
std::size_t sps = Document().SamplesPerSecond();
std::size_t max = 4096;
if(sps / signal_samples_per_grid > max)
{
signal_samples_per_grid = 2;
while(sps / signal_samples_per_grid > max)
signal_samples_per_grid += 2;
}
assert(gl_canvases);
gl_canvases->insert(canvas);
std::shared_ptr<SpectraVisDataUploader> data_uploader(
std::make_shared<SpectraVisDataUploader>(
&gl_context,
gl_canvases,
calculator,
document,
spectrum_data
)
);
uploader_ref = data_uploader;
spectrum_tex.Bind(oglplus::Texture::Target::Buffer);
oglplus::Texture::Buffer(
oglplus::Texture::Target::Buffer,
oglplus::PixelDataInternalFormat::R32F,
spectrum_data
);
main_frame->StartCoroutine(data_uploader);
}
SpectraVisualisation::~SpectraVisualisation(void)
{
if(!uploader_ref.expired())
{
std::shared_ptr<SpectraVisDataUploader>
data_uploader(uploader_ref.lock());
if(data_uploader) data_uploader->Cancel();
}
}
void SpectraVisualisation::AddCanvas(wxGLCanvas* canvas)
{
gl_canvases->insert(canvas);
}
void SpectraVisualisation::RemoveCanvas(wxGLCanvas* canvas)
{
gl_canvases->erase(canvas);
}
wxGLContext& SpectraVisualisation::GLContext(void)
{
return gl_context;
}
oglplus::Reference<oglplus::Texture> SpectraVisualisation::SpectrumTex(void)
{
return spectrum_tex;
}
wxString SpectraVisualisation::Name(void)
{
return Document().Name();
}
const SpectraDocument& SpectraVisualisation::Document(void) const
{
assert(document);
return *document;
}
void SpectraVisualisation::Play(void)
{
assert(document);
document->Play(SelectionBegin(), SelectionEnd());
}
std::size_t SpectraVisualisation::SignalSpectrumSize(void) const
{
return spectrum_size;
}
std::size_t SpectraVisualisation::SignalSamplesPerGrid(void) const
{
return Document().SamplesPerSecond();
}
std::size_t SpectraVisualisation::SignalSamplesPerGridPatch(void) const
{
return signal_samples_per_grid;
}
std::size_t SpectraVisualisation::GridSamples(void) const
{
return SignalSamplesPerGrid() / SignalSamplesPerGridPatch();
}
void SpectraVisualisation::SelectedTime(float time)
{
selected_time = time;
}
float SpectraVisualisation::SelectedTime(void) const
{
return selected_time;
}
void SpectraVisualisation::DragSelection(float time, float delta)
{
float eps = (selection_end - selection_begin)*0.2;
if(time-delta <= selection_begin+eps)
{
selection_begin = time;
}
else if(time-delta >= selection_end-eps)
{
selection_end = time;
}
else
{
selection_begin += delta;
selection_end += delta;
}
if(selection_begin > selection_end)
selection_begin = selection_end;
if(selection_begin < 0.0f)
selection_begin = 0.0f;
if(selection_end > Document().MaxTime())
selection_end = Document().MaxTime();
}
float SpectraVisualisation::SelectionBegin(void) const
{
return selection_begin;
}
float SpectraVisualisation::SelectionEnd(void) const
{
return selection_end;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__strdup_wchar_t_33.cpp
Label Definition File: CWE401_Memory_Leak__strdup.label.xml
Template File: sources-sinks-33.tmpl.cpp
*/
/*
* @description
* CWE: 401 Memory Leak
* BadSource: Allocate data using wcsdup()
* GoodSource: Allocate data on the stack
* Sinks:
* GoodSink: call free() on data
* BadSink : no deallocation of data
* Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE401_Memory_Leak__strdup_wchar_t_33
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
wchar_t * &dataRef = data;
data = NULL;
{
wchar_t myString[] = L"myString";
/* POTENTIAL FLAW: Allocate memory from the heap using a function that requires free() for deallocation */
data = wcsdup(myString);
/* Use data */
printWLine(data);
}
{
wchar_t * data = dataRef;
/* POTENTIAL FLAW: No deallocation of memory */
/* no deallocation */
; /* empty statement needed for some flow variants */
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t * &dataRef = data;
data = NULL;
/* FIX: Use memory allocated on the stack with ALLOCA */
data = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
/* Initialize then use data */
wcscpy(data, L"a string");
printWLine(data);
{
wchar_t * data = dataRef;
/* POTENTIAL FLAW: No deallocation of memory */
/* no deallocation */
; /* empty statement needed for some flow variants */
}
}
/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
wchar_t * data;
wchar_t * &dataRef = data;
data = NULL;
{
wchar_t myString[] = L"myString";
/* POTENTIAL FLAW: Allocate memory from the heap using a function that requires free() for deallocation */
data = wcsdup(myString);
/* Use data */
printWLine(data);
}
{
wchar_t * data = dataRef;
/* FIX: Deallocate memory initialized in the source */
free(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 CWE401_Memory_Leak__strdup_wchar_t_33; /* 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
|
#include "3ds.hpp"
#include <iostream>
bool running = true;
int main(int argc, char* argv[]) {
RSGL::init();
RSGL::window topScreen = RSGL::createWindow(TOP_SCREEN, 0,0,SCREEN_WIDTH,SCREEN_LENGTH, {255,255,255});
Event e;
RSGL::color c = {255,0,0};
RSGL::rect r = {100,100,50,50};
while (running) {
e.CheckEvents();
if (RSGL::isPressed(KEY_START)){
running = false;
}
if (RSGL::isPressed(RK_Right)){r.x++;}
if (RSGL::isPressed(RK_Left)){r.x--;}
RSGL::InitWindow(topScreen);
RSGL::drawRect({200,200,25,25},{0,0,0},false);
RSGL::drawRect(r,c);
RSGL::RenderWindow(topScreen);
}
RSGL::Quit();
}
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchlib/query/tree/querybuilder.h>
#include <vespa/searchlib/query/tree/simplequery.h>
#include <vespa/searchlib/query/tree/stackdumpcreator.h>
#include <vespa/searchvisitor/querywrapper.h>
#include <iostream>
using namespace search;
using namespace search::query;
using namespace search::streaming;
namespace streaming {
class QueryWrapperTest : public vespalib::TestApp
{
private:
void testQueryWrapper();
public:
int Main() override;
};
void
QueryWrapperTest::testQueryWrapper()
{
QueryNodeResultFactory empty;
PhraseQueryNode * null = NULL;
{
QueryBuilder<SimpleQueryNodeTypes> builder;
builder.addAnd(3);
{
builder.addStringTerm("a", "", 0, Weight(0));
builder.addPhrase(3, "", 0, Weight(0));
{
builder.addStringTerm("b", "", 0, Weight(0));
builder.addStringTerm("c", "", 0, Weight(0));
builder.addStringTerm("d", "", 0, Weight(0));
}
builder.addStringTerm("e", "", 0, Weight(0));
}
Node::UP node = builder.build();
vespalib::string stackDump = StackDumpCreator::create(*node);
Query q(empty, stackDump);
QueryWrapper wrap(q);
QueryWrapper::TermList & tl = wrap.getTermList();
QueryTermList terms;
q.getLeafs(terms);
ASSERT_TRUE(tl.size() == 5 && terms.size() == 5);
for (size_t i = 0; i < 5; ++i) {
EXPECT_EQUAL(tl[i].getTerm(), terms[i]);
std::cout << "t[" << i << "]:" << terms[i] << std::endl;
}
QueryNodeRefList phrases;
q.getPhrases(phrases);
for (size_t i = 0; i < phrases.size(); ++i) {
std::cout << "p[" << i << "]:" << phrases[i] << std::endl;
}
EXPECT_EQUAL(phrases.size(), 1u);
ASSERT_TRUE(phrases.size() == 1);
EXPECT_EQUAL(tl[0].getParent(), null);
EXPECT_EQUAL(tl[1].getParent(), phrases[0]);
EXPECT_EQUAL(tl[2].getParent(), phrases[0]);
EXPECT_EQUAL(tl[3].getParent(), phrases[0]);
EXPECT_EQUAL(tl[4].getParent(), null);
EXPECT_EQUAL(tl[0].getIndex(), 0u);
EXPECT_EQUAL(tl[1].getIndex(), 0u);
EXPECT_EQUAL(tl[2].getIndex(), 1u);
EXPECT_EQUAL(tl[3].getIndex(), 2u);
EXPECT_EQUAL(tl[4].getIndex(), 0u);
EXPECT_TRUE(!tl[0].isFirstPhraseTerm());
EXPECT_TRUE( tl[1].isFirstPhraseTerm());
EXPECT_TRUE(!tl[2].isFirstPhraseTerm());
EXPECT_TRUE(!tl[3].isFirstPhraseTerm());
EXPECT_TRUE(!tl[4].isFirstPhraseTerm());
EXPECT_TRUE(!tl[0].isPhraseTerm());
EXPECT_TRUE( tl[1].isPhraseTerm());
EXPECT_TRUE( tl[2].isPhraseTerm());
EXPECT_TRUE( tl[3].isPhraseTerm());
EXPECT_TRUE(!tl[4].isPhraseTerm());
EXPECT_EQUAL(tl[0].getPosAdjust(), 0u);
EXPECT_EQUAL(tl[1].getPosAdjust(), 2u);
EXPECT_EQUAL(tl[2].getPosAdjust(), 2u);
EXPECT_EQUAL(tl[3].getPosAdjust(), 2u);
EXPECT_EQUAL(tl[4].getPosAdjust(), 0u);
}
}
int
QueryWrapperTest::Main()
{
TEST_INIT("querywrapper_test");
testQueryWrapper();
TEST_DONE();
}
} // namespace streaming
TEST_APPHOOK(::streaming::QueryWrapperTest)
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "openvino/op/util/framework_node.hpp"
#include <gtest/gtest.h>
#include "openvino/opsets/opset8.hpp"
#include "util/type_prop.hpp"
using namespace std;
TEST(type_prop, framework_node) {
auto param = std::make_shared<ov::opset8::Parameter>(ov::element::i64, ov::Shape{1, 64});
auto f_node = std::make_shared<ov::op::util::FrameworkNode>(ov::OutputVector{param});
f_node->set_output_type(0, ov::element::i64, ov::Shape{1, 64});
// Set partially dynamic shape
param->set_partial_shape(ov::PartialShape{ov::Dimension::dynamic(), 64});
param->validate_and_infer_types();
ASSERT_NO_THROW(f_node->validate_and_infer_types());
ASSERT_EQ(f_node->get_output_partial_shape(0), ov::PartialShape::dynamic());
// Set dynamic shape
param->set_partial_shape(ov::PartialShape::dynamic(2));
param->validate_and_infer_types();
ASSERT_NO_THROW(f_node->validate_and_infer_types());
ASSERT_EQ(f_node->get_output_partial_shape(0), ov::PartialShape::dynamic());
// Set fully dynamic shape
param->set_partial_shape(ov::PartialShape::dynamic());
param->validate_and_infer_types();
ASSERT_NO_THROW(f_node->validate_and_infer_types());
ASSERT_EQ(f_node->get_output_partial_shape(0), ov::PartialShape::dynamic());
// Set original static shape
param->set_partial_shape(ov::Shape{1, 64});
param->validate_and_infer_types();
ASSERT_NO_THROW(f_node->validate_and_infer_types());
ASSERT_EQ(f_node->get_output_partial_shape(0), ov::PartialShape({1, 64}));
// Set different static shape
param->set_partial_shape(ov::Shape{2, 64});
param->validate_and_infer_types();
ASSERT_THROW(f_node->validate_and_infer_types(), ov::Exception);
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2014, Itseez Inc, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not 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 Itseez Inc or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef OPENCV_DATASETS_OR_MNIST_HPP
#define OPENCV_DATASETS_OR_MNIST_HPP
#include <string>
#include <vector>
#include "opencv2/datasets/dataset.hpp"
#include <opencv2/core.hpp>
namespace cv
{
namespace datasets
{
//! @addtogroup datasets_or
//! @{
struct OR_mnistObj : public Object
{
char label; // 0..9
Mat image; // [28][28]
};
class CV_EXPORTS OR_mnist : public Dataset
{
public:
virtual void load(const std::string &path) = 0;
static Ptr<OR_mnist> create();
};
//! @}
}
}
#endif
|
// Copyright 2006-2019 Flenniken
// All Rights Reserved.
#include "stdafx.h"
#include "people.h"
#include "Klondike.h"
#include <vector>
#include "Game.h"
#include <shlwapi.h>
#include <gdiplus.h>
#include "Stats.h"
#include "Options.h"
#include <WindowsX.h>
#include "Utils.h"
#include <commctrl.h>
#include <algorithm>
#include "SolitaireIniFile.h"
#include "DrawUtils.h"
class Options
{
public:
Options();
~Options();
bool ShowDialog(bool &dealOneAtATime, bool &allowPartialPileMoves, bool &oneTimeThrough);
void ReadOptions();
void WriteOptions();
void GetOptions(bool &dealOneAtATime, bool &allowPartialPileMoves, bool &oneTimeThrough) const;
private:
static INT_PTR CALLBACK OptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
void InitializeDialog(HWND hDlg);
void SaveData(HWND hDlg);
bool fDealOneAtATime;
bool fAllowPartialPileMoves;
bool fOneTimeThrough;
bool fUserCanceled;
};
Options gOptions;
extern HWND gMainWindow;
extern HINSTANCE gInstance;
static int32 gX = -1; // Last position of dialog.
static int32 gY = -1;
static TCHAR gDealOneAtATimeStr[] = _T("Deal One At a Time");
static TCHAR gAllowPartialPileMovesStr[] = _T("Allow Partial Pile Moves");
static TCHAR gOneTimeThrough[] = _T("One Time Through");
static INT_PTR CALLBACK OptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
static void PositionDialog(HWND hDlg);
static void RememberPosition(HWND hDlg);
// Show the dialog and return true when the user cancels.
bool OptionsUtils::ShowDialog(bool &dealOneAtATime, bool &allowPartialPileMoves, bool &oneTimeThrough)
{
return gOptions.ShowDialog(dealOneAtATime, allowPartialPileMoves, oneTimeThrough);
}
void OptionsUtils::ReadOptions()
{
gOptions.ReadOptions();
}
void OptionsUtils::WriteOptions()
{
gOptions.WriteOptions();
}
void OptionsUtils::GetOptions(bool &dealOneAtATime, bool &allowPartialPileMoves, bool &oneTimeThrough)
{
gOptions.GetOptions(dealOneAtATime, allowPartialPileMoves, oneTimeThrough);
}
Options::Options() :
fDealOneAtATime(true),
fAllowPartialPileMoves(true),
fOneTimeThrough(true)
{
}
Options::~Options()
{
}
bool Options::ShowDialog(bool &dealOneAtATime, bool &allowPartialPileMoves, bool &oneTimeThrough)
{
gOptions.fDealOneAtATime = dealOneAtATime;
gOptions.fAllowPartialPileMoves = allowPartialPileMoves;
gOptions.fOneTimeThrough = oneTimeThrough;
DialogBox(gInstance, MAKEINTRESOURCE(IDD_OPTIONS), gMainWindow, OptionsDialog);
dealOneAtATime = gOptions.fDealOneAtATime;
allowPartialPileMoves = gOptions.fAllowPartialPileMoves;
oneTimeThrough = gOptions.fOneTimeThrough;
return gOptions.fUserCanceled;
}
INT_PTR CALLBACK Options::OptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
gOptions.InitializeDialog(hDlg);
return (INT_PTR)true;
}
case WM_DRAWITEM:
switch (wParam)
{
case kPictureControl:
DrawUtils::PaintControlPicture(hDlg, ((LPDRAWITEMSTRUCT)lParam)->hDC, kPictureControl, Card::kHearts);
break;
}
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
gOptions.SaveData(hDlg);
// fall thru
case IDCANCEL:
RememberPosition(hDlg);
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
}
void Options::InitializeDialog(HWND hDlg)
{
fUserCanceled = true;
// Select the current options.
Button_SetCheck(GetDlgItem(hDlg, fDealOneAtATime ? IDC_ONEATATIME : IDC_THREEATATIME), true);
Button_SetCheck(GetDlgItem(hDlg, fAllowPartialPileMoves ? IDC_ALLOWPARTIALPILEMOVES : IDC_ANYCARD), true);
Button_SetCheck(GetDlgItem(hDlg, fOneTimeThrough ? IDC_ONETIME : IDC_MULTIPLETIMES), true);
// Position the dialog at the last place it was.
PositionDialog(hDlg);
}
void PositionDialog(HWND hDlg)
{
if (gX == -1)
Utils::CenterWindow(hDlg);
else
{
RECT rect;
GetWindowRect(hDlg, &rect);
MoveWindow(hDlg, gX, gY, rect.right-rect.left, rect.bottom-rect.top, false);
}
}
void RememberPosition(HWND hDlg)
{
RECT rect;
GetWindowRect(hDlg, &rect);
gX = rect.left;
gY = rect.top;
}
void Options::SaveData(HWND hDlg)
{
fDealOneAtATime = (Button_GetState(GetDlgItem(hDlg, IDC_ONEATATIME))) ? true : false;
fAllowPartialPileMoves = (Button_GetState(GetDlgItem(hDlg, IDC_ALLOWPARTIALPILEMOVES))) ? true : false;
fOneTimeThrough = (Button_GetState(GetDlgItem(hDlg, IDC_ONETIME))) ? true : false;
fUserCanceled = false;
}
void Options::ReadOptions()
{
IniFileAccess *iniFileAccess = SolitaireIniFile::GetIniFileAccess();
iniFileAccess->GetBoolean(gDealOneAtATimeStr, fDealOneAtATime);
iniFileAccess->GetBoolean(gAllowPartialPileMovesStr, fAllowPartialPileMoves);
iniFileAccess->GetBoolean(gOneTimeThrough, fOneTimeThrough);
}
void Options::WriteOptions()
{
IniFileAccess *iniFileAccess = SolitaireIniFile::GetIniFileAccess();
iniFileAccess->SetBoolean(gDealOneAtATimeStr, fDealOneAtATime);
iniFileAccess->SetBoolean(gAllowPartialPileMovesStr, fAllowPartialPileMoves);
iniFileAccess->SetBoolean(gOneTimeThrough, fOneTimeThrough);
}
void Options::GetOptions(bool &dealOneAtATime, bool &allowPartialPileMoves, bool &oneTimeThrough) const
{
dealOneAtATime = fDealOneAtATime;
allowPartialPileMoves = fAllowPartialPileMoves;
oneTimeThrough = fOneTimeThrough;
}
|
/* mbed Microcontroller Library
* Copyright (c) 2018-2020 ARM Limited
* 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.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS //Required for PRIu64
#endif
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "mbed_trace.h"
#include <inttypes.h>
#include <stdlib.h>
#include "BufferedBlockDevice.h"
#include "BlockDevice.h"
#include <algorithm>
#if COMPONENT_SPIF
#include "SPIFBlockDevice.h"
#endif
#if COMPONENT_QSPIF
#include "QSPIFBlockDevice.h"
#endif
#if COMPONENT_OSPIF
#include "OSPIFBlockDevice.h"
#endif
#if COMPONENT_DATAFLASH
#include "DataFlashBlockDevice.h"
#endif
#if COMPONENT_SD
#include "SDBlockDevice.h"
#endif
#if COMPONENT_FLASHIAP
#include "FlashIAPBlockDevice.h"
#endif
// Debug available
#ifndef MODE_DEBUG
#define MODE_DEBUG 0
#endif
#if MODE_DEBUG
#define DEBUG_PRINTF(...) printf(__VA_ARGS__)
#else
#define DEBUG_PRINTF(...)
#endif
using namespace utest::v1;
#define TEST_BLOCK_COUNT 10
#define TEST_ERROR_MASK 16
#define TEST_NUM_OF_THREADS 5
#define TEST_THREAD_STACK_SIZE 1152
uint8_t num_of_sectors = TEST_NUM_OF_THREADS * TEST_BLOCK_COUNT;
uint32_t sectors_addr[TEST_NUM_OF_THREADS * TEST_BLOCK_COUNT] = {0};
bd_size_t max_sector_size = 0;
const struct {
const char *name;
bd_size_t (BlockDevice::*method)() const;
} ATTRS[] = {
{"read size", &BlockDevice::get_read_size},
{"program size", &BlockDevice::get_program_size},
{"erase size", &BlockDevice::get_erase_size},
{"total size", &BlockDevice::size},
};
enum bd_type {
spif = 0,
qspif,
dataflash,
sd,
flashiap,
ospif,
default_bd
};
uint8_t bd_arr[6] = {0};
static uint8_t test_iteration = 0;
static SingletonPtr<PlatformMutex> _mutex;
BlockDevice *block_device = NULL;
#if COMPONENT_FLASHIAP
static inline uint32_t align_up(uint32_t val, uint32_t size)
{
return (((val - 1) / size) + 1) * size;
}
#endif
static BlockDevice *get_bd_instance(uint8_t bd_type)
{
switch (bd_arr[bd_type]) {
case spif: {
#if COMPONENT_SPIF
static SPIFBlockDevice default_bd(
MBED_CONF_SPIF_DRIVER_SPI_MOSI,
MBED_CONF_SPIF_DRIVER_SPI_MISO,
MBED_CONF_SPIF_DRIVER_SPI_CLK,
MBED_CONF_SPIF_DRIVER_SPI_CS,
MBED_CONF_SPIF_DRIVER_SPI_FREQ
);
return &default_bd;
#endif
break;
}
case qspif: {
#if COMPONENT_QSPIF
static QSPIFBlockDevice default_bd(
MBED_CONF_QSPIF_QSPI_IO0,
MBED_CONF_QSPIF_QSPI_IO1,
MBED_CONF_QSPIF_QSPI_IO2,
MBED_CONF_QSPIF_QSPI_IO3,
MBED_CONF_QSPIF_QSPI_SCK,
MBED_CONF_QSPIF_QSPI_CSN,
MBED_CONF_QSPIF_QSPI_POLARITY_MODE,
MBED_CONF_QSPIF_QSPI_FREQ
);
return &default_bd;
#endif
break;
}
case ospif: {
#if COMPONENT_OSPIF
static OSPIFBlockDevice default_bd(
MBED_CONF_OSPIF_OSPI_IO0,
MBED_CONF_OSPIF_OSPI_IO1,
MBED_CONF_OSPIF_OSPI_IO2,
MBED_CONF_OSPIF_OSPI_IO3,
MBED_CONF_OSPIF_OSPI_IO4,
MBED_CONF_OSPIF_OSPI_IO5,
MBED_CONF_OSPIF_OSPI_IO6,
MBED_CONF_OSPIF_OSPI_IO7,
MBED_CONF_OSPIF_OSPI_SCK,
MBED_CONF_OSPIF_OSPI_CSN,
MBED_CONF_OSPIF_OSPI_DQS,
MBED_CONF_OSPIF_OSPI_POLARITY_MODE,
MBED_CONF_OSPIF_OSPI_FREQ
);
return &default_bd;
#endif
break;
}
case dataflash: {
#if COMPONENT_DATAFLASH
static DataFlashBlockDevice default_bd(
MBED_CONF_DATAFLASH_SPI_MOSI,
MBED_CONF_DATAFLASH_SPI_MISO,
MBED_CONF_DATAFLASH_SPI_CLK,
MBED_CONF_DATAFLASH_SPI_CS
);
return &default_bd;
#endif
break;
}
case sd: {
#if COMPONENT_SD
static SDBlockDevice default_bd(
MBED_CONF_SD_SPI_MOSI,
MBED_CONF_SD_SPI_MISO,
MBED_CONF_SD_SPI_CLK,
MBED_CONF_SD_SPI_CS
);
return &default_bd;
#endif
break;
}
case flashiap: {
#if COMPONENT_FLASHIAP
#if (MBED_CONF_FLASHIAP_BLOCK_DEVICE_SIZE == 0) && (MBED_CONF_FLASHIAP_BLOCK_DEVICE_BASE_ADDRESS == 0xFFFFFFFF)
size_t flash_size;
uint32_t start_address;
uint32_t bottom_address;
mbed::FlashIAP flash;
int ret = flash.init();
if (ret != 0) {
return NULL;
}
//Find the start of first sector after text area
bottom_address = align_up(FLASHIAP_APP_ROM_END_ADDR, flash.get_sector_size(FLASHIAP_APP_ROM_END_ADDR));
start_address = flash.get_flash_start();
flash_size = flash.get_flash_size();
ret = flash.deinit();
static FlashIAPBlockDevice default_bd(bottom_address, start_address + flash_size - bottom_address);
#else
static FlashIAPBlockDevice default_bd;
#endif
return &default_bd;
#endif
break;
}
}
return NULL;
}
// Mutex is protecting rand() per srand for buffer writing and verification.
// Mutex is also protecting printouts for clear logs.
// Mutex is NOT protecting Block Device actions: erase/program/read - which is the purpose of the multithreaded test!
void basic_erase_program_read_test(BlockDevice *block_device, bd_size_t block_size, uint8_t *write_block,
uint8_t *read_block, unsigned addrwidth, int thread_num)
{
int err = 0;
_mutex->lock();
// Make sure block address per each test is unique
static unsigned block_seed = 1;
srand(block_seed++);
// Find a random block
bd_addr_t block = sectors_addr[thread_num];
bd_size_t curr_block_size = block_device->get_erase_size(block);
block_size = std::min(block_size, curr_block_size);
// Use next random number as temporary seed to keep
// the address progressing in the pseudorandom sequence
unsigned seed = rand();
// Fill with random sequence
srand(seed);
for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) {
write_block[i_ind] = 0xff & rand();
}
// Write, sync, and read the block
DEBUG_PRINTF("test %0*llx:%llu...\n", addrwidth, block, curr_block_size);
err = block_device->erase(block, curr_block_size);
TEST_ASSERT_EQUAL(0, err);
err = block_device->program(write_block, block, block_size);
TEST_ASSERT_EQUAL(0, err);
err = block_device->read(read_block, block, block_size);
TEST_ASSERT_EQUAL(0, err);
// Check that the data was unmodified
srand(seed);
int val_rand;
for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) {
val_rand = rand();
if ((0xff & val_rand) != read_block[i_ind]) {
utest_printf("\n Assert Failed Buf Read - block:size: %llx:%llu \n", block, block_size);
utest_printf("\n pos: %llu, exp: %02x, act: %02x, wrt: %02x \n", i_ind, (0xff & val_rand),
read_block[i_ind],
write_block[i_ind]);
}
TEST_ASSERT_EQUAL(0xff & val_rand, read_block[i_ind]);
}
_mutex->unlock();
}
void test_init_bd()
{
utest_printf("\nTest Init block device.\n");
block_device = get_bd_instance(test_iteration);
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
int err = block_device->init();
TEST_ASSERT_EQUAL(0, err);
bd_addr_t start_address = 0;
bd_size_t curr_sector_size = 0;
uint8_t i = 0;
for (; i < num_of_sectors && start_address < block_device->size(); i++) {
sectors_addr[i] = start_address;
curr_sector_size = block_device->get_erase_size(start_address);
DEBUG_PRINTF("start_address = 0x%llx, sector_size = %d\n", start_address, curr_sector_size);
if (curr_sector_size > max_sector_size) {
max_sector_size = curr_sector_size;
}
start_address += curr_sector_size;
}
num_of_sectors = i;
}
void test_random_program_read_erase()
{
utest_printf("\nTest Random Program Read Erase Starts..\n");
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) {
static const char *prefixes[] = {"", "k", "M", "G"};
for (int i_ind = 3; i_ind >= 0; i_ind--) {
bd_size_t size = (block_device->*ATTRS[atr].method)();
if (size >= (1ULL << 10 * i_ind)) {
utest_printf("%s: %llu%sbytes (%llubytes)\n",
ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size);
break;
}
}
}
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
uint8_t *write_buffer = new (std::nothrow) uint8_t[max_sector_size];
uint8_t *read_buffer = new (std::nothrow) uint8_t[max_sector_size];
if (!write_buffer || !read_buffer) {
utest_printf("Not enough memory for test\n");
goto end;
}
for (int b = 0; b < std::min((uint8_t)TEST_BLOCK_COUNT, num_of_sectors); b++) {
// basic_erase_program_read_test() can handle non-uniform sector sizes
// and use only part of the buffers if the sector is smaller
basic_erase_program_read_test(block_device, max_sector_size, write_buffer, read_buffer, addrwidth, b);
}
end:
delete[] read_buffer;
delete[] write_buffer;
}
#if defined(MBED_CONF_RTOS_PRESENT)
static void test_thread_job()
{
static int thread_num = 0;
_mutex->lock();
int block_num = thread_num++ % TEST_NUM_OF_THREADS;
_mutex->unlock();
uint8_t sector_per_thread = (num_of_sectors / TEST_NUM_OF_THREADS);
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
uint8_t *write_buffer = new (std::nothrow) uint8_t[max_sector_size];
uint8_t *read_buffer = new (std::nothrow) uint8_t[max_sector_size];
if (!write_buffer || !read_buffer) {
// Some targets have sectors up to 256KB each and a relatively small RAM.
// This test may not be able to run in this case.
utest_printf("Not enough memory for test, is the sector size (%llu) too big?\n", max_sector_size);
goto end;
}
for (int b = 0; b < sector_per_thread; b++) {
// basic_erase_program_read_test() can handle non-uniform sector sizes
// and use only part of the buffers if the sector is smaller
basic_erase_program_read_test(block_device, max_sector_size, write_buffer, read_buffer, addrwidth, block_num * sector_per_thread + b);
}
end:
delete[] read_buffer;
delete[] write_buffer;
}
void test_multi_threads()
{
utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n");
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) {
static const char *prefixes[] = {"", "k", "M", "G"};
for (int i_ind = 3; i_ind >= 0; i_ind--) {
bd_size_t size = (block_device->*ATTRS[atr].method)();
if (size >= (1ULL << 10 * i_ind)) {
utest_printf("%s: %llu%sbytes (%llubytes)\n",
ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size);
break;
}
}
}
osStatus threadStatus;
int i_ind, j_ind;
char *dummy;
rtos::Thread **bd_thread = new (std::nothrow) rtos::Thread*[TEST_NUM_OF_THREADS];
TEST_SKIP_UNLESS_MESSAGE((*bd_thread) != NULL, "not enough heap to run test.");
memset(bd_thread, 0, TEST_NUM_OF_THREADS * sizeof(rtos::Thread *));
for (i_ind = 0; i_ind < TEST_NUM_OF_THREADS; i_ind++) {
bd_thread[i_ind] = new (std::nothrow) rtos::Thread((osPriority_t)((int)osPriorityNormal), TEST_THREAD_STACK_SIZE);
dummy = new (std::nothrow) char[TEST_THREAD_STACK_SIZE];
if (!bd_thread[i_ind] || !dummy) {
utest_printf("Not enough heap to run Thread %d !\n", i_ind + 1);
break;
}
delete[] dummy;
threadStatus = bd_thread[i_ind]->start(callback(test_thread_job));
if (threadStatus != 0) {
utest_printf("Thread %d Start Failed!\n", i_ind + 1);
break;
}
}
for (j_ind = 0; j_ind < i_ind; j_ind++) {
bd_thread[j_ind]->join();
}
if (bd_thread) {
for (j_ind = 0; j_ind < i_ind; j_ind++) {
delete bd_thread[j_ind];
}
delete[] bd_thread;
}
}
#endif
void test_erase_functionality()
{
utest_printf("\nTest BlockDevice::get_erase_value()..\n");
// Test flow:
// 1. Write data to selected region
// - Known starting point
// 2. Erase selected region
// 3. Read erased region and compare with get_erase_value()
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
// Check erase value
int erase_value_int = block_device->get_erase_value();
TEST_SKIP_UNLESS_MESSAGE(erase_value_int >= 0, "Erase not supported in this block device. Test skipped.");
// Assuming that get_erase_value() returns byte value as documentation mentions
// "If get_erase_value() returns a non-negative byte value" for unknown case.
TEST_ASSERT(erase_value_int <= 255);
uint8_t erase_value = (uint8_t)erase_value_int;
// Determine start_address
bd_addr_t start_address = sectors_addr[rand() % num_of_sectors];
utest_printf("start_address=0x%016" PRIx64 "\n", start_address);
// Determine data_buf_size
bd_size_t erase_size = block_device->get_erase_size(start_address);
TEST_ASSERT(erase_size > 0);
bd_size_t data_buf_size = erase_size;
// Allocate buffer for write test data
uint8_t *data_buf = new (std::nothrow) uint8_t[data_buf_size];
TEST_SKIP_UNLESS_MESSAGE(data_buf != NULL, "Not enough memory for test");
// Allocate buffer for read test data
uint8_t *out_data_buf = new (std::nothrow) uint8_t[data_buf_size];
TEST_SKIP_UNLESS_MESSAGE(out_data_buf != NULL, "Not enough memory for test");
// First must Erase given memory region
utest_printf("erasing given memory region\n");
int err = block_device->erase(start_address, data_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Write random data to selected region to make sure data is not accidentally set to "erased" value.
// With this pre-write, the test case will fail even if block_device->erase() is broken.
for (bd_size_t i = 0; i < data_buf_size; i++) {
data_buf[i] = (uint8_t) rand();
}
utest_printf("writing given memory region\n");
err = block_device->program((const void *)data_buf, start_address, data_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Read written memory region to verify it contains information
memset(out_data_buf, 0, data_buf_size);
utest_printf("reading written memory region\n");
err = block_device->read((void *)out_data_buf, start_address, data_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Verify erased memory region
utest_printf("verifying written memory region\n");
for (bd_size_t i = 0; i < data_buf_size; i++) {
TEST_ASSERT_EQUAL(out_data_buf[i], data_buf[i]);
}
// Erase given memory region
utest_printf("erasing written memory region\n");
err = block_device->erase(start_address, data_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Read erased memory region
utest_printf("reading erased memory region\n");
memset(out_data_buf, 0, data_buf_size);
err = block_device->read((void *)out_data_buf, start_address, data_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Verify erased memory region
utest_printf("verifying erased memory region\n");
for (bd_size_t i = 0; i < data_buf_size; i++) {
TEST_ASSERT_EQUAL(erase_value, out_data_buf[i]);
}
delete[] out_data_buf;
delete[] data_buf;
}
void test_contiguous_erase_write_read()
{
utest_printf("\nTest Contiguous Erase/Program/Read Starts..\n");
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
// Test flow:
// 1. Erase whole test area
// - Tests contiguous erase
// 2. Write smaller memory area
// - Tests contiguous sector writes
// 3. Return step 2 for whole erase region
// Test parameters
bd_size_t program_size = block_device->get_program_size();
TEST_ASSERT(program_size > 0);
utest_printf("program_size=%" PRId64 "\n", program_size);
utest_printf("block_device->size()=%" PRId64 "\n", block_device->size());
// Determine start_address & stop_address
uint8_t sector_num = rand() % (num_of_sectors - 2);
bd_addr_t start_address = sectors_addr[sector_num];
bd_addr_t stop_address = sectors_addr[sector_num + 2];
utest_printf("start_address=0x%016" PRIx64 "\n", start_address);
utest_printf("stop_address=0x%016" PRIx64 "\n", stop_address);
bd_size_t contiguous_erase_size = stop_address - start_address;
TEST_ASSERT(contiguous_erase_size > 0);
utest_printf("contiguous_erase_size=0x%" PRIx64 "\n", contiguous_erase_size);
bd_size_t write_read_buf_size = program_size;
// Reading/writing in larger chunks reduces the number of operations,
// helping to avoid test timeouts. Try 256-byte chunks if contiguous_erase_size
// (which should be a power of 2) is greater than that. If it's less than
// that, the test finishes quickly anyway...
if ((program_size < 256) && (256 % program_size == 0)
&& (contiguous_erase_size >= 256) && (contiguous_erase_size % 256 == 0)) {
utest_printf("using 256-byte write/read buffer\n");
write_read_buf_size = 256;
}
// Allocate write/read buffer
uint8_t *write_read_buf = new (std::nothrow) uint8_t[write_read_buf_size];
TEST_SKIP_UNLESS_MESSAGE(contiguous_erase_size, "Not enough memory for test.\n");
// Must Erase the whole region first
utest_printf("erasing memory, from 0x%" PRIx64 " of size 0x%" PRIx64 "\n", start_address, contiguous_erase_size);
int err = block_device->erase(start_address, contiguous_erase_size);
TEST_ASSERT_EQUAL(0, err);
// Pre-fill the to-be-erased region. By pre-filling the region,
// we can be sure the test will not pass if the erase doesn't work.
for (bd_size_t offset = 0; start_address + offset < stop_address; offset += write_read_buf_size) {
for (size_t i = 0; i < write_read_buf_size; i++) {
write_read_buf[i] = (uint8_t)rand();
}
DEBUG_PRINTF("pre-filling memory, from 0x%" PRIx64 " of size 0x%" PRIx64 "", start_address + offset,
write_read_buf_size);
err = block_device->program((const void *)write_read_buf, start_address + offset, write_read_buf_size);
TEST_ASSERT_EQUAL(0, err);
}
// Erase the whole region again
utest_printf("erasing memory, from 0x%" PRIx64 " of size 0x%" PRIx64 "\n", start_address, contiguous_erase_size);
err = block_device->erase(start_address, contiguous_erase_size);
TEST_ASSERT_EQUAL(0, err);
// Loop through all write/read regions
int region = 0;
for (; start_address < stop_address; start_address += write_read_buf_size) {
// Generate test data
unsigned int seed = rand();
srand(seed);
for (size_t i = 0; i < write_read_buf_size; i++) {
write_read_buf[i] = (uint8_t)rand();
}
// Write test data
err = block_device->program((const void *)write_read_buf, start_address, write_read_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Read test data
memset(write_read_buf, 0, (size_t)write_read_buf_size);
err = block_device->read(write_read_buf, start_address, write_read_buf_size);
TEST_ASSERT_EQUAL(0, err);
// Verify read data
srand(seed);
for (size_t i = 0; i < write_read_buf_size; i++) {
uint8_t expected_value = (uint8_t)rand();
if (write_read_buf[i] != expected_value) {
utest_printf("data verify failed, write_read_buf[%d]=%" PRIu8 " and not %" PRIu8 "\n",
i, write_read_buf[i], expected_value);
}
TEST_ASSERT_EQUAL(write_read_buf[i], expected_value);
}
}
free(write_read_buf);
}
void test_program_read_small_data_sizes()
{
utest_printf("\nTest program-read small data sizes, from 1 to 7 bytes..\n");
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
bd_size_t program_size = block_device->get_program_size();
bd_size_t read_size = block_device->get_read_size();
TEST_ASSERT(program_size > 0);
// See that we have enough memory for buffered block device
char *dummy = new (std::nothrow) char[program_size + read_size];
TEST_SKIP_UNLESS_MESSAGE(dummy, "Not enough memory for test.\n");
delete[] dummy;
// use BufferedBlockDevice for better handling of block devices program and read
BufferedBlockDevice *buff_block_device = new BufferedBlockDevice(block_device);
// BlockDevice initialization
int err = buff_block_device->init();
TEST_ASSERT_EQUAL(0, err);
const char write_buffer[] = "1234567";
char read_buffer[7] = {};
// Determine starting address
bd_addr_t start_address = 0;
bd_size_t erase_size = block_device->get_erase_size(start_address);
for (int i = 1; i <= 7; i++) {
err = buff_block_device->erase(start_address, erase_size);
TEST_ASSERT_EQUAL(0, err);
err = buff_block_device->program((const void *)write_buffer, start_address, i);
TEST_ASSERT_EQUAL(0, err);
err = buff_block_device->sync();
TEST_ASSERT_EQUAL(0, err);
err = buff_block_device->read(read_buffer, start_address, i);
TEST_ASSERT_EQUAL(0, err);
err = memcmp(write_buffer, read_buffer, i);
TEST_ASSERT_EQUAL(0, err);
}
// BlockDevice deinitialization
err = buff_block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
delete buff_block_device;
}
void test_unaligned_erase_blocks()
{
utest_printf("\nTest Unaligned Erase Starts..\n");
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
TEST_SKIP_UNLESS_MESSAGE(block_device->get_erase_value() != -1, "block device has no erase functionality.");
bd_addr_t addr = 0;
bd_size_t sector_erase_size = block_device->get_erase_size(addr);
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
utest_printf("\ntest %0*llx:%llu...", addrwidth, addr, sector_erase_size);
//unaligned start address
addr += 1;
int err = block_device->erase(addr, sector_erase_size - 1);
TEST_ASSERT_NOT_EQUAL(0, err);
err = block_device->erase(addr, sector_erase_size);
TEST_ASSERT_NOT_EQUAL(0, err);
err = block_device->erase(addr, 1);
TEST_ASSERT_NOT_EQUAL(0, err);
//unaligned end address
addr = 0;
err = block_device->erase(addr, 1);
TEST_ASSERT_NOT_EQUAL(0, err);
err = block_device->erase(addr, sector_erase_size + 1);
TEST_ASSERT_NOT_EQUAL(0, err);
//erase size exceeds flash device size
err = block_device->erase(addr, block_device->size() + 1);
TEST_ASSERT_NOT_EQUAL(0, err);
// Valid erase
err = block_device->erase(addr, sector_erase_size);
TEST_ASSERT_EQUAL(0, err);
}
void test_deinit_bd()
{
utest_printf("\nTest deinit block device.\n");
test_iteration++;
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
int err = block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
block_device = NULL;
}
void test_write_deinit_init()
{
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
// Determine start_address & stop_address
bd_addr_t addr = sectors_addr[rand() % num_of_sectors];
bd_size_t erase_size = block_device->get_erase_size(addr);
bd_size_t prog_size = block_device->get_program_size();
uint8_t *prog = (uint8_t *) malloc(prog_size);
TEST_ASSERT_NOT_EQUAL(prog, 0);
uint8_t *buf = (uint8_t *) malloc(prog_size);
TEST_ASSERT_NOT_EQUAL(buf, 0);
for (int i = 0; i < 3; i++) {
// Generate test pattern
for (int j = 0; j < prog_size; j++) {
prog[j] = (uint8_t)'0' + i + j;
}
int err;
err = block_device->erase(addr, erase_size);
TEST_ASSERT_EQUAL(err, 0);
err = block_device->program(prog, addr, prog_size);
TEST_ASSERT_EQUAL(err, 0);
err = block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
err = block_device->init();
TEST_ASSERT_EQUAL(0, err);
err = block_device->read(buf, addr, prog_size);
TEST_ASSERT_EQUAL(0, memcmp(prog, buf, prog_size));
}
free(prog);
free(buf);
}
void test_get_type_functionality()
{
utest_printf("\nTest get blockdevice type..\n");
block_device = BlockDevice::get_default_instance();
TEST_SKIP_UNLESS_MESSAGE(block_device != NULL, "no block device found.");
const char *bd_type = block_device->get_type();
TEST_ASSERT_NOT_EQUAL(0, bd_type);
#if COMPONENT_QSPIF
TEST_ASSERT_EQUAL(0, strcmp(bd_type, "QSPIF"));
#elif COMPONENT_OSPIF
TEST_ASSERT_EQUAL(0, strcmp(bd_type, "OSPIF"));
#elif COMPONENT_SPIF
TEST_ASSERT_EQUAL(0, strcmp(bd_type, "SPIF"));
#elif COMPONENT_DATAFLASH
TEST_ASSERT_EQUAL(0, strcmp(bd_type, "DATAFLASH"));
#elif COMPONENT_SD
TEST_ASSERT_EQUAL(0, strcmp(bd_type, "SD"));
#elif COMPONENT_FLASHIAP
TEST_ASSERT_EQUAL(0, strcmp(bd_type, "FLASHIAP"));
#endif
}
utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason)
{
greentea_case_failure_abort_handler(source, reason);
return STATUS_CONTINUE;
}
typedef struct {
const char *description;
const case_handler_t case_handler;
const case_failure_handler_t failure_handler;
} template_case_t;
template_case_t template_cases[] = {
{"Testing Init block device", test_init_bd, greentea_failure_handler},
{"Testing write -> deinit -> init -> read", test_write_deinit_init, greentea_failure_handler},
{"Testing read write random blocks", test_random_program_read_erase, greentea_failure_handler},
#if defined(MBED_CONF_RTOS_PRESENT)
{"Testing multi threads erase program read", test_multi_threads, greentea_failure_handler},
#endif
{"Testing contiguous erase, write and read", test_contiguous_erase_write_read, greentea_failure_handler},
{"Testing BlockDevice erase functionality", test_erase_functionality, greentea_failure_handler},
{"Testing program read small data sizes", test_program_read_small_data_sizes, greentea_failure_handler},
{"Testing unaligned erase blocks", test_unaligned_erase_blocks, greentea_failure_handler},
{"Testing Deinit block device", test_deinit_bd, greentea_failure_handler},
};
template_case_t def_template_case = {"Testing get type functionality", test_get_type_functionality, greentea_failure_handler};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
return greentea_test_setup_handler(number_of_cases);
}
int get_bd_count()
{
int count = 0;
#if COMPONENT_SPIF
bd_arr[count++] = spif; //0
#endif
#if COMPONENT_QSPIF
bd_arr[count++] = qspif; //1
#endif
#if COMPONENT_DATAFLASH
bd_arr[count++] = dataflash; //2
#endif
#if COMPONENT_SD
bd_arr[count++] = sd; //3
#endif
#if COMPONENT_FLASHIAP
bd_arr[count++] = flashiap; //4
#endif
#if COMPONENT_OSPIF
bd_arr[count++] = ospif; //5
#endif
return count;
}
static const char *prefix[] = {"SPIF ", "QSPIF ", "DATAFLASH ", "SD ", "FLASHIAP ", "OSPIF ", "DEFAULT "};
int main()
{
GREENTEA_SETUP(300, "default_auto");
// We want to replicate our test cases to different types
size_t num_cases = sizeof(template_cases) / sizeof(template_case_t);
size_t total_num_cases = 0;
int bd_count = get_bd_count();
void *raw_mem = new (std::nothrow) uint8_t[(bd_count * num_cases + 1) * sizeof(Case)];
Case *cases = static_cast<Case *>(raw_mem);
for (int j = 0; j < bd_count; j++) {
for (size_t i = 0; i < num_cases; i++) {
char desc[128], *desc_ptr;
sprintf(desc, "%s%s", prefix[bd_arr[j]], template_cases[i].description);
desc_ptr = new char[strlen(desc) + 1];
strcpy(desc_ptr, desc);
new (&cases[total_num_cases]) Case((const char *) desc_ptr, template_cases[i].case_handler,
template_cases[i].failure_handler);
total_num_cases++;
}
//Add test_get_type_functionality once, runs on default blockdevice
if (j == bd_count - 1) {
char desc[128], *desc_ptr;
sprintf(desc, "%s%s", prefix[default_bd], def_template_case.description);
desc_ptr = new char[strlen(desc) + 1];
strcpy(desc_ptr, desc);
new (&cases[total_num_cases]) Case((const char *) desc_ptr, def_template_case.case_handler,
def_template_case.failure_handler);
total_num_cases++;
}
}
Specification specification(greentea_test_setup, cases, total_num_cases,
greentea_test_teardown_handler, default_handler);
return !Harness::run(specification);
}
|
/*=============================================================================
Copyright (c) 2011 RiSK (sscrisk)
https://github.com/sscrisk/CEL---ConstExpr-Library
Copyright (c) 2011-2017 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_RANGE_ALGORITHM_IS_HEAP_UNTIL_HPP
#define SPROUT_RANGE_ALGORITHM_IS_HEAP_UNTIL_HPP
#include <sprout/config.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/range/range_return.hpp>
#include <sprout/algorithm/is_heap_until.hpp>
namespace sprout {
namespace range {
// 25.4.6.5 is_heap
template<typename RandomAccessRange>
inline SPROUT_CONSTEXPR typename sprout::range::range_return<RandomAccessRange>::type
is_heap_until(RandomAccessRange&& range) {
return sprout::range::range_return<RandomAccessRange>::pack(
sprout::is_heap_until(
sprout::begin(SPROUT_FORWARD(RandomAccessRange, range)),
sprout::end(SPROUT_FORWARD(RandomAccessRange, range))
),
SPROUT_FORWARD(RandomAccessRange, range)
);
}
template<typename RandomAccessRange, typename Compare>
inline SPROUT_CONSTEXPR typename sprout::range::range_return<RandomAccessRange>::type
is_heap_until(RandomAccessRange&& range, Compare comp) {
return sprout::range::range_return<RandomAccessRange>::pack(
sprout::is_heap_until(
sprout::begin(SPROUT_FORWARD(RandomAccessRange, range)),
sprout::end(SPROUT_FORWARD(RandomAccessRange, range)),
comp
),
SPROUT_FORWARD(RandomAccessRange, range)
);
}
template<sprout::range::range_return_value RetV, typename RandomAccessRange>
inline SPROUT_CONSTEXPR typename sprout::range::range_return<RandomAccessRange, RetV>::type
is_heap_until(RandomAccessRange&& range) {
return sprout::range::range_return<RandomAccessRange, RetV>::pack(
sprout::is_heap_until(
sprout::begin(SPROUT_FORWARD(RandomAccessRange, range)),
sprout::end(SPROUT_FORWARD(RandomAccessRange, range))
),
SPROUT_FORWARD(RandomAccessRange, range)
);
}
template<sprout::range::range_return_value RetV, typename RandomAccessRange, typename Compare>
inline SPROUT_CONSTEXPR typename sprout::range::range_return<RandomAccessRange, RetV>::type
is_heap_until(RandomAccessRange&& range, Compare comp) {
return sprout::range::range_return<RandomAccessRange, RetV>::pack(
sprout::is_heap_until(
sprout::begin(SPROUT_FORWARD(RandomAccessRange, range)),
sprout::end(SPROUT_FORWARD(RandomAccessRange, range)),
comp
),
SPROUT_FORWARD(RandomAccessRange, range)
);
}
} // namespace range
} // namespace sprout
#endif // #ifndef SPROUT_RANGE_ALGORITHM_IS_HEAP_UNTIL_HPP
|
//-----------------------------------------------------------------------------
// boost mpl/arg_fwd.hpp header file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2001-02
// Peter Dimov, Aleksey Gurtovoy
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appears in all copies and
// that both the copyright notice and this permission notice appear in
// supporting documentation. No representations are made about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
#ifndef BOOST_MPL_ARG_FWD_HPP_INCLUDED
#define BOOST_MPL_ARG_FWD_HPP_INCLUDED
#include "boost/mpl/aux_/config/nttp.hpp"
namespace boost {
namespace mpl {
template< BOOST_MPL_AUX_NTTP_DECL(int, N) > struct arg;
} // namespace mpl
} // namespace boost
#endif // BOOST_MPL_ARG_FWD_HPP_INCLUDED
|
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017-2019 The Raven Core developers
// Copyright (c) 2020-2021 The Foxdcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/foxdcoin-config.h"
#endif
#include "rpcconsole.h"
#include "ui_debugwindow.h"
#include "sendcoinsdialog.h"
#include "bantablemodel.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "chainparams.h"
#include "netbase.h"
#include "rpc/server.h"
#include "rpc/client.h"
#include "util.h"
#include <openssl/crypto.h>
#include <univalue.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#include <wallet/wallet.h>
#endif
#include <QDir>
#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#include <QScreen>
#include <QScrollBar>
#include <QSettings>
#include <QSignalMapper>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QStringList>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
const QSize FONT_RANGE(4, 40);
const char fontSizeSettingsKey[] = "consoleFontSize";
// Repair parameters
const QString RESCAN("-rescan");
const QString ZAPTXES1("-zapwallettxes=1");
const QString REINDEX("-reindex");
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{nullptr, nullptr}
};
namespace {
// don't add private key handling cmd's to the history
const QStringList historyFilter = QStringList()
<< "importprivkey"
<< "importmulti"
<< "signmessagewithprivkey"
<< "signrawtransaction"
<< "walletpassphrase"
<< "walletpassphrasechange"
<< "encryptwallet";
}
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public Q_SLOTS:
void request(const QString &command);
Q_SIGNALS:
void reply(int category, const QString &command);
};
/** Class for handling RPC timers
* (used for e.g. re-locking the wallet after a timeout)
*/
class QtRPCTimerBase: public QObject, public RPCTimerBase
{
Q_OBJECT
public:
QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis):
func(_func)
{
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
timer.start(millis);
}
~QtRPCTimerBase() {}
private Q_SLOTS:
void timeout() { func(); }
private:
QTimer timer;
std::function<void(void)> func;
};
class QtRPCTimerInterface: public RPCTimerInterface
{
public:
~QtRPCTimerInterface() {}
const char *Name() { return "Qt"; }
RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis)
{
return new QtRPCTimerBase(func, millis);
}
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments and optionally execute the command(s).
* Aims to emulate \c bash and friends.
*
* - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress())
* - Arguments are delimited with whitespace or comma
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] result stringified Result from the executed command(chain)
* @param[in] strCommand Command line to split
* @param[in] fExecute set true if you want the command to be executed
* @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
*/
bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut)
{
std::vector< std::vector<std::string> > stack;
stack.push_back(std::vector<std::string>());
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_EATING_SPACES_IN_ARG,
STATE_EATING_SPACES_IN_BRACKETS,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED,
STATE_COMMAND_EXECUTED,
STATE_COMMAND_EXECUTED_INNER
} state = STATE_EATING_SPACES;
std::string curarg;
UniValue lastResult;
unsigned nDepthInsideSensitive = 0;
size_t filter_begin_pos = 0, chpos;
std::vector<std::pair<size_t, size_t>> filter_ranges;
auto add_to_current_stack = [&](const std::string& strArg) {
if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
nDepthInsideSensitive = 1;
filter_begin_pos = chpos;
}
// Make sure stack is not empty before adding something
if (stack.empty()) {
stack.push_back(std::vector<std::string>());
}
stack.back().push_back(strArg);
};
auto close_out_params = [&]() {
if (nDepthInsideSensitive) {
if (!--nDepthInsideSensitive) {
assert(filter_begin_pos);
filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos));
filter_begin_pos = 0;
}
}
stack.pop_back();
};
std::string strCommandTerminated = strCommand;
if (strCommandTerminated.back() != '\n')
strCommandTerminated += "\n";
for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
{
char ch = strCommandTerminated[chpos];
switch(state)
{
case STATE_COMMAND_EXECUTED_INNER:
case STATE_COMMAND_EXECUTED:
{
bool breakParsing = true;
switch(ch)
{
case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
default:
if (state == STATE_COMMAND_EXECUTED_INNER)
{
if (ch != ']')
{
// append char to the current argument (which is also used for the query command)
curarg += ch;
break;
}
if (curarg.size() && fExecute)
{
// if we have a value query, query arrays with index and objects with a string key
UniValue subelement;
if (lastResult.isArray())
{
for(char argch: curarg)
if (!std::isdigit(argch))
throw std::runtime_error("Invalid result query");
subelement = lastResult[atoi(curarg.c_str())];
}
else if (lastResult.isObject())
subelement = find_value(lastResult, curarg);
else
throw std::runtime_error("Invalid result query"); //no array or object: abort
lastResult = subelement;
}
state = STATE_COMMAND_EXECUTED;
break;
}
// don't break parsing when the char is required for the next argument
breakParsing = false;
// pop the stack and return the result to the current command arguments
close_out_params();
// don't stringify the json in case of a string to avoid doublequotes
if (lastResult.isStr())
curarg = lastResult.get_str();
else
curarg = lastResult.write(2);
// if we have a non empty result, use it as stack argument otherwise as general result
if (curarg.size())
{
if (stack.size())
add_to_current_stack(curarg);
else
strResult = curarg;
}
curarg.clear();
// assume eating space state
state = STATE_EATING_SPACES;
}
if (breakParsing)
break;
}
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES_IN_ARG:
case STATE_EATING_SPACES_IN_BRACKETS:
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case '(': case ')': case '\n':
if (state == STATE_EATING_SPACES_IN_ARG)
throw std::runtime_error("Invalid Syntax");
if (state == STATE_ARGUMENT)
{
if (ch == '(' && stack.size() && stack.back().size() > 0)
{
if (nDepthInsideSensitive) {
++nDepthInsideSensitive;
}
stack.push_back(std::vector<std::string>());
}
// don't allow commands after executed commands on baselevel
if (!stack.size())
throw std::runtime_error("Invalid Syntax");
add_to_current_stack(curarg);
curarg.clear();
state = STATE_EATING_SPACES_IN_BRACKETS;
}
if ((ch == ')' || ch == '\n') && stack.size() > 0)
{
if (fExecute) {
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
JSONRPCRequest req;
req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
req.strMethod = stack.back()[0];
#ifdef ENABLE_WALLET
// TODO: Move this logic to WalletModel
if (!vpwallets.empty()) {
// in Qt, use always the wallet with index 0 when running with multiple wallets
QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName()));
req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
}
#endif
lastResult = tableRPC.execute(req);
}
state = STATE_COMMAND_EXECUTED;
curarg.clear();
}
break;
case ' ': case ',': case '\t':
if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
throw std::runtime_error("Invalid Syntax");
else if(state == STATE_ARGUMENT) // Space ends argument
{
add_to_current_stack(curarg);
curarg.clear();
}
if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
{
state = STATE_EATING_SPACES_IN_ARG;
break;
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
if (pstrFilteredOut) {
if (STATE_COMMAND_EXECUTED == state) {
assert(!stack.empty());
close_out_params();
}
*pstrFilteredOut = strCommand;
for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
}
}
switch(state) // final state
{
case STATE_COMMAND_EXECUTED:
if (lastResult.isStr())
strResult = lastResult.get_str();
else
strResult = lastResult.write(2);
case STATE_ARGUMENT:
case STATE_EATING_SPACES:
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
try
{
std::string result;
std::string executableCommand = command.toStdString() + "\n";
if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
}
catch (UniValue& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
}
}
catch (const std::exception& e)
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
QWidget(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
platformStyle(_platformStyle),
peersTableContextMenu(0),
banTableContextMenu(0),
consoleFontSize(0)
{
ui->setupUi(this);
QSettings settings;
if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) {
// Restore failed (perhaps missing setting), center the window
move(QGuiApplication::primaryScreen()->geometry().center() - frameGeometry().center());
}
ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
if (platformStyle->getImagesOnButtons()) {
ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
}
ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
// Wallet Repair Buttons
connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan()));
connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1()));
connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex()));
// set library version labels
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
std::string walletPath = GetDataDir().string();
walletPath += QDir::separator().toLatin1() + gArgs.GetArg("-wallet", "wallet.dat");
ui->wallet_path->setText(QString::fromStdString(walletPath));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
// Register RPC timer interface
rpcTimerInterface = new QtRPCTimerInterface();
// avoid accidentally overwriting an existing, non QTThread
// based timer interface
RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
clear();
}
RPCConsole::~RPCConsole()
{
QSettings settings;
settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
RPCUnsetTimerInterface(rpcTimerInterface);
delete rpcTimerInterface;
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
case Qt::Key_Return:
case Qt::Key_Enter:
// forward these events to lineEdit
if(obj == autoCompleter->popup()) {
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QWidget::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
clientModel = model;
ui->trafficGraph->setClientModel(model);
if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false);
connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
updateNetworkState();
connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
// create peer table context menu actions
QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
// create peer table context menu
peersTableContextMenu = new QMenu(this);
peersTableContextMenu->addAction(disconnectAction);
peersTableContextMenu->addAction(banAction1h);
peersTableContextMenu->addAction(banAction24h);
peersTableContextMenu->addAction(banAction7d);
peersTableContextMenu->addAction(banAction365d);
// Add a signal mapping to allow dynamic context menu arguments.
// We need to use int (instead of int64_t), because signal mapper only supports
// int or objects, which is okay because max bantime (1 year) is < int_max.
QSignalMapper* signalMapper = new QSignalMapper(this);
signalMapper->setMapping(banAction1h, 60*60);
signalMapper->setMapping(banAction24h, 60*60*24);
signalMapper->setMapping(banAction7d, 60*60*24*7);
signalMapper->setMapping(banAction365d, 60*60*24*365);
connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
// peer table context menu signals
connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
// peer table signal handling - update peer details when selecting new node
connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
// peer table signal handling - update peer details when new nodes are added to the model
connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
// peer table signal handling - cache selected node ids
connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
// set up ban table
ui->banlistWidget->setModel(model->getBanTableModel());
ui->banlistWidget->verticalHeader()->hide();
ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
// create ban table context menu action
QAction* unbanAction = new QAction(tr("&Unban"), this);
// create ban table context menu
banTableContextMenu = new QMenu(this);
banTableContextMenu->addAction(unbanAction);
// ban table context menu signals
connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
// ban table signal handling - clear peer details when clicking a peer in the ban table
connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
// ban table signal handling - ensure ban table is shown or hidden (if empty)
connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
showOrHideBanTableIfRequired();
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientUserAgent->setText(model->formatSubVersion());
ui->dataDir->setText(model->dataDir());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(GetParams().NetworkIDString()));
//Setup autocomplete and attach it
QStringList wordList;
std::vector<std::string> commandList = tableRPC.listCommands();
for (size_t i = 0; i < commandList.size(); ++i)
{
wordList << commandList[i].c_str();
wordList << ("help " + commandList[i]).c_str();
}
wordList.sort();
autoCompleter = new QCompleter(wordList, this);
autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
ui->lineEdit->setCompleter(autoCompleter);
autoCompleter->popup()->installEventFilter(this);
// Start thread to execute RPC commands.
startExecutor();
}
if (!model) {
// Client model is being set to 0, this means shutdown() is about to be called.
// Make sure we clean up the executor thread
Q_EMIT stopExecutor();
thread.wait();
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::fontBigger()
{
setFontSize(consoleFontSize+1);
}
void RPCConsole::fontSmaller()
{
setFontSize(consoleFontSize-1);
}
void RPCConsole::setFontSize(int newSize)
{
QSettings settings;
//don't allow an insane font size
if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
return;
// temp. store the console content
QString str = ui->messagesWidget->toHtml();
// replace font tags size in current content
str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
// store the new font size
consoleFontSize = newSize;
settings.setValue(fontSizeSettingsKey, consoleFontSize);
// clear console (reset icon sizes, default stylesheet) and re-add the content
float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
clear(false);
ui->messagesWidget->setHtml(str);
ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
}
#ifdef ENABLE_WALLET
/** Restart wallet with "-rescan" */
void RPCConsole::walletRescan()
{
buildParameterlist(RESCAN);
}
/** Restart wallet with "-zapwallettxes=1" */
void RPCConsole::walletZaptxes1()
{
buildParameterlist(ZAPTXES1);
}
/** Restart wallet with "-reindex" */
void RPCConsole::walletReindex()
{
QString questionString = tr("Are you sure you want to reindex?");
questionString.append(QString("<br /><br />This process may take a few hours."));
SendConfirmationDialog confirmationDialog(tr("Confirm reindex"), questionString, 0, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if(retval != QMessageBox::Yes)
{
return;
}
buildParameterlist(REINDEX);
}
#endif
/** Build command-line parameter list for restart */
void RPCConsole::buildParameterlist(QString arg)
{
// Get command-line arguments and remove the application name
QStringList args = QApplication::arguments();
args.removeFirst();
// Remove existing repair-options
args.removeAll(RESCAN);
args.removeAll(ZAPTXES1);
args.removeAll(REINDEX);
// Append repair parameter to command line.
args.append(arg);
// Send command-line arguments to FoxdcoinGUI::handleRestart()
Q_EMIT handleRestart(args);
}
void RPCConsole::clear(bool clearHistory)
{
ui->messagesWidget->clear();
if(clearHistory)
{
history.clear();
historyPtr = 0;
}
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
ui->messagesWidget->document()->setDefaultStyleSheet(
QString(
"table { }"
"td.time { color: #808080; font-size: %2; padding-top: 3px; } "
"td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
".secwarning { color: red; }"
"b { color: #006060; } "
).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
);
#ifdef Q_OS_MAC
QString clsKey = "(⌘)-L";
#else
QString clsKey = "Ctrl-L";
#endif
message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")) +
"<br><span class=\"secwarning\">" +
tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
"</span>",
true);
}
void RPCConsole::keyPressEvent(QKeyEvent *event)
{
if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
{
close();
}
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, false);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::updateNetworkState()
{
QString connections = QString::number(clientModel->getNumConnections()) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
if(!clientModel->getNetworkActive()) {
connections += " (" + tr("Network activity disabled") + ")";
}
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
updateNetworkState();
}
void RPCConsole::setNetworkActive(bool networkActive)
{
updateNetworkState();
}
void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers)
{
if (!headers) {
ui->numberOfBlocks->setText(QString::number(count));
ui->lastBlockTime->setText(blockDate.toString());
}
}
void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
{
ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
if (dynUsage < 1000000)
ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
else
ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
if(!cmd.isEmpty())
{
std::string strFilteredCmd;
try {
std::string dummy;
if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
// Failed to parse command, so we cannot even filter it for the history
throw std::runtime_error("Invalid command line");
}
} catch (const std::exception& e) {
QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
return;
}
ui->lineEdit->clear();
cmdBeforeBrowsing = QString();
message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
Q_EMIT cmdRequest(cmd);
cmd = QString::fromStdString(strFilteredCmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
// store current text when start browsing through the history
if (historyPtr == history.size()) {
cmdBeforeBrowsing = ui->lineEdit->text();
}
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
else if (!cmdBeforeBrowsing.isNull()) {
cmd = cmdBeforeBrowsing;
}
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(&thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit()));
// - queue executor for deletion (in execution thread)
connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection);
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread.start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if (ui->tabWidget->widget(index) == ui->tab_console)
ui->lineEdit->setFocus();
else if (ui->tabWidget->widget(index) != ui->tab_peers)
clearSelectedNode();
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(GUIUtil::formatBytes(totalBytesIn));
ui->lblBytesOut->setText(GUIUtil::formatBytes(totalBytesOut));
}
void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
return;
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutAboutToChange()
{
QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
cachedNodeids.clear();
for(int i = 0; i < selected.size(); i++)
{
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
cachedNodeids.append(stats->nodeStats.nodeid);
}
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel || !clientModel->getPeerTableModel())
return;
const CNodeCombinedStats *stats = nullptr;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeids.empty()) // no node selected yet
return;
// find the currently selected row
int selectedRow = -1;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (!selectedModelIndex.isEmpty()) {
selectedRow = selectedModelIndex.first().row();
}
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
if (detailNodeRow < 0)
{
// detail node disappeared from table (node disconnected)
fUnselect = true;
}
else
{
if (detailNodeRow != selectedRow)
{
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0) {
clearSelectedNode();
}
if (fReselect)
{
for(int i = 0; i < cachedNodeids.size(); i++)
{
ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
}
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
{
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
// Common height is init to -1
if (stats->nodeStateStats.nCommonHeight > -1)
ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
else
ui->peerCommonHeight->setText(tr("Unknown"));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
}
void RPCConsole::hideEvent(QHideEvent *event)
{
QWidget::hideEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
}
void RPCConsole::showPeersTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->peerWidget->indexAt(point);
if (index.isValid())
peersTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::showBanTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->banlistWidget->indexAt(point);
if (index.isValid())
banTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::disconnectSelectedNode()
{
if(!g_connman)
return;
// Get selected peer addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
for(int i = 0; i < nodes.count(); i++)
{
// Get currently selected peer address
NodeId id = nodes.at(i).data().toLongLong();
// Find the node, disconnect it and clear the selected node
if(g_connman->DisconnectNode(id))
clearSelectedNode();
}
}
void RPCConsole::banSelectedNode(int bantime)
{
if (!clientModel || !g_connman)
return;
// Get selected peer addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
for(int i = 0; i < nodes.count(); i++)
{
// Get currently selected peer address
NodeId id = nodes.at(i).data().toLongLong();
// Get currently selected peer address
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
if(detailNodeRow < 0)
return;
// Find possible nodes, ban it and clear the selected node
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
if(stats) {
g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
}
}
clearSelectedNode();
clientModel->getBanTableModel()->refresh();
}
void RPCConsole::unbanSelectedNode()
{
if (!clientModel)
return;
// Get selected ban addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
for(int i = 0; i < nodes.count(); i++)
{
// Get currently selected ban address
QString strNode = nodes.at(i).data().toString();
CSubNet possibleSubnet;
LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
if (possibleSubnet.IsValid() && g_connman)
{
g_connman->Unban(possibleSubnet);
clientModel->getBanTableModel()->refresh();
}
}
}
void RPCConsole::clearSelectedNode()
{
ui->peerWidget->selectionModel()->clearSelection();
cachedNodeids.clear();
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
}
void RPCConsole::showOrHideBanTableIfRequired()
{
if (!clientModel)
return;
bool visible = clientModel->getBanTableModel()->shouldShow();
ui->banlistWidget->setVisible(visible);
ui->banHeading->setVisible(visible);
}
void RPCConsole::setTabFocus(enum TabTypes tabType)
{
ui->tabWidget->setCurrentIndex(tabType);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: ILStubCache.cpp
//
//
#include "common.h"
#include "ilstubcache.h"
#include "dllimport.h"
#include <formattype.h>
#include "jitinterface.h"
#include "sigbuilder.h"
#include "ngenhash.inl"
#include "compile.h"
#include "eventtrace.h"
const char* FormatSig(MethodDesc* pMD, LoaderHeap *pHeap, AllocMemTracker *pamTracker);
ILStubCache::ILStubCache(LoaderHeap *pHeap) :
CClosedHashBase(
#ifdef _DEBUG
3,
#else
17, // CClosedHashTable will grow as necessary
#endif
sizeof(ILCHASHENTRY),
FALSE
),
m_crst(CrstStubCache, CRST_UNSAFE_ANYMODE),
m_heap(pHeap),
m_pStubMT(NULL)
{
WRAPPER_NO_CONTRACT;
}
void ILStubCache::Init(LoaderHeap* pHeap)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(NULL == m_heap);
m_heap = pHeap;
}
#ifndef DACCESS_COMPILE
void CreateModuleIndependentSignature(LoaderHeap* pCreationHeap,
AllocMemTracker* pamTracker,
Module* pSigModule,
PCCOR_SIGNATURE pSig, DWORD cbSig,
SigTypeContext *pTypeContext,
PCCOR_SIGNATURE* ppNewSig, DWORD* pcbNewSig)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pSigModule, NULL_NOT_OK));
PRECONDITION(CheckPointer(ppNewSig, NULL_NOT_OK));
PRECONDITION(CheckPointer(pcbNewSig, NULL_NOT_OK));
}
CONTRACTL_END;
SigPointer sigPtr(pSig, cbSig);
SigBuilder sigBuilder;
sigPtr.ConvertToInternalSignature(pSigModule, pTypeContext, &sigBuilder);
DWORD cbNewSig;
PVOID pConvertedSig = sigBuilder.GetSignature(&cbNewSig);
PVOID pNewSig = pamTracker->Track(pCreationHeap->AllocMem(S_SIZE_T(cbNewSig)));
memcpy(pNewSig, pConvertedSig, cbNewSig);
*ppNewSig = (PCCOR_SIGNATURE)pNewSig;
*pcbNewSig = cbNewSig;
}
// static
MethodDesc* ILStubCache::CreateAndLinkNewILStubMethodDesc(LoaderAllocator* pAllocator, MethodTable* pMT, DWORD dwStubFlags,
Module* pSigModule, PCCOR_SIGNATURE pSig, DWORD cbSig, SigTypeContext *pTypeContext,
ILStubLinker* pStubLinker)
{
CONTRACT (MethodDesc*)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMT, NULL_NOT_OK));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
AllocMemTracker amTracker;
MethodDesc *pStubMD = ILStubCache::CreateNewMethodDesc(pAllocator->GetHighFrequencyHeap(),
pMT,
dwStubFlags,
pSigModule,
pSig, cbSig,
pTypeContext,
&amTracker);
amTracker.SuppressRelease();
ILStubResolver *pResolver = pStubMD->AsDynamicMethodDesc()->GetILStubResolver();
pResolver->SetStubMethodDesc(pStubMD);
{
UINT maxStack;
size_t cbCode;
DWORD cbSig;
BYTE * pbBuffer;
BYTE * pbLocalSig;
cbCode = pStubLinker->Link(&maxStack);
cbSig = pStubLinker->GetLocalSigSize();
COR_ILMETHOD_DECODER * pILHeader = pResolver->AllocGeneratedIL(cbCode, cbSig, maxStack);
pbBuffer = (BYTE *)pILHeader->Code;
pbLocalSig = (BYTE *)pILHeader->LocalVarSig;
_ASSERTE(cbSig == pILHeader->cbLocalVarSig);
pStubLinker->GenerateCode(pbBuffer, cbCode);
pStubLinker->GetLocalSig(pbLocalSig, cbSig);
pResolver->SetJitFlags(CORJIT_FLAGS(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB));
}
pResolver->SetTokenLookupMap(pStubLinker->GetTokenLookupMap());
RETURN pStubMD;
}
// static
MethodDesc* ILStubCache::CreateNewMethodDesc(LoaderHeap* pCreationHeap, MethodTable* pMT, DWORD dwStubFlags,
Module* pSigModule, PCCOR_SIGNATURE pSig, DWORD cbSig, SigTypeContext *pTypeContext,
AllocMemTracker* pamTracker)
{
CONTRACT (MethodDesc*)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMT, NULL_NOT_OK));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
// @TODO: reuse the same chunk for multiple methods
MethodDescChunk* pChunk = MethodDescChunk::CreateChunk(pCreationHeap,
1,
mcDynamic,
TRUE /* fNonVtableSlot */,
TRUE /* fNativeCodeSlot */,
FALSE /* fComPlusCallInfo */,
pMT,
pamTracker);
// Note: The method desc memory is zero initialized
DynamicMethodDesc* pMD = (DynamicMethodDesc*)pChunk->GetFirstMethodDesc();
pMD->SetMemberDef(0);
pMD->SetSlot(MethodTable::NO_SLOT); // we can't ever use the slot for dynamic methods
// the no metadata part of the method desc
pMD->m_pszMethodName = (PTR_CUTF8)"IL_STUB";
pMD->m_dwExtendedFlags = mdPublic | DynamicMethodDesc::nomdILStub;
pMD->SetTemporaryEntryPoint(pMT->GetLoaderAllocator(), pamTracker);
//
// convert signature to a compatible signature if needed
//
PCCOR_SIGNATURE pNewSig;
DWORD cbNewSig;
// If we are in the same module and don't have any generics, we can use the incoming signature.
// Note that pTypeContext may be non-empty and the signature can still have no E_T_(M)VAR in it.
// We could do a more precise check if we cared.
if (pMT->GetModule() == pSigModule && (pTypeContext == NULL || pTypeContext->IsEmpty()))
{
pNewSig = pSig;
cbNewSig = cbSig;
}
else
{
CreateModuleIndependentSignature(pCreationHeap, pamTracker, pSigModule, pSig, cbSig, pTypeContext, &pNewSig, &cbNewSig);
}
pMD->SetStoredMethodSig(pNewSig, cbNewSig);
SigPointer sigPtr(pNewSig, cbNewSig);
ULONG callConvInfo;
IfFailThrow(sigPtr.GetCallingConvInfo(&callConvInfo));
if (!(callConvInfo & CORINFO_CALLCONV_HASTHIS))
{
pMD->m_dwExtendedFlags |= mdStatic;
pMD->SetStatic();
}
pMD->m_pResolver = (ILStubResolver*)pamTracker->Track(pCreationHeap->AllocMem(S_SIZE_T(sizeof(ILStubResolver))));
#ifdef _DEBUG
// Poison the ILStubResolver storage
memset((void*)pMD->m_pResolver, 0xCC, sizeof(ILStubResolver));
#endif // _DEBUG
pMD->m_pResolver = new (pMD->m_pResolver) ILStubResolver();
#ifdef FEATURE_ARRAYSTUB_AS_IL
if (SF_IsArrayOpStub(dwStubFlags))
{
pMD->GetILStubResolver()->SetStubType(ILStubResolver::ArrayOpStub);
}
else
#endif
#ifdef FEATURE_STUBS_AS_IL
if (SF_IsSecureDelegateStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdSecureDelegateStub;
pMD->GetILStubResolver()->SetStubType(ILStubResolver::SecureDelegateStub);
}
else
if (SF_IsMulticastDelegateStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdMulticastStub;
pMD->GetILStubResolver()->SetStubType(ILStubResolver::MulticastDelegateStub);
}
else
if (SF_IsUnboxingILStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdUnboxingILStub;
pMD->GetILStubResolver()->SetStubType(ILStubResolver::UnboxingILStub);
}
else
if (SF_IsInstantiatingStub(dwStubFlags))
{
pMD->GetILStubResolver()->SetStubType(ILStubResolver::InstantiatingStub);
}
else
#endif
#ifdef FEATURE_COMINTEROP
if (SF_IsCOMStub(dwStubFlags))
{
// mark certain types of stub MDs with random flags so ILStubManager recognizes them
if (SF_IsReverseStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdReverseStub;
ILStubResolver::ILStubType type = (SF_IsWinRTStub(dwStubFlags) ? ILStubResolver::WinRTToCLRInteropStub : ILStubResolver::COMToCLRInteropStub);
pMD->GetILStubResolver()->SetStubType(type);
}
else
{
ILStubResolver::ILStubType type = (SF_IsWinRTStub(dwStubFlags) ? ILStubResolver::CLRToWinRTInteropStub : ILStubResolver::CLRToCOMInteropStub);
pMD->GetILStubResolver()->SetStubType(type);
}
if (SF_IsWinRTDelegateStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdDelegateCOMStub;
}
}
else
#endif
{
// mark certain types of stub MDs with random flags so ILStubManager recognizes them
if (SF_IsReverseStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdReverseStub;
pMD->GetILStubResolver()->SetStubType(ILStubResolver::NativeToCLRInteropStub);
}
else
{
if (SF_IsDelegateStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdDelegateStub;
}
else if (SF_IsCALLIStub(dwStubFlags))
{
pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdCALLIStub;
}
pMD->GetILStubResolver()->SetStubType(ILStubResolver::CLRToNativeInteropStub);
}
}
// if we made it this far, we can set a more descriptive stub name
#ifdef FEATURE_ARRAYSTUB_AS_IL
if (SF_IsArrayOpStub(dwStubFlags))
{
switch(dwStubFlags)
{
case ILSTUB_ARRAYOP_GET: pMD->m_pszMethodName = (PTR_CUTF8)"IL_STUB_Array_Get";
break;
case ILSTUB_ARRAYOP_SET: pMD->m_pszMethodName = (PTR_CUTF8)"IL_STUB_Array_Set";
break;
case ILSTUB_ARRAYOP_ADDRESS: pMD->m_pszMethodName = (PTR_CUTF8)"IL_STUB_Array_Address";
break;
default: _ASSERTE(!"Unknown array il stub");
}
}
else
#endif
{
pMD->m_pszMethodName = pMD->GetILStubResolver()->GetStubMethodName();
}
#ifdef _DEBUG
pMD->m_pszDebugMethodName = pMD->m_pszMethodName;
pMD->m_pszDebugClassName = ILStubResolver::GetStubClassName(pMD); // must be called after type is set
pMD->m_pszDebugMethodSignature = FormatSig(pMD, pCreationHeap, pamTracker);
pMD->m_pDebugMethodTable.SetValue(pMT);
#endif // _DEBUG
RETURN pMD;
}
//
// This will get or create a MethodTable in the Module/AppDomain on which
// we can place a new IL stub MethodDesc.
//
MethodTable* ILStubCache::GetOrCreateStubMethodTable(Module* pModule)
{
CONTRACT (MethodTable*)
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
#ifdef _DEBUG
if (pModule->GetDomain()->IsSharedDomain() || pModule->GetDomain()->AsAppDomain()->IsCompilationDomain())
{
// in the shared domain and compilation AD we are associated with the module
CONSISTENCY_CHECK(pModule->GetILStubCache() == this);
}
else
{
// otherwise we are associated with the AD
AppDomain* pStubCacheDomain = AppDomain::GetDomain(this);
CONSISTENCY_CHECK(pStubCacheDomain == pModule->GetDomain()->AsAppDomain());
}
#endif // _DEBUG
if (NULL == m_pStubMT)
{
CrstHolder ch(&m_crst);
if (NULL == m_pStubMT)
{
AllocMemTracker amt;
MethodTable* pNewMT = CreateMinimalMethodTable(pModule, m_heap, &amt);
amt.SuppressRelease();
VolatileStore<MethodTable*>(&m_pStubMT, pNewMT);
}
}
RETURN m_pStubMT;
}
#endif // DACCESS_COMPILE
//
// NGEN'ed IL stubs
//
// - We will never NGEN a CALLI pinvoke or vararg pinvoke
//
// - We will always place the IL stub MethodDesc on the same MethodTable that the
// PInvoke or COM Interop call declaration lives on.
//
// - We will not pre-populate our runtime ILStubCache with compile-time
// information (i.e. NGENed stubs are only reachable from the same NGEN image.)
//
// JIT'ed IL stubs
//
// - The ILStubCache is per-BaseDomain
//
// - Each BaseDomain's ILStubCache will lazily create a "minimal MethodTable" to
// serve as the home for IL stub MethodDescs
//
// - The created MethodTables will use the Module belonging to one of the
// following, based on what type of interop stub we need to create first.
//
// - If that stub is for a static-sig-based pinvoke, we will use the
// Module belonging to that pinvoke's MethodDesc.
//
// - If that stub is for a CALLI or vararg pinvoke, we will use the
// Module belonging to the VASigCookie that the caller supplied to us.
//
// It's important to point out that the Module we latch onto here has no knowledge
// of the MethodTable that we've just "added" to it. There only exists a "back
// pointer" to the Module from the MethodTable itself. So we're really only using
// that module to answer the question of what BaseDomain the MethodTable lives in.
// So as long as the BaseDomain for that module is the same as the BaseDomain the
// ILStubCache lives in, I think we have a fairly consistent story here.
//
// We're relying on the fact that a VASigCookie may only mention types within the
// corresponding module used to qualify the signature and the fact that interop
// stubs may only reference mscorlib code or code related to a type mentioned in
// the signature. Both of these are true unless the sig is allowed to contain
// ELEMENT_TYPE_INTERNAL, which may refer to any type.
//
// We can only access E_T_INTERNAL through LCG, which does not permit referring
// to types in other BaseDomains.
//
//
// Places for improvement:
//
// - allow NGEN'ing of CALLI pinvoke and vararg pinvoke
//
// - pre-populate the per-BaseDomain cache with IL stubs from NGEN'ed image
//
MethodDesc* ILStubCache::GetStubMethodDesc(
MethodDesc *pTargetMD,
ILStubHashBlob* pParams,
DWORD dwStubFlags,
Module* pSigModule,
PCCOR_SIGNATURE pSig,
DWORD cbSig,
AllocMemTracker* pamTracker,
bool& bILStubCreator,
MethodDesc *pLastMD)
{
CONTRACT (MethodDesc*)
{
STANDARD_VM_CHECK;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
MethodDesc* pMD = NULL;
bool bFireETWCacheHitEvent = true;
#ifndef DACCESS_COMPILE
ILStubHashBlob* pBlob = NULL;
INDEBUG(LPCSTR pszResult = "[hit cache]");
if (SF_IsSharedStub(dwStubFlags))
{
CrstHolder ch(&m_crst);
// Try to find the stub
ILCHASHENTRY* phe = NULL;
phe = (ILCHASHENTRY*)Find((LPVOID)pParams);
if (phe)
{
pMD = phe->m_pMethodDesc;
if (pMD == pLastMD)
bFireETWCacheHitEvent = false;
}
}
if (!pMD)
{
size_t cbSizeOfBlob = pParams->m_cbSizeOfBlob;
AllocMemHolder<ILStubHashBlob> pBlobHolder( m_heap->AllocMem(S_SIZE_T(cbSizeOfBlob)) );
//
// Couldn't find it, let's make a new one.
//
Module *pContainingModule = pSigModule;
if (pTargetMD != NULL)
{
// loader module may be different from signature module for generic targets
pContainingModule = pTargetMD->GetLoaderModule();
}
MethodTable *pStubMT = GetOrCreateStubMethodTable(pContainingModule);
SigTypeContext typeContext;
if (pTargetMD != NULL)
{
SigTypeContext::InitTypeContext(pTargetMD, &typeContext);
}
pMD = ILStubCache::CreateNewMethodDesc(m_heap, pStubMT, dwStubFlags, pSigModule, pSig, cbSig, &typeContext, pamTracker);
if (SF_IsSharedStub(dwStubFlags))
{
CrstHolder ch(&m_crst);
ILCHASHENTRY* phe = NULL;
bool bNew;
phe = (ILCHASHENTRY*)FindOrAdd((LPVOID)pParams, bNew);
bILStubCreator |= bNew;
if (NULL != phe)
{
if (bNew)
{
pBlobHolder.SuppressRelease();
phe->m_pMethodDesc = pMD;
pBlob = pBlobHolder;
phe->m_pBlob = pBlob;
_ASSERTE(pParams->m_cbSizeOfBlob == cbSizeOfBlob);
memcpy(pBlob, pParams, cbSizeOfBlob);
INDEBUG(pszResult = "[missed cache]");
bFireETWCacheHitEvent = false;
}
else
{
INDEBUG(pszResult = "[hit cache][wasted new MethodDesc due to race]");
}
pMD = phe->m_pMethodDesc;
}
else
{
pMD = NULL;
}
}
else
{
INDEBUG(pszResult = "[cache disabled for COM->CLR field access stubs]");
}
}
if (!pMD)
{
// Couldn't grow hash table due to lack of memory.
COMPlusThrowOM();
}
#ifdef _DEBUG
CQuickBytes qbManaged;
PrettyPrintSig(pSig, cbSig, "*", &qbManaged, pSigModule->GetMDImport(), NULL);
LOG((LF_STUBS, LL_INFO1000, "ILSTUBCACHE: ILStubCache::GetStubMethodDesc %s StubMD: %p module: %p blob: %p sig: %s\n", pszResult, pMD, pSigModule, pBlob, qbManaged.Ptr()));
#endif // _DEBUG
#endif // DACCESS_COMPILE
RETURN pMD;
}
void ILStubCache::DeleteEntry(void* pParams)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
CrstHolder ch(&m_crst);
ILCHASHENTRY* phe = NULL;
phe = (ILCHASHENTRY*)Find((LPVOID)pParams);
if (phe)
{
#ifdef _DEBUG
LOG((LF_STUBS, LL_INFO1000, "ILSTUBCACHE: ILStubCache::DeleteEntry StubMD: %p\n", phe->m_pMethodDesc));
#endif
Delete(pParams);
}
}
void ILStubCache::AddMethodDescChunkWithLockTaken(MethodDesc *pMD)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
CrstHolder ch(&m_crst);
pMD->GetMethodTable()->GetClass()->AddChunkIfItHasNotBeenAdded(pMD->GetMethodDescChunk());
#endif // DACCESS_COMPILE
}
//---------------------------------------------------------
// Destructor
//---------------------------------------------------------
ILStubCache::~ILStubCache()
{
}
//*****************************************************************************
// Hash is called with a pointer to an element in the table. You must override
// this method and provide a hash algorithm for your element type.
//*****************************************************************************
unsigned int ILStubCache::Hash( // The key value.
void const* pData) // Raw data to hash.
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
const ILStubHashBlob* pBlob = (const ILStubHashBlob *)pData;
size_t cb = pBlob->m_cbSizeOfBlob - sizeof(ILStubHashBlobBase);
int hash = 0;
for (size_t i = 0; i < cb; i++)
{
hash = _rotl(hash,1) + pBlob->m_rgbBlobData[i];
}
return hash;
}
//*****************************************************************************
// Compare is used in the typical memcmp way, 0 is eqaulity, -1/1 indicate
// direction of miscompare. In this system everything is always equal or not.
//*****************************************************************************
unsigned int ILStubCache::Compare( // 0, -1, or 1.
void const* pData, // Raw key data on lookup.
BYTE* pElement) // The element to compare data against.
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
const ILStubHashBlob* pBlob1 = (const ILStubHashBlob*)pData;
const ILStubHashBlob* pBlob2 = (const ILStubHashBlob*)GetKey(pElement);
size_t cb1 = pBlob1->m_cbSizeOfBlob - sizeof(ILStubHashBlobBase);
size_t cb2 = pBlob2->m_cbSizeOfBlob - sizeof(ILStubHashBlobBase);
if (cb1 != cb2)
{
return 1; // not equal
}
else
{
// @TODO: use memcmp
for (size_t i = 0; i < cb1; i++)
{
if (pBlob1->m_rgbBlobData[i] != pBlob2->m_rgbBlobData[i])
{
return 1; // not equal
}
}
return 0; // equal
}
}
//*****************************************************************************
// Return true if the element is free to be used.
//*****************************************************************************
CClosedHashBase::ELEMENTSTATUS ILStubCache::Status( // The status of the entry.
BYTE* pElement) // The element to check.
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
MethodDesc* pMD = ((ILCHASHENTRY*)pElement)->m_pMethodDesc;
if (pMD == NULL)
{
return FREE;
}
else if (pMD == (MethodDesc*)(-((INT_PTR)1)))
{
return DELETED;
}
else
{
return USED;
}
}
//*****************************************************************************
// Sets the status of the given element.
//*****************************************************************************
void ILStubCache::SetStatus(
BYTE* pElement, // The element to set status for.
CClosedHashBase::ELEMENTSTATUS eStatus) // New status.
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
ILCHASHENTRY* phe = (ILCHASHENTRY*)pElement;
switch (eStatus)
{
case FREE: phe->m_pMethodDesc = NULL; break;
case DELETED: phe->m_pMethodDesc = (MethodDesc*)(-((INT_PTR)1)); break;
default:
_ASSERTE(!"MLCacheEntry::SetStatus(): Bad argument.");
}
}
//*****************************************************************************
// Returns the internal key value for an element.
//*****************************************************************************
void* ILStubCache::GetKey( // The data to hash on.
BYTE* pElement) // The element to return data ptr for.
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
ILCHASHENTRY* phe = (ILCHASHENTRY*)pElement;
return (void *)(phe->m_pBlob);
}
#ifdef FEATURE_PREJIT
// ============================================================================
// Stub method hash entry methods
// ============================================================================
PTR_MethodDesc StubMethodHashEntry::GetMethod()
{
LIMITED_METHOD_DAC_CONTRACT;
return pMD;
}
PTR_MethodDesc StubMethodHashEntry::GetStubMethod()
{
LIMITED_METHOD_DAC_CONTRACT;
return pStubMD;
}
#ifndef DACCESS_COMPILE
void StubMethodHashEntry::SetMethodAndStub(MethodDesc *pMD, MethodDesc *pStubMD)
{
LIMITED_METHOD_CONTRACT;
this->pMD = pMD;
this->pStubMD = pStubMD;
}
// ============================================================================
// Stub method hash table methods
// ============================================================================
/* static */ StubMethodHashTable *StubMethodHashTable::Create(LoaderAllocator *pAllocator, Module *pModule, DWORD dwNumBuckets, AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LoaderHeap *pHeap = pAllocator->GetLowFrequencyHeap();
StubMethodHashTable *pThis = (StubMethodHashTable *)pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(StubMethodHashTable)));
new (pThis) StubMethodHashTable(pModule, pHeap, dwNumBuckets);
return pThis;
}
// Calculate a hash value for a key
static DWORD Hash(MethodDesc *pMD)
{
LIMITED_METHOD_CONTRACT;
DWORD dwHash = 0x87654321;
#define INST_HASH_ADD(_value) dwHash = ((dwHash << 5) + dwHash) ^ (_value)
INST_HASH_ADD(pMD->GetMemberDef());
Instantiation inst = pMD->GetClassInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle thArg = inst[i];
if (thArg.GetMethodTable())
{
INST_HASH_ADD(thArg.GetCl());
Instantiation sArgInst = thArg.GetInstantiation();
for (DWORD j = 0; j < sArgInst.GetNumArgs(); j++)
{
TypeHandle thSubArg = sArgInst[j];
if (thSubArg.GetMethodTable())
INST_HASH_ADD(thSubArg.GetCl());
else
INST_HASH_ADD(thSubArg.GetSignatureCorElementType());
}
}
else
INST_HASH_ADD(thArg.GetSignatureCorElementType());
}
return dwHash;
}
MethodDesc *StubMethodHashTable::FindMethodDesc(MethodDesc *pMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
MethodDesc *pMDResult = NULL;
DWORD dwHash = Hash(pMD);
StubMethodHashEntry_t* pSearch;
LookupContext sContext;
for (pSearch = BaseFindFirstEntryByHash(dwHash, &sContext);
pSearch != NULL;
pSearch = BaseFindNextEntryByHash(&sContext))
{
if (pSearch->GetMethod() == pMD)
{
pMDResult = pSearch->GetStubMethod();
break;
}
}
return pMDResult;
}
// Add method desc to the hash table; must not be present already
void StubMethodHashTable::InsertMethodDesc(MethodDesc *pMD, MethodDesc *pStubMD)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pMD));
PRECONDITION(CheckPointer(pStubMD));
}
CONTRACTL_END
StubMethodHashEntry_t *pNewEntry = (StubMethodHashEntry_t *)BaseAllocateEntry(NULL);
pNewEntry->SetMethodAndStub(pMD, pStubMD);
DWORD dwHash = Hash(pMD);
BaseInsertEntry(dwHash, pNewEntry);
}
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
// Save the hash table and any method descriptors referenced by it
void StubMethodHashTable::Save(DataImage *image, CorProfileData *pProfileData)
{
WRAPPER_NO_CONTRACT;
BaseSave(image, pProfileData);
}
void StubMethodHashTable::Fixup(DataImage *image)
{
WRAPPER_NO_CONTRACT;
BaseFixup(image);
}
void StubMethodHashTable::FixupEntry(DataImage *pImage, StubMethodHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset)
{
WRAPPER_NO_CONTRACT;
pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(StubMethodHashEntry_t, pMD), pEntry->GetMethod());
pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(StubMethodHashEntry_t, pStubMD), pEntry->GetStubMethod());
}
bool StubMethodHashTable::ShouldSave(DataImage *pImage, StubMethodHashEntry_t *pEntry)
{
STANDARD_VM_CONTRACT;
MethodDesc *pMD = pEntry->GetMethod();
if (pMD->GetClassification() == mcInstantiated)
{
// save entries only for "accepted" methods
if (!pImage->GetPreloader()->IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE(pMD)))
return false;
}
// Save the entry only if the native code was successfully generated for the stub
if (pImage->GetCodeAddress(pEntry->GetStubMethod()) == NULL)
return false;
return true;
}
#endif // FEATURE_NATIVE_IMAGE_GENERATION
#endif // !DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void StubMethodHashTable::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
BaseEnumMemoryRegions(flags);
}
void StubMethodHashTable::EnumMemoryRegionsForEntry(StubMethodHashEntry_t *pEntry, CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
if (pEntry->GetMethod().IsValid())
pEntry->GetMethod()->EnumMemoryRegions(flags);
}
#endif // DACCESS_COMPILE
#endif // FEATURE_PREJIT
|
/******************************************************************************
*
* Project: GDAL
* Purpose: Fuzzer
* Author: Even Rouault, even.rouault at spatialys.com
*
******************************************************************************
* Copyright (c) 2017, Even Rouault <even.rouault at spatialys.com>
*
* 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 "../wkt_import_fuzzer.cpp"
int main()
{
const char szJUNK[] = "junk";
LLVMFuzzerTestOneInput(reinterpret_cast<const uint8_t*>(szJUNK),
strlen(szJUNK));
return 0;
}
|
#ifndef UNIT_TEST
#ifdef ARDUINO
#include <lcd-rotary-menu.h>
#include <lcd-rotary-menuitem.h>
#include <sys-debug.h>
// rotary menu example
LCDRotaryMenu *menu;
// check i2c lcd address using i2c scanner
#define LCD_ADDR 0x27
#define LCD_COLS 20
#define LCD_ROWS 4
// PB5
#define ROT_A_PIN 4
// PB3
#define ROT_B_PIN 3
// PA10
#define ROT_SW_PIN 2
#define SPLASH_TIMEOUT_MS 1000
void LCDSplash(LiquidCrystal_I2C &lcd)
{
lcd.setCursor(0, 0);
lcd.print("firmware");
lcd.setCursor(0, 1);
lcd.print("version");
}
void reboot()
{
debug("would to reboot...");
}
void setup()
{
Serial.begin(9600);
setSystemPrinter(Serial); // for debug and error notice
auto inverted = true;
menu = new LCDRotaryMenu(LCD_ADDR, LCD_COLS, LCD_ROWS, ROT_A_PIN, ROT_B_PIN, ROT_SW_PIN,
inverted, 200);
// splash screen ( custom lcd usage ) ; call this before menu init
menu->setSplashCb(LCDSplash, SPLASH_TIMEOUT_MS);
menu->init();
// compose follow menu
//
// sample1
// sample2
// dev---+
// reboot
// test
auto &root = menu->getRoot();
root.append("sample1");
root.append("sample2");
auto &input = root.append("00000");
input.setAsNumericInput();
auto &dev = root.append("dev");
dev.append("reboot").onSelect(reboot);
dev.append("test1");
}
void loop()
{
menu->loop();
}
#endif
#endif
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 "config.h"
#include "platform/Partitions.h"
namespace blink {
SizeSpecificPartitionAllocator<3072> Partitions::m_objectModelAllocator;
SizeSpecificPartitionAllocator<1024> Partitions::m_renderingAllocator;
void Partitions::init()
{
m_objectModelAllocator.init();
m_renderingAllocator.init();
}
void Partitions::shutdown()
{
// We could ASSERT here for a memory leak within the partition, but it leads
// to very hard to diagnose ASSERTs, so it's best to leave leak checking for
// the valgrind and heapcheck bots, which run without partitions.
(void) m_renderingAllocator.shutdown();
(void) m_objectModelAllocator.shutdown();
}
} // namespace blink
|
//
// Common non-engine code/data for EDuke32 and Mapster32
//
#include "ns.h" // Must come before everything else!
#include "compat.h"
#include "build.h"
#include "baselayer.h"
#include "palette.h"
#include "gamecvars.h"
#include "cmdlib.h"
#include "rts.h"
#include "gamecontrol.h"
#include "common.h"
#include "common_game.h"
BEGIN_DUKE_NS
// Set up new-style multi-psky handling.
void G_InitMultiPsky(int CLOUDYOCEAN__DYN, int MOONSKY1__DYN, int BIGORBIT1__DYN, int LA__DYN)
{
// When adding other multi-skies, take care that the tileofs[] values are
// <= PSKYOFF_MAX. (It can be increased up to MAXPSKYTILES, but should be
// set as tight as possible.)
// The default sky properties (all others are implicitly zero):
psky_t *sky = tileSetupSky(DEFAULTPSKY);
sky->lognumtiles = 3;
sky->horizfrac = 32768;
// CLOUDYOCEAN
// Aligns with the drawn scene horizon because it has one itself.
sky = tileSetupSky(CLOUDYOCEAN__DYN);
sky->lognumtiles = 3;
sky->horizfrac = 65536;
// MOONSKY1
// earth mountain mountain sun
sky = tileSetupSky(MOONSKY1__DYN);
sky->lognumtiles = 3;
sky->horizfrac = 32768;
sky->tileofs[6] = 1;
sky->tileofs[1] = 2;
sky->tileofs[4] = 2;
sky->tileofs[2] = 3;
// BIGORBIT1 // orbit
// earth1 2 3 moon/sun
sky = tileSetupSky(BIGORBIT1__DYN);
sky->lognumtiles = 3;
sky->horizfrac = 32768;
sky->tileofs[5] = 1;
sky->tileofs[6] = 2;
sky->tileofs[7] = 3;
sky->tileofs[2] = 4;
// LA // la city
// earth1 2 3 moon/sun
sky = tileSetupSky(LA__DYN);
sky->lognumtiles = 3;
sky->horizfrac = 16384 + 1024;
sky->tileofs[0] = 1;
sky->tileofs[1] = 2;
sky->tileofs[2] = 1;
sky->tileofs[3] = 3;
sky->tileofs[4] = 4;
sky->tileofs[5] = 0;
sky->tileofs[6] = 2;
sky->tileofs[7] = 3;
#if 0
// This assertion should hold. See note above.
for (bssize_t i=0; i<pskynummultis; ++i)
for (bssize_t j=0; j<(1<<multipsky[i].lognumtiles); ++j)
Bassert(multipsky[i].tileofs[j] <= PSKYOFF_MAX);
#endif
}
void G_SetupGlobalPsky(void)
{
int skyIdx = 0;
// NOTE: Loop must be running backwards for the same behavior as the game
// (greatest sector index with matching parallaxed sky takes precedence).
for (int i = numsectors - 1; i >= 0; i--)
{
if (sector[i].ceilingstat & 1)
{
skyIdx = getpskyidx(sector[i].ceilingpicnum);
if (skyIdx > 0)
break;
}
}
g_pskyidx = skyIdx;
}
//////////
void G_LoadLookups(void)
{
int32_t j;
auto fr = fileSystem.OpenFileReader("lookup.dat", 0);
if (!fr.isOpen())
return;
j = paletteLoadLookupTable(fr);
if (j < 0)
{
if (j == -1)
initprintf("ERROR loading \"lookup.dat\": failed reading enough data.\n");
return;
}
uint8_t paldata[768];
for (j=1; j<=5; j++)
{
// Account for TITLE and REALMS swap between basepal number and on-disk order.
int32_t basepalnum = (j == 3 || j == 4) ? 4+3-j : j;
if (fr.Read(paldata, 768) != 768)
return;
for (unsigned char & k : paldata)
k <<= 2;
paletteSetColorTable(basepalnum, paldata);
}
}
END_DUKE_NS
|
// preprocessed version of 'boost/mpl/vector_c.hpp' header
// see the original for copyright information
namespace boost {
namespace mpl {
template<
typename T
, long C0 = LONG_MAX, long C1 = LONG_MAX, long C2 = LONG_MAX
, long C3 = LONG_MAX, long C4 = LONG_MAX, long C5 = LONG_MAX
, long C6 = LONG_MAX, long C7 = LONG_MAX, long C8 = LONG_MAX
, long C9 = LONG_MAX
>
struct vector_c;
template<
typename T
>
struct vector_c<
T, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
>
: vector0_c<T>
{
typedef vector0_c<T> type;
};
template<
typename T
, long C0
>
struct vector_c<
T, C0, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
, LONG_MAX, LONG_MAX, LONG_MAX
>
: vector1_c< T,C0 >
{
typedef vector1_c< T,C0 > type;
};
template<
typename T
, long C0, long C1
>
struct vector_c<
T, C0, C1, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
, LONG_MAX, LONG_MAX, LONG_MAX
>
: vector2_c< T,C0,C1 >
{
typedef vector2_c< T,C0,C1 > type;
};
template<
typename T
, long C0, long C1, long C2
>
struct vector_c<
T, C0, C1, C2, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
, LONG_MAX, LONG_MAX
>
: vector3_c< T,C0,C1,C2 >
{
typedef vector3_c< T,C0,C1,C2 > type;
};
template<
typename T
, long C0, long C1, long C2, long C3
>
struct vector_c<
T, C0, C1, C2, C3, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
, LONG_MAX
>
: vector4_c< T,C0,C1,C2,C3 >
{
typedef vector4_c< T,C0,C1,C2,C3 > type;
};
template<
typename T
, long C0, long C1, long C2, long C3, long C4
>
struct vector_c<
T, C0, C1, C2, C3, C4, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
, LONG_MAX
>
: vector5_c< T,C0,C1,C2,C3,C4 >
{
typedef vector5_c< T,C0,C1,C2,C3,C4 > type;
};
template<
typename T
, long C0, long C1, long C2, long C3, long C4, long C5
>
struct vector_c<
T, C0, C1, C2, C3, C4, C5, LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX
>
: vector6_c< T,C0,C1,C2,C3,C4,C5 >
{
typedef vector6_c< T,C0,C1,C2,C3,C4,C5 > type;
};
template<
typename T
, long C0, long C1, long C2, long C3, long C4, long C5, long C6
>
struct vector_c<
T, C0, C1, C2, C3, C4, C5, C6, LONG_MAX, LONG_MAX, LONG_MAX
>
: vector7_c< T,C0,C1,C2,C3,C4,C5,C6 >
{
typedef vector7_c< T,C0,C1,C2,C3,C4,C5,C6 > type;
};
template<
typename T
, long C0, long C1, long C2, long C3, long C4, long C5, long C6, long C7
>
struct vector_c< T,C0,C1,C2,C3,C4,C5,C6,C7,LONG_MAX,LONG_MAX >
: vector8_c< T,C0,C1,C2,C3,C4,C5,C6,C7 >
{
typedef vector8_c< T,C0,C1,C2,C3,C4,C5,C6,C7 > type;
};
template<
typename T
, long C0, long C1, long C2, long C3, long C4, long C5, long C6, long C7
, long C8
>
struct vector_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,LONG_MAX >
: vector9_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8 >
{
typedef vector9_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8 > type;
};
// primary template (not a specialization!)
template<
typename T
, long C0, long C1, long C2, long C3, long C4, long C5, long C6, long C7
, long C8, long C9
>
struct vector_c
: vector10_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9 >
{
typedef vector10_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9 > type;
};
} // namespace mpl
} // namespace boost
|
// Parameters for Centauro Planner
// Author: Tobias Klamt <klamt@ais.uni-bonn.de
// 2016
#include <planning_abstraction_net/priority_queue_discr_pose.h>
namespace planning_abstraction_net
{
typedef fibonacci_heap<std::pair<Eigen::Vector3i, float>, compare<heap_compare_discr_pose>> fib_heap;
void PriorityQueueDiscrPose::Clear()
{
m_priority_queue = fib_heap();
}
fib_heap::handle_type PriorityQueueDiscrPose::push (const Eigen::Vector3i cell, const float f_cost)
{
return m_priority_queue.push(std::pair<Eigen::Vector3i, float>(cell, f_cost));
}
std::pair<Eigen::Vector3i, float> PriorityQueueDiscrPose::top()
{
return m_priority_queue.top();
}
void PriorityQueueDiscrPose::pop()
{
m_priority_queue.pop();
}
void PriorityQueueDiscrPose::DecreaseKey(const Eigen::Vector3i& cell, const float new_f_cost, fib_heap::handle_type priority_queue_handle)
{
m_priority_queue.increase(priority_queue_handle, std::pair<Eigen::Vector3i, float>(cell, new_f_cost));
}
unsigned int PriorityQueueDiscrPose::size()
{
return m_priority_queue.size();
}
}
|
#include <algorithm>
#include <iostream>
#include <cstring>
#include <climits>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define Re register
#define LL long long
#define U unsigned
#define FOR(i,a,b) for(Re int i = a;i <= b;++i)
#define ROF(i,a,b) for(Re int i = a;i >= b;--i)
#define SFOR(i,a,b,c) for(Re int i = a;i <= b;i+=c)
#define SROF(i,a,b,c) for(Re int i = a;i >= b;i-=c)
#define CLR(i,a) memset(i,a,sizeof(i))
#define BR printf("--------------------\n")
#define DEBUG(x) std::cerr << #x << '=' << x << std::endl
const int MAXN = 1000000+5;
char str[MAXN];
int N,sa[MAXN],tax[MAXN],M;
int pool1[MAXN],*rk = pool1,pool2[MAXN],*tp = pool2;
int height[MAXN];
int heightSUM[MAXN];
int saSUM[MAXN];
int ansSUM[MAXN];
inline void sort(){
FOR(i,0,M) tax[i] = 0;
FOR(i,1,N) tax[rk[i]]++;
FOR(i,1,M) tax[i] += tax[i-1];
ROF(i,N,1) sa[tax[rk[tp[i]]]--] = tp[i];
}
inline void SuffixSort(){
M = 75;
FOR(i,1,N) rk[i] = str[i]-'0'+1,tp[i] = i;
sort();
for(int w = 1,p = 0;p < N;w <<= 1,M = p){
p = 0;
FOR(i,1,w) tp[++p] = N-w+i;
FOR(i,1,N) if(sa[i] > w) tp[++p] = sa[i]-w;
sort();
std::swap(tp,rk);
rk[sa[1]] = p = 1;
FOR(i,2,N) rk[sa[i]] = (tp[sa[i-1]] == tp[sa[i]] && tp[sa[i-1]+w] == tp[sa[i]+w]) ? p : ++p;
}
}
inline void getHeight(){
int j,k = 0;
FOR(i,1,N){
if(k) --k;
int j = sa[rk[i]-1];
while(str[i+k] == str[j+k]) ++k;
height[rk[i]] = k;
}
}
int main(){
int q;
scanf("%d%d",&N,&q);
scanf("%s",str+1);
SuffixSort();
getHeight();
FOR(i,1,N) {
heightSUM[i] = height[rk[i]];
saSUM[i] = i;
// printf("%d %d %d\n", rk[i], height[rk[i]], sa[rk[i]]);
}
FOR(i,1,N) {
ansSUM[i] = ansSUM[i-1] + N-saSUM[i] + 1 - heightSUM[i];
heightSUM[i] += heightSUM[i-1];
saSUM[i] += saSUM[i-1];
printf("%d %d %d\n", heightSUM[i], saSUM[i], ansSUM[i]);
}
int st,et;
printf("%d\n", N);
FOR(i,1,q) {
scanf("%d%d",&st,&et);
et++;
printf("%d %d %d %d %d %d\n", et, st, saSUM[et], saSUM[st], heightSUM[et], heightSUM[st]);
printf("%d\n",(et-st)*(N+1)-(saSUM[et]-saSUM[st])-(heightSUM[et]-heightSUM[st]));
}
return 0;
}
|
/* The smooth Class Library
* Copyright (C) 1998-2021 Robert Kausch <robert.kausch@gmx.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of "The Artistic License, Version 2.0".
*
* THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
#include <smooth/graphics/imageloader/imageloader.h>
#include <smooth/graphics/imageloader/pci.h>
#include <smooth/graphics/imageloader/png.h>
#include <smooth/graphics/imageloader/jpeg.h>
#include <smooth/graphics/imageloader/webp.h>
#include <smooth/graphics/imageloader/icon.h>
#include <smooth/gui/application/application.h>
#include <smooth/io/instream.h>
using namespace smooth::IO;
namespace smooth
{
namespace GUI
{
static Short DetectImageFormat(const Buffer<UnsignedByte> &buffer)
{
Short format = IMAGE_FORMAT_AUTO;
if (buffer.Size() < 12) return format;
if (buffer[ 0] == 0x50 && buffer[ 1] == 0x43 &&
buffer[ 2] == 0x49 && buffer[ 3] == 0x46) format = IMAGE_FORMAT_PCI;
else if (buffer[ 0] == 0xFF && buffer[ 1] == 0xD8) format = IMAGE_FORMAT_JPEG;
else if (buffer[ 0] == 0x89 && buffer[ 1] == 0x50 &&
buffer[ 2] == 0x4E && buffer[ 3] == 0x47 &&
buffer[ 4] == 0x0D && buffer[ 5] == 0x0A &&
buffer[ 6] == 0x1A && buffer[ 7] == 0x0A) format = IMAGE_FORMAT_PNG;
else if (buffer[ 0] == 0x52 && buffer[ 1] == 0x49 &&
buffer[ 2] == 0x46 && buffer[ 3] == 0x46 &&
buffer[ 8] == 0x57 && buffer[ 9] == 0x45 &&
buffer[10] == 0x42 && buffer[11] == 0x50) format = IMAGE_FORMAT_WEBP;
return format;
}
};
};
S::GUI::ImageLoader::ImageLoader(const String &iFileName)
{
fileName = iFileName;
gotFileName = True;
gotBuffer = False;
}
S::GUI::ImageLoader::ImageLoader(const Buffer<UnsignedByte> &iBuffer)
{
buffer = iBuffer;
gotBuffer = True;
gotFileName = False;
}
S::GUI::ImageLoader::~ImageLoader()
{
}
S::GUI::Bitmap S::GUI::ImageLoader::Load(const String &fileName)
{
ImageLoader *loader = NIL;
if (fileName.ToLower().Contains(".pci:")) loader = new ImageLoaderPCI(fileName);
#ifdef __WIN32__
else if (fileName.StartsWith("Icon:")) loader = new ImageLoaderIcon(fileName);
#endif
if (loader == NIL)
{
/* Auto-detect image format.
*/
Buffer<UnsignedByte> buffer(12);
InStream in(STREAM_FILE, fileName, IS_READ);
in.InputData(buffer, 12);
Short format = DetectImageFormat(buffer);
if (format == IMAGE_FORMAT_PCI) loader = new ImageLoaderPCI(fileName);
else if (format == IMAGE_FORMAT_PNG) loader = new ImageLoaderPNG(fileName);
else if (format == IMAGE_FORMAT_JPEG) loader = new ImageLoaderJPEG(fileName);
else if (format == IMAGE_FORMAT_WEBP) loader = new ImageLoaderWebP(fileName);
}
/* Load image.
*/
Bitmap bitmap;
if (loader != NIL)
{
bitmap = loader->Load();
delete loader;
}
/* Look in the startup and application folders if no image has been found yet.
*/
if (!fileName.StartsWith(Application::GetStartupDirectory()) && !fileName.StartsWith(Application::GetApplicationDirectory()))
{
if (bitmap == NIL) bitmap = Load(Application::GetStartupDirectory().Append(fileName));
if (bitmap == NIL) bitmap = Load(Application::GetApplicationDirectory().Append(fileName));
}
return bitmap;
}
S::GUI::Bitmap S::GUI::ImageLoader::Load(const Buffer<UnsignedByte> &buffer, Short format)
{
/* Auto-detect image format.
*/
if (format == IMAGE_FORMAT_AUTO) format = DetectImageFormat(buffer);
/* Create image loader.
*/
ImageLoader *loader = NIL;
if (format == IMAGE_FORMAT_PCI) loader = new ImageLoaderPCI(buffer);
else if (format == IMAGE_FORMAT_PNG) loader = new ImageLoaderPNG(buffer);
else if (format == IMAGE_FORMAT_JPEG) loader = new ImageLoaderJPEG(buffer);
else if (format == IMAGE_FORMAT_WEBP) loader = new ImageLoaderWebP(buffer);
if (loader == NIL) return NIL;
Bitmap bitmap = loader->Load();
delete loader;
return bitmap;
}
|
#include "XrdBlockFetcher.h"
#include "XrdClient/XrdClient.hh"
#include <pcrecpp.h>
#include <memory>
#include <string>
#include <list>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
//==============================================================================
// Utility
//==============================================================================
std::string strprintf(const char* fmt, ...)
{
int size = 128;
std::string str;
va_list ap;
while (true)
{
str.resize(size);
va_start(ap, fmt);
int n = vsnprintf((char *)str.c_str(), size, fmt, ap);
va_end(ap);
if (n > -1 && n < size)
return str;
if (n > -1)
size = n + 1;
else
size *= 2;
}
}
//==============================================================================
// C++ class
//==============================================================================
class XrdMan
{
public:
struct Config
{
std::string prefix;
std::string postfix;
int pfn_to_lfn_size;
std::vector<pcrecpp::RE*> pfn_to_lfn_regexps;
std::vector<std::string> pfn_to_lfn_replacements;
bool pfn_to_lfn_must_match;
Config() :
pfn_to_lfn_size (0),
pfn_to_lfn_must_match (true)
{
// Static init of XrdBlockFetcher java reads /etc/hadoop/xfbfs-site.xml
// and calls C++ implementation of initConfig() ... see further down.
fprintf(stderr, "\n"
"XrdMan::Config instantiated, will be filled from Hadoop that reads config\n"
"from /etc/hadoop/xfbfs-site.xml on first exception.\n");
prefix = "root://uaf-9.t2.ucsd.edu/";
}
~Config()
{
for (std::vector<pcrecpp::RE*>::iterator i = pfn_to_lfn_regexps.begin(); i != pfn_to_lfn_regexps.end(); ++i)
delete *i;
}
void add_pfn_to_lfn_rule(const std::string ®exp, const std::string &replace)
{
++pfn_to_lfn_size;
pfn_to_lfn_regexps .push_back(new pcrecpp::RE(regexp));
pfn_to_lfn_replacements.push_back(replace);
}
bool pfn_to_lfn(std::string &pfn)
{
// Returns true on first successful match'n'replace.
// Returns false if all matches fail.
for (int i = 0; i < pfn_to_lfn_size; ++i)
{
if (pfn_to_lfn_regexps[i]->Replace(pfn_to_lfn_replacements[i], &pfn))
{
return true;
}
}
return false;
}
};
static Config s_config;
static int s_udp_log_fd;
private:
std::string m_url;
int m_block_size;
XrdClient *m_xrd_client;
XrdClientStatInfo m_stat_info;
std::vector<jbyte> m_cache;
long long m_cache_offset;
const int m_cache_capacity;
int m_cache_size;
void throw_io(JNIEnv *env, const std::string& what)
{
env->ThrowNew(env->FindClass("java/io/IOException"), what.c_str());
}
void send_log(JNIEnv *env, jint lvl, const std::string& message)
{
// XXXX Can jcls and jmth be kept across different envs in member variables?
jclass jcls = env->FindClass("org/xrootd/hdfs/fallback/XrdUdpLog");
jmethodID jmth = env->GetStaticMethodID(jcls, "send", "(ILjava/lang/String;)V");
jstring jmsg = env->NewStringUTF(message.c_str());
env->CallStaticVoidMethod(jcls, jmth, lvl, jmsg);
// Apparently this is not needed if the thread returns to java.
// env->DeleteLocalRef(jmsg);
// env->DeleteLocalRef(jcls);
}
jbyte* get_cache(long long offset, int &bytes_available)
{
// Make sure we have byte 'offset' in the local cache.
//
// Returns the cache position storing the byte at 'offset' and sets
// 'bytes_available' argument to the number of bytes available in cache
// from 'offset' onwards.
if (offset < m_cache_offset || offset >= m_cache_offset + m_cache_size)
{
// We have to refetch cache, let's decide how much.
// Do not read more than cache capacity.
int len = m_cache_capacity;
// Do not read beyond block boundary.
{
long long boundary = (offset / m_block_size + 1) * m_block_size;
if (offset + len > boundary)
{
len = boundary - offset;
}
}
// Do not read beyond file size.
{
if (offset + len > m_stat_info.size)
{
len = m_stat_info.size - offset;
}
}
m_xrd_client->Read(&m_cache[0], offset, len);
m_cache_offset = offset;
m_cache_size = len;
bytes_available = len;
return &m_cache[0];
}
else
{
int off_diff = offset - m_cache_offset;
bytes_available = m_cache_size - off_diff;
return &m_cache[off_diff];
}
}
public:
XrdMan(JNIEnv* env, const char* url, int block_size) :
m_block_size (block_size),
m_cache_offset (-1),
m_cache_capacity (std::min(512*1024, block_size)),
m_cache_size (0)
{
m_url = url;
if (s_config.pfn_to_lfn(m_url))
{
send_log(env, 1, strprintf("XrdMan::XrdMan() PFN to LFN:\n %s\n %s", url, m_url.c_str()));
}
/* drop lfn error handling until we fix throws in JNI
else
{
if (s_config.pfn_to_lfn_must_match)
{
throw_io(env, strprintf("XrdMan::XrdMan() Mandatory PFN to LFN match/replace failed for '%s'.",
url));
}
}
*/
m_url = strprintf("%s%s?hdfs_block_size=%d%s",
s_config.prefix.c_str(),
m_url.c_str(), block_size,
s_config.postfix.c_str());
m_xrd_client = new XrdClient(m_url.c_str());
m_cache.resize(m_cache_capacity);
}
~XrdMan()
{
delete m_xrd_client;
}
void AboutToDestroy(JNIEnv *env)
{
// This just sends a log message. Ideally would do it in the detructor
// but I do need JNIenv for sending.
send_log (env, 0, strprintf("XrdMan::~XrdMan() Closing LFN '%s'", m_url.c_str()));
}
bool Open(JNIEnv *env)
{
send_log(env, 0, strprintf("XrdMan::XrdMan() Opening LFN '%s'", m_url.c_str()));
if ( ! m_xrd_client->Open(0, kXR_async) ||
m_xrd_client->LastServerResp()->status != kXR_ok)
{
struct ServerResponseBody_Error *srb = m_xrd_client->LastServerError();
throw_io(env, strprintf("XrdMan::XrdMan() Failed opening URL '%s', errnum=%d. Server error:\n%s",
m_url.c_str(), srb->errnum, srb->errmsg));
return false;
}
m_xrd_client->Stat(&m_stat_info);
return true;
}
void Read(JNIEnv *env, long long offset, int length, jbyteArray arr, int arr_offset)
{
send_log(env, 2, strprintf("XrdMan::Read(off=%lld, len=%d) %s", offset, length, m_url.c_str()));
if (length <= 0)
{
return;
}
if (offset + length > m_stat_info.size || offset < 0)
{
throw_io(env, strprintf("XrdMan::Read(off=%lld, len=%d) Request for data outside of file, file-size=%lld.",
offset, length, m_stat_info.size));
return;
}
long long position = 0;
while (length > 0)
{
int bytes_available;
jbyte *cache = get_cache(offset + position, bytes_available);
int to_copy = std::min(bytes_available, length);
env->SetByteArrayRegion(arr, arr_offset, to_copy, cache);
length -= to_copy;
position += to_copy;
arr_offset += to_copy;
}
}
};
XrdMan::Config XrdMan::s_config;
int XrdMan::s_udp_log_fd = -1;
//==============================================================================
// Implementation of Java methods
//==============================================================================
namespace
{
std::string getJniString(JNIEnv *env, jstring jstr)
{
if (jstr == 0) return std::string();
const char *str = env->GetStringUTFChars(jstr, 0);
std::string ret(str);
env->ReleaseStringUTFChars(jstr, str);
return ret;
}
}
JNIEXPORT void JNICALL Java_org_xrootd_hdfs_fallback_XrdBlockFetcher_initConfig
(JNIEnv *env, jclass cls,
jstring prefix, jstring postfix,
jobjectArray p2l_regexps,
jboolean p2l_must_match)
{
// Open socket to UDP listener
// XrdMan::s_udp_log_fd = ...
XrdMan::s_config.prefix = getJniString(env, prefix);
XrdMan::s_config.postfix = getJniString(env, postfix);
XrdMan::s_config.pfn_to_lfn_must_match = p2l_must_match;
printf("================================================================================\n"
"XrdBlockFetcher native configuration\n"
"--------------------------------------------------------------------------------\n"
"prefix=%s\n"
"postfix=%s\n"
"regexp_must_match=%s\n",
XrdMan::s_config.prefix.c_str(), XrdMan::s_config.postfix.c_str(), p2l_must_match ? "true" : "false");
printf("--------------------------------------------------------------------------------\n");
int re_count = env->GetArrayLength(p2l_regexps) / 2;
for (int i = 0; i < re_count; ++i)
{
std::string regexp = getJniString(env, (jstring) env->GetObjectArrayElement(p2l_regexps, 2*i));
std::string replace = getJniString(env, (jstring) env->GetObjectArrayElement(p2l_regexps, 2*i + 1));
printf("regexp %2d: '%s' -> '%s'\n", i, regexp.c_str(), replace.c_str());
XrdMan::s_config.add_pfn_to_lfn_rule(regexp, replace);
}
printf("================================================================================\n");
fflush(stdout);
}
JNIEXPORT void JNICALL Java_org_xrootd_hdfs_fallback_XrdBlockFetcher_createXrdClient
(JNIEnv *env, jobject self, jstring url, jint block_size)
{
jclass jcls = env->GetObjectClass(self);
jfieldID jfid = env->GetFieldID(jcls, "m_native_handle", "J");
XrdMan *xman = new XrdMan(env,
getJniString(env, url).c_str(),
block_size);
env->SetLongField(self, jfid, (long long) xman);
}
JNIEXPORT void JNICALL Java_org_xrootd_hdfs_fallback_XrdBlockFetcher_destroyXrdClient
(JNIEnv *env, jobject self, jlong handle)
{
XrdMan *xman = (XrdMan*) handle;
xman->AboutToDestroy(env);
delete xman;
}
//------------------------------------------------------------------------------
JNIEXPORT void JNICALL Java_org_xrootd_hdfs_fallback_XrdBlockFetcher_openXrd
(JNIEnv *env, jobject self, jlong handle)
{
jclass jcls = env->GetObjectClass(self);
jfieldID jfid = env->GetFieldID(jcls, "m_is_open", "Z");
XrdMan *xman = (XrdMan*) handle;
if (xman->Open(env))
env->SetBooleanField(self, jfid, true);
}
JNIEXPORT void JNICALL Java_org_xrootd_hdfs_fallback_XrdBlockFetcher_readXrd
(JNIEnv *env, jobject self, jlong handle, jlong offset, jint length,
jbyteArray arr, jint arr_offset)
{
XrdMan *xman = (XrdMan*) handle;
xman->Read(env, offset, length, arr, arr_offset);
}
|
/* A Bison parser, made by GNU Bison 3.7.6. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation,
Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual,
especially those whose name start with YY_ or yy_. They are
private implementation details that can be changed or removed. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output, and Bison version. */
#define YYBISON 30706
/* Bison version string. */
#define YYBISON_VERSION "3.7.6"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 0
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Substitute the type names. */
#define YYSTYPE DSTYPE
/* Substitute the variable and function names. */
#define yyparse dparse
#define yylex dlex
#define yyerror derror
#define yydebug ddebug
#define yynerrs dnerrs
#define yylval dlval
#define yychar dchar
/* First part of user prologue. */
#line 15 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
#define YY_NO_UNISTD_H 1
#include <cstddef>
#include <cstdint>
#include <cmath>
#include <iostream>
#include "../core/parsers/dstype.h"
#include "aeongui/DrawType.h"
extern int dlex();
extern "C"
{
int derror ( std::vector<AeonGUI::DrawType>& aPath, const char *s );
}
static void Merge ( dstype& aLeft, dstype& aRight )
{
auto& left = std::get<std::vector<AeonGUI::DrawType>> ( aLeft );
auto& right = std::get<std::vector<AeonGUI::DrawType>> ( aRight );
left.reserve ( left.size() + right.size() );
left.insert ( left.end(), right.begin(), right.end() );
}
static void AddCommandToPath ( std::vector<AeonGUI::DrawType>& aPath, const AeonGUI::DrawType& aCommand, std::vector<AeonGUI::DrawType>& aArguments )
{
aPath.reserve ( aPath.size() + aArguments.size() + 1 );
aPath.emplace_back ( aCommand );
aPath.insert ( aPath.end(), aArguments.begin(), aArguments.end() );
}
static dstype GetArcArgs ( const dstype& aRadii, const dstype& aRotation, const dstype& aLarge, const dstype& aSweep, const dstype& aEnd )
{
return std::vector<AeonGUI::DrawType>
{
std::get<std::vector<AeonGUI::DrawType>> ( aRadii ) [0],
std::get<std::vector<AeonGUI::DrawType>> ( aRadii ) [1],
std::get<AeonGUI::DrawType> ( aRotation ),
std::get<double> ( std::get<AeonGUI::DrawType> ( aLarge ) ) ? true : false,
std::get<double> ( std::get<AeonGUI::DrawType> ( aSweep ) ) ? true : false,
std::get<std::vector<AeonGUI::DrawType>> ( aEnd ) [0],
std::get<std::vector<AeonGUI::DrawType>> ( aEnd ) [1]
};
}
#line 120 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
# ifndef YY_CAST
# ifdef __cplusplus
# define YY_CAST(Type, Val) static_cast<Type> (Val)
# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val)
# else
# define YY_CAST(Type, Val) ((Type) (Val))
# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val))
# endif
# endif
# ifndef YY_NULLPTR
# if defined __cplusplus
# if 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# else
# define YY_NULLPTR ((void*)0)
# endif
# endif
#include "path_data_parser.hpp"
/* Symbol kind. */
enum yysymbol_kind_t
{
YYSYMBOL_YYEMPTY = -2,
YYSYMBOL_YYEOF = 0, /* "end of file" */
YYSYMBOL_YYerror = 1, /* error */
YYSYMBOL_YYUNDEF = 2, /* "invalid token" */
YYSYMBOL_NUMBER = 3, /* NUMBER */
YYSYMBOL_4_M_ = 4, /* 'M' */
YYSYMBOL_5_m_ = 5, /* 'm' */
YYSYMBOL_6_Z_ = 6, /* 'Z' */
YYSYMBOL_7_z_ = 7, /* 'z' */
YYSYMBOL_8_L_ = 8, /* 'L' */
YYSYMBOL_9_l_ = 9, /* 'l' */
YYSYMBOL_10_H_ = 10, /* 'H' */
YYSYMBOL_11_h_ = 11, /* 'h' */
YYSYMBOL_12_V_ = 12, /* 'V' */
YYSYMBOL_13_v_ = 13, /* 'v' */
YYSYMBOL_14_C_ = 14, /* 'C' */
YYSYMBOL_15_c_ = 15, /* 'c' */
YYSYMBOL_16_S_ = 16, /* 'S' */
YYSYMBOL_17_s_ = 17, /* 's' */
YYSYMBOL_18_Q_ = 18, /* 'Q' */
YYSYMBOL_19_q_ = 19, /* 'q' */
YYSYMBOL_20_T_ = 20, /* 'T' */
YYSYMBOL_21_t_ = 21, /* 't' */
YYSYMBOL_22_A_ = 22, /* 'A' */
YYSYMBOL_23_a_ = 23, /* 'a' */
YYSYMBOL_YYACCEPT = 24, /* $accept */
YYSYMBOL_25_svg_path = 25, /* svg-path */
YYSYMBOL_26_moveto_drawto_command_groups = 26, /* moveto-drawto-command-groups */
YYSYMBOL_27_moveto_drawto_command_group = 27, /* moveto-drawto-command-group */
YYSYMBOL_28_drawto_commands = 28, /* drawto-commands */
YYSYMBOL_29_drawto_command = 29, /* drawto-command */
YYSYMBOL_moveto = 30, /* moveto */
YYSYMBOL_closepath = 31, /* closepath */
YYSYMBOL_lineto = 32, /* lineto */
YYSYMBOL_33_horizontal_lineto = 33, /* horizontal-lineto */
YYSYMBOL_34_vertical_lineto = 34, /* vertical-lineto */
YYSYMBOL_curveto = 35, /* curveto */
YYSYMBOL_36_smooth_curveto = 36, /* smooth-curveto */
YYSYMBOL_37_quadratic_bezier_curveto = 37, /* quadratic-bezier-curveto */
YYSYMBOL_38_smooth_quadratic_bezier_curveto = 38, /* smooth-quadratic-bezier-curveto */
YYSYMBOL_39_elliptical_arc = 39, /* elliptical-arc */
YYSYMBOL_40_elliptical_arc_argument_sequence = 40, /* elliptical-arc-argument-sequence */
YYSYMBOL_41_elliptical_arc_argument = 41, /* elliptical-arc-argument */
YYSYMBOL_42_triple_coordinate_pair_argument_sequence = 42, /* triple-coordinate-pair-argument-sequence */
YYSYMBOL_43_triple_coordinate_pair_argument = 43, /* triple-coordinate-pair-argument */
YYSYMBOL_44_double_coordinate_pair_argument_sequence = 44, /* double-coordinate-pair-argument-sequence */
YYSYMBOL_45_double_coordinate_pair_argument = 45, /* double-coordinate-pair-argument */
YYSYMBOL_46_single_coordinate_pair_argument_sequence = 46, /* single-coordinate-pair-argument-sequence */
YYSYMBOL_47_coordinate_pair = 47, /* coordinate-pair */
YYSYMBOL_48_coordinate_argument_sequence = 48, /* coordinate-argument-sequence */
YYSYMBOL_coordinate = 49 /* coordinate */
};
typedef enum yysymbol_kind_t yysymbol_kind_t;
#ifdef short
# undef short
#endif
/* On compilers that do not define __PTRDIFF_MAX__ etc., make sure
<limits.h> and (if available) <stdint.h> are included
so that the code can choose integer types of a good width. */
#ifndef __PTRDIFF_MAX__
# include <limits.h> /* INFRINGES ON USER NAME SPACE */
# if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__
# include <stdint.h> /* INFRINGES ON USER NAME SPACE */
# define YY_STDINT_H
# endif
#endif
/* Narrow types that promote to a signed type and that can represent a
signed or unsigned integer of at least N bits. In tables they can
save space and decrease cache pressure. Promoting to a signed type
helps avoid bugs in integer arithmetic. */
#ifdef __INT_LEAST8_MAX__
typedef __INT_LEAST8_TYPE__ yytype_int8;
#elif defined YY_STDINT_H
typedef int_least8_t yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef __INT_LEAST16_MAX__
typedef __INT_LEAST16_TYPE__ yytype_int16;
#elif defined YY_STDINT_H
typedef int_least16_t yytype_int16;
#else
typedef short yytype_int16;
#endif
/* Work around bug in HP-UX 11.23, which defines these macros
incorrectly for preprocessor constants. This workaround can likely
be removed in 2023, as HPE has promised support for HP-UX 11.23
(aka HP-UX 11i v2) only through the end of 2022; see Table 2 of
<https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>. */
#ifdef __hpux
# undef UINT_LEAST8_MAX
# undef UINT_LEAST16_MAX
# define UINT_LEAST8_MAX 255
# define UINT_LEAST16_MAX 65535
#endif
#if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__
typedef __UINT_LEAST8_TYPE__ yytype_uint8;
#elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \
&& UINT_LEAST8_MAX <= INT_MAX)
typedef uint_least8_t yytype_uint8;
#elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX
typedef unsigned char yytype_uint8;
#else
typedef short yytype_uint8;
#endif
#if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__
typedef __UINT_LEAST16_TYPE__ yytype_uint16;
#elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \
&& UINT_LEAST16_MAX <= INT_MAX)
typedef uint_least16_t yytype_uint16;
#elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX
typedef unsigned short yytype_uint16;
#else
typedef int yytype_uint16;
#endif
#ifndef YYPTRDIFF_T
# if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__
# define YYPTRDIFF_T __PTRDIFF_TYPE__
# define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__
# elif defined PTRDIFF_MAX
# ifndef ptrdiff_t
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# endif
# define YYPTRDIFF_T ptrdiff_t
# define YYPTRDIFF_MAXIMUM PTRDIFF_MAX
# else
# define YYPTRDIFF_T long
# define YYPTRDIFF_MAXIMUM LONG_MAX
# endif
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned
# endif
#endif
#define YYSIZE_MAXIMUM \
YY_CAST (YYPTRDIFF_T, \
(YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \
? YYPTRDIFF_MAXIMUM \
: YY_CAST (YYSIZE_T, -1)))
#define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X))
/* Stored state numbers (used for stacks). */
typedef yytype_int8 yy_state_t;
/* State numbers in computations. */
typedef int yy_state_fast_t;
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__)
# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__))
# else
# define YY_ATTRIBUTE_PURE
# endif
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__)
# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__))
# else
# define YY_ATTRIBUTE_UNUSED
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YY_USE(E) ((void) (E))
#else
# define YY_USE(E) /* empty */
#endif
#if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__
# define YY_IGNORE_USELESS_CAST_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"")
# define YY_IGNORE_USELESS_CAST_END \
_Pragma ("GCC diagnostic pop")
#endif
#ifndef YY_IGNORE_USELESS_CAST_BEGIN
# define YY_IGNORE_USELESS_CAST_BEGIN
# define YY_IGNORE_USELESS_CAST_END
#endif
#define YY_ASSERT(E) ((void) (0 && (E)))
#if !defined yyoverflow
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc ( YYSIZE_T ); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free ( void * ); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* !defined yyoverflow */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined DSTYPE_IS_TRIVIAL && DSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yy_state_t yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYPTRDIFF_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / YYSIZEOF (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYPTRDIFF_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 12
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 117
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 24
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 26
/* YYNRULES -- Number of rules. */
#define YYNRULES 53
/* YYNSTATES -- Number of states. */
#define YYNSTATES 80
/* YYMAXUTOK -- Last valid token kind. */
#define YYMAXUTOK 258
/* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, with out-of-bounds checking. */
#define YYTRANSLATE(YYX) \
(0 <= (YYX) && (YYX) <= YYMAXUTOK \
? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \
: YYSYMBOL_YYUNDEF)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex. */
static const yytype_int8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 22, 2, 14, 2, 2,
2, 2, 10, 2, 2, 2, 8, 4, 2, 2,
2, 18, 2, 16, 20, 2, 12, 2, 2, 2,
6, 2, 2, 2, 2, 2, 2, 23, 2, 15,
2, 2, 2, 2, 11, 2, 2, 2, 9, 5,
2, 2, 2, 19, 2, 17, 21, 2, 13, 2,
2, 2, 7, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3
};
#if DDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint8 yyrline[] =
{
0, 59, 59, 60, 63, 64, 66, 67, 70, 71,
73, 74, 75, 76, 77, 78, 79, 80, 81, 83,
85, 88, 89, 92, 94, 97, 98, 101, 102, 105,
106, 109, 110, 113, 114, 117, 118, 121, 123, 126,
127, 134, 140, 141, 148, 160, 162, 169, 176, 178,
185, 188, 193, 200
};
#endif
/** Accessing symbol of state STATE. */
#define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State])
#if DDEBUG || 0
/* The user-facing name of the symbol whose (internal) number is
YYSYMBOL. No bounds checking. */
static const char *yysymbol_name ( yysymbol_kind_t yysymbol ) YY_ATTRIBUTE_UNUSED;
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"\"end of file\"", "error", "\"invalid token\"", "NUMBER", "'M'", "'m'",
"'Z'", "'z'", "'L'", "'l'", "'H'", "'h'", "'V'", "'v'", "'C'", "'c'",
"'S'", "'s'", "'Q'", "'q'", "'T'", "'t'", "'A'", "'a'", "$accept",
"svg-path", "moveto-drawto-command-groups",
"moveto-drawto-command-group", "drawto-commands", "drawto-command",
"moveto", "closepath", "lineto", "horizontal-lineto", "vertical-lineto",
"curveto", "smooth-curveto", "quadratic-bezier-curveto",
"smooth-quadratic-bezier-curveto", "elliptical-arc",
"elliptical-arc-argument-sequence", "elliptical-arc-argument",
"triple-coordinate-pair-argument-sequence",
"triple-coordinate-pair-argument",
"double-coordinate-pair-argument-sequence",
"double-coordinate-pair-argument",
"single-coordinate-pair-argument-sequence", "coordinate-pair",
"coordinate-argument-sequence", "coordinate", YY_NULLPTR
};
static const char *
yysymbol_name ( yysymbol_kind_t yysymbol )
{
return yytname[yysymbol];
}
#endif
#ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_int16 yytoknum[] =
{
0, 256, 257, 258, 77, 109, 90, 122, 76, 108,
72, 104, 86, 118, 67, 99, 83, 115, 81, 113,
84, 116, 65, 97
};
#endif
#define YYPACT_NINF (-63)
#define yypact_value_is_default(Yyn) \
((Yyn) == YYPACT_NINF)
#define YYTABLE_NINF (-1)
#define yytable_value_is_error(Yyn) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int8 yypact[] =
{
21, 1, 1, 14, 21, -63, 94, -63, 1, -63,
1, 1, -63, -63, -63, -63, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 94, -63, -63, -63, -63, -63, -63, -63,
-63, -63, -63, -63, -63, 1, 1, 1, -63, 1,
1, 1, 1, -63, 1, 1, 1, -63, 1, 1,
1, 1, 1, 1, 1, -63, 1, 1, -63, -63,
-63, 1, -63, -63, -63, 1, -63, 1, 1, -63
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_int8 yydefact[] =
{
2, 0, 0, 0, 3, 4, 6, 53, 19, 48,
0, 20, 1, 5, 21, 22, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 7, 8, 10, 11, 12, 13, 14, 15,
16, 17, 18, 49, 50, 23, 24, 25, 51, 26,
27, 28, 29, 42, 0, 30, 31, 45, 0, 32,
33, 34, 35, 36, 37, 39, 0, 38, 9, 52,
43, 0, 46, 47, 40, 0, 44, 0, 0, 41
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-63, -63, -63, 16, -63, 2, -63, -63, -63, -63,
-63, -63, -63, -63, -63, -63, 0, -62, 10, -49,
-8, -48, 7, -1, 18, 22
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
0, 3, 4, 5, 32, 33, 6, 34, 35, 36,
37, 38, 39, 40, 41, 42, 64, 65, 52, 53,
56, 57, 8, 58, 47, 10
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int8 yytable[] =
{
9, 9, 74, 70, 7, 74, 70, 43, 72, 11,
43, 72, 72, 72, 12, 9, 9, 59, 60, 61,
13, 54, 54, 45, 46, 1, 2, 9, 9, 66,
66, 67, 44, 55, 68, 62, 63, 49, 50, 51,
48, 48, 48, 48, 43, 43, 0, 0, 0, 0,
0, 54, 0, 71, 54, 0, 0, 73, 0, 0,
0, 43, 43, 66, 0, 0, 66, 0, 0, 69,
76, 69, 69, 69, 0, 0, 0, 79, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 75, 0,
0, 0, 0, 0, 0, 0, 0, 77, 0, 78,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31
};
static const yytype_int8 yycheck[] =
{
1, 2, 64, 52, 3, 67, 55, 8, 56, 2,
11, 59, 60, 61, 0, 16, 17, 25, 26, 27,
4, 22, 23, 16, 17, 4, 5, 28, 29, 30,
31, 31, 10, 23, 32, 28, 29, 19, 20, 21,
18, 19, 20, 21, 45, 46, -1, -1, -1, -1,
-1, 52, -1, 54, 55, -1, -1, 58, -1, -1,
-1, 62, 63, 64, -1, -1, 67, -1, -1, 47,
71, 49, 50, 51, -1, -1, -1, 78, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 66, -1,
-1, -1, -1, -1, -1, -1, -1, 75, -1, 77,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_int8 yystos[] =
{
0, 4, 5, 25, 26, 27, 30, 3, 46, 47,
49, 46, 0, 27, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 28, 29, 31, 32, 33, 34, 35, 36,
37, 38, 39, 47, 49, 46, 46, 48, 49, 48,
48, 48, 42, 43, 47, 42, 44, 45, 47, 44,
44, 44, 46, 46, 40, 41, 47, 40, 29, 49,
43, 47, 45, 47, 41, 49, 47, 49, 49, 47
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_int8 yyr1[] =
{
0, 24, 25, 25, 26, 26, 27, 27, 28, 28,
29, 29, 29, 29, 29, 29, 29, 29, 29, 30,
30, 31, 31, 32, 32, 33, 33, 34, 34, 35,
35, 36, 36, 37, 37, 38, 38, 39, 39, 40,
40, 41, 42, 42, 43, 44, 44, 45, 46, 46,
47, 48, 48, 49
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_int8 yyr2[] =
{
0, 2, 0, 1, 1, 2, 1, 2, 1, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
2, 5, 1, 2, 3, 1, 2, 2, 1, 2,
2, 1, 2, 1
};
enum { YYENOMEM = -2 };
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = DEMPTY)
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == DEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (aPath, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Backward compatibility with an undocumented macro.
Use Derror or DUNDEF. */
#define YYERRCODE DUNDEF
/* Enable debugging if requested. */
#if DDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
# ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Kind, Value, aPath); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*-----------------------------------.
| Print this symbol's value on YYO. |
`-----------------------------------*/
static void
yy_symbol_value_print ( FILE *yyo,
yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, std::vector<AeonGUI::DrawType>& aPath )
{
FILE *yyoutput = yyo;
YY_USE ( yyoutput );
YY_USE ( aPath );
if ( !yyvaluep )
{
return;
}
# ifdef YYPRINT
if ( yykind < YYNTOKENS )
{
YYPRINT ( yyo, yytoknum[yykind], *yyvaluep );
}
# endif
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YY_USE ( yykind );
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*---------------------------.
| Print this symbol on YYO. |
`---------------------------*/
static void
yy_symbol_print ( FILE *yyo,
yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, std::vector<AeonGUI::DrawType>& aPath )
{
YYFPRINTF ( yyo, "%s %s (",
yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name ( yykind ) );
yy_symbol_value_print ( yyo, yykind, yyvaluep, aPath );
YYFPRINTF ( yyo, ")" );
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print ( yy_state_t *yybottom, yy_state_t *yytop )
{
YYFPRINTF ( stderr, "Stack now" );
for ( ; yybottom <= yytop; yybottom++ )
{
int yybot = *yybottom;
YYFPRINTF ( stderr, " %d", yybot );
}
YYFPRINTF ( stderr, "\n" );
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print ( yy_state_t *yyssp, YYSTYPE *yyvsp,
int yyrule, std::vector<AeonGUI::DrawType>& aPath )
{
int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF ( stderr, "Reducing stack by rule %d (line %d):\n",
yyrule - 1, yylno );
/* The symbols being reduced. */
for ( yyi = 0; yyi < yynrhs; yyi++ )
{
YYFPRINTF ( stderr, " $%d = ", yyi + 1 );
yy_symbol_print ( stderr,
YY_ACCESSING_SYMBOL ( +yyssp[yyi + 1 - yynrhs] ),
&yyvsp[ ( yyi + 1 ) - ( yynrhs )], aPath );
YYFPRINTF ( stderr, "\n" );
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule, aPath); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !DDEBUG */
# define YYDPRINTF(Args) ((void) 0)
# define YY_SYMBOL_PRINT(Title, Kind, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !DDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct ( const char *yymsg,
yysymbol_kind_t yykind, YYSTYPE *yyvaluep, std::vector<AeonGUI::DrawType>& aPath )
{
YY_USE ( yyvaluep );
YY_USE ( aPath );
if ( !yymsg )
{
yymsg = "Deleting";
}
YY_SYMBOL_PRINT ( yymsg, yykind, yyvaluep, yylocationp );
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YY_USE ( yykind );
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/* Lookahead token kind. */
int yychar;
/* The semantic value of the lookahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
/*----------.
| yyparse. |
`----------*/
int
yyparse ( std::vector<AeonGUI::DrawType>& aPath )
{
yy_state_fast_t yystate = 0;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus = 0;
/* Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* Their size. */
YYPTRDIFF_T yystacksize = YYINITDEPTH;
/* The state stack: array, bottom, top. */
yy_state_t yyssa[YYINITDEPTH];
yy_state_t *yyss = yyssa;
yy_state_t *yyssp = yyss;
/* The semantic value stack: array, bottom, top. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs = yyvsa;
YYSTYPE *yyvsp = yyvs;
int yyn;
/* The return value of yyparse. */
int yyresult;
/* Lookahead symbol kind. */
yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
YYDPRINTF ( ( stderr, "Starting parse\n" ) );
yychar = DEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
/*--------------------------------------------------------------------.
| yysetstate -- set current state (the top of the stack) to yystate. |
`--------------------------------------------------------------------*/
yysetstate:
YYDPRINTF ( ( stderr, "Entering state %d\n", yystate ) );
YY_ASSERT ( 0 <= yystate && yystate < YYNSTATES );
YY_IGNORE_USELESS_CAST_BEGIN
*yyssp = YY_CAST ( yy_state_t, yystate );
YY_IGNORE_USELESS_CAST_END
YY_STACK_PRINT ( yyss, yyssp );
if ( yyss + yystacksize - 1 <= yyssp )
#if !defined yyoverflow && !defined YYSTACK_RELOCATE
goto yyexhaustedlab;
#else
{
/* Get the current used size of the three stacks, in elements. */
YYPTRDIFF_T yysize = yyssp - yyss + 1;
# if defined yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
yy_state_t *yyss1 = yyss;
YYSTYPE *yyvs1 = yyvs;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow ( YY_ ( "memory exhausted" ),
&yyss1, yysize * YYSIZEOF ( *yyssp ),
&yyvs1, yysize * YYSIZEOF ( *yyvsp ),
&yystacksize );
yyss = yyss1;
yyvs = yyvs1;
}
# else /* defined YYSTACK_RELOCATE */
/* Extend the stack our own way. */
if ( YYMAXDEPTH <= yystacksize )
{
goto yyexhaustedlab;
}
yystacksize *= 2;
if ( YYMAXDEPTH < yystacksize )
{
yystacksize = YYMAXDEPTH;
}
{
yy_state_t *yyss1 = yyss;
union yyalloc *yyptr =
YY_CAST ( union yyalloc *,
YYSTACK_ALLOC ( YY_CAST ( YYSIZE_T, YYSTACK_BYTES ( yystacksize ) ) ) );
if ( ! yyptr )
{
goto yyexhaustedlab;
}
YYSTACK_RELOCATE ( yyss_alloc, yyss );
YYSTACK_RELOCATE ( yyvs_alloc, yyvs );
# undef YYSTACK_RELOCATE
if ( yyss1 != yyssa )
{
YYSTACK_FREE ( yyss1 );
}
}
# endif
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YY_IGNORE_USELESS_CAST_BEGIN
YYDPRINTF ( ( stderr, "Stack size increased to %ld\n",
YY_CAST ( long, yystacksize ) ) );
YY_IGNORE_USELESS_CAST_END
if ( yyss + yystacksize - 1 <= yyssp )
{
YYABORT;
}
}
#endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */
if ( yystate == YYFINAL )
{
YYACCEPT;
}
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if ( yypact_value_is_default ( yyn ) )
{
goto yydefault;
}
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either empty, or end-of-input, or a valid lookahead. */
if ( yychar == DEMPTY )
{
YYDPRINTF ( ( stderr, "Reading a token\n" ) );
yychar = yylex ();
}
if ( yychar <= DEOF )
{
yychar = DEOF;
yytoken = YYSYMBOL_YYEOF;
YYDPRINTF ( ( stderr, "Now at end of input.\n" ) );
}
else if ( yychar == Derror )
{
/* The scanner already issued an error message, process directly
to error recovery. But do not keep the error token as
lookahead, it is too special and may lead us to an endless
loop in error recovery. */
yychar = DUNDEF;
yytoken = YYSYMBOL_YYerror;
goto yyerrlab1;
}
else
{
yytoken = YYTRANSLATE ( yychar );
YY_SYMBOL_PRINT ( "Next token is", yytoken, &yylval, &yylloc );
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if ( yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken )
{
goto yydefault;
}
yyn = yytable[yyn];
if ( yyn <= 0 )
{
if ( yytable_value_is_error ( yyn ) )
{
goto yyerrlab;
}
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if ( yyerrstatus )
{
yyerrstatus--;
}
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ( "Shifting", yytoken, &yylval, &yylloc );
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Discard the shifted token. */
yychar = DEMPTY;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if ( yyn == 0 )
{
goto yyerrlab;
}
goto yyreduce;
/*-----------------------------.
| yyreduce -- do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1 - yylen];
YY_REDUCE_PRINT ( yyn );
switch ( yyn )
{
case 19: /* moveto: 'M' single-coordinate-pair-argument-sequence */
#line 83 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1228 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 20: /* moveto: 'm' single-coordinate-pair-argument-sequence */
#line 85 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1234 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 21: /* closepath: 'Z' */
#line 88 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
aPath.emplace_back ( std::get<AeonGUI::DrawType> ( yyvsp[0] ) );
}
#line 1240 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 22: /* closepath: 'z' */
#line 89 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
aPath.emplace_back ( std::get<AeonGUI::DrawType> ( yyvsp[0] ) );
}
#line 1246 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 23: /* lineto: 'L' single-coordinate-pair-argument-sequence */
#line 92 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1252 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 24: /* lineto: 'l' single-coordinate-pair-argument-sequence */
#line 94 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1258 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 25: /* horizontal-lineto: 'H' coordinate-argument-sequence */
#line 97 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1264 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 26: /* horizontal-lineto: 'h' coordinate-argument-sequence */
#line 98 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1270 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 27: /* vertical-lineto: 'V' coordinate-argument-sequence */
#line 101 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1276 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 28: /* vertical-lineto: 'v' coordinate-argument-sequence */
#line 102 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1282 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 29: /* curveto: 'C' triple-coordinate-pair-argument-sequence */
#line 105 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1288 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 30: /* curveto: 'c' triple-coordinate-pair-argument-sequence */
#line 106 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1294 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 31: /* smooth-curveto: 'S' double-coordinate-pair-argument-sequence */
#line 109 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1300 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 32: /* smooth-curveto: 's' double-coordinate-pair-argument-sequence */
#line 110 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1306 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 33: /* quadratic-bezier-curveto: 'Q' double-coordinate-pair-argument-sequence */
#line 113 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1312 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 34: /* quadratic-bezier-curveto: 'q' double-coordinate-pair-argument-sequence */
#line 114 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1318 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 35: /* smooth-quadratic-bezier-curveto: 'T' single-coordinate-pair-argument-sequence */
#line 117 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1324 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 36: /* smooth-quadratic-bezier-curveto: 't' single-coordinate-pair-argument-sequence */
#line 118 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1330 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 37: /* elliptical-arc: 'A' elliptical-arc-argument-sequence */
#line 121 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1336 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 38: /* elliptical-arc: 'a' elliptical-arc-argument-sequence */
#line 123 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
AddCommandToPath ( aPath, std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] ) );
}
#line 1342 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 39: /* elliptical-arc-argument-sequence: elliptical-arc-argument */
#line 126 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = std::move ( yyvsp[0] );
}
#line 1348 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 40: /* elliptical-arc-argument-sequence: elliptical-arc-argument-sequence elliptical-arc-argument */
#line 128 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
Merge ( yyvsp[-1], yyvsp[0] );
yyval = std::move ( yyvsp[-1] );
}
#line 1357 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 41: /* elliptical-arc-argument: coordinate-pair coordinate coordinate coordinate coordinate-pair */
#line 135 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = GetArcArgs ( yyvsp[-4], yyvsp[-3], yyvsp[-2], yyvsp[-1], yyvsp[0] );
}
#line 1365 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 42: /* triple-coordinate-pair-argument-sequence: triple-coordinate-pair-argument */
#line 140 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = std::move ( yyvsp[0] );
}
#line 1371 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 43: /* triple-coordinate-pair-argument-sequence: triple-coordinate-pair-argument-sequence triple-coordinate-pair-argument */
#line 142 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
Merge ( yyvsp[-1], yyvsp[0] );
yyval = std::move ( yyvsp[-1] );
}
#line 1380 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 44: /* triple-coordinate-pair-argument: coordinate-pair coordinate-pair coordinate-pair */
#line 149 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
auto& left = std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[-2] );
auto& center = std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[-1] );
auto& right = std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[0] );
left.reserve ( left.size() + center.size() + right.size() );
left.insert ( left.end(), center.begin(), center.end() );
left.insert ( left.end(), right.begin(), right.end() );
yyval = std::move ( yyvsp[-2] );
}
#line 1394 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 45: /* double-coordinate-pair-argument-sequence: double-coordinate-pair-argument */
#line 160 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = std::move ( yyvsp[0] );
}
#line 1400 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 46: /* double-coordinate-pair-argument-sequence: double-coordinate-pair-argument-sequence double-coordinate-pair-argument */
#line 163 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
Merge ( yyvsp[-1], yyvsp[0] );
yyval = std::move ( yyvsp[-1] );
}
#line 1409 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 47: /* double-coordinate-pair-argument: coordinate-pair coordinate-pair */
#line 170 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
Merge ( yyvsp[-1], yyvsp[0] );
yyval = std::move ( yyvsp[-1] );
}
#line 1418 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 48: /* single-coordinate-pair-argument-sequence: coordinate-pair */
#line 176 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = std::move ( yyvsp[0] );
}
#line 1424 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 49: /* single-coordinate-pair-argument-sequence: single-coordinate-pair-argument-sequence coordinate-pair */
#line 179 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
Merge ( yyvsp[-1], yyvsp[0] );
yyval = std::move ( yyvsp[-1] );
}
#line 1433 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 50: /* coordinate-pair: coordinate coordinate */
#line 185 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = std::vector<AeonGUI::DrawType> {std::get<AeonGUI::DrawType> ( yyvsp[-1] ), std::get<AeonGUI::DrawType> ( yyvsp[0] ) };
}
#line 1439 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 51: /* coordinate-argument-sequence: coordinate */
#line 189 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
yyval = std::vector<AeonGUI::DrawType> {std::get<AeonGUI::DrawType> ( yyvsp[0] ) };
}
#line 1447 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
case 52: /* coordinate-argument-sequence: coordinate-argument-sequence coordinate */
#line 194 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
{
std::get<std::vector<AeonGUI::DrawType>> ( yyvsp[-1] ).emplace_back ( std::get<AeonGUI::DrawType> ( yyvsp[0] ) );
yyval = std::move ( yyvsp[-1] );
}
#line 1456 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
break;
#line 1460 "C:/Code/AeonGUI/mingw64/core/path_data_parser.cpp"
default:
break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ( "-> $$ =", YY_CAST ( yysymbol_kind_t, yyr1[yyn] ), &yyval, &yyloc );
YYPOPSTACK ( yylen );
yylen = 0;
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
{
const int yylhs = yyr1[yyn] - YYNTOKENS;
const int yyi = yypgoto[yylhs] + *yyssp;
yystate = ( 0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp
? yytable[yyi]
: yydefgoto[yylhs] );
}
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == DEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE ( yychar );
/* If not already recovering from an error, report this error. */
if ( !yyerrstatus )
{
++yynerrs;
yyerror ( aPath, YY_ ( "syntax error" ) );
}
if ( yyerrstatus == 3 )
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if ( yychar <= DEOF )
{
/* Return failure if at end of input. */
if ( yychar == DEOF )
{
YYABORT;
}
}
else
{
yydestruct ( "Error: discarding",
yytoken, &yylval, aPath );
yychar = DEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers when the user code never invokes YYERROR and the
label yyerrorlab therefore never appears in user code. */
if ( 0 )
{
YYERROR;
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK ( yylen );
yylen = 0;
YY_STACK_PRINT ( yyss, yyssp );
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
/* Pop stack until we find a state that shifts the error token. */
for ( ;; )
{
yyn = yypact[yystate];
if ( !yypact_value_is_default ( yyn ) )
{
yyn += YYSYMBOL_YYerror;
if ( 0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror )
{
yyn = yytable[yyn];
if ( 0 < yyn )
{
break;
}
}
}
/* Pop the current state because it cannot handle the error token. */
if ( yyssp == yyss )
{
YYABORT;
}
yydestruct ( "Error: popping",
YY_ACCESSING_SYMBOL ( yystate ), yyvsp, aPath );
YYPOPSTACK ( 1 );
yystate = *yyssp;
YY_STACK_PRINT ( yyss, yyssp );
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ( "Shifting", YY_ACCESSING_SYMBOL ( yyn ), yyvsp, yylsp );
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror ( aPath, YY_ ( "memory exhausted" ) );
yyresult = 2;
goto yyreturn;
#endif
/*-------------------------------------------------------.
| yyreturn -- parsing is finished, clean up and return. |
`-------------------------------------------------------*/
yyreturn:
if ( yychar != DEMPTY )
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE ( yychar );
yydestruct ( "Cleanup: discarding lookahead",
yytoken, &yylval, aPath );
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK ( yylen );
YY_STACK_PRINT ( yyss, yyssp );
while ( yyssp != yyss )
{
yydestruct ( "Cleanup: popping",
YY_ACCESSING_SYMBOL ( +*yyssp ), yyvsp, aPath );
YYPOPSTACK ( 1 );
}
#ifndef yyoverflow
if ( yyss != yyssa )
{
YYSTACK_FREE ( yyss );
}
#endif
return yyresult;
}
#line 201 "C:/Code/AeonGUI/core/parsers/path_data.ypp"
extern "C"
{
int derror ( std::vector<AeonGUI::DrawType>& aPath, const char *s )
{
std::cerr << s << std::endl;
return 0;
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: OVRPlugin
#include "GlobalNamespace/OVRPlugin.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Version
class Version;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: OVRPlugin/OVRP_1_12_0
class OVRPlugin::OVRP_1_12_0 : public ::Il2CppObject {
public:
// Creating value type constructor for type: OVRP_1_12_0
OVRP_1_12_0() noexcept {}
// Get static field: static public readonly System.Version version
static System::Version* _get_version();
// Set static field: static public readonly System.Version version
static void _set_version(System::Version* value);
// static public System.Single ovrp_GetAppFramerate()
// Offset: 0x1605BEC
static float ovrp_GetAppFramerate();
// static public OVRPlugin/PoseStatef ovrp_GetNodePoseState(OVRPlugin/Step stepId, OVRPlugin/Node nodeId)
// Offset: 0x1605C5C
static GlobalNamespace::OVRPlugin::PoseStatef ovrp_GetNodePoseState(GlobalNamespace::OVRPlugin::Step stepId, GlobalNamespace::OVRPlugin::Node nodeId);
// static public OVRPlugin/ControllerState2 ovrp_GetControllerState2(System.UInt32 controllerMask)
// Offset: 0x1605CF4
static GlobalNamespace::OVRPlugin::ControllerState2 ovrp_GetControllerState2(uint controllerMask);
// static private System.Void .cctor()
// Offset: 0x1605D84
static void _cctor();
}; // OVRPlugin/OVRP_1_12_0
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRPlugin::OVRP_1_12_0*, "", "OVRPlugin/OVRP_1_12_0");
|
// Optimise
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
const int NAX = 2e5 + 5, MOD = 1000000007;
void solveCase()
{
int n, m, a, b;
cin >> n >> m >> a >> b;
--a, --b;
vector<int> adj[n];
for (size_t i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
--u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
vector<int> comp(n);
function<void(int, int)> dfs_comp = [&](int node, int id) -> void {
comp[node] = id;
for (auto &x : adj[node])
if (x != a && comp[x] == 0)
dfs_comp(x, id);
};
int comp_cnt = 0;
for (size_t i = 0; i < n; i++)
if (i != a && comp[i] == 0)
dfs_comp(i, ++comp_cnt);
db(comp);
vector<int> vis(n);
function<void(int)> dfs = [&](int node) -> void {
if (vis[node])
return;
vis[node] = 1;
for (auto &x : adj[node])
if (x != b && vis[x] == 0)
dfs(x);
};
dfs(a);
db(vis);
ll cnt1 = 0, cnt2 = 0;
for (size_t i = 0; i < n; i++)
{
if (i != a && comp[i] != comp[b])
cnt1++;
if (i != b && comp[i] == comp[b] && !vis[i])
cnt2++;
}
cout << cnt1 * cnt2 << '\n';
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
cin >> t;
for (int i = 1; i <= t; ++i)
{
solveCase();
#ifdef LOCAL
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
}
|
/* Copyright 2017-2018 PaGMO development team
This file is part of the PaGMO library.
The PaGMO library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any
later version.
or both in parallel, as here.
The PaGMO library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the PaGMO library. If not,
see https://www.gnu.org/licenses/. */
#ifndef PAGMO_PROBLEM_GOLOMB_RULER_HPP
#define PAGMO_PROBLEM_GOLOMB_RULER_HPP
#include <iostream>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <pagmo/detail/custom_comparisons.hpp>
#include <pagmo/exceptions.hpp>
#include <pagmo/problem.hpp> // needed for cereal registration macro
#include <pagmo/types.hpp>
namespace pagmo
{
/// The Golomb Ruler Problem
/**
*
* \image html golomb_ruler.png "The optimal Golomb Ruler of order 4" width=3cm
*
* In mathematics, a Golomb ruler is a set of marks at integer positions along an imaginary ruler such that no two pairs
* of marks are the same distance apart. The number of marks on the ruler is its order, and the largest distance between
* two of its marks is its length. Translation and reflection of a Golomb ruler are considered trivial, so the smallest
* mark is customarily put at 0 and the next mark at the smaller of its two possible values. There is no requirement
* that a Golomb ruler be able to measure all distances up to its length, but if it does, it is called a perfect Golomb
* ruler.
*
* A Golomb ruler is optimal if no shorter Golomb ruler of the same order exists. Creating Golomb rulers is easy,
* but finding the optimal Golomb ruler (or rulers) for a specified order is computationally very challenging.
*
* This UDP represents the problem of finding an optimal Golomb ruler of a given order \f$ n\f$. A maximal distance \f$
* l_{max}\f$ between consecutive marks is also specified to make the problem representation possible. The resulting
* optimization problem is an integer programming problem with one equality constraint.
*
* In this UDP, the decision vector is \f$ x=[d_1, d_2, d_{n-1}]\f$, where the distances between consecutive ticks are
* indicated with \f$ d_i\f$. The ticks on the ruler can then be reconstructed as \f$ a_0 = 0\f$, \f$ a_i = sum_{j=1}^i
* d_i, i=1 .. n-1\f$
*
* Its formulation can thus be written as:
*
* \f[
* \begin{array}{rl}
* \mbox{find:} & 1 \le d_i \le l_{max}, \forall i=1..n-1 \\
* \mbox{to minimize: } & \sum_i d_i \\
* \mbox{subject to:} & |a_i-a_j| \neq |a_l - a_m|, \forall (\mbox{distinct}) i,j,l,m \in [0, n]
* \end{array}
* \f]
*
* We transcribe the constraints as one single equality constraint: \f$ c = 0 \f$ where \f$ c\f$ is the count of
* repeated distances.
*
* See: https://en.wikipedia.org/wiki/Golomb_ruler
*
*/
class golomb_ruler
{
public:
/// Constructor from ruler order and maximal consecutive ticks distance
/**
* Constructs a Golomb Ruler problem.
*
* @param order ruler order.
* @param upper_bound maximum distance between consecutive ticks.
*
* @throw std::invalid_argument if \p order is < 2 or \p upper_bound is < 1.
* @throw std::overflow_error if \p upper_bound is too large.
*/
golomb_ruler(unsigned order = 3u, unsigned upper_bound = 10) : m_order(order), m_upper_bound(upper_bound)
{
if (order < 2u) {
pagmo_throw(std::invalid_argument, "Golomb ruler problem must have at least order 2, while "
+ std::to_string(order) + " was requested.");
}
if (upper_bound < 2u) {
pagmo_throw(
std::invalid_argument,
"The upper bound for the maximum distance between consecutive ticks has to be at least 2, while "
+ std::to_string(upper_bound) + " was requested.");
}
// Overflow can occur when evaluating the fitness later if the upper_bound is too large.
if (upper_bound > std::numeric_limits<unsigned>::max() / (order - 1u)) {
pagmo_throw(
std::overflow_error,
"Overflow in Golomb ruler problem, select a smaller maximum distance between consecutive ticks.");
}
}
/// Fitness computation
/**
* Computes the fitness for this UDP
*
* @param x the decision vector.
*
* @return the fitness of \p x.
*/
vector_double fitness(const vector_double &x) const
{
vector_double f(2, 0.);
// 1 - We compute the ticks (the ruler length will be the last tick since we start from 0)
vector_double ticks(x.size() + 1, 0.);
std::partial_sum(x.begin(), x.end(), ticks.begin() + 1u);
f[0] = ticks.back();
// 2 - We compute all pairwise distances
vector_double distances;
distances.reserve(x.size() * (x.size() - 1) / 2);
for (decltype(ticks.size()) i = 0; i < ticks.size() - 1; ++i) {
for (decltype(ticks.size()) j = i + 1; j < ticks.size(); ++j) {
distances.push_back(ticks[j] - ticks[i]);
}
}
// 3 - We compute how many duplicate distances are there.
std::sort(distances.begin(), distances.end(), detail::less_than_f<double>);
f[1] = static_cast<double>(distances.size())
- static_cast<double>(std::distance(
distances.begin(), std::unique(distances.begin(), distances.end(), detail::equal_to_f<double>)));
return f;
}
/// Box-bounds
/**
* Returns the box-bounds for this UDP.
*
* @return the lower and upper bounds for each of the decision vector components
*/
std::pair<vector_double, vector_double> get_bounds() const
{
unsigned prob_dim = m_order - 1u;
vector_double lb(prob_dim, 1);
vector_double ub(prob_dim, m_upper_bound);
return {lb, ub};
}
/// Equality constraint dimension
/**
* Returns the number of equality constraints
*
* @return the number of equality constraints
*/
vector_double::size_type get_nec() const
{
return 1u;
}
/// Integer dimension
/**
* Returns the integer dimension of the problem.
*
* @return the integer dimension of the problem.
*/
vector_double::size_type get_nix() const
{
return m_order - 1u;
}
/// Problem name
/**
* Returns the problem name.
*
* @return a string containing the problem name
*/
std::string get_name() const
{
return "Golomb Ruler (order " + std::to_string(m_order) + ")";
}
/// Object serialization
/**
* This method will save/load \p this into the archive \p ar.
*
* @param ar target archive.
*
* @throws unspecified any exception thrown by the serialization of the UDP and of primitive types.
*/
template <typename Archive>
void serialize(Archive &ar)
{
ar(m_order, m_upper_bound);
}
private:
/// Ruler Order.
unsigned m_order;
/// Maximum distance between consecutive ticks.
unsigned m_upper_bound;
};
} // namespace pagmo
PAGMO_REGISTER_PROBLEM(pagmo::golomb_ruler)
#endif
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#include "Expression.h"
#include "Operators.h"
using namespace std;
namespace Common
{
class FabricEnvironmentTest
{
protected:
FabricEnvironmentTest() { BOOST_REQUIRE(Setup()); }
TEST_CLASS_SETUP(Setup)
~FabricEnvironmentTest() { BOOST_REQUIRE(Cleanup()); }
TEST_CLASS_CLEANUP(Cleanup)
void VerifyRegistryKeyExistence(bool shouldExist);
bool registryKeyExists_;
wstring fabricDataRoot_;
wstring fabricLogRoot_;
wstring fabricBinRoot_;
wstring fabricCodePath_;
};
BOOST_FIXTURE_TEST_SUITE(FabricEnvironmentTestSuite,FabricEnvironmentTest)
BOOST_AUTO_TEST_CASE(NoEnvironmentSet)
{
wstring value;
ErrorCode error = FabricEnvironment::GetFabricBinRoot(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricBinRootNotFound));
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricCodePath(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricCodePathNotFound));
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricDataRoot(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricDataRootNotFound));
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricLogRoot(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricLogRootNotFound));
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricDnsServerIPAddress(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::DnsServerIPAddressNotFound));
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricHostServicePath(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricHostServicePathNotFound));
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetUpdaterServicePath(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::UpdaterServicePathNotFound));
VerifyRegistryKeyExistence(false);
}
BOOST_AUTO_TEST_CASE(EnvironmentVariablesSet)
{
const wstring MockDnsServerIPAddress = L"0.1.2.3";
Environment::SetEnvironmentVariableW(L"FabricDataRoot", L"FabricDataRoot");
Environment::SetEnvironmentVariableW(L"FabricBinRoot", L"FabricBinRoot");
Environment::SetEnvironmentVariableW(L"FabricCodePath", L"FabricCodePath");
Environment::SetEnvironmentVariableW(L"FabricLogRoot", L"FabricLogRoot");
Environment::SetEnvironmentVariableW(L"FabricLogRoot", L"FabricLogRoot");
Environment::SetEnvironmentVariableW(L"FabricDnsServerIPAddress", MockDnsServerIPAddress);
Environment::SetEnvironmentVariableW(L"FabricHostServicePath", L"FabricHostServicePath");
Environment::SetEnvironmentVariableW(L"UpdaterServicePath", L"UpdaterServicePath");
wstring value;
ErrorCode error = FabricEnvironment::GetFabricBinRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricBinRoot");
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricCodePath(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricCodePath");
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricDataRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricDataRoot");
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricLogRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricLogRoot");
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricDnsServerIPAddress(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, MockDnsServerIPAddress);
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetFabricHostServicePath(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricHostServicePath");
VerifyRegistryKeyExistence(false);
error = FabricEnvironment::GetUpdaterServicePath(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"UpdaterServicePath");
VerifyRegistryKeyExistence(false);
}
BOOST_AUTO_TEST_CASE(EnvironmentVariablesAndRegistryKeySet)
{
const wstring MockDnsServerIPAddressEnvtVal = L"0.1.2.3";
const wstring MockDnsServerIPAddressRegVal = L"4.5.6.7";
Environment::SetEnvironmentVariableW(L"FabricDataRoot", L"FabricDataRoot");
Environment::SetEnvironmentVariableW(L"FabricBinRoot", L"FabricBinRoot");
Environment::SetEnvironmentVariableW(L"FabricCodePath", L"FabricCodePath");
Environment::SetEnvironmentVariableW(L"FabricLogRoot", L"FabricLogRoot");
Environment::SetEnvironmentVariableW(L"EnableCircularTraceSession", L"1");
Environment::SetEnvironmentVariableW(L"FabricDnsServerIPAddress", MockDnsServerIPAddressEnvtVal);
Environment::SetEnvironmentVariableW(L"FabricHostServicePath", L"FabricHostServicePath");
Environment::SetEnvironmentVariableW(L"UpdaterServicePath", L"UpdaterServicePath");
// Create regkey
RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, false, false);
regKey.SetValue(FabricConstants::FabricDataRootRegKeyName, L"FabricDataRoot");
regKey.SetValue(FabricConstants::FabricBinRootRegKeyName, L"FabricBinRoot");
regKey.SetValue(FabricConstants::FabricCodePathRegKeyName, L"FabricCodePath");
regKey.SetValue(FabricConstants::FabricLogRootRegKeyName, L"FabricLogRoot");
regKey.SetValue(FabricConstants::EnableCircularTraceSessionRegKeyName, 1);
regKey.SetValue(FabricConstants::FabricDnsServerIPAddressRegKeyName, MockDnsServerIPAddressRegVal);
regKey.SetValue(FabricConstants::FabricHostServicePathRegKeyName, L"FabricHostServicePath");
regKey.SetValue(FabricConstants::UpdaterServicePathRegKeyName, L"UpdaterServicePath");
wstring value;
ErrorCode error = FabricEnvironment::GetFabricBinRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricBinRoot");
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricCodePath(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricCodePath");
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricDataRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricDataRoot");
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricLogRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricLogRoot");
VerifyRegistryKeyExistence(true);
BOOLEAN bValue;
error = FabricEnvironment::GetEnableCircularTraceSession(bValue);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_IS_TRUE_FMT(bValue == TRUE, "Env value 1 should be treated as true.");
VerifyRegistryKeyExistence(true);
// Verify disabled case
Environment::SetEnvironmentVariableW(L"EnableCircularTraceSession", L"0");
error = FabricEnvironment::GetEnableCircularTraceSession(bValue);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_IS_TRUE_FMT(bValue == FALSE, "Env value 0 should be treated as false.");
VerifyRegistryKeyExistence(true);
// Verify envt. var takes precedence over reg key
error = FabricEnvironment::GetFabricDnsServerIPAddress(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, MockDnsServerIPAddressEnvtVal);
VerifyRegistryKeyExistence(true);
// Remove env var and test with regkey only
Environment::SetEnvironmentVariableW(L"EnableCircularTraceSession", L"");
regKey.SetValue(FabricConstants::EnableCircularTraceSessionRegKeyName, 1);
error = FabricEnvironment::GetEnableCircularTraceSession(bValue);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_IS_TRUE_FMT(bValue == TRUE, "Registry 1 should be treated as true.");
VerifyRegistryKeyExistence(true);
Environment::SetEnvironmentVariableW(L"FabricDnsServerIPAddress", L"");
error = FabricEnvironment::GetFabricDnsServerIPAddress(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, MockDnsServerIPAddressRegVal);
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricHostServicePath(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"FabricHostServicePath");
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetUpdaterServicePath(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"UpdaterServicePath");
VerifyRegistryKeyExistence(true);
Environment::SetEnvironmentVariableW(L"FabricDataRoot", L"");
Environment::SetEnvironmentVariableW(L"FabricBinRoot", L"");
Environment::SetEnvironmentVariableW(L"FabricCodePath", L"");
Environment::SetEnvironmentVariableW(L"FabricLogRoot", L"");
Environment::SetEnvironmentVariableW(L"EnableCircularTraceSession", L"1");
Environment::SetEnvironmentVariableW(L"FabricHostServicePath", L"");
Environment::SetEnvironmentVariableW(L"UpdaterServicePath", L"");
}
BOOST_AUTO_TEST_CASE(OnlyRegistryRootSet)
{
// Create regkey
RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, false, false);
regKey.SetValue(FabricConstants::EnableCircularTraceSessionRegKeyName, 1);
wstring value;
ErrorCode error = FabricEnvironment::GetFabricBinRoot(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricBinRootNotFound));
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricCodePath(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricCodePathNotFound));
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricDataRoot(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricDataRootNotFound));
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricLogRoot(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricLogRootNotFound));
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricDnsServerIPAddress(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::DnsServerIPAddressNotFound));
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetFabricHostServicePath(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::FabricHostServicePathNotFound));
VerifyRegistryKeyExistence(true);
error = FabricEnvironment::GetUpdaterServicePath(value);
VERIFY_IS_TRUE(error.IsError(ErrorCodeValue::UpdaterServicePathNotFound));
VerifyRegistryKeyExistence(true);
}
BOOST_AUTO_TEST_CASE(RegistryKeySet)
{
VERIFY_IS_TRUE(true);
}
BOOST_AUTO_TEST_CASE(ExpandVariable)
{
Environment::SetEnvironmentVariableW(L"__TestEnv", L"TestEnv");
Environment::SetEnvironmentVariableW(L"FabricDataRoot", L"%__TestEnv%\\FabricDataRoot");
wstring value;
ErrorCode error = FabricEnvironment::GetFabricDataRoot(value);
VERIFY_IS_TRUE(error.IsSuccess());
VERIFY_ARE_EQUAL2(value, L"TestEnv\\FabricDataRoot");
VerifyRegistryKeyExistence(false);
VERIFY_IS_TRUE(true);
}
BOOST_AUTO_TEST_SUITE_END()
bool FabricEnvironmentTest::Setup()
{
RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, true, true);
if (regKey.IsValid)
{
registryKeyExists_ = true;
if (!regKey.GetValue(FabricConstants::FabricCodePathRegKeyName, this->fabricCodePath_))
{
this->fabricCodePath_ = L"";
}
else
{
regKey.DeleteValue(FabricConstants::FabricCodePathRegKeyName);
}
if (!regKey.GetValue(FabricConstants::FabricDataRootRegKeyName, this->fabricDataRoot_))
{
this->fabricDataRoot_ = L"";
}
else
{
regKey.DeleteValue(FabricConstants::FabricDataRootRegKeyName);
}
if (!regKey.GetValue(FabricConstants::FabricLogRootRegKeyName, this->fabricLogRoot_))
{
this->fabricLogRoot_ = L"";
}
else
{
regKey.DeleteValue(FabricConstants::FabricLogRootRegKeyName);
}
if (!regKey.GetValue(FabricConstants::FabricBinRootRegKeyName, this->fabricBinRoot_))
{
this->fabricBinRoot_ = L"";
}
else
{
regKey.DeleteValue(FabricConstants::FabricBinRootRegKeyName);
}
return regKey.DeleteKey();
}
return true;
}
bool FabricEnvironmentTest::Cleanup()
{
RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, true, true);
if (regKey.IsValid)
{
if (registryKeyExists_ == true)
{
if (this->fabricCodePath_ != L"")
{
regKey.SetValue(FabricConstants::FabricCodePathRegKeyName, this->fabricCodePath_);
}
if (this->fabricDataRoot_ != L"")
{
regKey.SetValue(FabricConstants::FabricDataRootRegKeyName, this->fabricDataRoot_);
}
if (this->fabricLogRoot_ != L"")
{
regKey.SetValue(FabricConstants::FabricLogRootRegKeyName, this->fabricLogRoot_);
}
if (this->fabricBinRoot_ != L"")
{
regKey.SetValue(FabricConstants::FabricBinRootRegKeyName, this->fabricBinRoot_);
}
}
else
{
regKey.DeleteKey();
}
}
return true;
}
void FabricEnvironmentTest::VerifyRegistryKeyExistence(bool shouldExist)
{
RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, true, true);
VERIFY_ARE_EQUAL2(shouldExist, regKey.IsValid);
}
}
|
/*
* Copyright 2011, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Oliver Tappe <zooey@hirschkaefer.de>
* Ingo Weinhold <ingo_weinhold@gmx.de>
*/
#include <package/PackageInfoSet.h>
#include <new>
#include <Referenceable.h>
#include <AutoDeleter.h>
#include <util/OpenHashTable.h>
#include <package/PackageInfo.h>
namespace BPackageKit {
// #pragma mark - PackageInfo
struct BPackageInfoSet::PackageInfo : public BPackageInfo {
PackageInfo* hashNext;
PackageInfo* listNext;
PackageInfo(const BPackageInfo& other)
:
BPackageInfo(other),
listNext(NULL)
{
}
void DeleteList()
{
PackageInfo* info = this;
while (info != NULL) {
PackageInfo* next = info->listNext;
delete info;
info = next;
}
}
};
// #pragma mark - PackageInfoHashDefinition
struct BPackageInfoSet::PackageInfoHashDefinition {
typedef const char* KeyType;
typedef PackageInfo ValueType;
size_t HashKey(const char* key) const
{
return BString::HashValue(key);
}
size_t Hash(const PackageInfo* value) const
{
return value->Name().HashValue();
}
bool Compare(const char* key, const PackageInfo* value) const
{
return value->Name() == key;
}
PackageInfo*& GetLink(PackageInfo* value) const
{
return value->hashNext;
}
};
// #pragma mark - PackageMap
struct BPackageInfoSet::PackageMap : public BReferenceable,
public BOpenHashTable<PackageInfoHashDefinition> {
PackageMap()
:
fCount(0)
{
}
~PackageMap()
{
DeleteAllPackageInfos();
}
static PackageMap* Create()
{
PackageMap* map = new(std::nothrow) PackageMap;
if (map == NULL || map->Init() != B_OK) {
delete map;
return NULL;
}
return map;
}
PackageMap* Clone() const
{
PackageMap* newMap = Create();
if (newMap == NULL)
return NULL;
ObjectDeleter<PackageMap> newMapDeleter(newMap);
for (BPackageInfoSet::Iterator it(this); it.HasNext();) {
const BPackageInfo* info = it.Next();
if (newMap->AddNewPackageInfo(*info) != B_OK)
return NULL;
}
return newMapDeleter.Detach();
}
void AddPackageInfo(PackageInfo* info)
{
if (PackageInfo* oldInfo = Lookup(info->Name())) {
info->listNext = oldInfo->listNext;
oldInfo->listNext = info;
} else
Insert(info);
fCount++;
}
status_t AddNewPackageInfo(const BPackageInfo& oldInfo)
{
PackageInfo* info = new(std::nothrow) PackageInfo(oldInfo);
if (info == NULL)
return B_NO_MEMORY;
ObjectDeleter<PackageInfo> infoDeleter(info);
status_t error = info->InitCheck();
if (error != B_OK)
return error;
AddPackageInfo(infoDeleter.Detach());
return B_OK;
}
void DeleteAllPackageInfos()
{
PackageInfo* info = Clear(true);
while (info != NULL) {
PackageInfo* next = info->hashNext;
info->DeleteList();
info = next;
}
}
uint32 CountPackageInfos() const
{
return fCount;
}
private:
uint32 fCount;
};
// #pragma mark - Iterator
BPackageInfoSet::Iterator::Iterator(const PackageMap* map)
:
fMap(map),
fNextInfo(map != NULL ? map->GetIterator().Next() : NULL)
{
}
bool BPackageInfoSet::Iterator::HasNext() const
{
return fNextInfo != NULL;
}
const BPackageInfo*
BPackageInfoSet::Iterator::Next()
{
BPackageInfo* result = fNextInfo;
if (fNextInfo != NULL) {
if (fNextInfo->listNext != NULL) {
// get next in list
fNextInfo = fNextInfo->listNext;
} else {
// get next in hash table
PackageMap::Iterator iterator
= fMap->GetIterator(fNextInfo->Name());
iterator.Next();
fNextInfo = iterator.Next();
}
}
return result;
}
// #pragma mark - BPackageInfoSet
BPackageInfoSet::BPackageInfoSet()
:
fPackageMap(NULL)
{
}
BPackageInfoSet::~BPackageInfoSet()
{
if (fPackageMap != NULL)
fPackageMap->ReleaseReference();
}
BPackageInfoSet::BPackageInfoSet(const BPackageInfoSet& other)
:
fPackageMap(other.fPackageMap)
{
if (fPackageMap != NULL)
fPackageMap->AcquireReference();
}
status_t BPackageInfoSet::AddInfo(const BPackageInfo& info)
{
if (!_CopyOnWrite())
return B_NO_MEMORY;
return fPackageMap->AddNewPackageInfo(info);
}
void BPackageInfoSet::MakeEmpty()
{
if (fPackageMap == NULL || fPackageMap->CountPackageInfos() == 0)
return;
// If our map is shared, just set it to NULL.
if (fPackageMap->CountReferences() != 1) {
fPackageMap->ReleaseReference();
fPackageMap = NULL;
return;
}
// Our map is not shared -- make it empty.
fPackageMap->DeleteAllPackageInfos();
}
uint32 BPackageInfoSet::CountInfos() const
{
if (fPackageMap == NULL)
return 0;
return fPackageMap->CountPackageInfos();
}
BPackageInfoSet::Iterator
BPackageInfoSet::GetIterator() const
{
return Iterator(fPackageMap);
}
BPackageInfoSet&
BPackageInfoSet::operator=(const BPackageInfoSet& other)
{
if (other.fPackageMap == fPackageMap)
return *this;
if (fPackageMap != NULL)
fPackageMap->ReleaseReference();
fPackageMap = other.fPackageMap;
if (fPackageMap != NULL)
fPackageMap->AcquireReference();
return *this;
}
bool BPackageInfoSet::_CopyOnWrite()
{
if (fPackageMap == NULL) {
fPackageMap = PackageMap::Create();
return fPackageMap != NULL;
}
if (fPackageMap->CountReferences() == 1)
return true;
PackageMap* newMap = fPackageMap->Clone();
if (newMap == NULL)
return false;
fPackageMap->ReleaseReference();
fPackageMap = newMap;
return true;
}
} // namespace BPackageKit
|
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Developed by Minigraph
//
// Author: James Stanard
//
#include "pch.h"
#include "SystemTime.h"
#include "GraphicsCore.h"
#include "TextRenderer.h"
#include "GraphRenderer.h"
#include "GameInput.h"
#include "GpuTimeManager.h"
#include "CommandContext.h"
#include <vector>
#include <unordered_map>
#include <array>
using namespace Graphics;
using namespace GraphRenderer;
using namespace Math;
using namespace std;
#define PERF_GRAPH_ERROR uint32_t(0xFFFFFFFF)
namespace EngineProfiling
{
bool Paused = false;
}
class StatHistory
{
public:
StatHistory()
{
for (uint32_t i = 0; i < kHistorySize; ++i)
m_RecentHistory[i] = 0.0f;
for (uint32_t i = 0; i < kExtendedHistorySize; ++i)
m_ExtendedHistory[i] = 0.0f;
m_Average = 0.0f;
m_Minimum = 0.0f;
m_Maximum = 0.0f;
}
void RecordStat( uint32_t FrameIndex, float Value )
{
m_RecentHistory[FrameIndex % kHistorySize] = Value;
m_ExtendedHistory[FrameIndex % kExtendedHistorySize] = Value;
m_Recent = Value;
uint32_t ValidCount = 0;
m_Minimum = FLT_MAX;
m_Maximum = 0.0f;
m_Average = 0.0f;
for (float val : m_RecentHistory)
{
if (val > 0.0f)
{
++ValidCount;
m_Average += val;
m_Minimum = min(val, m_Minimum);
m_Maximum = max(val, m_Maximum);
}
}
if (ValidCount > 0)
m_Average /= (float)ValidCount;
else
m_Minimum = 0.0f;
}
float GetLast(void) const { return m_Recent; }
float GetMax(void) const { return m_Maximum; }
float GetMin(void) const { return m_Minimum; }
float GetAvg(void) const { return m_Average; }
const float* GetHistory(void) const { return m_ExtendedHistory; }
uint32_t GetHistoryLength(void) const { return kExtendedHistorySize; }
private:
static const uint32_t kHistorySize = 64;
static const uint32_t kExtendedHistorySize = 256;
float m_RecentHistory[kHistorySize];
float m_ExtendedHistory[kExtendedHistorySize];
float m_Recent;
float m_Average;
float m_Minimum;
float m_Maximum;
};
class StatPlot
{
public:
StatPlot(StatHistory& Data, Color Col = Color(1.0f, 1.0f, 1.0f))
: m_StatData(Data), m_PlotColor(Col)
{
}
void SetColor( Color Col )
{
m_PlotColor = Col;
}
private:
StatHistory& m_StatData;
Color m_PlotColor;
};
class StatGraph
{
public:
StatGraph(const wstring& Label, D3D12_RECT Window)
: m_Label(Label), m_Window(Window), m_BGColor(0.0f, 0.0f, 0.0f, 0.2f)
{
}
void SetLabel(const wstring& Label)
{
m_Label = Label;
}
void SetWindow(D3D12_RECT Window)
{
m_Window = Window;
}
uint32_t AddPlot( const StatPlot& P )
{
uint32_t Idx = (uint32_t)m_Stats.size();
m_Stats.push_back(P);
return Idx;
}
StatPlot& GetPlot( uint32_t Handle );
void Draw( GraphicsContext& Context );
private:
wstring m_Label;
D3D12_RECT m_Window;
vector<StatPlot> m_Stats;
Color m_BGColor;
float m_PeakValue;
};
class GraphManager
{
public:
private:
vector<StatGraph> m_Graphs;
};
class GpuTimer
{
public:
GpuTimer::GpuTimer()
{
m_TimerIndex = GpuTimeManager::NewTimer();
}
void Start(CommandContext& Context)
{
GpuTimeManager::StartTimer(Context, m_TimerIndex);
}
void Stop(CommandContext& Context)
{
GpuTimeManager::StopTimer(Context, m_TimerIndex);
}
float GpuTimer::GetTime(void)
{
return GpuTimeManager::GetTime(m_TimerIndex);
}
uint32_t GetTimerIndex(void)
{
return m_TimerIndex;
}
private:
uint32_t m_TimerIndex;
};
class NestedTimingTree
{
public:
NestedTimingTree( const wstring& name, NestedTimingTree* parent = nullptr )
: m_Name(name), m_Parent(parent), m_IsExpanded(false), m_IsGraphed(false), m_GraphHandle(PERF_GRAPH_ERROR) {}
NestedTimingTree* GetChild( const wstring& name )
{
auto iter = m_LUT.find(name);
if (iter != m_LUT.end())
return iter->second;
NestedTimingTree* node = new NestedTimingTree(name, this);
m_Children.push_back(node);
m_LUT[name] = node;
return node;
}
NestedTimingTree* NextScope( void )
{
if (m_IsExpanded && m_Children.size() > 0)
return m_Children[0];
return m_Parent->NextChild(this);
}
NestedTimingTree* PrevScope( void )
{
NestedTimingTree* prev = m_Parent->PrevChild(this);
return prev == m_Parent ? prev : prev->LastChild();
}
NestedTimingTree* FirstChild( void )
{
return m_Children.size() == 0 ? nullptr : m_Children[0];
}
NestedTimingTree* LastChild( void )
{
if (!m_IsExpanded || m_Children.size() == 0)
return this;
return m_Children.back()->LastChild();
}
NestedTimingTree* NextChild( NestedTimingTree* curChild )
{
ASSERT(curChild->m_Parent == this);
for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)
{
if (*iter == curChild)
{
auto nextChild = iter; ++nextChild;
if (nextChild != m_Children.end())
return *nextChild;
}
}
if (m_Parent != nullptr)
return m_Parent->NextChild(this);
else
return &sm_RootScope;
}
NestedTimingTree* PrevChild( NestedTimingTree* curChild )
{
ASSERT(curChild->m_Parent == this);
if (*m_Children.begin() == curChild)
{
if (this == &sm_RootScope)
return sm_RootScope.LastChild();
else
return this;
}
for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)
{
if (*iter == curChild)
{
auto prevChild = iter; --prevChild;
return *prevChild;
}
}
ERROR("All attempts to find a previous timing sample failed");
return nullptr;
}
void StartTiming( CommandContext* Context )
{
m_StartTick = SystemTime::GetCurrentTick();
if (Context == nullptr)
return;
m_GpuTimer.Start(*Context);
Context->PIXBeginEvent(m_Name.c_str());
}
void StopTiming( CommandContext* Context )
{
m_EndTick = SystemTime::GetCurrentTick();
if (Context == nullptr)
return;
m_GpuTimer.Stop(*Context);
Context->PIXEndEvent();
}
void GatherTimes(uint32_t FrameIndex)
{
if (sm_SelectedScope == this)
{
GraphRenderer::SetSelectedIndex(m_GpuTimer.GetTimerIndex());
}
if (EngineProfiling::Paused)
{
for (auto node : m_Children)
node->GatherTimes(FrameIndex);
return;
}
m_CpuTime.RecordStat(FrameIndex, 1000.0f * (float)SystemTime::TimeBetweenTicks(m_StartTick, m_EndTick));
m_GpuTime.RecordStat(FrameIndex, 1000.0f * m_GpuTimer.GetTime());
for (auto node : m_Children)
node->GatherTimes(FrameIndex);
m_StartTick = 0;
m_EndTick = 0;
}
void SumInclusiveTimes(float& cpuTime, float& gpuTime)
{
cpuTime = 0.0f;
gpuTime = 0.0f;
for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)
{
cpuTime += (*iter)->m_CpuTime.GetLast();
gpuTime += (*iter)->m_GpuTime.GetLast();
}
}
static void PushProfilingMarker( const wstring& name, CommandContext* Context );
static void PopProfilingMarker( CommandContext* Context );
static void Update( void );
static void UpdateTimes( void )
{
uint32_t FrameIndex = (uint32_t)Graphics::GetFrameCount();
GpuTimeManager::BeginReadBack();
sm_RootScope.GatherTimes(FrameIndex);
s_FrameDelta.RecordStat(FrameIndex, GpuTimeManager::GetTime(0));
GpuTimeManager::EndReadBack();
float TotalCpuTime, TotalGpuTime;
sm_RootScope.SumInclusiveTimes(TotalCpuTime, TotalGpuTime);
s_TotalCpuTime.RecordStat(FrameIndex, TotalCpuTime);
s_TotalGpuTime.RecordStat(FrameIndex, TotalGpuTime);
GraphRenderer::Update(XMFLOAT2(TotalCpuTime, TotalGpuTime), 0, GraphType::Global);
}
static float GetTotalCpuTime(void) { return s_TotalCpuTime.GetAvg(); }
static float GetTotalGpuTime(void) { return s_TotalGpuTime.GetAvg(); }
static float GetFrameDelta(void) { return s_FrameDelta.GetAvg(); }
static void Display( TextContext& Text, float x )
{
float curX = Text.GetCursorX();
Text.DrawString(" ");
float indent = Text.GetCursorX() - curX;
Text.SetCursorX(curX);
sm_RootScope.DisplayNode( Text, x - indent, indent );
sm_RootScope.StoreToGraph();
}
void Toggle()
{
//if (m_GraphHandle == PERF_GRAPH_ERROR)
// m_GraphHandle = GraphRenderer::InitGraph(GraphType::Profile);
//m_IsGraphed = GraphRenderer::ManageGraphs(m_GraphHandle, GraphType::Profile);
}
bool IsGraphed(){ return m_IsGraphed;}
private:
void DisplayNode( TextContext& Text, float x, float indent );
void StoreToGraph(void);
void DeleteChildren( void )
{
for (auto node : m_Children)
delete node;
m_Children.clear();
}
wstring m_Name;
NestedTimingTree* m_Parent;
vector<NestedTimingTree*> m_Children;
unordered_map<wstring, NestedTimingTree*> m_LUT;
int64_t m_StartTick;
int64_t m_EndTick;
StatHistory m_CpuTime;
StatHistory m_GpuTime;
bool m_IsExpanded;
GpuTimer m_GpuTimer;
bool m_IsGraphed;
GraphHandle m_GraphHandle;
static StatHistory s_TotalCpuTime;
static StatHistory s_TotalGpuTime;
static StatHistory s_FrameDelta;
static NestedTimingTree sm_RootScope;
static NestedTimingTree* sm_CurrentNode;
static NestedTimingTree* sm_SelectedScope;
static bool sm_CursorOnGraph;
};
StatHistory NestedTimingTree::s_TotalCpuTime;
StatHistory NestedTimingTree::s_TotalGpuTime;
StatHistory NestedTimingTree::s_FrameDelta;
NestedTimingTree NestedTimingTree::sm_RootScope(L"");
NestedTimingTree* NestedTimingTree::sm_CurrentNode = &NestedTimingTree::sm_RootScope;
NestedTimingTree* NestedTimingTree::sm_SelectedScope = &NestedTimingTree::sm_RootScope;
bool NestedTimingTree::sm_CursorOnGraph = false;
namespace EngineProfiling
{
BoolVar DrawFrameRate("Display Frame Rate", true);
BoolVar DrawProfiler("Display Profiler", false);
//BoolVar DrawPerfGraph("Display Performance Graph", false);
const bool DrawPerfGraph = false;
void Update( void )
{
if (GameInput::IsFirstPressed( GameInput::kStartButton )
|| GameInput::IsFirstPressed( GameInput::kKey_space ))
{
Paused = !Paused;
}
NestedTimingTree::UpdateTimes();
}
void BeginBlock(const wstring& name, CommandContext* Context)
{
NestedTimingTree::PushProfilingMarker(name, Context);
}
void EndBlock(CommandContext* Context)
{
NestedTimingTree::PopProfilingMarker(Context);
}
bool IsPaused()
{
return Paused;
}
void DisplayFrameRate( TextContext& Text )
{
if (!DrawFrameRate)
return;
float cpuTime = NestedTimingTree::GetTotalCpuTime();
float gpuTime = NestedTimingTree::GetTotalGpuTime();
float frameRate = 1.0f / NestedTimingTree::GetFrameDelta();
Text.DrawFormattedString( "%7.3f ms, %3u Hz\n",
gpuTime, (uint32_t)(frameRate + 0.5f));
}
void DisplayPerfGraph( GraphicsContext& Context )
{
if (DrawPerfGraph)
GraphRenderer::RenderGraphs(Context, GraphType::Global );
}
void Display( TextContext& Text, float x, float y, float /*w*/, float /*h*/ )
{
Text.ResetCursor(x, y);
if (DrawProfiler)
{
//Text.GetCommandContext().SetScissor((uint32_t)Floor(x), (uint32_t)Floor(y), (uint32_t)Ceiling(w), (uint32_t)Ceiling(h));
NestedTimingTree::Update();
Text.SetColor( Color(0.5f, 1.0f, 1.0f) );
Text.DrawString("Engine Profiling");
Text.SetColor(Color(0.8f, 0.8f, 0.8f));
Text.SetTextSize(20.0f);
Text.DrawString(" CPU GPU");
Text.SetTextSize(24.0f);
Text.NewLine();
Text.SetTextSize(20.0f);
Text.SetColor( Color(1.0f, 1.0f, 1.0f) );
NestedTimingTree::Display( Text, x );
}
Text.GetCommandContext().SetScissor(0, 0, g_DisplayWidth, g_DisplayHeight);
}
} // EngineProfiling
void NestedTimingTree::PushProfilingMarker( const wstring& name, CommandContext* Context )
{
sm_CurrentNode = sm_CurrentNode->GetChild(name);
sm_CurrentNode->StartTiming(Context);
}
void NestedTimingTree::PopProfilingMarker( CommandContext* Context )
{
sm_CurrentNode->StopTiming(Context);
sm_CurrentNode = sm_CurrentNode->m_Parent;
}
void NestedTimingTree::Update( void )
{
ASSERT(sm_SelectedScope != nullptr, "Corrupted profiling data structure");
if (sm_SelectedScope == &sm_RootScope)
{
sm_SelectedScope = sm_RootScope.FirstChild();
if (sm_SelectedScope == &sm_RootScope)
return;
}
if (GameInput::IsFirstPressed( GameInput::kDPadLeft )
|| GameInput::IsFirstPressed( GameInput::kKey_numpad1 ))
{
//if still on graphs go back to text
if (sm_CursorOnGraph)
sm_CursorOnGraph = !sm_CursorOnGraph;
else
sm_SelectedScope->m_IsExpanded = false;
}
else if (GameInput::IsFirstPressed( GameInput::kDPadRight )
|| GameInput::IsFirstPressed( GameInput::kKey_numpad3))
{
if (sm_SelectedScope->m_IsExpanded == true && !sm_CursorOnGraph)
sm_CursorOnGraph = true;
else
sm_SelectedScope->m_IsExpanded = true;
//if already expanded go over to graphs
}
else if (GameInput::IsFirstPressed( GameInput::kDPadDown )
|| GameInput::IsFirstPressed( GameInput::kKey_numpad2))
{
sm_SelectedScope = sm_SelectedScope ? sm_SelectedScope->NextScope() : nullptr;
}
else if (GameInput::IsFirstPressed( GameInput::kDPadUp )
|| GameInput::IsFirstPressed( GameInput::kKey_numpad5))
{
sm_SelectedScope = sm_SelectedScope ? sm_SelectedScope->PrevScope() : nullptr;
}
else if (GameInput::IsFirstPressed( GameInput::kAButton )
|| GameInput::IsFirstPressed( GameInput::kKey_return ))
{
sm_SelectedScope->Toggle();
}
}
void NestedTimingTree::DisplayNode( TextContext& Text, float leftMargin, float indent )
{
if (this == &sm_RootScope)
{
m_IsExpanded = true;
sm_RootScope.FirstChild()->m_IsExpanded = true;
}
else
{
if (sm_SelectedScope == this && !sm_CursorOnGraph)
Text.SetColor( Color(1.0f, 1.0f, 0.5f) );
else
Text.SetColor( Color(1.0f, 1.0f, 1.0f) );
Text.SetLeftMargin(leftMargin);
Text.SetCursorX(leftMargin);
if (m_Children.size() == 0)
Text.DrawString(" ");
else if (m_IsExpanded)
Text.DrawString("- ");
else
Text.DrawString("+ ");
Text.DrawString(m_Name.c_str());
Text.SetCursorX(leftMargin + 300.0f);
Text.DrawFormattedString("%6.3f %6.3f ", m_CpuTime.GetAvg(), m_GpuTime.GetAvg());
if (IsGraphed())
{
Text.SetColor(GraphRenderer::GetGraphColor(m_GraphHandle, GraphType::Profile));
Text.DrawString(" []\n");
}
else
Text.DrawString("\n");
}
if (!m_IsExpanded)
return;
for (auto node : m_Children)
node->DisplayNode(Text, leftMargin + indent, indent);
}
void NestedTimingTree::StoreToGraph(void)
{
if (m_GraphHandle != PERF_GRAPH_ERROR)
GraphRenderer::Update( XMFLOAT2(m_CpuTime.GetLast(), m_GpuTime.GetLast()), m_GraphHandle, GraphType::Profile);
for (auto node : m_Children)
node->StoreToGraph();
}
|
/*
* sgwsOverloadControlInformationInCreateBearerResponse.cpp
*
* Revisit header later
* Author: hariharanb
*/
#include "sgwsOverloadControlInformationInCreateBearerResponse.h"
#include "manual/gtpV2Ie.h"
#include "gtpV2IeFactory.h"
#include "sequenceNumberIe.h"
#include "metricIe.h"
#include "epcTimerIe.h"
SgwsOverloadControlInformationInCreateBearerResponse::
SgwsOverloadControlInformationInCreateBearerResponse()
{
Uint16 mandIe;
mandIe = SequenceNumberIeType;
mandIe = (mandIe << 8) | 0; // overloadControlSequenceNumber
mandatoryIeSet.insert(mandIe);
mandIe = MetricIeType;
mandIe = (mandIe << 8) | 0; // overloadReductionMetric
mandatoryIeSet.insert(mandIe);
mandIe = EpcTimerIeType;
mandIe = (mandIe << 8) | 0; // periodOfValidity
mandatoryIeSet.insert(mandIe);
}
SgwsOverloadControlInformationInCreateBearerResponse::
~SgwsOverloadControlInformationInCreateBearerResponse()
{
}
bool SgwsOverloadControlInformationInCreateBearerResponse::
encodeSgwsOverloadControlInformationInCreateBearerResponse(MsgBuffer &buffer,
SgwsOverloadControlInformationInCreateBearerResponseData
const &data)
{
bool rc = false;
GtpV2IeHeader header;
Uint16 startIndex = 0;
Uint16 endIndex = 0;
Uint16 length = 0;
// Encode the Ie Header
header.ieType = SequenceNumberIeType;
header.instance = 0;
header.length = 0; // We will encode the IE first and then update the length
GtpV2Ie::encodeGtpV2IeHeader(buffer, header);
startIndex = buffer.getCurrentIndex();
SequenceNumberIe sequenceNumber=
dynamic_cast<
SequenceNumberIe&>(GtpV2IeFactory::getInstance().getIeObject(SequenceNumberIeType));
rc = sequenceNumber.encodeSequenceNumberIe(buffer, data.overloadControlSequenceNumber);
endIndex = buffer.getCurrentIndex();
length = endIndex - startIndex;
// encode the length value now
buffer.goToIndex(startIndex - 3);
buffer.writeUint16(length, false);
buffer.goToIndex(endIndex);
if (!(rc))
{
errorStream.add("Failed to encode IE: overloadControlSequenceNumber\n");
return false;
}
// Encode the Ie Header
header.ieType = MetricIeType;
header.instance = 0;
header.length = 0; // We will encode the IE first and then update the length
GtpV2Ie::encodeGtpV2IeHeader(buffer, header);
startIndex = buffer.getCurrentIndex();
MetricIe metric=
dynamic_cast<
MetricIe&>(GtpV2IeFactory::getInstance().getIeObject(MetricIeType));
rc = metric.encodeMetricIe(buffer, data.overloadReductionMetric);
endIndex = buffer.getCurrentIndex();
length = endIndex - startIndex;
// encode the length value now
buffer.goToIndex(startIndex - 3);
buffer.writeUint16(length, false);
buffer.goToIndex(endIndex);
if (!(rc))
{
errorStream.add("Failed to encode IE: overloadReductionMetric\n");
return false;
}
// Encode the Ie Header
header.ieType = EpcTimerIeType;
header.instance = 0;
header.length = 0; // We will encode the IE first and then update the length
GtpV2Ie::encodeGtpV2IeHeader(buffer, header);
startIndex = buffer.getCurrentIndex();
EpcTimerIe epcTimer=
dynamic_cast<
EpcTimerIe&>(GtpV2IeFactory::getInstance().getIeObject(EpcTimerIeType));
rc = epcTimer.encodeEpcTimerIe(buffer, data.periodOfValidity);
endIndex = buffer.getCurrentIndex();
length = endIndex - startIndex;
// encode the length value now
buffer.goToIndex(startIndex - 3);
buffer.writeUint16(length, false);
buffer.goToIndex(endIndex);
if (!(rc))
{
errorStream.add("Failed to encode IE: periodOfValidity\n");
return false;
}
return rc;
}
bool SgwsOverloadControlInformationInCreateBearerResponse::
decodeSgwsOverloadControlInformationInCreateBearerResponse(MsgBuffer &buffer,
SgwsOverloadControlInformationInCreateBearerResponseData
&data, Uint16 length)
{
bool rc = false;
GtpV2IeHeader ieHeader;
set<Uint16> mandatoryIeLocalList = mandatoryIeSet;
while (buffer.lengthLeft() > IE_HEADER_SIZE)
{
GtpV2Ie::decodeGtpV2IeHeader(buffer, ieHeader);
if (ieHeader.length > buffer.lengthLeft())
{
// We do not have enough bytes left in the message for this IE
errorStream.add("IE Length exceeds beyond message boundary\n");
errorStream.add(" Offending IE Type: ");
errorStream.add(ieHeader.ieType);
errorStream.add("\n Ie Length in Header: ");
errorStream.add(ieHeader.length);
errorStream.add("\n Bytes left in message: ");
errorStream.add(buffer.lengthLeft());
errorStream.endOfLine();
return false;
}
switch (ieHeader.ieType){
case SequenceNumberIeType:
{
SequenceNumberIe ieObject =
dynamic_cast<
SequenceNumberIe&>(GtpV2IeFactory::getInstance().
getIeObject(SequenceNumberIeType));
if(ieHeader.instance == 0)
{
rc = ieObject.decodeSequenceNumberIe(buffer, data.overloadControlSequenceNumber, ieHeader.length);
if (!(rc))
{
errorStream.add("Failed to decode IE: overloadControlSequenceNumber\n");
return false;
}
Uint16 mandIe = SequenceNumberIeType;
mandIe = (mandIe << 8) | 0;
mandatoryIeLocalList.erase(mandIe);
}
else
{
// Unknown IE instance print error TODO
errorStream.add("Unknown IE Type: ");
errorStream.add(ieHeader.ieType);
errorStream.endOfLine();
buffer.skipBytes(ieHeader.length);
}
break;
}
case MetricIeType:
{
MetricIe ieObject =
dynamic_cast<
MetricIe&>(GtpV2IeFactory::getInstance().
getIeObject(MetricIeType));
if(ieHeader.instance == 0)
{
rc = ieObject.decodeMetricIe(buffer, data.overloadReductionMetric, ieHeader.length);
if (!(rc))
{
errorStream.add("Failed to decode IE: overloadReductionMetric\n");
return false;
}
Uint16 mandIe = MetricIeType;
mandIe = (mandIe << 8) | 0;
mandatoryIeLocalList.erase(mandIe);
}
else
{
// Unknown IE instance print error TODO
errorStream.add("Unknown IE Type: ");
errorStream.add(ieHeader.ieType);
errorStream.endOfLine();
buffer.skipBytes(ieHeader.length);
}
break;
}
case EpcTimerIeType:
{
EpcTimerIe ieObject =
dynamic_cast<
EpcTimerIe&>(GtpV2IeFactory::getInstance().
getIeObject(EpcTimerIeType));
if(ieHeader.instance == 0)
{
rc = ieObject.decodeEpcTimerIe(buffer, data.periodOfValidity, ieHeader.length);
if (!(rc))
{
errorStream.add("Failed to decode IE: periodOfValidity\n");
return false;
}
Uint16 mandIe = EpcTimerIeType;
mandIe = (mandIe << 8) | 0;
mandatoryIeLocalList.erase(mandIe);
}
else
{
// Unknown IE instance print error TODO
errorStream.add("Unknown IE Type: ");
errorStream.add(ieHeader.ieType);
errorStream.endOfLine();
buffer.skipBytes(ieHeader.length);
}
break;
}
default:
{
// Unknown IE print error
errorStream.add("Unknown IE Type: ");
errorStream.add(ieHeader.ieType);
errorStream.endOfLine();
buffer.skipBytes(ieHeader.length);
}
}
}
if (!mandatoryIeLocalList.empty())
{
// some mandatory IEs are missing
errorStream.add("Missing Mandatory IEs:");
errorStream.endOfLine();
while (!mandatoryIeLocalList.empty())
{
Uint16 missingMandIe = *mandatoryIeLocalList.begin ();
mandatoryIeLocalList.erase (mandatoryIeLocalList.begin ());
Uint16 missingInstance = missingMandIe & 0x00FF;
Uint16 missingIeType = (missingMandIe >> 8);
errorStream.add ("Missing Ie type: ");
errorStream.add (missingIeType);
errorStream.add (" Instance: ");
errorStream.add (missingInstance);
errorStream.endOfLine();
}
rc = false;
}
return rc;
}
void SgwsOverloadControlInformationInCreateBearerResponse::
displaySgwsOverloadControlInformationInCreateBearerResponseData_v
(SgwsOverloadControlInformationInCreateBearerResponseData const &data, Debug &stream)
{
stream.incrIndent();
stream.add("SgwsOverloadControlInformationInCreateBearerResponse:");
stream.endOfLine();
stream.incrIndent();
stream.decrIndent();
stream.decrIndent();
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_struct_declare_13.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.nonpointer.label.xml
Template File: sources-sink-13.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_struct_declare_13
{
#ifndef OMITBAD
void bad()
{
twoIntsStruct * data;
data = NULL; /* Initialize data */
if(GLOBAL_CONST_FIVE==5)
{
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
twoIntsStruct dataBuffer;
dataBuffer.intOne = 1;
dataBuffer.intTwo = 1;
data = &dataBuffer;
}
}
printStructLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */
static void goodG2B1()
{
twoIntsStruct * data;
data = NULL; /* Initialize data */
if(GLOBAL_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
twoIntsStruct * dataBuffer = new twoIntsStruct;
dataBuffer->intOne = 2;
dataBuffer->intTwo = 2;
data = dataBuffer;
}
}
printStructLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
twoIntsStruct * data;
data = NULL; /* Initialize data */
if(GLOBAL_CONST_FIVE==5)
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
twoIntsStruct * dataBuffer = new twoIntsStruct;
dataBuffer->intOne = 2;
dataBuffer->intTwo = 2;
data = dataBuffer;
}
}
printStructLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
void good()
{
goodG2B1();
goodG2B2();
}
#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 CWE590_Free_Memory_Not_on_Heap__delete_struct_declare_13; /* 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
|
#include <cstdio>
#include <iostream>
#include <queue>
#include <climits>
using namespace std;
int top, numnodes;
struct node {
int flow, dst;
node *next, *rev;
} pool[12580], *H[12580];
void Edge(int from, int to, int cap) {
node *pA = &pool[top++], *re = &pool[top++];
pA->dst = to;
pA->flow = cap;
pA->next = H[from];
H[from] = pA;
pA->rev = re;
re->dst = from;
re->flow = 0;
re->next = H[to];
H[to] = re;
re->rev = pA;
}
queue<int> Q;
int Level[12580];
bool makelevel() {
for(int i = 1; i <= numnodes; i ++) Level[i] = -1;
while(! Q.empty()) Q.pop();
Q.push(1);
Level[1] = 0;
while(! Q.empty()) {
int i = Q.front(); Q.pop();
for(node *p = H[i]; p; p = p->next)
if(Level[p->dst] == -1 && p->flow) {
Level[p->dst] = Level[i] + 1;
Q.push(p->dst);
}
if(Level[numnodes] > 0)
return true;
}
return false;
}
int Find(int frx, int mxx) {
if(frx == numnodes) return mxx;
int sum = 0, t;
for(node *p = H[frx]; p && sum <= mxx; p = p->next) {
if(p->flow && Level[p->dst] == Level[frx] + 1) {
t = Find(p->dst, min(mxx - sum, p->flow));
if(t) {
sum += t;
p->flow -= t;
p->rev->flow += t;
}
}
}
if(!sum) Level[frx] = -1;
return sum;
}
int Wx() {
int su = 0, t;
while(makelevel()) while(t=Find(1, INT_MAX)) su+=t;
return su;
}
int main() {
int numedges;
while(scanf("%d%d", &numedges, &numnodes) != -1) {
for(int i = 1; i <= numnodes; i ++) H[i] = 0;
top = 0;
for(int i = 1; i <= numedges; i ++) {
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
Edge(x, y, c);
}
printf("%d\n", Wx());
}
}
|
#include "main.hpp"
#include "crc32.hpp"
#include <iomanip>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstddef>
/**
* Parse a line of code, replacing the single quoted string
* in the macro SID('any-string'), by the corresponding hashed
* integer value, writing the parsed line on a output file
*/
void preprocess_line(std::string line, std::fstream & output_file_stream)
{
const std::string keyword("SID");
const std::string blank_characters(" \t\r");
const std::string alphanum("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789_");
std::size_t sid_pos = 0;
sid_pos = line.find(keyword, sid_pos);
while (sid_pos != std::string::npos) {
auto opening_paren_pos = line.find_first_not_of(blank_characters,
sid_pos + keyword.length());
if (opening_paren_pos == std::string::npos || line[opening_paren_pos] != '(') {
std::cerr << "Error: could not find open param" << std::endl;
sid_pos = line.find(keyword, opening_paren_pos);
continue;
}
auto first_quote_pos = line.find_first_not_of(blank_characters,
opening_paren_pos + 1);
if (first_quote_pos == std::string::npos || line[first_quote_pos] != '\'') {
sid_pos = first_quote_pos;
std::cerr << "Error: could not find opening quote" << std::endl;
sid_pos = line.find(keyword, first_quote_pos);
continue;
}
auto second_quote_pos = line.find_first_not_of(alphanum, first_quote_pos + 1);
if (second_quote_pos == std::string::npos || line[second_quote_pos] != '\'' ||
second_quote_pos == first_quote_pos + 1) {
std::cerr << "ERROR: Missing closing quote" << std::endl;
sid_pos = line.find(keyword, second_quote_pos);
continue;
}
auto closing_paren_pos = line.find_first_not_of(blank_characters,
second_quote_pos + 1);
// check if closing paren was found
if (closing_paren_pos == std::string::npos || line[closing_paren_pos] != ')') {
std::cerr << "ERROR: Missing closing paren" << std::endl;
sid_pos = line.find(keyword, closing_paren_pos);
continue;
}
// if everthing is ok, get the string and apply the hash function
std::string str_to_hash = line.substr(first_quote_pos + 1,
second_quote_pos - (first_quote_pos + 1));
std::uint32_t hashed_str = get_crc32(str_to_hash.c_str());
std::stringstream hex_str;
hex_str << "0x" << std::setfill('0') << std::setw(sizeof(std::uint32_t) * 2)
<< std::hex << hashed_str;
line.replace(opening_paren_pos + 1, closing_paren_pos - opening_paren_pos - 1,
hex_str.str());
// recalculate the position of closing paren before searching for the next word
closing_paren_pos = line.find_first_of(')', opening_paren_pos);
sid_pos = line.find(keyword, closing_paren_pos + 1);
}
// write to output file
output_file_stream << line << '\n';
}
/**
* Get a file stream to both an input and an output
* source file and, iterate through the input file
* running the sid parser on each line
*/
void sid_parser(const char * unprocessed_file_path, const char * preprocessed_file_path)
{
std::fstream preprocessed_stream(preprocessed_file_path,
std::fstream::in | std::fstream::out | std::fstream::trunc);
std::ifstream unprocessed_file(unprocessed_file_path);
if (!preprocessed_stream.good()) {
// file does not exist create it first
std::ofstream outfile_stream(preprocessed_file_path);
outfile_stream.close();
preprocessed_stream.close();
preprocessed_stream.open(preprocessed_file_path,
std::fstream::in | std::fstream::out);
}
std::string line;
while (std::getline(unprocessed_file, line)) {
preprocess_line(line, preprocessed_stream);
}
}
int main(int argc, char * argv[])
{
if (argc < 2) {
return -1;
}
const char *raw_file_path = argv[1];
const char *preprocessed_file_path = argv[2];
sid_parser(raw_file_path, preprocessed_file_path);
}
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/viz/host/host_frame_sink_manager.h"
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/containers/contains.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/time/time.h"
#include "components/viz/common/features.h"
#include "components/viz/common/surfaces/surface_info.h"
#include "components/viz/host/renderer_settings_creation.h"
#include "mojo/public/cpp/bindings/sync_call_restrictions.h"
#include "services/viz/privileged/mojom/compositing/renderer_settings.mojom.h"
namespace viz {
HostFrameSinkManager::HostFrameSinkManager()
: enable_sync_window_destruction_(
features::IsSyncWindowDestructionEnabled()),
debug_renderer_settings_(CreateDefaultDebugRendererSettings()) {}
HostFrameSinkManager::~HostFrameSinkManager() = default;
void HostFrameSinkManager::SetLocalManager(
mojom::FrameSinkManager* frame_sink_manager) {
DCHECK(!frame_sink_manager_remote_);
frame_sink_manager_ = frame_sink_manager;
}
void HostFrameSinkManager::BindAndSetManager(
mojo::PendingReceiver<mojom::FrameSinkManagerClient> receiver,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
mojo::PendingRemote<mojom::FrameSinkManager> remote) {
DCHECK(!receiver_.is_bound());
receiver_.Bind(std::move(receiver), std::move(task_runner));
frame_sink_manager_remote_.Bind(std::move(remote));
frame_sink_manager_ = frame_sink_manager_remote_.get();
frame_sink_manager_remote_.set_disconnect_handler(base::BindOnce(
&HostFrameSinkManager::OnConnectionLost, base::Unretained(this)));
if (connection_was_lost_) {
RegisterAfterConnectionLoss();
connection_was_lost_ = false;
}
}
void HostFrameSinkManager::SetConnectionLostCallback(
base::RepeatingClosure callback) {
connection_lost_callback_ = std::move(callback);
}
void HostFrameSinkManager::RegisterFrameSinkId(
const FrameSinkId& frame_sink_id,
HostFrameSinkClient* client,
ReportFirstSurfaceActivation report_activation) {
DCHECK(frame_sink_id.is_valid());
DCHECK(client);
FrameSinkData& data = frame_sink_data_map_[frame_sink_id];
DCHECK(!data.IsFrameSinkRegistered());
DCHECK(!data.has_created_compositor_frame_sink);
data.client = client;
data.report_activation = report_activation;
frame_sink_manager_->RegisterFrameSinkId(
frame_sink_id, report_activation == ReportFirstSurfaceActivation::kYes);
}
bool HostFrameSinkManager::IsFrameSinkIdRegistered(
const FrameSinkId& frame_sink_id) const {
auto iter = frame_sink_data_map_.find(frame_sink_id);
return iter != frame_sink_data_map_.end() && iter->second.client != nullptr;
}
void HostFrameSinkManager::InvalidateFrameSinkId(
const FrameSinkId& frame_sink_id) {
DCHECK(frame_sink_id.is_valid());
FrameSinkData& data = frame_sink_data_map_[frame_sink_id];
DCHECK(data.IsFrameSinkRegistered());
const bool destroy_synchronously =
data.has_created_compositor_frame_sink && data.wait_on_destruction;
data.has_created_compositor_frame_sink = false;
data.client = nullptr;
// There may be frame sink hierarchy information left in FrameSinkData.
if (data.IsEmpty())
frame_sink_data_map_.erase(frame_sink_id);
display_hit_test_query_.erase(frame_sink_id);
if (destroy_synchronously) {
// This synchronous call ensures that the GL context/surface that draw to
// the platform window (eg. XWindow or HWND) get destroyed before the
// platform window is destroyed.
mojo::SyncCallRestrictions::ScopedAllowSyncCall allow_sync_call;
frame_sink_manager_->DestroyCompositorFrameSink(frame_sink_id);
// Other synchronous IPCs continue to get processed while
// DestroyCompositorFrameSink() is happening, so it's possible
// HostFrameSinkManager has been mutated. |data| might not be a valid
// reference at this point.
}
frame_sink_manager_->InvalidateFrameSinkId(frame_sink_id);
}
void HostFrameSinkManager::SetFrameSinkDebugLabel(
const FrameSinkId& frame_sink_id,
const std::string& debug_label) {
DCHECK(frame_sink_id.is_valid());
FrameSinkData& data = frame_sink_data_map_[frame_sink_id];
DCHECK(data.IsFrameSinkRegistered());
data.debug_label = debug_label;
frame_sink_manager_->SetFrameSinkDebugLabel(frame_sink_id, debug_label);
}
void HostFrameSinkManager::CreateRootCompositorFrameSink(
mojom::RootCompositorFrameSinkParamsPtr params) {
// Should only be used with an out-of-process display compositor.
DCHECK(frame_sink_manager_remote_);
FrameSinkId frame_sink_id = params->frame_sink_id;
FrameSinkData& data = frame_sink_data_map_[frame_sink_id];
DCHECK(data.IsFrameSinkRegistered());
// If GL context is lost a new CompositorFrameSink will be created. Destroy
// the old CompositorFrameSink first.
if (data.has_created_compositor_frame_sink) {
frame_sink_manager_->DestroyCompositorFrameSink(frame_sink_id,
base::DoNothing());
}
data.is_root = true;
data.has_created_compositor_frame_sink = true;
// Only wait on destruction if using GPU compositing for the window.
data.wait_on_destruction =
enable_sync_window_destruction_ && params->gpu_compositing;
frame_sink_manager_->CreateRootCompositorFrameSink(std::move(params));
display_hit_test_query_[frame_sink_id] = std::make_unique<HitTestQuery>();
}
void HostFrameSinkManager::CreateCompositorFrameSink(
const FrameSinkId& frame_sink_id,
mojo::PendingReceiver<mojom::CompositorFrameSink> receiver,
mojo::PendingRemote<mojom::CompositorFrameSinkClient> client) {
FrameSinkData& data = frame_sink_data_map_[frame_sink_id];
DCHECK(data.IsFrameSinkRegistered());
// If GL context is lost a new CompositorFrameSink will be created. Destroy
// the old CompositorFrameSink first.
if (data.has_created_compositor_frame_sink) {
frame_sink_manager_->DestroyCompositorFrameSink(frame_sink_id,
base::DoNothing());
}
data.is_root = false;
data.has_created_compositor_frame_sink = true;
frame_sink_manager_->CreateCompositorFrameSink(
frame_sink_id, std::move(receiver), std::move(client));
}
void HostFrameSinkManager::OnFrameTokenChanged(
const FrameSinkId& frame_sink_id,
uint32_t frame_token,
base::TimeTicks activation_time) {
DCHECK(frame_sink_id.is_valid());
auto iter = frame_sink_data_map_.find(frame_sink_id);
if (iter == frame_sink_data_map_.end())
return;
const FrameSinkData& data = iter->second;
if (data.client)
data.client->OnFrameTokenChanged(frame_token, activation_time);
}
void HostFrameSinkManager::SetHitTestAsyncQueriedDebugRegions(
const FrameSinkId& root_frame_sink_id,
const std::vector<FrameSinkId>& hit_test_async_queried_debug_queue) {
frame_sink_manager_->SetHitTestAsyncQueriedDebugRegions(
root_frame_sink_id, hit_test_async_queried_debug_queue);
}
bool HostFrameSinkManager::RegisterFrameSinkHierarchy(
const FrameSinkId& parent_frame_sink_id,
const FrameSinkId& child_frame_sink_id) {
auto iter = frame_sink_data_map_.find(parent_frame_sink_id);
// |parent_frame_sink_id| isn't registered so it can't embed anything.
if (iter == frame_sink_data_map_.end() ||
!iter->second.IsFrameSinkRegistered()) {
return false;
}
// Register and store the parent.
frame_sink_manager_->RegisterFrameSinkHierarchy(parent_frame_sink_id,
child_frame_sink_id);
FrameSinkData& parent_data = iter->second;
DCHECK(!base::Contains(parent_data.children, child_frame_sink_id));
parent_data.children.push_back(child_frame_sink_id);
return true;
}
void HostFrameSinkManager::UnregisterFrameSinkHierarchy(
const FrameSinkId& parent_frame_sink_id,
const FrameSinkId& child_frame_sink_id) {
// Unregister and clear the stored parent.
FrameSinkData& parent_data = frame_sink_data_map_[parent_frame_sink_id];
DCHECK(base::Contains(parent_data.children, child_frame_sink_id));
base::Erase(parent_data.children, child_frame_sink_id);
if (parent_data.IsEmpty())
frame_sink_data_map_.erase(parent_frame_sink_id);
frame_sink_manager_->UnregisterFrameSinkHierarchy(parent_frame_sink_id,
child_frame_sink_id);
}
void HostFrameSinkManager::AddVideoDetectorObserver(
mojo::PendingRemote<mojom::VideoDetectorObserver> observer) {
frame_sink_manager_->AddVideoDetectorObserver(std::move(observer));
}
void HostFrameSinkManager::CreateVideoCapturer(
mojo::PendingReceiver<mojom::FrameSinkVideoCapturer> receiver) {
frame_sink_manager_->CreateVideoCapturer(std::move(receiver));
}
std::unique_ptr<ClientFrameSinkVideoCapturer>
HostFrameSinkManager::CreateVideoCapturer() {
return std::make_unique<ClientFrameSinkVideoCapturer>(base::BindRepeating(
[](base::WeakPtr<HostFrameSinkManager> self,
mojo::PendingReceiver<mojom::FrameSinkVideoCapturer> receiver) {
self->CreateVideoCapturer(std::move(receiver));
},
weak_ptr_factory_.GetWeakPtr()));
}
void HostFrameSinkManager::EvictSurfaces(
const std::vector<SurfaceId>& surface_ids) {
frame_sink_manager_->EvictSurfaces(surface_ids);
}
void HostFrameSinkManager::RequestCopyOfOutput(
const SurfaceId& surface_id,
std::unique_ptr<CopyOutputRequest> request) {
frame_sink_manager_->RequestCopyOfOutput(surface_id, std::move(request));
}
void HostFrameSinkManager::Throttle(const std::vector<FrameSinkId>& ids,
base::TimeDelta interval) {
frame_sink_manager_->Throttle(ids, interval);
}
void HostFrameSinkManager::AddHitTestRegionObserver(
HitTestRegionObserver* observer) {
observers_.AddObserver(observer);
}
void HostFrameSinkManager::RemoveHitTestRegionObserver(
HitTestRegionObserver* observer) {
observers_.RemoveObserver(observer);
}
void HostFrameSinkManager::OnConnectionLost() {
connection_was_lost_ = true;
receiver_.reset();
frame_sink_manager_remote_.reset();
frame_sink_manager_ = nullptr;
// Any cached back buffers are invalid once the connection to the
// FrameSinkManager is lost.
min_valid_cache_back_buffer_id_ = next_cache_back_buffer_id_;
// CompositorFrameSinks are lost along with the connection to
// mojom::FrameSinkManager.
for (auto& map_entry : frame_sink_data_map_) {
map_entry.second.has_created_compositor_frame_sink = false;
map_entry.second.wait_on_destruction = false;
}
if (!connection_lost_callback_.is_null())
connection_lost_callback_.Run();
}
void HostFrameSinkManager::RegisterAfterConnectionLoss() {
// Register FrameSinkIds first.
for (auto& map_entry : frame_sink_data_map_) {
const FrameSinkId& frame_sink_id = map_entry.first;
FrameSinkData& data = map_entry.second;
if (data.client) {
frame_sink_manager_->RegisterFrameSinkId(
frame_sink_id,
data.report_activation == ReportFirstSurfaceActivation::kYes);
}
if (!data.debug_label.empty()) {
frame_sink_manager_->SetFrameSinkDebugLabel(frame_sink_id,
data.debug_label);
}
}
// Register FrameSink hierarchy second.
for (auto& map_entry : frame_sink_data_map_) {
const FrameSinkId& frame_sink_id = map_entry.first;
FrameSinkData& data = map_entry.second;
for (auto& child_frame_sink_id : data.children) {
frame_sink_manager_->RegisterFrameSinkHierarchy(frame_sink_id,
child_frame_sink_id);
}
}
}
void HostFrameSinkManager::OnFirstSurfaceActivation(
const SurfaceInfo& surface_info) {
auto it = frame_sink_data_map_.find(surface_info.id().frame_sink_id());
// If we've received a bogus or stale SurfaceId from Viz then just ignore it.
if (it == frame_sink_data_map_.end())
return;
FrameSinkData& frame_sink_data = it->second;
if (frame_sink_data.client)
frame_sink_data.client->OnFirstSurfaceActivation(surface_info);
}
void HostFrameSinkManager::OnAggregatedHitTestRegionListUpdated(
const FrameSinkId& frame_sink_id,
const std::vector<AggregatedHitTestRegion>& hit_test_data) {
auto iter = display_hit_test_query_.find(frame_sink_id);
// The corresponding HitTestQuery has already been deleted, so drop the
// in-flight hit-test data.
if (iter == display_hit_test_query_.end())
return;
iter->second->OnAggregatedHitTestRegionListUpdated(hit_test_data);
// Ensure that HitTestQuery are updated so that observers are not working with
// stale data.
for (HitTestRegionObserver& observer : observers_)
observer.OnAggregatedHitTestRegionListUpdated(frame_sink_id, hit_test_data);
}
uint32_t HostFrameSinkManager::CacheBackBufferForRootSink(
const FrameSinkId& root_sink_id) {
auto it = frame_sink_data_map_.find(root_sink_id);
DCHECK(it != frame_sink_data_map_.end());
DCHECK(it->second.is_root);
DCHECK(it->second.IsFrameSinkRegistered());
DCHECK(frame_sink_manager_remote_);
uint32_t cache_id = next_cache_back_buffer_id_++;
frame_sink_manager_remote_->CacheBackBuffer(cache_id, root_sink_id);
return cache_id;
}
void HostFrameSinkManager::EvictCachedBackBuffer(uint32_t cache_id) {
DCHECK(frame_sink_manager_remote_);
if (cache_id < min_valid_cache_back_buffer_id_)
return;
// This synchronous call ensures that the GL context/surface that draw to
// the platform window (eg. XWindow or HWND) get destroyed before the
// platform window is destroyed.
mojo::SyncCallRestrictions::ScopedAllowSyncCall allow_sync_call;
frame_sink_manager_remote_->EvictBackBuffer(cache_id);
}
void HostFrameSinkManager::UpdateDebugRendererSettings(
const DebugRendererSettings& debug_settings) {
debug_renderer_settings_ = debug_settings;
frame_sink_manager_->UpdateDebugRendererSettings(debug_settings);
}
HostFrameSinkManager::FrameSinkData::FrameSinkData() = default;
HostFrameSinkManager::FrameSinkData::FrameSinkData(FrameSinkData&& other) =
default;
HostFrameSinkManager::FrameSinkData::~FrameSinkData() = default;
HostFrameSinkManager::FrameSinkData& HostFrameSinkManager::FrameSinkData::
operator=(FrameSinkData&& other) = default;
} // namespace viz
|
//
// TypeCastError.cpp
// Bump
//
// Created by Christian Noon on 1/4/13.
// Copyright (c) 2013 Christian Noon. All rights reserved.
//
// Bump headers
#include <bump/TypeCastError.h>
namespace bump {
TypeCastError::TypeCastError(const String& description, const String& location) throw() :
RuntimeError("bump::TypeCastError", description, location)
{
;
}
TypeCastError::~TypeCastError() throw()
{
;
}
} // End of bump namespace
|
#include "Poller.h"
#include "Logger.h"
#include "Channel.h"
#include "Timestamp.h"
#include <set>
#include <vector>
#include <unistd.h>
#include <string.h>
#include <sys/epoll.h>
namespace buzz
{
const int kReadEvent = EPOLLIN;
const int kWriteEvent = EPOLLOUT;
class PollerEpoll : public Poller
{
public:
PollerEpoll();
~PollerEpoll();
Timestamp Poll(int timeout, ChannelList* active_events) override;
void AddChannel(Channel* channel) override;
void UpdateChannel(Channel* channel) override;
void RemoveChannel(Channel* channel) override;
private:
int m_epfd;
std::set<Channel*> m_channels;
std::vector<struct epoll_event> m_active_events;
};
PollerEpoll::PollerEpoll()
:m_epfd(epoll_create1(EPOLL_CLOEXEC)),
m_active_events(64)
{
if (m_epfd == -1) {
LOG(FATAL) << "epoll_create1 error " << errno << " (" << ::strerror(errno) << ')';
}
LOG(DEBUG) << "poller epoll " << m_epfd << " created";
}
PollerEpoll::~PollerEpoll()
{
LOG(DEBUG) << "destroying PollerEpoll " << m_epfd;
for (auto it : m_channels) { delete it; }
::close(m_epfd);
}
Timestamp PollerEpoll::Poll(int timeout, ChannelList* active_events)
{
assert(active_events);
int nready = epoll_wait(m_epfd, m_active_events.data(), m_active_events.size(), timeout);
if (nready == -1 && errno != EINTR) {
LOG(FATAL) << "epoll_wait reutrn " << nready << " (" << ::strerror(errno) << ')';
}
Timestamp now(Timestamp::Now());
for (int i = 0; i < nready; i++) {
Channel* channel = static_cast<Channel*>(m_active_events[i].data.ptr);
channel->SetRevents(m_active_events[i].events);
active_events->push_back(channel);
}
if (static_cast<size_t>(nready) == m_active_events.size()) {
m_active_events.resize(nready << 1);
}
return now;
}
void PollerEpoll::AddChannel(Channel* channel)
{
assert(channel);
struct epoll_event ev[1];
ev[0].data.ptr = channel;
ev[0].events = channel->GetEvents();
LOG(TRACE) << "adding channel " << channel->GetId()
<< " fd " << channel->GetFd()
<< " events " << channel->GetEvents() << " epoll " << m_epfd;
int ret = epoll_ctl(m_epfd, EPOLL_CTL_ADD,channel->GetFd(), ev);
if (ret == -1) {
LOG(FATAL) << "epoll_ctl add failed " << errno << " (" << strerror(errno) << ')';
}
m_channels.insert(channel);
}
void PollerEpoll::UpdateChannel(Channel* channel)
{
assert(channel);
struct epoll_event ev[1];
ev[0].data.ptr = channel;
ev[0].events = channel->GetEvents();
LOG(TRACE) << "modifying channel " << channel->GetId()
<< " fd " << channel->GetFd()
<< " events " << channel->GetEvents() << " epoll " << m_epfd;
int ret = epoll_ctl(m_epfd, EPOLL_CTL_MOD, channel->GetFd(), ev);
if (ret == -1) {
LOG(FATAL) << "epoll_ctl mod failed " << errno << " (" << strerror(errno) << ')';
}
}
void PollerEpoll::RemoveChannel(Channel* channel)
{
assert(channel);
struct epoll_event ev[1];
ev[0].data.ptr = channel;
ev[0].events = channel->GetEvents();
LOG(TRACE) << "deleting channel " << channel->GetId()
<< " fd " << channel->GetFd()
<< " epoll " << m_epfd;
epoll_ctl(m_epfd, EPOLL_CTL_DEL, channel->GetFd(), ev);
m_channels.erase(channel);
}
Poller* MakePoller() { return new PollerEpoll(); }
}
|
// Copyright 2019 The JIMDB Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#include "admin_server.h"
#include <map>
#include <string>
#include <functional>
#include "common/server_config.h"
#include "common/logger.h"
namespace jim {
namespace ds {
namespace admin {
using namespace dspb;
using ConfigGeterMap = std::map<std::string, std::function<std::string()>> ;
#define ADD_CFG_GETTER(section, name) \
{#section"."#name, [] { return std::to_string(ds_config.section##_config.name); }}
#define ADD_CFG_GETTER_STR(section, name) \
{#section"."#name, [] { return std::string(ds_config.section##_config.name); }}
static const ConfigGeterMap cfg_getters = {
// log
{"log.level", []{return ds_config.logger_config.level;}},
// range
ADD_CFG_GETTER(range, recover_skip_fail),
ADD_CFG_GETTER(range, recover_concurrency),
ADD_CFG_GETTER(range, check_size),
ADD_CFG_GETTER(range, split_size),
ADD_CFG_GETTER(range, max_size),
ADD_CFG_GETTER(range, worker_threads),
// raft
ADD_CFG_GETTER(raft, port),
ADD_CFG_GETTER_STR(raft, log_path),
ADD_CFG_GETTER(raft, log_file_size),
ADD_CFG_GETTER(raft, max_log_files),
ADD_CFG_GETTER(raft, allow_log_corrupt),
ADD_CFG_GETTER(raft, consensus_threads),
ADD_CFG_GETTER(raft, consensus_queue),
ADD_CFG_GETTER(raft, transport_send_threads),
ADD_CFG_GETTER(raft, transport_recv_threads),
ADD_CFG_GETTER(raft, tick_interval_ms),
ADD_CFG_GETTER(raft, max_msg_size),
// worker
{"worker.schedule_worker", [] { return std::to_string(ds_config.worker_config.schedule_worker_num); }},
{"worker.slow_worker", [] { return std::to_string(ds_config.worker_config.slow_worker_num); }},
// manager
ADD_CFG_GETTER(manager, port),
// heartbeat
{"cluster.cluster.id", []{ return std::to_string(ds_config.cluster_config.cluster_id); }},
{"cluster.node_heartbeat_interval", []{ return std::to_string(ds_config.cluster_config.node_interval_secs ); }},
{"cluster.range_heartbeat_interval", []{ return std::to_string(ds_config.cluster_config.range_interval_secs); }},
{"cluster.master_host", []{
std::string result;
for (const auto &host : ds_config.cluster_config.master_host) {
if (!host.empty()) {
result += host;
result += ",";
}
}
if (!result.empty()) result.pop_back();
return result;
}},
};
static bool getConfigValue(const ConfigKey& key, std::string* value) {
FLOG_DEBUG("[Admin] get config: {}.{}", key.section(), key.name());
auto it = cfg_getters.find(key.section() + "." + key.name());
if (it != cfg_getters.end()) {
*value = (it->second)();
return true;
} else {
return false;
};
}
Status AdminServer::getConfig(const dspb::GetConfigRequest& req, dspb::GetConfigResponse* resp) {
for (const auto& key: req.key()) {
auto cfg = resp->add_configs();
cfg->mutable_key()->CopyFrom(key);
if(!getConfigValue(key, cfg->mutable_value())) {
return Status(Status::kNotFound, "config key", key.section() + "." + key.name());
}
}
return Status::OK();
}
} // namespace admin
} // namespace ds
} // namespace jim
|
//--------------------------------------------------------------------------
// 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 DOMAINSPEECH_SPEECHINPUTEVENTSTATE_CORE_H_
#define DOMAINSPEECH_SPEECHINPUTEVENTSTATE_CORE_H_
#include "DomainSpeech/SpeechInputEventStateData.hh"
#include <iostream>
#include <string>
#include <list>
namespace DomainSpeech {
class SpeechInputEventStateCore {
protected:
// data structure
DomainSpeechIDL::SpeechInputEventState idl_SpeechInputEventState;
public:
// give a publicly accessible type-name for the template parameter IDL
typedef DomainSpeechIDL::SpeechInputEventState DATATYPE;
#ifdef ENABLE_HASH
static size_t generateDataHash(const DATATYPE &);
#endif
static const char* getCompiledHash();
static void getAllHashValues(std::list<std::string> &hashes);
static void checkAllHashValues(std::list<std::string> &hashes);
// default constructors
SpeechInputEventStateCore();
SpeechInputEventStateCore(const DATATYPE &data);
// default destructor
virtual ~SpeechInputEventStateCore();
const DATATYPE& get() const { return idl_SpeechInputEventState; }
operator const DATATYPE&() const { return idl_SpeechInputEventState; }
DATATYPE& set() { return idl_SpeechInputEventState; }
static inline std::string identifier(void) { return "DomainSpeech::SpeechInputEventState"; }
// helper method to easily implement output stream in derived classes
void to_ostream(std::ostream &os = std::cout) const;
// convert to xml stream
void to_xml(std::ostream &os, const std::string &indent = "") const;
// restore from xml stream
void from_xml(std::istream &is);
// User Interface
// getter and setter for element Topic
inline std::string getTopic() const { return idl_SpeechInputEventState.topic; }
inline SpeechInputEventStateCore& setTopic(const std::string &topic) { idl_SpeechInputEventState.topic = topic; return *this; }
// getter and setter for element Text
inline std::string getText() const { return idl_SpeechInputEventState.text; }
inline SpeechInputEventStateCore& setText(const std::string &text) { idl_SpeechInputEventState.text = text; return *this; }
// getter and setter for element Semantic
inline std::string getSemantic() const { return idl_SpeechInputEventState.semantic; }
inline SpeechInputEventStateCore& setSemantic(const std::string &semantic) { idl_SpeechInputEventState.semantic = semantic; return *this; }
// getter and setter for element Confidence
inline double getConfidence() const { return idl_SpeechInputEventState.confidence; }
inline SpeechInputEventStateCore& setConfidence(const double &confidence) { idl_SpeechInputEventState.confidence = confidence; return *this; }
};
} /* namespace DomainSpeech */
#endif /* DOMAINSPEECH_SPEECHINPUTEVENTSTATE_CORE_H_ */
|
#include "logging.h"
#include "config.h"
#include "environment.h"
#include <spdlog/sinks/stdout_color_sinks.h>
namespace util {
static std::shared_ptr<spdlog::logger> logger;
static bool isInitialised = false;
void initLogging() {
if(isInitialised) {
return;
}
logger = spdlog::stderr_color_mt("console");
// Work out log level from environment
SystemConfig &conf = util::getSystemConfig();
if(conf.logLevel == "debug") {
spdlog::set_level(spdlog::level::debug);
}
else if(conf.logLevel == "trace") {
spdlog::set_level(spdlog::level::trace);
}
else if(conf.logLevel == "off") {
spdlog::set_level(spdlog::level::off);
}
else {
spdlog::set_level(spdlog::level::info);
}
isInitialised = true;
}
std::shared_ptr<spdlog::logger> getLogger() {
if(!isInitialised) {
initLogging();
}
return logger;
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* DiamondTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anolivei <anolivei@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/01/24 00:27:26 by anolivei #+# #+# */
/* Updated: 2022/01/25 14:05:44 by anolivei ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include "DiamondTrap.hpp"
#define PINK "\e[0;38;5;199m"
#define RESET "\e[0m"
DiamondTrap::DiamondTrap(void)
{
ClapTrap::_name = "Clap He Who Must Not Be Named";
this->_name = "He Who Must Not Be Named";
this->set_hit_points(FragTrap::_start_hit_points);
this->set_energy_points(ScavTrap::_start_energy_points);
this->set_atack_damage(FragTrap::_start_atack_damage);
std::cout
<< PINK
<< "DiamondTrap default constructor called"
<< RESET
<< std::endl;
return ;
}
DiamondTrap::DiamondTrap(const DiamondTrap& obj) : ClapTrap(obj),
ScavTrap(obj), FragTrap(obj)
{
std::cout
<< PINK
<< "DiamondTrap copy constructor called"
<< RESET
<< std::endl;
*this = obj;
return ;
}
DiamondTrap::DiamondTrap(std::string name)
{
ClapTrap::set_name("Clap" + name);
this->set_name(name);
this->set_hit_points(FragTrap::_start_hit_points);
this->set_energy_points(ScavTrap::_start_energy_points);
this->set_atack_damage(FragTrap::_start_atack_damage);
std::cout
<< PINK
<< "DiamondTrap string constructor called"
<< RESET
<< std::endl;
return ;
}
DiamondTrap::~DiamondTrap(void)
{
std::cout
<< PINK
<< "DiamondTrap destructor called"
<< RESET
<< std::endl;
return ;
}
DiamondTrap &DiamondTrap::operator=(const DiamondTrap &obj)
{
if (this != &obj)
{
this->_name = obj._name;
this->_hit_points = obj._hit_points;
this->_energy_points = obj._energy_points;
this->_atack_damage = obj._atack_damage;
}
return (*this);
}
std::string DiamondTrap::get_name(void) const
{
return (this->_name);
}
void DiamondTrap::set_name(std::string name)
{
this->_name = name;
}
void DiamondTrap::attack(std::string const& target)
{
ScavTrap::attack(target);
}
void DiamondTrap::who_am_i()
{
std::cout
<< PINK
<< "[OMG!] I'm "
<< get_name()
<< " and "
<< ClapTrap::get_name()
<< RESET
<< std::endl;
}
std::ostream& operator<<(std::ostream& o, const DiamondTrap& diamond_trap)
{
o
<< PINK
<< "[STATUS] "
<< diamond_trap.get_name()
<< " - Hit Points:"
<< diamond_trap.get_hit_points()
<< " Energy Points:"
<< diamond_trap.get_energy_points()
<< " Atack Damage:"
<< diamond_trap.get_atack_damage()
<< RESET
<< std::endl;
return (o);
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/chime/model/DeleteAttendeeRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Chime::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteAttendeeRequest::DeleteAttendeeRequest() :
m_meetingIdHasBeenSet(false),
m_attendeeIdHasBeenSet(false)
{
}
Aws::String DeleteAttendeeRequest::SerializePayload() const
{
return {};
}
|
/**
* @file
* @brief Summoning spells and other effects creating monsters.
**/
#include "AppHdr.h"
#include "spl-summoning.h"
#include <algorithm>
#include <cmath>
#include "act-iter.h"
#include "areas.h"
#include "artefact.h"
#include "cloud.h"
#include "colour.h"
#include "coordit.h"
#include "corpse.h"
#include "database.h"
#include "delay.h"
#include "directn.h"
#include "dungeon.h"
#include "english.h"
#include "env.h"
#include "fight.h"
#include "fprop.h"
#include "god-conduct.h"
#include "god-item.h"
#include "invent.h"
#include "item-prop.h"
#include "item-status-flag-type.h"
#include "items.h"
#include "libutil.h"
#include "mapmark.h"
#include "message.h"
#include "mgen-data.h"
#include "mon-abil.h"
#include "mon-act.h"
#include "mon-behv.h"
#include "mon-book.h" // MON_SPELL_WIZARD
#include "mon-cast.h"
#include "mon-death.h"
#include "mon-movetarget.h"
#include "mon-place.h"
#include "mon-speak.h"
#include "place.h" // absdungeon_depth
#include "player-equip.h"
#include "player-stats.h"
#include "prompt.h"
#include "religion.h"
#include "shout.h"
#include "spl-util.h"
#include "spl-zap.h"
#include "state.h"
#include "stepdown.h"
#include "stringutil.h"
#include "target.h"
#include "teleport.h"
#include "terrain.h"
#include "timed-effects.h"
#include "unwind.h"
#include "viewchar.h"
#include "xom.h"
static void _monster_greeting(monster *mons, const string &key)
{
string msg = getSpeakString(key);
if (msg == "__NONE")
msg.clear();
mons_speaks_msg(mons, msg, MSGCH_TALK, silenced(mons->pos()));
}
// combine with MG_AUTOFOE
static int _auto_autofoe(const actor *caster)
{
return (!caster || caster->is_player())
? int{MHITYOU}
: caster->as_monster()->foe;
}
static mgen_data _summon_data(const actor &caster, monster_type mtyp,
int dur, god_type god, spell_type spell)
{
return mgen_data(mtyp, BEH_COPY, caster.pos(),
_auto_autofoe(&caster),
MG_AUTOFOE)
.set_summoned(&caster, dur, spell, god);
}
static mgen_data _pal_data(monster_type pal, int dur, god_type god,
spell_type spell)
{
return _summon_data(you, pal, dur, god, spell);
}
spret cast_summon_small_mammal(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt())
return spret::abort;
fail_check();
monster_type mon = MONS_PROGRAM_BUG;
if (x_chance_in_y(10, pow + 1))
mon = random_choose(MONS_BAT, MONS_RAT);
else
mon = MONS_QUOKKA;
if (!create_monster(_pal_data(mon, 3, god, SPELL_SUMMON_SMALL_MAMMAL)))
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_call_canine_familiar(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt())
return spret::abort;
fail_check();
monster_type mon = MONS_PROGRAM_BUG;
const int chance = pow + random_range(-10, 10);
if (chance > 59)
mon = MONS_WARG;
else if (chance > 39)
mon = MONS_WOLF;
else
mon = MONS_HOUND;
const int dur = min(2 + (random2(pow) / 4), 6);
if (!create_monster(_pal_data(mon, dur, god, SPELL_CALL_CANINE_FAMILIAR)))
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_summon_cactus(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
mgen_data mg = _pal_data(MONS_CACTUS_GIANT, 3, god, SPELL_SUMMON_CACTUS);
mg.hp = hit_points(pow + 27, 1);
if (!create_monster(mg))
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_summon_armour_spirit(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
const item_def *armour = you.slot_item(EQ_BODY_ARMOUR);
if (armour == nullptr)
{
// I don't think we can ever reach this line, but let's be safe.
mpr("You aren't wearing any armour!");
return spret::abort;
}
int mitm_slot = get_mitm_slot(10);
if (mitm_slot == NON_ITEM)
{
canned_msg(MSG_NOTHING_HAPPENS);
return spret::abort;
}
fail_check();
mgen_data mg = _pal_data(MONS_ANIMATED_ARMOUR, 2, god,
SPELL_ANIMATE_ARMOUR);
mg.hd = 15 + div_rand_round(pow, 10);
monster* spirit = create_monster(mg);
if (!spirit)
{
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
item_def &fake_armour = env.item[mitm_slot];
fake_armour.clear();
fake_armour.base_type = OBJ_ARMOUR;
fake_armour.sub_type = armour->sub_type;
fake_armour.quantity = 1;
fake_armour.rnd = armour->rnd ? armour->rnd : 1; // unrands have no rnd; hackily add one
fake_armour.flags |= ISFLAG_SUMMONED | ISFLAG_KNOW_PLUSES;
item_set_appearance(fake_armour);
spirit->pickup_item(fake_armour, false, true);
return spret::success;
}
spret cast_summon_ice_beast(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
const int dur = min(2 + (random2(pow) / 4), 4);
mgen_data ice_beast = _pal_data(MONS_ICE_BEAST, dur, god,
SPELL_SUMMON_ICE_BEAST);
ice_beast.hd = (3 + div_rand_round(pow, 13));
if (create_monster(ice_beast))
mpr("A chill wind blows around you.");
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_monstrous_menagerie(actor* caster, int pow, god_type god, bool fail)
{
if (caster->is_player() && stop_summoning_prompt())
return spret::abort;
fail_check();
monster_type type = MONS_PROGRAM_BUG;
if (random2(pow) > 60 && coinflip())
type = MONS_SPHINX;
else
type = coinflip() ? MONS_MANTICORE : MONS_LINDWURM;
mgen_data mdata = _summon_data(*caster, type, 4, god,
SPELL_MONSTROUS_MENAGERIE);
if (caster->is_player())
mdata.hd = get_monster_data(type)->HD + div_rand_round(pow - 50, 25);
monster* beast = create_monster(mdata);
if (!beast)
{
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
if (you.can_see(*beast))
{
mprf("%s %s %s!", caster->name(DESC_THE).c_str(),
caster->conj_verb("summon").c_str(),
mons_type_name(type, DESC_A).c_str());
}
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_summon_hydra(actor *caster, int pow, god_type god, bool fail)
{
if (caster->is_player() && stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
// Power determines number of heads. Minimum 4 heads, maximum 12.
// Rare to get more than 8.
const int maxheads = one_chance_in(6) ? 12 : 8;
const int heads = max(4, min(random2(pow) / 6, maxheads));
// Duration is always very short - just 1.
mgen_data mg = _summon_data(*caster, MONS_HYDRA, 1, god,
SPELL_SUMMON_HYDRA);
mg.props[MGEN_NUM_HEADS] = heads;
if (monster *hydra = create_monster(mg))
{
if (you.see_cell(hydra->pos()))
mprf("%s appears.", hydra->name(DESC_A).c_str());
}
else if (caster->is_player())
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
static monster_type _choose_dragon_type(int pow, god_type /*god*/, bool player)
{
monster_type mon = MONS_PROGRAM_BUG;
const int chance = random2(pow);
if (chance >= 80 || one_chance_in(6))
mon = random_choose(MONS_GOLDEN_DRAGON, MONS_QUICKSILVER_DRAGON);
else if (chance >= 40 || one_chance_in(6))
mon = random_choose(MONS_IRON_DRAGON, MONS_SHADOW_DRAGON, MONS_STORM_DRAGON);
else
mon = random_choose(MONS_FIRE_DRAGON, MONS_ICE_DRAGON);
// For good gods, switch away from shadow dragons to storm/iron dragons.
if (player && god_hates_monster(mon))
mon = random_choose(MONS_STORM_DRAGON, MONS_IRON_DRAGON);
return mon;
}
spret cast_dragon_call(int pow, bool fail)
{
// Quicksilver and storm dragons don't have rPois, but that's fine.
if (stop_summoning_prompt(MR_RES_POISON, "call dragons"))
return spret::abort;
fail_check();
mpr("You call out to the draconic realm, and the dragon horde roars back!");
noisy(spell_effect_noise(SPELL_DRAGON_CALL), you.pos());
you.duration[DUR_DRAGON_CALL] = (15 + pow / 5 + random2(15)) * BASELINE_DELAY;
you.props[DRAGON_CALL_POWER_KEY].get_int() = pow;
return spret::success;
}
static void _place_dragon()
{
const int pow = you.props[DRAGON_CALL_POWER_KEY].get_int();
monster_type mon = _choose_dragon_type(pow, you.religion, true);
int mp_cost = random_range(2, 3);
vector<monster*> targets;
// Pick a random hostile in sight
for (monster_near_iterator mi(&you, LOS_NO_TRANS); mi; ++mi)
if (!mons_aligned(&you, *mi) && mons_is_threatening(**mi))
targets.push_back(*mi);
shuffle_array(targets);
// Attempt to place adjacent to the first chosen hostile. If there is no
// valid spot, move on to the next one.
for (monster *target : targets)
{
// Chose a random viable adjacent spot to the select target
vector<coord_def> spots;
for (adjacent_iterator ai(target->pos()); ai; ++ai)
{
if (monster_habitable_grid(MONS_FIRE_DRAGON, env.grid(*ai))
&& !actor_at(*ai))
{
spots.push_back(*ai);
}
}
// Now try to create the actual dragon
if (spots.size() <= 0)
continue;
// Abort if we lack sufficient MP, but the dragon call duration
// remains, as the player might soon have enough again.
if (!enough_mp(mp_cost, true))
{
mpr("A dragon tries to answer your call, but you don't have enough "
"magical power!");
return;
}
const coord_def pos = spots[random2(spots.size())];
monster *dragon = create_monster(
mgen_data(mon, BEH_COPY, pos, MHITYOU, MG_FORCE_PLACE | MG_AUTOFOE)
.set_summoned(&you, 2, SPELL_DRAGON_CALL));
if (!dragon)
continue;
pay_mp(mp_cost);
if (you.see_cell(dragon->pos()))
mpr("A dragon arrives to answer your call!");
finalize_mp_cost();
// The dragon is allowed to act immediately here
dragon->flags &= ~MF_JUST_SUMMONED;
return;
}
return;
}
void do_dragon_call(int time)
{
noisy(spell_effect_noise(SPELL_DRAGON_CALL), you.pos());
while (time > you.attribute[ATTR_NEXT_DRAGON_TIME]
&& you.duration[DUR_DRAGON_CALL])
{
time -= you.attribute[ATTR_NEXT_DRAGON_TIME];
_place_dragon();
you.attribute[ATTR_NEXT_DRAGON_TIME] = 3 + random2(5)
+ count_summons(&you, SPELL_DRAGON_CALL) * 5;
}
you.attribute[ATTR_NEXT_DRAGON_TIME] -= time;
}
/**
* Handle the Doom Howl status effect, possibly summoning hostile nasties
* around the player.
*
* @param time The number of aut that the howling has been going on for
* since the last doom_howl call.
*/
void doom_howl(int time)
{
// TODO: pull hound-count generation into a helper function
int howlcalled_count = 0;
if (!you.props.exists(NEXT_DOOM_HOUND_KEY))
you.props[NEXT_DOOM_HOUND_KEY] = random_range(20, 40);
// 1 nasty beast every 2-4 turns
while (time > 0)
{
const int time_to_call = you.props[NEXT_DOOM_HOUND_KEY].get_int();
if (time_to_call <= time)
{
you.props[NEXT_DOOM_HOUND_KEY] = random_range(20, 40);
++howlcalled_count;
}
else
you.props[NEXT_DOOM_HOUND_KEY].get_int() -= time;
time -= time_to_call;
}
if (!howlcalled_count)
return;
const actor *target = &you;
for (int i = 0; i < howlcalled_count; ++i)
{
const monster_type howlcalled = random_choose(
MONS_BONE_DRAGON, MONS_REAPER, MONS_TORMENTOR, MONS_TZITZIMITL,
MONS_PUTRID_MOUTH
);
vector<coord_def> spots;
for (adjacent_iterator ai(target->pos()); ai; ++ai)
{
if (monster_habitable_grid(howlcalled, env.grid(*ai))
&& !actor_at(*ai))
{
spots.push_back(*ai);
}
}
if (spots.size() <= 0)
continue;
const coord_def pos = spots[random2(spots.size())];
monster *mons = create_monster(mgen_data(howlcalled, BEH_HOSTILE,
pos, target->mindex(),
MG_FORCE_BEH));
if (mons)
{
mons->add_ench(mon_enchant(ENCH_HAUNTING, 1, target,
INFINITE_DURATION));
mons->behaviour = BEH_SEEK;
mons_add_blame(mons, "called by a doom hound"); // assumption!
check_place_cloud(CLOUD_BLACK_SMOKE, mons->pos(),
random_range(1,2), mons);
}
}
}
spret cast_summon_dragon(actor *caster, int pow, god_type god, bool fail)
{
// Dragons are always friendly. Dragon type depends on power and
// random chance, with two low-tier dragons possible at high power.
// Duration fixed at 6.
fail_check();
bool success = false;
if (god == GOD_NO_GOD)
god = caster->deity();
int how_many = 1;
monster_type mon = _choose_dragon_type(pow, god, caster->is_player());
if (pow >= 100 && (mon == MONS_FIRE_DRAGON || mon == MONS_ICE_DRAGON))
how_many = 2;
for (int i = 0; i < how_many; ++i)
{
if (monster *dragon = create_monster(
_summon_data(*caster, mon, 6, god, SPELL_SUMMON_DRAGON)))
{
if (you.see_cell(dragon->pos()))
mpr("A dragon appears.");
success = true;
}
}
if (!success && caster->is_player())
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_summon_mana_viper(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
mgen_data viper = _pal_data(MONS_MANA_VIPER, 2, god,
SPELL_SUMMON_MANA_VIPER);
viper.hd = (5 + div_rand_round(pow, 12));
// Don't scale hp at the same time as their antimagic power
viper.hp = hit_points(495); // avg 50
if (create_monster(viper))
mpr("A mana viper appears with a sibilant hiss.");
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
// This assumes that the specified monster can go berserk.
static void _make_mons_berserk_summon(monster* mon)
{
mon->go_berserk(false);
mon_enchant berserk = mon->get_ench(ENCH_BERSERK);
mon_enchant abj = mon->get_ench(ENCH_ABJ);
// Let Trog's gifts berserk longer, and set the abjuration timeout
// to the berserk timeout.
berserk.duration = berserk.duration * 3 / 2;
berserk.maxduration = berserk.duration;
abj.duration = abj.maxduration = berserk.duration;
mon->update_ench(berserk);
mon->update_ench(abj);
}
// This is actually one of Trog's wrath effects.
bool summon_berserker(int pow, actor *caster, monster_type override_mons)
{
monster_type mon = MONS_PROGRAM_BUG;
const int dur = min(2 + (random2(pow) / 4), 6);
if (override_mons != MONS_PROGRAM_BUG)
mon = override_mons;
else
{
if (pow <= 100)
{
// bears
mon = random_choose(MONS_BLACK_BEAR, MONS_POLAR_BEAR);
}
else if (pow <= 140)
{
// ogres
mon = random_choose_weighted(1, MONS_TWO_HEADED_OGRE, 2, MONS_OGRE);
}
else if (pow <= 180)
{
// trolls
mon = random_choose_weighted(3, MONS_TROLL,
3, MONS_DEEP_TROLL,
2, MONS_IRON_TROLL);
}
else
{
// giants
mon = random_choose(MONS_CYCLOPS, MONS_STONE_GIANT);
}
}
mgen_data mg(mon, caster ? BEH_COPY : BEH_HOSTILE,
caster ? caster->pos() : you.pos(),
_auto_autofoe(caster),
MG_AUTOFOE);
mg.set_summoned(caster, caster ? dur : 0, SPELL_NO_SPELL, GOD_TROG);
if (!caster)
{
mg.non_actor_summoner = "the rage of " + god_name(GOD_TROG, false);
mg.extra_flags |= (MF_NO_REWARD | MF_HARD_RESET);
}
monster *mons = create_monster(mg);
if (!mons)
return false;
_make_mons_berserk_summon(mons);
return true;
}
// Not a spell. Rather, this is TSO's doing.
bool summon_holy_warrior(int pow, bool punish)
{
mgen_data mg(random_choose(MONS_ANGEL, MONS_DAEVA),
punish ? BEH_HOSTILE : BEH_FRIENDLY,
you.pos(), MHITYOU, MG_FORCE_BEH | MG_AUTOFOE);
mg.set_summoned(punish ? 0 : &you,
punish ? 0 : min(2 + (random2(pow) / 4), 6),
SPELL_NO_SPELL, GOD_SHINING_ONE);
if (punish)
{
mg.extra_flags |= (MF_NO_REWARD | MF_HARD_RESET);
mg.non_actor_summoner = god_name(GOD_SHINING_ONE, false);
}
monster *summon = create_monster(mg);
if (!summon)
return false;
summon->flags |= MF_ATT_CHANGE_ATTEMPT;
if (!punish)
mpr("You are momentarily dazzled by a brilliant light.");
return true;
}
/**
* Essentially a macro to allow for a generic fail pattern to avoid leaking
* information about invisible enemies. (Not implemented as a macro because I
* find they create unreadable code.)
*
* @return spret::success
**/
static bool _fail_tukimas()
{
mprf("You can't see a target there!");
return false; // Waste the turn - no anti-invis tech
}
/**
* Checks if Tukima's Dance can actually affect the target (and anger them)
*
* @param target The targeted monster (or player).
* @return Whether the target can be affected by Tukima's Dance.
**/
bool tukima_affects(const actor &target)
{
const item_def* wpn = target.weapon();
return wpn
&& is_weapon(*wpn)
&& !target.is_player()
&& !is_special_unrandom_artefact(*wpn)
&& !mons_class_is_animated_weapon(target.type)
// XX use god_protects here. But, need to know the caster too...
&& !mons_is_hepliaklqana_ancestor(target.type);
}
/**
* Checks if Tukima's Dance is being cast on a valid target.
*
* @param target The spell's target.
* @return Whether the target is valid.
**/
static bool _check_tukima_validity(const actor *target)
{
const item_def* wpn = target->weapon();
bool can_see_target = target->visible_to(&you);
// See if the wielded item is appropriate.
if (!wpn)
{
if (!can_see_target)
return _fail_tukimas();
// FIXME: maybe move hands_act to class actor?
bool plural = true;
const string hand = target->hand_name(true, &plural);
mprf("%s %s %s.",
apostrophise(target->name(DESC_THE)).c_str(),
hand.c_str(), conjugate_verb("twitch", plural).c_str());
return false;
}
if (!tukima_affects(*target))
{
if (!can_see_target)
return _fail_tukimas();
if (mons_class_is_animated_weapon(target->type))
{
simple_monster_message(*(monster*)target,
" is already dancing.");
}
else
{
mprf("%s vibrate%s crazily for a second.",
wpn->name(DESC_THE).c_str(),
wpn->quantity > 1 ? "" : "s");
}
return false;
}
return true;
}
/**
* Actually animates the weapon of the target creature (no checks).
*
* @param pow Spellpower.
* @param target The spell's target.
**/
static void _animate_weapon(int pow, actor* target)
{
item_def * const wpn = target->weapon();
ASSERT(wpn);
// If sac love, the weapon will go after you, not the target.
const bool hostile = you.allies_forbidden();
const int dur = min(2 + (random2(pow) / 5), 6);
mgen_data mg(MONS_DANCING_WEAPON,
hostile ? BEH_HOSTILE : BEH_FRIENDLY,
target->pos(),
hostile ? MHITYOU : target->mindex(),
hostile ? MG_NONE : MG_FORCE_BEH);
mg.set_summoned(&you, dur, SPELL_TUKIMAS_DANCE);
mg.props[TUKIMA_WEAPON] = *wpn;
mg.props[TUKIMA_POWER] = pow;
monster * const mons = create_monster(mg);
if (!mons)
{
mprf("%s twitches for a moment.", wpn->name(DESC_THE).c_str());
return;
}
// Don't haunt yourself under sac love.
if (!hostile)
{
mons->add_ench(mon_enchant(ENCH_HAUNTING, 1, target,
INFINITE_DURATION));
mons->foe = target->mindex();
}
// We are successful. Unwield the weapon, removing any wield effects.
mprf("%s dances into the air!", wpn->name(DESC_THE).c_str());
monster * const montarget = target->as_monster();
const int primary_weap = montarget->inv[MSLOT_WEAPON];
const mon_inv_type wp_slot = (primary_weap != NON_ITEM
&& &env.item[primary_weap] == wpn) ?
MSLOT_WEAPON : MSLOT_ALT_WEAPON;
ASSERT(montarget->inv[wp_slot] != NON_ITEM);
ASSERT(&env.item[montarget->inv[wp_slot]] == wpn);
montarget->unequip(*(montarget->mslot_item(wp_slot)), false, true);
montarget->inv[wp_slot] = NON_ITEM;
// Also steal ammo for launchers.
if (is_range_weapon(*wpn))
{
const int ammo = montarget->inv[MSLOT_MISSILE];
if (ammo != NON_ITEM)
{
ASSERT(mons->inv[MSLOT_MISSILE] == NON_ITEM);
mons->inv[MSLOT_MISSILE] = ammo;
montarget->inv[MSLOT_MISSILE] = NON_ITEM;
env.item[ammo].set_holding_monster(*mons);
}
}
// Find out what our god thinks before killing the item.
conduct_type why = god_hates_item_handling(*wpn);
wpn->clear();
if (why)
{
simple_god_message(" booms: How dare you animate that foul thing!");
did_god_conduct(why, 10, true, mons);
}
}
/**
* Casts Tukima's Dance, animating the weapon of the target creature (if valid)
*
* @param pow Spellpower.
* @param where The target grid.
**/
void cast_tukimas_dance(int pow, actor* target)
{
ASSERT(target);
if (!_check_tukima_validity(target))
return;
_animate_weapon(pow, target);
}
/// When the player conjures ball lightning with the given spellpower, what
/// HD will the resulting lightning have?
int ball_lightning_hd(int pow, bool random)
{
if (random)
return max(1, div_rand_round(pow, 6) - 6);
return max(1, pow / 6 - 6);
}
int mons_ball_lightning_hd(int pow, bool random)
{
// We love players, don't we? Let's be nice.
return ball_lightning_hd(pow, random) / 2;
}
spret cast_conjure_ball_lightning(int pow, god_type god, bool fail)
{
fail_check();
bool success = false;
mgen_data cbl =_pal_data(MONS_BALL_LIGHTNING, 0, god,
SPELL_CONJURE_BALL_LIGHTNING);
cbl.hd = ball_lightning_hd(pow);
for (int i = 0; i < 3; ++i)
{
if (monster *ball = create_monster(cbl))
{
success = true;
ball->add_ench(ENCH_SHORT_LIVED);
// Avoid ball lightnings without targets always moving towards (0,0)
if (!(ball->get_foe() && ball->get_foe()->is_monster()))
set_random_target(ball);
}
}
if (success)
mpr("You create some ball lightning!");
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_summon_lightning_spire(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
mgen_data spire = _pal_data(MONS_LIGHTNING_SPIRE, 2, god,
SPELL_SUMMON_LIGHTNING_SPIRE);
spire.hd = max(1, div_rand_round(pow, 10));
monster* mons = create_monster(spire);
if (mons && !silenced(mons->pos()))
mpr("An electric hum fills the air.");
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret cast_summon_guardian_golem(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
mgen_data golem = _pal_data(MONS_GUARDIAN_GOLEM, 3, god,
SPELL_SUMMON_GUARDIAN_GOLEM);
golem.flags &= ~MG_AUTOFOE; // !!!
golem.hd = 4 + div_rand_round(pow, 16);
monster* mons = (create_monster(golem));
if (mons)
{
// Immediately apply injury bond
guardian_golem_bond(*mons);
mpr("A guardian golem appears, shielding your allies.");
}
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
/**
* Choose a type of imp to summon with Call Imp.
*
* @return An appropriate imp type.
*/
static monster_type _get_imp_type()
{
if (x_chance_in_y(5, 18))
return MONS_WHITE_IMP;
// 3/13 * 13/18 = 1/6 chance of one of these two.
if (x_chance_in_y(3, 13))
return one_chance_in(3) ? MONS_IRON_IMP : MONS_SHADOW_IMP;
// 5/9 chance of getting, regrettably, a crimson imp.
return MONS_CRIMSON_IMP;
}
static map<monster_type, const char*> _imp_summon_messages = {
{ MONS_WHITE_IMP,
"A beastly little devil appears in a puff of frigid air." },
{ MONS_IRON_IMP, "A metallic apparition takes form in the air." },
{ MONS_SHADOW_IMP, "A shadowy apparition takes form in the air." },
{ MONS_CRIMSON_IMP, "A beastly little devil appears in a puff of flame." },
};
/**
* Cast the spell Call Imp, summoning a friendly imp nearby.
*
* @param pow The spellpower at which the spell is being cast.
* @param god The god of the caster.
* @param fail Whether the caster (you) failed to cast the spell.
* @return spret::fail if fail is true; spret::success otherwise.
*/
spret cast_call_imp(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
const monster_type imp_type = _get_imp_type();
const int dur = min(2 + (random2(pow) / 4), 6);
mgen_data imp_data = _pal_data(imp_type, dur, god, SPELL_CALL_IMP);
if (monster *imp = create_monster(imp_data))
{
mpr(_imp_summon_messages[imp_type]);
_monster_greeting(imp, "_friendly_imp_greeting");
}
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
static bool _summon_demon_wrapper(int pow, god_type god, int spell,
monster_type mon, int dur, bool friendly,
bool charmed)
{
bool success = false;
if (monster *demon = create_monster(
mgen_data(mon,
friendly ? BEH_FRIENDLY :
charmed ? BEH_CHARMED
: BEH_HOSTILE,
you.pos(), MHITYOU, MG_FORCE_BEH | MG_AUTOFOE)
.set_summoned(&you, dur, spell, god)))
{
success = true;
mpr("A demon appears!");
if (!friendly)
{
mpr(charmed ? "You don't feel so good about this..."
: "It doesn't seem very happy.");
}
else if (mon == MONS_CRIMSON_IMP || mon == MONS_WHITE_IMP
|| mon == MONS_IRON_IMP || mon == MONS_SHADOW_IMP)
{
_monster_greeting(demon, "_friendly_imp_greeting");
}
if (charmed && !friendly)
{
int charm_dur = random_range(15 + pow / 14, 27 + pow / 11)
* BASELINE_DELAY;
mon_enchant charm = demon->get_ench(ENCH_CHARM);
charm.duration = charm_dur;
demon->update_ench(charm);
// Ensure that temporarily-charmed demons will outlast their charm
mon_enchant abj = demon->get_ench(ENCH_ABJ);
if (charm.duration + 100 > abj.duration)
{
abj.duration = charm.duration + 100;
demon->update_ench(abj);
}
// Affects messaging, and stuns demon a turn upon charm wearing off
demon->props[CHARMED_DEMON_KEY].get_bool() = true;
}
}
return success;
}
static bool _summon_common_demon(int pow, god_type god, int spell)
{
const int chance = 70 - (pow / 3);
monster_type type = MONS_PROGRAM_BUG;
if (x_chance_in_y(chance, 100))
type = random_demon_by_tier(4);
else
type = random_demon_by_tier(3);
return _summon_demon_wrapper(pow, god, spell, type,
min(2 + (random2(pow) / 4), 6),
random2(pow) > 3, false);
}
bool summon_demon_type(monster_type mon, int pow, god_type god,
int spell, bool friendly)
{
return _summon_demon_wrapper(pow, god, spell, mon,
min(2 + (random2(pow) / 4), 6),
friendly, false);
}
spret cast_summon_demon(int pow)
{
// Don't prompt here, since this is invoked automatically by the
// obsidian axe. The player shouldn't have control.
mpr("You open a gate to Pandemonium!");
if (!_summon_common_demon(pow, GOD_NO_GOD, SPELL_SUMMON_DEMON))
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret summon_shadow_creatures()
{
// Hard to predict what resistances might come from this.
if (stop_summoning_prompt())
return spret::abort;
mpr("Wisps of shadow whirl around you...");
int num = roll_dice(2, 2);
int num_created = 0;
for (int i = 0; i < num; ++i)
{
if (monster *mons = create_monster(
mgen_data(RANDOM_COMPATIBLE_MONSTER, BEH_FRIENDLY, you.pos(),
MHITYOU, MG_FORCE_BEH | MG_AUTOFOE | MG_NO_OOD)
// This duration is only used for band members.
.set_summoned(&you, 2, MON_SUMM_SCROLL)
.set_place(level_id::current()),
false))
{
// Choose a new duration based on HD.
int x = max(mons->get_experience_level() - 3, 1);
int d = min(4, 1 + div_rand_round(17, x));
mon_enchant me = mon_enchant(ENCH_ABJ, d);
me.set_duration(mons, &me);
mons->update_ench(me);
// Set summon ID, to share summon cap with its band members
mons->props[SUMMON_ID_KEY].get_int() = mons->mid;
// Remove any band members that would turn hostile, and link their
// summon IDs
for (monster_iterator mi; mi; ++mi)
{
if (testbits(mi->flags, MF_BAND_MEMBER)
&& (mid_t) mi->props[BAND_LEADER_KEY].get_int() == mons->mid)
{
if (god_hates_monster(**mi))
monster_die(**mi, KILL_RESET, NON_MONSTER);
mi->props[SUMMON_ID_KEY].get_int() = mons->mid;
}
}
num_created++;
}
}
if (!num_created)
mpr("The shadows disperse without effect.");
return spret::success;
}
bool can_cast_malign_gateway()
{
timeout_malign_gateways(0);
return count_malign_gateways() < 1;
}
coord_def find_gateway_location(actor* caster)
{
vector<coord_def> points;
for (coord_def delta : Compass)
{
coord_def test = coord_def(-1, -1);
for (int t = 0; t < 11; t++)
{
test = caster->pos() + (delta * (2+t));
if (!in_bounds(test) || !feat_is_malign_gateway_suitable(env.grid(test))
|| actor_at(test)
|| count_neighbours_with_func(test, &feat_is_solid) != 0
|| !caster->see_cell_no_trans(test))
{
continue;
}
points.push_back(test);
}
}
if (points.empty())
return coord_def(0, 0);
return points[random2(points.size())];
}
void create_malign_gateway(coord_def point, beh_type beh, string cause,
int pow, god_type god, bool is_player)
{
const int malign_gateway_duration = BASELINE_DELAY * (random2(2) + 1);
env.markers.add(new map_malign_gateway_marker(point,
malign_gateway_duration,
is_player,
is_player ? "" : cause,
beh,
god,
pow));
env.markers.clear_need_activate();
env.grid(point) = DNGN_MALIGN_GATEWAY;
set_terrain_changed(point);
noisy(spell_effect_noise(SPELL_MALIGN_GATEWAY), point);
mprf(MSGCH_WARN, "The dungeon shakes, a horrible noise fills the air, "
"and a portal to some otherworldly place is opened!");
}
spret cast_malign_gateway(actor * caster, int pow, god_type god,
bool fail, bool test)
{
if (!test && caster->is_player() && stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
coord_def point = find_gateway_location(caster);
bool success = point != coord_def(0, 0);
if (test)
return success ? spret::success : spret::abort;
bool is_player = caster->is_player();
if (success)
{
fail_check();
create_malign_gateway(
point,
is_player ? BEH_FRIENDLY
: attitude_creation_behavior(
caster->as_monster()->attitude),
is_player ? ""
: caster->as_monster()->full_name(DESC_A),
pow,
god,
is_player);
return spret::success;
}
return spret::abort;
}
spret cast_summon_horrible_things(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
if (god == GOD_NO_GOD && one_chance_in(5))
{
// if someone deletes the db, no message is ok
mpr(getMiscString("SHT_int_loss"));
lose_stat(STAT_INT, 1);
}
int num_abominations = random_range(2, 4) + x_chance_in_y(pow, 200);
int num_tmons = random2(pow) > 120 ? 2 : random2(pow) > 50 ? 1 : 0;
if (num_tmons == 0)
num_abominations++;
int count = 0;
while (num_abominations-- > 0)
{
const mgen_data abom = _pal_data(MONS_ABOMINATION_LARGE, 3, god,
SPELL_SUMMON_HORRIBLE_THINGS);
if (create_monster(abom))
++count;
}
while (num_tmons-- > 0)
{
const mgen_data tmons = _pal_data(MONS_TENTACLED_MONSTROSITY, 3, god,
SPELL_SUMMON_HORRIBLE_THINGS);
if (create_monster(tmons))
++count;
}
if (!count)
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
static bool _water_adjacent(coord_def p)
{
for (orth_adjacent_iterator ai(p); ai; ++ai)
{
if (feat_is_water(env.grid(*ai)))
return true;
}
return false;
}
// Is this area open enough to summon a forest?
static bool _can_summon_forest(actor &caster)
{
for (adjacent_iterator ai(caster.pos(), false); ai; ++ai)
if (count_neighbours_with_func(*ai, &feat_is_solid) == 0)
return true;
return false;
}
/**
* Cast summon forest.
*
* @param caster The caster.
* @param pow The spell power.
* @param god The god of the summoned dryad (usually the caster's).
* @param fail Did this spell miscast? If true, abort the cast.
* @return spret::abort if a summoning area couldn't be found,
* spret::fail if one could be found but we miscast, and
* spret::success if the spell was successfully cast.
*/
spret cast_summon_forest(actor* caster, int pow, god_type god, bool fail, bool test)
{
if (!_can_summon_forest(*caster))
return spret::abort;
if (test)
return spret::success;
const int duration = random_range(120 + pow, 200 + pow * 3 / 2);
// Hm, should dryads have rPois?
if (stop_summoning_prompt(MR_NO_FLAGS, "summon a forest"))
return spret::abort;
fail_check();
// Replace some rock walls with trees, then scatter a smaller number
// of trees on unoccupied floor (such that they do not break connectivity)
for (distance_iterator di(caster->pos(), false, true,
LOS_DEFAULT_RANGE); di; ++di)
{
if ((feat_is_wall(env.grid(*di)) && !feat_is_permarock(env.grid(*di))
&& x_chance_in_y(pow, 150))
|| (env.grid(*di) == DNGN_FLOOR && x_chance_in_y(pow, 1250)
&& !actor_at(*di) && !plant_forbidden_at(*di, true)))
{
temp_change_terrain(*di, DNGN_TREE, duration,
TERRAIN_CHANGE_FORESTED);
}
}
// Maybe make a pond
if (coinflip())
{
coord_def pond = find_gateway_location(caster);
int num = random_range(10, 22);
int deep = (!one_chance_in(3) ? div_rand_round(num, 3) : 0);
for (distance_iterator di(pond, true, false, 4); di && num > 0; ++di)
{
if (env.grid(*di) == DNGN_FLOOR
&& (di.radius() == 0 || _water_adjacent(*di))
&& x_chance_in_y(4, di.radius() + 3))
{
num--;
deep--;
dungeon_feature_type feat = DNGN_SHALLOW_WATER;
if (deep > 0 && *di != you.pos())
{
monster* mon = monster_at(*di);
if (!mon || mon->is_habitable_feat(DNGN_DEEP_WATER))
feat = DNGN_DEEP_WATER;
}
temp_change_terrain(*di, feat, duration, TERRAIN_CHANGE_FORESTED);
}
}
}
mpr("A forested plane collides here with a resounding crunch!");
noisy(spell_effect_noise(SPELL_SUMMON_FOREST), caster->pos());
mgen_data dryad_data = _pal_data(MONS_DRYAD, 1, god,
SPELL_SUMMON_FOREST);
dryad_data.hd = 5 + div_rand_round(pow, 18);
if (monster *dryad = create_monster(dryad_data))
{
mon_enchant abj = dryad->get_ench(ENCH_ABJ);
abj.duration = duration - 10;
dryad->update_ench(abj);
// Pre-awaken the forest just summoned.
bolt dummy;
mons_cast(dryad, dummy, SPELL_AWAKEN_FOREST,
dryad->spell_slot_flags(SPELL_AWAKEN_FOREST));
}
you.duration[DUR_FORESTED] = duration;
return spret::success;
}
monster_type pick_random_wraith()
{
return random_choose_weighted(1, MONS_SHADOW_WRAITH,
5, MONS_WRAITH,
2, MONS_FREEZING_WRAITH,
2, MONS_PHANTASMAL_WARRIOR);
}
spret cast_haunt(int pow, const coord_def& where, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON, "haunt your foes"))
return spret::abort;
monster* m = monster_at(where);
if (m == nullptr)
{
fail_check();
mpr("An evil force gathers, but it quickly dissipates.");
return spret::success; // still losing a turn
}
else if (m->wont_attack())
{
mpr("You cannot haunt those who bear you no hostility.");
return spret::abort;
}
int mi = m->mindex();
ASSERT(!invalid_monster_index(mi));
if (stop_attack_prompt(m, false, you.pos()))
return spret::abort;
fail_check();
bool friendly = true;
int success = 0;
int to_summon = stepdown_value(2 + (random2(pow) / 10) + (random2(pow) / 10),
2, 2, 6, -1);
while (to_summon--)
{
const monster_type mon = pick_random_wraith();
if (monster *mons = create_monster(
mgen_data(mon, BEH_FRIENDLY, where, mi, MG_FORCE_BEH)
.set_summoned(&you, 3, SPELL_HAUNT, god)))
{
success++;
mons->add_ench(mon_enchant(ENCH_HAUNTING, 1, m, INFINITE_DURATION));
mons->foe = mi;
}
}
if (success > 1)
{
mpr(friendly ? "Insubstantial figures form in the air."
: "You sense hostile presences.");
}
else if (success)
{
mpr(friendly ? "An insubstantial figure forms in the air."
: "You sense a hostile presence.");
}
else
{
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
return spret::success;
}
static spell_type servitor_spells[] =
{
// primary spells
SPELL_LEHUDIBS_CRYSTAL_SPEAR,
SPELL_IOOD,
SPELL_IRON_SHOT,
SPELL_BOLT_OF_COLD, // left in for frederick
SPELL_LIGHTNING_BOLT,
SPELL_FIREBALL,
SPELL_STONE_ARROW,
SPELL_LRD,
SPELL_AIRSTRIKE,
SPELL_FORCE_LANCE, // left in for frederick
// less desirable
SPELL_CONJURE_BALL_LIGHTNING,
SPELL_FREEZING_CLOUD,
SPELL_MEPHITIC_CLOUD,
SPELL_STICKY_FLAME,
};
/**
* Return the spell a player spellforged servitor would use, for the spell
* description.
*
* @return spell_type The spell a player servitor would use if cast now
*/
spell_type player_servitor_spell()
{
for (const spell_type spell : servitor_spells)
if (you.has_spell(spell) && raw_spell_fail(spell) < 50)
return spell;
return SPELL_NO_SPELL;
}
bool spell_servitorable(spell_type to_serve)
{
for (const spell_type spell : servitor_spells)
if (spell == to_serve)
return true;
return false;
}
/**
* Initialize the given spellforged servitor's HD and spellset, based on the
* caster's spellpower and castable attack spells.
*
* @param mon The spellforged servitor to be initialized.
* @param caster The entity summoning the servitor; may be the player.
* @param pow The caster's spellpower.
*/
static void _init_servitor_monster(monster &mon, const actor& caster, int pow)
{
const monster* caster_mon = caster.as_monster();
mon.set_hit_dice(9 + div_rand_round(pow, 14));
mon.max_hit_points = mon.hit_points = 60 + roll_dice(7, 5); // 67-95
// mhp doesn't vary with HD
int spell_levels = 0;
for (const spell_type spell : servitor_spells)
{
if (caster.has_spell(spell)
&& (caster_mon || raw_spell_fail(spell) < 50))
{
mon.spells.emplace_back(spell, 0, MON_SPELL_WIZARD);
spell_levels += spell_difficulty(spell);
// Player servitors take a single spell
if (!caster_mon)
break;
}
}
// Fix up frequencies now that we know the total number of spell levels.
const int base_freq = caster_mon ? 67 : 150;
for (auto& slot : mon.spells)
{
slot.freq = max(1, div_rand_round(spell_difficulty(slot.spell)
* base_freq,
spell_levels));
}
mon.props[CUSTOM_SPELLS_KEY].get_bool() = true;
}
void init_servitor(monster* servitor, actor* caster, int pow)
{
ASSERT(servitor); // XXX: change to monster &servitor
ASSERT(caster); // XXX: change to actor &caster
_init_servitor_monster(*servitor, *caster, pow);
if (you.can_see(*caster))
{
mprf("%s %s a servant imbued with %s destructive magic!",
caster->name(DESC_THE).c_str(),
caster->conj_verb("summon").c_str(),
caster->pronoun(PRONOUN_POSSESSIVE).c_str());
}
else
simple_monster_message(*servitor, " appears!");
int shortest_range = LOS_RADIUS + 1;
for (const mon_spell_slot &slot : servitor->spells)
{
if (slot.spell == SPELL_NO_SPELL)
continue;
int range = spell_range(slot.spell, 100, false);
if (range < shortest_range)
shortest_range = range;
}
servitor->props[IDEAL_RANGE_KEY].get_int() = shortest_range;
}
spret cast_spellforged_servitor(int pow, god_type god, bool fail)
{
if (stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
mgen_data mdata = _pal_data(MONS_SPELLFORGED_SERVITOR, 4, god,
SPELL_SPELLFORGED_SERVITOR);
if (monster* mon = create_monster(mdata))
init_servitor(mon, &you, pow);
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
monster* find_battlesphere(const actor* agent)
{
if (agent->props.exists(BATTLESPHERE_KEY))
return monster_by_mid(agent->props[BATTLESPHERE_KEY].get_int());
else
return nullptr;
}
static int _battlesphere_hd(int pow, bool random = true)
{
if (random)
return 1 + div_rand_round(pow, 11);
return 1 + pow / 11;
}
static dice_def _battlesphere_damage(int hd)
{
return dice_def(2, 5 + hd);
}
dice_def battlesphere_damage(int pow)
{
return _battlesphere_damage(_battlesphere_hd(pow, false));
}
spret cast_battlesphere(actor* agent, int pow, god_type god, bool fail)
{
if (agent->is_player() && stop_summoning_prompt(MR_RES_POISON))
return spret::abort;
fail_check();
monster* battlesphere;
if (agent->is_player() && (battlesphere = find_battlesphere(&you)))
{
bool recalled = false;
if (!you.can_see(*battlesphere))
{
coord_def empty;
if (find_habitable_spot_near(agent->pos(), MONS_BATTLESPHERE, 2,
false, empty)
&& battlesphere->move_to_pos(empty))
{
recalled = true;
}
}
if (recalled)
{
mpr("You recall your battlesphere and imbue it with additional"
" charge.");
}
else
mpr("You imbue your battlesphere with additional charge.");
battlesphere->battlecharge = min(20, (int) battlesphere->battlecharge
+ 4 + random2(pow + 10) / 10);
// Increase duration
mon_enchant abj = battlesphere->get_ench(ENCH_FAKE_ABJURATION);
abj.duration = min(abj.duration + (7 + roll_dice(2, pow)) * 10, 500);
battlesphere->update_ench(abj);
}
else
{
ASSERT(!find_battlesphere(agent));
mgen_data mg (MONS_BATTLESPHERE,
agent->is_player() ? BEH_FRIENDLY
: SAME_ATTITUDE(agent->as_monster()),
agent->pos(), agent->mindex());
mg.set_summoned(agent, 0, SPELL_BATTLESPHERE, god);
mg.hd = _battlesphere_hd(pow);
battlesphere = create_monster(mg);
if (battlesphere)
{
int dur = min((7 + roll_dice(2, pow)) * 10, 500);
battlesphere->add_ench(mon_enchant(ENCH_FAKE_ABJURATION, 1, 0, dur));
battlesphere->summoner = agent->mid;
agent->props[BATTLESPHERE_KEY].get_int() = battlesphere->mid;
if (agent->is_player())
mpr("You conjure a globe of magical energy.");
else
{
if (you.can_see(*agent) && you.can_see(*battlesphere))
{
simple_monster_message(*agent->as_monster(),
" conjures a globe of magical energy!");
}
else if (you.can_see(*battlesphere))
simple_monster_message(*battlesphere, " appears!");
battlesphere->props[BAND_LEADER_KEY].get_int() = agent->mid;
}
battlesphere->battlecharge = 4 + random2(pow + 10) / 10;
battlesphere->foe = agent->mindex();
battlesphere->target = agent->pos();
}
else if (agent->is_player() || you.can_see(*agent))
canned_msg(MSG_NOTHING_HAPPENS);
}
return spret::success;
}
void end_battlesphere(monster* mons, bool killed)
{
// Should only happen if you dismiss it in wizard mode, I think
if (!mons)
return;
actor* agent = actor_by_mid(mons->summoner);
if (agent)
agent->props.erase(BATTLESPHERE_KEY);
if (!killed)
{
if (agent && agent->is_player())
{
if (you.can_see(*mons))
{
if (mons->battlecharge == 0)
{
mpr("Your battlesphere expends the last of its energy"
" and dissipates.");
}
else
mpr("Your battlesphere wavers and loses cohesion.");
}
else
mpr("You feel your bond with your battlesphere wane.");
}
else if (you.can_see(*mons))
simple_monster_message(*mons, " dissipates.");
if (!cell_is_solid(mons->pos()))
place_cloud(CLOUD_MAGIC_TRAIL, mons->pos(), 3 + random2(3), mons);
monster_die(*mons, KILL_RESET, NON_MONSTER);
}
}
bool battlesphere_can_mirror(spell_type spell)
{
return spell_typematch(spell, spschool::conjuration)
&& spell != SPELL_BATTLESPHERE
&& spell != SPELL_SPELLFORGED_SERVITOR;
}
bool aim_battlesphere(actor* agent, spell_type spell)
{
//Is this spell something that will trigger the battlesphere?
if (battlesphere_can_mirror(spell))
{
monster* battlesphere = find_battlesphere(agent);
// If we've somehow gotten separated from the battlesphere (ie:
// abyss level teleport), bail out and cancel the battlesphere bond
if (!battlesphere)
{
agent->props.erase(BATTLESPHERE_KEY);
return false;
}
// In case the battlesphere was in the middle of a (failed)
// target-seeking action, cancel it so that it can focus on a new
// target
reset_battlesphere(battlesphere);
battlesphere->props.erase(MON_FOE_KEY);
// Pick a random baddie in LOS
vector<actor *> targets;
for (actor_near_iterator ai(agent, LOS_NO_TRANS); ai; ++ai)
{
if (battlesphere->can_see(**ai)
&& !mons_aligned(agent, *ai)
&& (ai->is_player() || !mons_is_firewood(*ai->as_monster())))
{
targets.push_back(*ai);
}
}
if (targets.empty())
return false;
const actor * target = *random_iterator(targets);
battlesphere->foe = target->mindex();
battlesphere->props[MON_FOE_KEY] = battlesphere->foe;
battlesphere->props["ready"] = true;
return true;
}
return false;
}
bool trigger_battlesphere(actor* agent)
{
monster* battlesphere = find_battlesphere(agent);
if (!battlesphere)
return false;
if (battlesphere->props.exists("ready"))
{
battlesphere->props.erase("ready");
battlesphere->props["firing"] = true;
// Since monsters may be acting out of sequence, give the battlesphere
// enough energy to attempt to fire this round, and requeue if it's
// already passed its turn
if (agent->is_monster())
{
battlesphere->speed_increment = 100;
queue_monster_for_action(battlesphere);
}
return true;
}
return false;
}
// Called at the start of each round. Cancels firing orders given in the
// previous round, if the battlesphere was not able to execute them fully
// before the next player action
void reset_battlesphere(monster* mons)
{
if (!mons || mons->type != MONS_BATTLESPHERE)
return;
mons->props.erase("ready");
if (mons->props.exists("tracking"))
{
mons->props.erase("tracking");
mons->props.erase("firing");
if (mons->props.exists(MON_FOE_KEY))
mons->foe = mons->props[MON_FOE_KEY].get_int();
mons->behaviour = BEH_SEEK;
}
}
bool fire_battlesphere(monster* mons)
{
if (!mons || mons->type != MONS_BATTLESPHERE)
return false;
actor* agent = actor_by_mid(mons->summoner);
if (!agent || !agent->alive())
{
end_battlesphere(mons, false);
return false;
}
bool used = false;
if (mons->props.exists("firing") && mons->battlecharge > 0)
{
if (mons->props.exists("tracking"))
{
if (mons->pos() == mons->props[TRACKING_TARGET_KEY].get_coord())
{
mons->props.erase("tracking");
if (mons->props.exists(MON_FOE_KEY))
mons->foe = mons->props[MON_FOE_KEY].get_int();
mons->behaviour = BEH_SEEK;
}
else // Currently tracking, but have not reached target pos
{
mons->target = mons->props[TRACKING_TARGET_KEY].get_coord();
return false;
}
}
else
{
// If the battlesphere forgot its foe (due to being out of los),
// remind it
if (mons->props.exists(MON_FOE_KEY))
mons->foe = mons->props[MON_FOE_KEY].get_int();
}
// Set up the beam.
bolt beam;
beam.source_name = BATTLESPHERE_KEY;
// If we are locked onto a foe, use its current position
if (!invalid_monster_index(mons->foe) && env.mons[mons->foe].alive())
beam.target = env.mons[mons->foe].pos();
// Sanity check: if we have somehow ended up targeting ourselves, bail
if (beam.target == mons->pos())
{
mprf(MSGCH_ERROR, "Battlesphere targeting itself? Fixing.");
mons->props.erase("firing");
mons->props.erase(MON_FOE_KEY);
return false;
}
beam.name = "barrage of energy";
beam.range = LOS_RADIUS;
beam.hit = AUTOMATIC_HIT;
beam.damage = _battlesphere_damage(mons->get_hit_dice());
beam.glyph = dchar_glyph(DCHAR_FIRED_ZAP);
beam.colour = MAGENTA;
beam.flavour = BEAM_MMISSILE;
beam.pierce = false;
// Fire tracer.
fire_tracer(mons, beam);
// Never fire if we would hurt the caster, and ensure that the beam
// would hit at least SOMETHING, unless it was targeted at empty space
// in the first place
if (beam.friend_info.count == 0 && beam.foe_info.count > 0)
{
beam.thrower = (agent->is_player()) ? KILL_YOU : KILL_MON;
simple_monster_message(*mons, " fires!");
beam.fire();
used = true;
// Decrement # of volleys left and possibly expire the battlesphere.
if (--mons->battlecharge == 0)
end_battlesphere(mons, false);
mons->props.erase("firing");
}
// If we are firing at something, try to find a nearby position
// from which we could safely fire at it
else
{
const bool empty_beam = (beam.foe_info.count == 0);
for (distance_iterator di(mons->pos(), true, true, 2); di; ++di)
{
if (*di == beam.target || actor_at(*di)
|| cell_is_solid(*di)
|| !agent->see_cell(*di))
{
continue;
}
beam.source = *di;
beam.is_tracer = true;
beam.friend_info.reset();
beam.foe_info.reset();
beam.fire();
if (beam.friend_info.count == 0
&& (beam.foe_info.count > 0 || empty_beam))
{
if (empty_beam
&& find(beam.path_taken.begin(), beam.path_taken.end(),
beam.target) == beam.path_taken.end())
{
continue;
}
mons->firing_pos = coord_def(0, 0);
mons->target = *di;
mons->behaviour = BEH_WANDER;
mons->props[MON_FOE_KEY] = mons->foe;
mons->props["tracking"] = true;
mons->foe = MHITNOT;
mons->props[TRACKING_TARGET_KEY] = *di;
break;
}
}
// If we didn't find a better firing position nearby, cancel firing
if (!mons->props.exists("tracking"))
mons->props.erase("firing");
}
}
// If our last target is dead, or the player wandered off, resume
// following the player
if ((mons->foe == MHITNOT || !mons->can_see(*agent)
|| (!invalid_monster_index(mons->foe)
&& !agent->can_see(env.mons[mons->foe])))
&& !mons->props.exists("tracking"))
{
mons->foe = agent->mindex();
}
return used;
}
int prism_hd(int pow, bool random)
{
if (random)
return div_rand_round(pow, 10);
return pow / 10;
}
spret cast_fulminating_prism(actor* caster, int pow,
const coord_def& where, bool fail)
{
if (grid_distance(where, caster->pos())
> spell_range(SPELL_FULMINANT_PRISM, pow))
{
if (caster->is_player())
mpr("That's too far away.");
return spret::abort;
}
if (cell_is_solid(where))
{
if (caster->is_player())
mpr("You can't conjure that within a solid object!");
return spret::abort;
}
actor* victim = monster_at(where);
if (victim)
{
if (caster->can_see(*victim))
{
if (caster->is_player())
mpr("You can't place the prism on a creature.");
return spret::abort;
}
fail_check();
// FIXME: maybe should do _paranoid_option_disable() here?
if (caster->is_player()
|| (you.can_see(*caster) && you.see_cell(where)))
{
if (you.can_see(*victim))
{
mprf("%s %s.", victim->name(DESC_THE).c_str(),
victim->conj_verb("twitch").c_str());
}
else
canned_msg(MSG_GHOSTLY_OUTLINE);
}
return spret::success; // Don't give free detection!
}
fail_check();
const int hd = prism_hd(pow);
mgen_data prism_data = mgen_data(MONS_FULMINANT_PRISM,
caster->is_player()
? BEH_FRIENDLY
: SAME_ATTITUDE(caster->as_monster()),
where, MHITNOT, MG_FORCE_PLACE);
prism_data.set_summoned(caster, 0, SPELL_FULMINANT_PRISM);
prism_data.hd = hd;
monster *prism = create_monster(prism_data);
if (prism)
{
if (caster->observable())
{
mprf("%s %s a prism of explosive energy!",
caster->name(DESC_THE).c_str(),
caster->conj_verb("conjure").c_str());
}
else if (you.can_see(*prism))
mprf("A prism of explosive energy appears from nowhere!");
}
else if (you.can_see(*caster))
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
monster* find_spectral_weapon(const actor* agent)
{
if (agent->props.exists(SPECTRAL_WEAPON_KEY))
return monster_by_mid(agent->props[SPECTRAL_WEAPON_KEY].get_int());
else
return nullptr;
}
void end_spectral_weapon(monster* mons, bool killed, bool quiet)
{
// Should only happen if you dismiss it in wizard mode, I think
if (!mons)
return;
actor *owner = actor_by_mid(mons->summoner);
if (owner)
owner->props.erase(SPECTRAL_WEAPON_KEY);
if (!quiet)
{
if (you.can_see(*mons))
{
simple_monster_message(*mons, " fades away.",
MSGCH_MONSTER_DAMAGE, MDAM_DEAD);
}
else if (owner && owner->is_player())
mpr("You feel your bond with your spectral weapon wane.");
}
if (!killed)
monster_die(*mons, KILL_RESET, NON_MONSTER);
}
static void _setup_infestation(bolt &beam, int pow)
{
beam.name = "infestation";
beam.aux_source = "infestation";
beam.flavour = BEAM_INFESTATION;
beam.glyph = dchar_glyph(DCHAR_FIRED_BURST);
beam.colour = GREEN;
beam.source_id = MID_PLAYER;
beam.thrower = KILL_YOU;
beam.is_explosion = true;
beam.ex_size = 2;
beam.ench_power = pow;
beam.origin_spell = SPELL_INFESTATION;
}
spret cast_infestation(int pow, bolt &beam, bool fail)
{
if (cell_is_solid(beam.target))
{
canned_msg(MSG_SOMETHING_IN_WAY);
return spret::abort;
}
fail_check();
_setup_infestation(beam, pow);
mpr("You call forth a plague of scarabs!");
beam.explode();
return spret::success;
}
struct summon_cap
{
int player_cap;
int monster_cap;
};
// spell type, player cap, monster cap
static const map<spell_type, summon_cap> summonsdata =
{
// Player- and monster-castable spells
{ SPELL_SUMMON_SMALL_MAMMAL, { 2, 4 } },
{ SPELL_CALL_CANINE_FAMILIAR, { 1, 1 } },
{ SPELL_SUMMON_ICE_BEAST, { 1, 3 } },
{ SPELL_SUMMON_HYDRA, { 2, 3 } },
{ SPELL_SUMMON_MANA_VIPER, { 1, 3 } },
{ SPELL_CALL_IMP, { 1, 3 } },
{ SPELL_MONSTROUS_MENAGERIE, { 2, 3 } },
{ SPELL_SUMMON_HORRIBLE_THINGS, { 8, 8 } },
{ SPELL_SUMMON_LIGHTNING_SPIRE, { 1, 1 } },
{ SPELL_SUMMON_GUARDIAN_GOLEM, { 1, 1 } },
{ SPELL_SPELLFORGED_SERVITOR, { 1, 1 } },
{ SPELL_ANIMATE_ARMOUR, { 1, 1 } },
{ SPELL_HAUNT, { 8, 8 } },
{ SPELL_SUMMON_CACTUS, { 1, 1 } },
// Monster-only spells
{ SPELL_SHADOW_CREATURES, { 0, 4 } },
{ SPELL_SUMMON_SPIDERS, { 0, 5 } },
{ SPELL_SUMMON_UFETUBUS, { 0, 8 } },
{ SPELL_SUMMON_HELL_BEAST, { 0, 8 } },
{ SPELL_SUMMON_UNDEAD, { 0, 8 } },
{ SPELL_SUMMON_DRAKES, { 0, 4 } },
{ SPELL_SUMMON_MUSHROOMS, { 0, 8 } },
{ SPELL_SUMMON_EYEBALLS, { 0, 4 } },
{ SPELL_WATER_ELEMENTALS, { 0, 3 } },
{ SPELL_FIRE_ELEMENTALS, { 0, 3 } },
{ SPELL_EARTH_ELEMENTALS, { 0, 3 } },
{ SPELL_AIR_ELEMENTALS, { 0, 3 } },
{ SPELL_SUMMON_SPECTRAL_ORCS, { 0, 3 } },
{ SPELL_FIRE_SUMMON, { 0, 4 } },
{ SPELL_SUMMON_MINOR_DEMON, { 0, 3 } },
{ SPELL_CALL_LOST_SOUL, { 0, 3 } },
{ SPELL_SUMMON_VERMIN, { 0, 5 } },
{ SPELL_FORCEFUL_INVITATION, { 0, 3 } },
{ SPELL_PLANEREND, { 0, 6 } },
{ SPELL_SUMMON_DRAGON, { 0, 4 } },
{ SPELL_PHANTOM_MIRROR, { 0, 4 } },
{ SPELL_FAKE_MARA_SUMMON, { 0, 2 } },
{ SPELL_SUMMON_EMPEROR_SCORPIONS, { 0, 6 } },
{ SPELL_SUMMON_SCARABS, { 0, 8 } },
{ SPELL_SUMMON_HOLIES, { 0, 4 } },
{ SPELL_SUMMON_EXECUTIONERS, { 0, 3 } },
{ SPELL_AWAKEN_EARTH, { 0, 9 } },
{ SPELL_GREATER_SERVANT_MAKHLEB, { 0, 1 } },
{ SPELL_SUMMON_GREATER_DEMON, { 0, 3 } },
{ SPELL_SUMMON_DEMON, { 0, 3 } },
{ SPELL_SUMMON_TZITZIMITL, { 0, 3 } },
{ SPELL_SUMMON_HELL_SENTINEL, { 0, 3 } },
{ SPELL_CONJURE_LIVING_SPELLS, { 0, 6 } },
{ SPELL_SHEZAS_DANCE, { 0, 6 } },
};
bool summons_are_capped(spell_type spell)
{
ASSERT_RANGE(spell, 0, NUM_SPELLS);
return summonsdata.count(spell);
}
int summons_limit(spell_type spell, bool player)
{
const summon_cap *cap = map_find(summonsdata, spell);
if (!cap)
return 0;
else
return player ? cap->player_cap : cap->monster_cap;
}
static bool _spell_has_variable_cap(spell_type spell)
{
return spell == SPELL_SHADOW_CREATURES;
}
static void _expire_capped_summon(monster* mon, bool recurse)
{
// Timeout the summon
mon_enchant abj = mon->get_ench(ENCH_ABJ);
abj.duration = 10;
mon->update_ench(abj);
// Mark our cap abjuration so we don't keep abjuring the same
// one if creating multiple summons (also, should show a status light).
mon->add_ench(ENCH_SUMMON_CAPPED);
if (recurse && mon->props.exists(SUMMON_ID_KEY))
{
const int summon_id = mon->props[SUMMON_ID_KEY].get_int();
for (monster_iterator mi; mi; ++mi)
{
// Summoner check should be technically unnecessary, but saves
// scanning props for all monsters on the level.
if (mi->summoner == mon->summoner
&& mi->props.exists(SUMMON_ID_KEY)
&& mi->props[SUMMON_ID_KEY].get_int() == summon_id
&& !mi->has_ench(ENCH_SUMMON_CAPPED))
{
_expire_capped_summon(*mi, false);
}
}
}
}
// Call when a monster has been summoned, to manage this summoner's caps.
void summoned_monster(const monster *mons, const actor *caster,
spell_type spell)
{
int cap = summons_limit(spell, caster->is_player());
if (!cap) // summons aren't capped
return;
// Cap large abominations and tentacled monstrosities separately
if (spell == SPELL_SUMMON_HORRIBLE_THINGS)
{
cap = (mons->type == MONS_ABOMINATION_LARGE ? cap * 3 / 4
: cap * 1 / 4);
}
monster* oldest_summon = 0;
int oldest_duration = 0;
// Linked summons that have already been counted once
set<int> seen_ids;
int count = 1;
for (monster_iterator mi; mi; ++mi)
{
if (mons == *mi)
continue;
int duration = 0;
int stype = 0;
const bool summoned = mi->is_summoned(&duration, &stype);
if (summoned && stype == spell && caster->mid == mi->summoner
&& mons_aligned(caster, *mi))
{
// Count large abominations and tentacled monstrosities separately
if (spell == SPELL_SUMMON_HORRIBLE_THINGS && mi->type != mons->type)
continue;
if (_spell_has_variable_cap(spell) && mi->props.exists(SUMMON_ID_KEY))
{
const int id = mi->props[SUMMON_ID_KEY].get_int();
// Skip any linked summon whose set we have seen already,
// otherwise add it to the list of seen summon IDs
if (seen_ids.find(id) == seen_ids.end())
seen_ids.insert(id);
else
continue;
}
count++;
// If this summon is the oldest (well, the closest to expiry)
// remember it (unless already expiring due to a cap)
if (!mi->has_ench(ENCH_SUMMON_CAPPED)
&& (!oldest_summon || duration < oldest_duration))
{
oldest_summon = *mi;
oldest_duration = duration;
}
}
}
if (oldest_summon && count > cap)
_expire_capped_summon(oldest_summon, true);
}
int count_summons(const actor *summoner, spell_type spell)
{
int count = 0;
for (monster_iterator mi; mi; ++mi)
{
if (summoner == *mi)
continue;
int stype = 0;
const bool summoned = mi->is_summoned(nullptr, &stype);
if (summoned && stype == spell && summoner->mid == mi->summoner
&& mons_aligned(summoner, *mi))
{
count++;
}
}
return count;
}
static bool _create_briar_patch(coord_def& target)
{
mgen_data mgen = mgen_data(MONS_BRIAR_PATCH, BEH_FRIENDLY, target,
MHITNOT, MG_FORCE_PLACE, GOD_FEDHAS);
mgen.hd = mons_class_hit_dice(MONS_BRIAR_PATCH) +
you.skill_rdiv(SK_INVOCATIONS);
mgen.set_summoned(&you, min(2 + you.skill_rdiv(SK_INVOCATIONS, 1, 5), 6),
SPELL_NO_SPELL);
if (create_monster(mgen))
{
mpr("A briar patch grows up from the ground.");
return true;
}
return false;
}
vector<coord_def> find_briar_spaces(bool just_check)
{
vector<coord_def> result;
for (adjacent_iterator adj_it(you.pos()); adj_it; ++adj_it)
{
if (monster_habitable_grid(MONS_BRIAR_PATCH, env.grid(*adj_it))
&& (!actor_at(*adj_it)
|| just_check && !you.can_see(*actor_at(*adj_it))))
{
result.push_back(*adj_it);
}
}
return result;
}
void fedhas_wall_of_briars()
{
// How many adjacent open spaces are there?
vector<coord_def> adjacent = find_briar_spaces();
if (adjacent.empty())
{
mpr("Something you can't see blocks your briars from growing!");
return;
}
int created_count = 0;
for (auto p : adjacent)
{
if (_create_briar_patch(p))
created_count++;
}
if (!created_count)
canned_msg(MSG_NOTHING_HAPPENS);
return;
}
static void _overgrow_wall(const coord_def &pos)
{
const dungeon_feature_type feat = env.grid(pos);
const string what = feature_description(feat, NUM_TRAPS, "", DESC_THE);
if (monster_at(pos))
{
mprf("Something unseen blocks growth in %s.", what.c_str());
return;
}
destroy_wall(pos);
const monster_type mon = random_choose_weighted(4, MONS_OKLOB_SAPLING,
4, MONS_BURNING_BUSH,
4, MONS_WANDERING_MUSHROOM,
1, MONS_BALLISTOMYCETE,
1, MONS_OKLOB_PLANT);
mgen_data mgen(mon, BEH_FRIENDLY, pos, MHITYOU, MG_FORCE_PLACE);
mgen.hd = mons_class_hit_dice(mon) + you.skill_rdiv(SK_INVOCATIONS);
mgen.set_summoned(&you, min(3 + you.skill_rdiv(SK_INVOCATIONS, 1, 5), 6),
SPELL_NO_SPELL);
if (const monster* const plant = create_monster(mgen))
{
mprf("%s is torn apart as %s grows in its place.", what.c_str(),
plant->name(DESC_A).c_str());
}
// XXX: Maybe try to make this revert the terrain if a monster isn't placed.
else
mprf("%s falls apart, but nothing grows.", what.c_str());
}
spret fedhas_overgrow(bool fail)
{
targeter_overgrow tgt;
direction_chooser_args args;
args.hitfunc = &tgt;
args.restricts = DIR_TARGET;
args.mode = TARG_ANY;
args.range = LOS_RADIUS;
args.just_looking = false;
args.needs_path = false;
args.top_prompt = "Aiming: <white>Overgrow</white>";
dist sdirect;
direction(sdirect, args);
if (!sdirect.isValid)
return spret::abort;
fail_check();
for (auto site : tgt.affected_positions)
_overgrow_wall(site);
return spret::success;
}
spret fedhas_grow_ballistomycete(const coord_def& target, bool fail)
{
if (grid_distance(target, you.pos()) > 2 || !in_bounds(target))
{
mpr("That's too far away.");
return spret::abort;
}
if (!monster_habitable_grid(MONS_BALLISTOMYCETE, env.grid(target)))
{
mpr("You can't grow a ballistomycete there.");
return spret::abort;
}
monster* mons = monster_at(target);
if (mons)
{
if (you.can_see(*mons))
{
mpr("That space is already occupied.");
return spret::abort;
}
fail_check();
// invisible monster
mpr("Something you can't see occupies that space!");
return spret::success;
}
fail_check();
mgen_data mgen(MONS_BALLISTOMYCETE, BEH_FRIENDLY, target, MHITYOU,
MG_FORCE_BEH | MG_FORCE_PLACE | MG_AUTOFOE);
mgen.hd = mons_class_hit_dice(MONS_BALLISTOMYCETE) +
you.skill_rdiv(SK_INVOCATIONS);
mgen.set_summoned(&you, min(3 + you.skill_rdiv(SK_INVOCATIONS, 1, 5), 6),
SPELL_NO_SPELL);
if (create_monster(mgen))
mpr("A ballistomycete grows from the ground.");
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret fedhas_grow_oklob(const coord_def& target, bool fail)
{
if (grid_distance(target, you.pos()) > 2 || !in_bounds(target))
{
mpr("That's too far away.");
return spret::abort;
}
if (!monster_habitable_grid(MONS_OKLOB_PLANT, env.grid(target)))
{
mpr("You can't grow an oklob plant there.");
return spret::abort;
}
monster* mons = monster_at(target);
if (mons)
{
if (you.can_see(*mons))
{
mpr("That space is already occupied.");
return spret::abort;
}
fail_check();
// invisible monster
mpr("Something you can't see is occupying that space!");
return spret::success;
}
fail_check();
mgen_data mgen(MONS_OKLOB_PLANT, BEH_FRIENDLY, target, MHITYOU,
MG_FORCE_BEH | MG_FORCE_PLACE | MG_AUTOFOE);
mgen.hd = mons_class_hit_dice(MONS_OKLOB_PLANT) +
you.skill_rdiv(SK_INVOCATIONS);
mgen.set_summoned(&you, min(3 + you.skill_rdiv(SK_INVOCATIONS, 1, 5), 6),
SPELL_NO_SPELL);
if (create_monster(mgen))
mpr("An oklob plant grows from the ground.");
else
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
void kiku_unearth_wretches()
{
const int pow = you.skill(SK_NECROMANCY, 6);
const int min_wretches = 2;
const int max_wretches = min_wretches + div_rand_round(pow, 27); // 8 max
const int wretches = random_range(min_wretches, max_wretches);
bool created = false;
for (int i = 0; i < wretches; ++i)
{
// choose a type
const int typ_pow = you.skill(SK_NECROMANCY, 4);
const int adjusted_power = min(typ_pow / 4, random2(random2(typ_pow)));
const level_id lev(you.where_are_you, adjusted_power
- absdungeon_depth(you.where_are_you, 0));
const monster_type mon_type = pick_local_corpsey_monster(lev);
ASSERT(mons_class_can_be_zombified(mons_species(mon_type)));
// place a monster
mgen_data mg(mon_type,
BEH_HOSTILE, // so players don't have attack prompts
you.pos(),
MHITNOT);
mg.extra_flags = MF_NO_REWARD // ?
| MF_NO_REGEN;
mg.props[KIKU_WRETCH_KEY] = true;
monster *mon = create_monster(mg);
if (!mon)
continue;
created = true;
mons_add_blame(mon, "unearthed by the player character");
mon->hit_points = 1;
mon->props[ALWAYS_CORPSE_KEY] = true;
mon->props[KIKU_WRETCH_KEY] = true;
// Die in 2-3 turns.
mon->add_ench(mon_enchant(ENCH_SLOWLY_DYING, 1, nullptr,
20 + random2(10)));
mon->add_ench(mon_enchant(ENCH_PARALYSIS, 0, &you, 9999));
}
if (!created)
simple_god_message(" has no space to call forth the wretched!");
else
simple_god_message(" calls piteous wretches from the earth!");
}
static bool _create_foxfire(const actor &agent, coord_def pos,
god_type god, int pow)
{
const auto att = agent.is_player() ? BEH_FRIENDLY
: SAME_ATTITUDE(agent.as_monster());
mgen_data fox(MONS_FOXFIRE, att,
pos, MHITNOT, MG_FORCE_PLACE | MG_AUTOFOE);
fox.set_summoned(&agent, 0, SPELL_FOXFIRE, god);
fox.hd = pow;
monster *foxfire;
if (cell_is_solid(pos) || actor_at(pos))
return false;
foxfire = create_monster(fox);
if (!foxfire)
return false;
foxfire->add_ench(ENCH_SHORT_LIVED);
foxfire->steps_remaining = you.current_vision + 2;
// Avoid foxfire without targets always moving towards (0,0)
if (!foxfire->get_foe()
|| !foxfire->get_foe()->is_monster() && !agent.is_monster())
{
set_random_target(foxfire);
}
return true;
}
spret cast_foxfire(actor &agent, int pow, god_type god, bool fail)
{
bool see_space = false;
for (adjacent_iterator ai(agent.pos()); ai; ++ai)
{
if (cell_is_solid(*ai))
continue;
if (actor_at(*ai) && agent.can_see(*actor_at(*ai)))
continue;
see_space = true;
break;
}
if (agent.is_player() && !see_space)
{
mpr("There is not enough space to conjure foxfire!");
return spret::abort;
}
fail_check();
int created = 0;
for (fair_adjacent_iterator ai(agent.pos()); ai; ++ai)
{
if (!_create_foxfire(agent, *ai, god, pow))
continue;
++created;
if (created == 2)
break;
}
if (created && you.see_cell(agent.pos()))
{
mprf("%s conjure%s some foxfire!",
agent.name(DESC_THE).c_str(),
agent.is_monster() ? "s" : "");
}
else if (agent.is_player())
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
spret foxfire_swarm()
{
bool created = false;
bool unknown_unseen = false;
for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_NO_TRANS); ri; ++ri)
{
if (_create_foxfire(you, *ri, GOD_NO_GOD, 10))
{
created = true;
continue;
}
const actor* agent = actor_at(*ri);
if (agent && !you.can_see(*agent))
unknown_unseen = true;
}
if (created)
{
mpr("Flames leap up around you!");
return spret::success;
}
if (!unknown_unseen)
{
mpr("There's no space to create foxfire here.");
return spret::abort;
}
canned_msg(MSG_NOTHING_HAPPENS);
return spret::fail; // don't spend piety, do spend a turn
}
bool summon_spider(const actor &agent, coord_def pos, god_type god,
spell_type spell, int pow)
{
monster_type mon = random_choose_weighted(100, MONS_REDBACK,
100, MONS_JUMPING_SPIDER,
75, MONS_TARANTELLA,
50, MONS_CULICIVORA,
50, MONS_ORB_SPIDER,
pow / 2, MONS_WOLF_SPIDER);
monster *mons = create_monster(
mgen_data(mon, BEH_COPY, pos, _auto_autofoe(&agent), MG_AUTOFOE)
.set_summoned(&agent, 3, spell, god));
if (mons)
return true;
return false;
}
spret summon_spiders(actor &agent, int pow, god_type god, bool fail)
{
// Can't happen at present, but why not check just to be sure.
if (agent.is_player() && stop_summoning_prompt())
return spret::abort;
fail_check();
int created = 0;
for (int i = 0; i < 1 + div_rand_round(random2(pow), 80); i++)
{
if (summon_spider(agent, agent.pos(), god, SPELL_SUMMON_SPIDERS, pow))
created++;
}
if (created && you.see_cell(agent.pos()))
{
mprf("%s %s %s!",
agent.name(DESC_THE).c_str(),
agent.conj_verb("summon").c_str(),
created > 1 ? "spiders" : "a spider");
}
else if (agent.is_player())
canned_msg(MSG_NOTHING_HAPPENS);
return spret::success;
}
|
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2016 Hotride
#include "SkillGroup.h"
#include "Managers/SkillsManager.h"
CSkillGroupObject::CSkillGroupObject()
{
memset(m_Items, 0xFF, sizeof(m_Items));
}
CSkillGroupObject::~CSkillGroupObject()
{
}
uint8_t CSkillGroupObject::GetItem(intptr_t index)
{
if (index < 0 || index >= Count)
{
return 0xFF;
}
return m_Items[index];
}
void CSkillGroupObject::Add(uint8_t index)
{
if (Contains(index))
{
return;
}
m_Items[Count] = index;
Count++;
}
void CSkillGroupObject::AddSorted(uint8_t index)
{
if (Contains(index))
{
return;
}
m_Items[Count] = index;
Count++;
Sort();
}
void CSkillGroupObject::Remove(uint8_t index)
{
bool removed = false;
for (int i = 0; i < Count; i++)
{
if (m_Items[i] == index)
{
removed = true;
for (; i < Count - 1; i++)
{
m_Items[i] = m_Items[i + 1];
}
break;
}
}
if (removed)
{
Count--;
if (Count < 0)
{
Count = 0;
}
m_Items[Count] = 0xFF;
}
}
bool CSkillGroupObject::Contains(uint8_t index)
{
for (int i = 0; i < Count; i++)
{
if (m_Items[i] == index)
{
return true;
}
}
return false;
}
void CSkillGroupObject::Sort()
{
uint8_t table[60] = { 0 };
int Ptr = 0;
for (uint32_t i = 0; i < g_SkillsManager.Count; i++)
{
for (int j = 0; j < Count; j++)
{
if (g_SkillsManager.GetSortedIndex((int)i) == m_Items[j])
{
table[Ptr] = m_Items[j];
Ptr++;
break;
}
}
}
for (int j = 0; j < Count; j++)
{
m_Items[j] = table[j];
}
}
void CSkillGroupObject::TransferTo(CSkillGroupObject *group)
{
for (int i = 0; i < Count; i++)
{
group->Add(m_Items[i]);
}
group->Sort();
}
|
// 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 "base/file_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/object_watcher.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_hdc.h"
#include "chrome/common/crash_keys.h"
#include "chrome/service/cloud_print/print_system_win.h"
#include "chrome/service/service_process.h"
#include "chrome/service/service_utility_process_host.h"
#include "grit/generated_resources.h"
#include "printing/backend/win_helper.h"
#include "printing/emf_win.h"
#include "printing/page_range.h"
#include "printing/printing_utils.h"
#include "ui/base/l10n/l10n_util.h"
namespace cloud_print {
namespace {
class DevMode {
public:
DevMode() : dm_(NULL) {}
~DevMode() { Free(); }
void Allocate(int size) {
Free();
dm_ = reinterpret_cast<DEVMODE*>(new char[size]);
}
void Free() {
if (dm_)
delete [] dm_;
dm_ = NULL;
}
DEVMODE* dm_;
private:
DISALLOW_COPY_AND_ASSIGN(DevMode);
};
HRESULT StreamFromPrintTicket(const std::string& print_ticket,
IStream** stream) {
DCHECK(stream);
HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, stream);
if (FAILED(hr)) {
return hr;
}
ULONG bytes_written = 0;
(*stream)->Write(print_ticket.c_str(), print_ticket.length(), &bytes_written);
DCHECK(bytes_written == print_ticket.length());
LARGE_INTEGER pos = {0};
ULARGE_INTEGER new_pos = {0};
(*stream)->Seek(pos, STREAM_SEEK_SET, &new_pos);
return S_OK;
}
HRESULT PrintTicketToDevMode(const std::string& printer_name,
const std::string& print_ticket,
DevMode* dev_mode) {
DCHECK(dev_mode);
printing::ScopedXPSInitializer xps_initializer;
if (!xps_initializer.initialized()) {
// TODO(sanjeevr): Handle legacy proxy case (with no prntvpt.dll)
return E_FAIL;
}
base::win::ScopedComPtr<IStream> pt_stream;
HRESULT hr = StreamFromPrintTicket(print_ticket, pt_stream.Receive());
if (FAILED(hr))
return hr;
HPTPROVIDER provider = NULL;
hr = printing::XPSModule::OpenProvider(UTF8ToWide(printer_name), 1,
&provider);
if (SUCCEEDED(hr)) {
ULONG size = 0;
DEVMODE* dm = NULL;
// Use kPTJobScope, because kPTDocumentScope breaks duplex.
hr = printing::XPSModule::ConvertPrintTicketToDevMode(provider,
pt_stream,
kUserDefaultDevmode,
kPTJobScope,
&size,
&dm,
NULL);
if (SUCCEEDED(hr)) {
dev_mode->Allocate(size);
memcpy(dev_mode->dm_, dm, size);
printing::XPSModule::ReleaseMemory(dm);
}
printing::XPSModule::CloseProvider(provider);
}
return hr;
}
class JobSpoolerWin : public PrintSystem::JobSpooler {
public:
JobSpoolerWin() : core_(new Core) {}
// PrintSystem::JobSpooler implementation.
virtual bool Spool(const std::string& print_ticket,
const base::FilePath& print_data_file_path,
const std::string& print_data_mime_type,
const std::string& printer_name,
const std::string& job_title,
const std::vector<std::string>& tags,
JobSpooler::Delegate* delegate) OVERRIDE {
// TODO(gene): add tags handling.
scoped_refptr<printing::PrintBackend> print_backend(
printing::PrintBackend::CreateInstance(NULL));
crash_keys::ScopedPrinterInfo crash_key(
print_backend->GetPrinterDriverInfo(printer_name));
return core_->Spool(print_ticket, print_data_file_path,
print_data_mime_type, printer_name, job_title,
delegate);
}
protected:
virtual ~JobSpoolerWin() {}
private:
// We use a Core class because we want a separate RefCountedThreadSafe
// implementation for ServiceUtilityProcessHost::Client.
class Core : public ServiceUtilityProcessHost::Client,
public base::win::ObjectWatcher::Delegate {
public:
Core()
: last_page_printed_(-1),
job_id_(-1),
delegate_(NULL),
saved_dc_(0) {
}
~Core() {}
bool Spool(const std::string& print_ticket,
const base::FilePath& print_data_file_path,
const std::string& print_data_mime_type,
const std::string& printer_name,
const std::string& job_title,
JobSpooler::Delegate* delegate) {
scoped_refptr<printing::PrintBackend> print_backend(
printing::PrintBackend::CreateInstance(NULL));
crash_keys::ScopedPrinterInfo crash_key(
print_backend->GetPrinterDriverInfo(printer_name));
if (delegate_) {
// We are already in the process of printing.
NOTREACHED();
return false;
}
last_page_printed_ = -1;
// We only support PDF and XPS documents for now.
if (print_data_mime_type == "application/pdf") {
DevMode pt_dev_mode;
HRESULT hr = PrintTicketToDevMode(printer_name, print_ticket,
&pt_dev_mode);
if (FAILED(hr)) {
NOTREACHED();
return false;
}
HDC dc = CreateDC(L"WINSPOOL", UTF8ToWide(printer_name).c_str(),
NULL, pt_dev_mode.dm_);
if (!dc) {
NOTREACHED();
return false;
}
hr = E_FAIL;
DOCINFO di = {0};
di.cbSize = sizeof(DOCINFO);
string16 doc_name = UTF8ToUTF16(job_title);
DCHECK(printing::SimplifyDocumentTitle(doc_name) == doc_name);
di.lpszDocName = doc_name.c_str();
job_id_ = StartDoc(dc, &di);
if (job_id_ <= 0)
return false;
printer_dc_.Set(dc);
saved_dc_ = SaveDC(printer_dc_.Get());
print_data_file_path_ = print_data_file_path;
delegate_ = delegate;
RenderNextPDFPages();
} else if (print_data_mime_type == "application/vnd.ms-xpsdocument") {
bool ret = PrintXPSDocument(printer_name,
job_title,
print_data_file_path,
print_ticket);
if (ret)
delegate_ = delegate;
return ret;
} else {
NOTREACHED();
return false;
}
return true;
}
void PreparePageDCForPrinting(HDC, double scale_factor) {
SetGraphicsMode(printer_dc_.Get(), GM_ADVANCED);
// Setup the matrix to translate and scale to the right place. Take in
// account the scale factor.
// Note that the printing output is relative to printable area of
// the page. That is 0,0 is offset by PHYSICALOFFSETX/Y from the page.
int offset_x = ::GetDeviceCaps(printer_dc_.Get(), PHYSICALOFFSETX);
int offset_y = ::GetDeviceCaps(printer_dc_.Get(), PHYSICALOFFSETY);
XFORM xform = {0};
xform.eDx = static_cast<float>(-offset_x);
xform.eDy = static_cast<float>(-offset_y);
xform.eM11 = xform.eM22 = 1.0 / scale_factor;
SetWorldTransform(printer_dc_.Get(), &xform);
}
// ServiceUtilityProcessHost::Client implementation.
virtual void OnRenderPDFPagesToMetafileSucceeded(
const printing::Emf& metafile,
int highest_rendered_page_number,
double scale_factor) OVERRIDE {
PreparePageDCForPrinting(printer_dc_.Get(), scale_factor);
metafile.SafePlayback(printer_dc_.Get());
bool done_printing = (highest_rendered_page_number !=
last_page_printed_ + kPageCountPerBatch);
last_page_printed_ = highest_rendered_page_number;
if (done_printing)
PrintJobDone();
else
RenderNextPDFPages();
}
// base::win::ObjectWatcher::Delegate implementation.
virtual void OnObjectSignaled(HANDLE object) OVERRIDE {
DCHECK(xps_print_job_);
DCHECK(object == job_progress_event_.Get());
ResetEvent(job_progress_event_.Get());
if (!delegate_)
return;
XPS_JOB_STATUS job_status = {0};
xps_print_job_->GetJobStatus(&job_status);
bool done = false;
if ((job_status.completion == XPS_JOB_CANCELLED) ||
(job_status.completion == XPS_JOB_FAILED)) {
delegate_->OnJobSpoolFailed();
done = true;
} else if (job_status.jobId ||
(job_status.completion == XPS_JOB_COMPLETED)) {
// Note: In the case of the XPS document being printed to the
// Microsoft XPS Document Writer, it seems to skip spooling the job
// and goes to the completed state without ever assigning a job id.
delegate_->OnJobSpoolSucceeded(job_status.jobId);
done = true;
} else {
job_progress_watcher_.StopWatching();
job_progress_watcher_.StartWatching(job_progress_event_.Get(), this);
}
if (done)
com_initializer_.reset();
}
virtual void OnRenderPDFPagesToMetafileFailed() OVERRIDE {
PrintJobDone();
}
virtual void OnChildDied() OVERRIDE {
PrintJobDone();
}
private:
// Helper class to allow PrintXPSDocument() to have multiple exits.
class PrintJobCanceler {
public:
explicit PrintJobCanceler(
base::win::ScopedComPtr<IXpsPrintJob>* job_ptr)
: job_ptr_(job_ptr) {
}
~PrintJobCanceler() {
if (job_ptr_ && *job_ptr_) {
(*job_ptr_)->Cancel();
job_ptr_->Release();
}
}
void reset() { job_ptr_ = NULL; }
private:
base::win::ScopedComPtr<IXpsPrintJob>* job_ptr_;
DISALLOW_COPY_AND_ASSIGN(PrintJobCanceler);
};
void PrintJobDone() {
// If there is no delegate, then there is nothing pending to process.
if (!delegate_)
return;
RestoreDC(printer_dc_.Get(), saved_dc_);
EndDoc(printer_dc_.Get());
if (-1 == last_page_printed_) {
delegate_->OnJobSpoolFailed();
} else {
delegate_->OnJobSpoolSucceeded(job_id_);
}
delegate_ = NULL;
}
void RenderNextPDFPages() {
printing::PageRange range;
// Render 10 pages at a time.
range.from = last_page_printed_ + 1;
range.to = last_page_printed_ + kPageCountPerBatch;
std::vector<printing::PageRange> page_ranges;
page_ranges.push_back(range);
int printer_dpi = ::GetDeviceCaps(printer_dc_.Get(), LOGPIXELSX);
int dc_width = GetDeviceCaps(printer_dc_.Get(), PHYSICALWIDTH);
int dc_height = GetDeviceCaps(printer_dc_.Get(), PHYSICALHEIGHT);
gfx::Rect render_area(0, 0, dc_width, dc_height);
g_service_process->io_thread()->message_loop_proxy()->PostTask(
FROM_HERE,
base::Bind(&JobSpoolerWin::Core::RenderPDFPagesInSandbox, this,
print_data_file_path_, render_area, printer_dpi,
page_ranges, base::MessageLoopProxy::current()));
}
// Called on the service process IO thread.
void RenderPDFPagesInSandbox(
const base::FilePath& pdf_path, const gfx::Rect& render_area,
int render_dpi, const std::vector<printing::PageRange>& page_ranges,
const scoped_refptr<base::MessageLoopProxy>&
client_message_loop_proxy) {
DCHECK(g_service_process->io_thread()->message_loop_proxy()->
BelongsToCurrentThread());
scoped_ptr<ServiceUtilityProcessHost> utility_host(
new ServiceUtilityProcessHost(this, client_message_loop_proxy));
// TODO(gene): For now we disabling autorotation for CloudPrinting.
// Landscape/Portrait setting is passed in the print ticket and
// server is generating portrait PDF always.
// We should enable autorotation once server will be able to generate
// PDF that matches paper size and orientation.
if (utility_host->StartRenderPDFPagesToMetafile(
pdf_path,
printing::PdfRenderSettings(render_area, render_dpi, false),
page_ranges)) {
// The object will self-destruct when the child process dies.
utility_host.release();
}
}
bool PrintXPSDocument(const std::string& printer_name,
const std::string& job_title,
const base::FilePath& print_data_file_path,
const std::string& print_ticket) {
if (!printing::XPSPrintModule::Init())
return false;
job_progress_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!job_progress_event_.Get())
return false;
scoped_ptr<base::win::ScopedCOMInitializer> com_initializer(
new base::win::ScopedCOMInitializer(
base::win::ScopedCOMInitializer::kMTA));
PrintJobCanceler job_canceler(&xps_print_job_);
base::win::ScopedComPtr<IXpsPrintJobStream> doc_stream;
base::win::ScopedComPtr<IXpsPrintJobStream> print_ticket_stream;
if (FAILED(printing::XPSPrintModule::StartXpsPrintJob(
UTF8ToWide(printer_name).c_str(), UTF8ToWide(job_title).c_str(),
NULL, job_progress_event_.Get(), NULL, NULL, NULL,
xps_print_job_.Receive(), doc_stream.Receive(),
print_ticket_stream.Receive())))
return false;
ULONG print_bytes_written = 0;
if (FAILED(print_ticket_stream->Write(print_ticket.c_str(),
print_ticket.length(),
&print_bytes_written)))
return false;
DCHECK_EQ(print_ticket.length(), print_bytes_written);
if (FAILED(print_ticket_stream->Close()))
return false;
std::string document_data;
base::ReadFileToString(print_data_file_path, &document_data);
ULONG doc_bytes_written = 0;
if (FAILED(doc_stream->Write(document_data.c_str(),
document_data.length(),
&doc_bytes_written)))
return false;
DCHECK_EQ(document_data.length(), doc_bytes_written);
if (FAILED(doc_stream->Close()))
return false;
job_progress_watcher_.StartWatching(job_progress_event_.Get(), this);
com_initializer_.swap(com_initializer);
job_canceler.reset();
return true;
}
// Some Cairo-generated PDFs from Chrome OS result in huge metafiles.
// So the PageCountPerBatch is set to 1 for now.
// TODO(sanjeevr): Figure out a smarter way to determine the pages per
// batch. Filed a bug to track this at
// http://code.google.com/p/chromium/issues/detail?id=57350.
static const int kPageCountPerBatch = 1;
int last_page_printed_;
PlatformJobId job_id_;
PrintSystem::JobSpooler::Delegate* delegate_;
int saved_dc_;
base::win::ScopedCreateDC printer_dc_;
base::FilePath print_data_file_path_;
base::win::ScopedHandle job_progress_event_;
base::win::ObjectWatcher job_progress_watcher_;
base::win::ScopedComPtr<IXpsPrintJob> xps_print_job_;
scoped_ptr<base::win::ScopedCOMInitializer> com_initializer_;
DISALLOW_COPY_AND_ASSIGN(Core);
};
scoped_refptr<Core> core_;
DISALLOW_COPY_AND_ASSIGN(JobSpoolerWin);
};
// A helper class to handle the response from the utility process to the
// request to fetch printer capabilities and defaults.
class PrinterCapsHandler : public ServiceUtilityProcessHost::Client {
public:
PrinterCapsHandler(
const std::string& printer_name,
const PrintSystem::PrinterCapsAndDefaultsCallback& callback)
: printer_name_(printer_name), callback_(callback) {
}
// ServiceUtilityProcessHost::Client implementation.
virtual void OnChildDied() OVERRIDE {
OnGetPrinterCapsAndDefaultsFailed(printer_name_);
}
virtual void OnGetPrinterCapsAndDefaultsSucceeded(
const std::string& printer_name,
const printing::PrinterCapsAndDefaults& caps_and_defaults) OVERRIDE {
callback_.Run(true, printer_name, caps_and_defaults);
callback_.Reset();
Release();
}
virtual void OnGetPrinterCapsAndDefaultsFailed(
const std::string& printer_name) OVERRIDE {
printing::PrinterCapsAndDefaults caps_and_defaults;
callback_.Run(false, printer_name, caps_and_defaults);
callback_.Reset();
Release();
}
void Start() {
g_service_process->io_thread()->message_loop_proxy()->PostTask(
FROM_HERE,
base::Bind(&PrinterCapsHandler::GetPrinterCapsAndDefaultsImpl, this,
base::MessageLoopProxy::current()));
}
private:
// Called on the service process IO thread.
void GetPrinterCapsAndDefaultsImpl(
const scoped_refptr<base::MessageLoopProxy>&
client_message_loop_proxy) {
DCHECK(g_service_process->io_thread()->message_loop_proxy()->
BelongsToCurrentThread());
scoped_ptr<ServiceUtilityProcessHost> utility_host(
new ServiceUtilityProcessHost(this, client_message_loop_proxy));
if (utility_host->StartGetPrinterCapsAndDefaults(printer_name_)) {
// The object will self-destruct when the child process dies.
utility_host.release();
} else {
client_message_loop_proxy->PostTask(
FROM_HERE,
base::Bind(&PrinterCapsHandler::OnGetPrinterCapsAndDefaultsFailed,
this, printer_name_));
}
}
std::string printer_name_;
PrintSystem::PrinterCapsAndDefaultsCallback callback_;
};
class PrintSystemWinXPS : public PrintSystemWin {
public:
PrintSystemWinXPS();
virtual ~PrintSystemWinXPS();
// PrintSystem implementation.
virtual PrintSystemResult Init() OVERRIDE;
virtual void GetPrinterCapsAndDefaults(
const std::string& printer_name,
const PrinterCapsAndDefaultsCallback& callback) OVERRIDE;
virtual bool PrintSystemWinXPS::ValidatePrintTicket(
const std::string& printer_name,
const std::string& print_ticket_data) OVERRIDE;
virtual PrintSystem::JobSpooler* CreateJobSpooler() OVERRIDE;
virtual std::string GetSupportedMimeTypes() OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(PrintSystemWinXPS);
};
PrintSystemWinXPS::PrintSystemWinXPS() {
}
PrintSystemWinXPS::~PrintSystemWinXPS() {
}
PrintSystem::PrintSystemResult PrintSystemWinXPS::Init() {
if (!printing::XPSModule::Init()) {
std::string message = l10n_util::GetStringFUTF8(
IDS_CLOUD_PRINT_XPS_UNAVAILABLE,
l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT));
return PrintSystemResult(false, message);
}
return PrintSystemResult(true, std::string());
}
void PrintSystemWinXPS::GetPrinterCapsAndDefaults(
const std::string& printer_name,
const PrinterCapsAndDefaultsCallback& callback) {
// Launch as child process to retrieve the capabilities and defaults because
// this involves invoking a printer driver DLL and crashes have been known to
// occur.
PrinterCapsHandler* handler =
new PrinterCapsHandler(printer_name, callback);
handler->AddRef();
handler->Start();
}
bool PrintSystemWinXPS::ValidatePrintTicket(
const std::string& printer_name,
const std::string& print_ticket_data) {
crash_keys::ScopedPrinterInfo crash_key(GetPrinterDriverInfo(printer_name));
printing::ScopedXPSInitializer xps_initializer;
if (!xps_initializer.initialized()) {
// TODO(sanjeevr): Handle legacy proxy case (with no prntvpt.dll)
return false;
}
bool ret = false;
HPTPROVIDER provider = NULL;
printing::XPSModule::OpenProvider(UTF8ToWide(printer_name.c_str()),
1,
&provider);
if (provider) {
base::win::ScopedComPtr<IStream> print_ticket_stream;
CreateStreamOnHGlobal(NULL, TRUE, print_ticket_stream.Receive());
ULONG bytes_written = 0;
print_ticket_stream->Write(print_ticket_data.c_str(),
print_ticket_data.length(),
&bytes_written);
DCHECK(bytes_written == print_ticket_data.length());
LARGE_INTEGER pos = {0};
ULARGE_INTEGER new_pos = {0};
print_ticket_stream->Seek(pos, STREAM_SEEK_SET, &new_pos);
base::win::ScopedBstr error;
base::win::ScopedComPtr<IStream> result_ticket_stream;
CreateStreamOnHGlobal(NULL, TRUE, result_ticket_stream.Receive());
ret = SUCCEEDED(printing::XPSModule::MergeAndValidatePrintTicket(
provider,
print_ticket_stream.get(),
NULL,
kPTJobScope,
result_ticket_stream.get(),
error.Receive()));
printing::XPSModule::CloseProvider(provider);
}
return ret;
}
PrintSystem::JobSpooler* PrintSystemWinXPS::CreateJobSpooler() {
return new JobSpoolerWin();
}
std::string PrintSystemWinXPS::GetSupportedMimeTypes() {
if (printing::XPSPrintModule::Init())
return "application/vnd.ms-xpsdocument,application/pdf";
return "application/pdf";
}
} // namespace
scoped_refptr<PrintSystem> PrintSystem::CreateInstance(
const base::DictionaryValue* print_system_settings) {
return new PrintSystemWinXPS;
}
} // namespace cloud_print
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "soundenvelope.h"
#include "npc_manhack.h"
#include "ai_default.h"
#include "ai_node.h"
#include "ai_navigator.h"
#include "ai_pathfinder.h"
#include "ai_moveprobe.h"
#include "ai_memory.h"
#include "ai_squad.h"
#include "ai_route.h"
#include "explode.h"
#include "basegrenade_shared.h"
#include "ndebugoverlay.h"
#include "decals.h"
#include "gib.h"
#include "game.h"
#include "ai_interactions.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "engine/IEngineSound.h"
#include "movevars_shared.h"
#include "npcevent.h"
#include "props.h"
#include "te_effect_dispatch.h"
#include "ai_squadslot.h"
#include "world.h"
#include "smoke_trail.h"
#include "func_break.h"
#include "physics_impact_damage.h"
#include "weapon_physcannon.h"
#include "physics_prop_ragdoll.h"
#include "soundent.h"
#include "ammodef.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// When the engine is running and the manhack is operating under power
// we don't let gravity affect him.
#define MANHACK_GRAVITY 0.000
#define MANHACK_GIB_COUNT 5
#define MANHACK_INGORE_WATER_DIST 384
// Sound stuff
#define MANHACK_PITCH_DIST1 512
#define MANHACK_MIN_PITCH1 (100)
#define MANHACK_MAX_PITCH1 (160)
#define MANHACK_WATER_PITCH1 (85)
#define MANHACK_VOLUME1 0.55
#define MANHACK_PITCH_DIST2 400
#define MANHACK_MIN_PITCH2 (85)
#define MANHACK_MAX_PITCH2 (190)
#define MANHACK_WATER_PITCH2 (90)
#define MANHACK_NOISEMOD_HIDE 5000
#define MANHACK_BODYGROUP_BLADE 1
#define MANHACK_BODYGROUP_BLUR 2
#define MANHACK_BODYGROUP_OFF 0
#define MANHACK_BODYGROUP_ON 1
// ANIMATION EVENTS
#define MANHACK_AE_START_ENGINE 50
#define MANHACK_AE_DONE_UNPACKING 51
#define MANHACK_AE_OPEN_BLADE 52
//#define MANHACK_GLOW_SPRITE "sprites/laserdot.vmt"
#define MANHACK_GLOW_SPRITE "sprites/glow1.vmt"
#define MANHACK_CHARGE_MIN_DIST 200
ConVar sk_manhack_health( "sk_manhack_health","0");
ConVar sk_manhack_melee_dmg( "sk_manhack_melee_dmg","0");
ConVar sk_manhack_v2( "sk_manhack_v2","1");
extern void SpawnBlood(Vector vecSpot, const Vector &vAttackDir, int bloodColor, float flDamage);
extern float GetFloorZ(const Vector &origin);
//-----------------------------------------------------------------------------
// Private activities.
//-----------------------------------------------------------------------------
Activity ACT_MANHACK_UNPACK;
//-----------------------------------------------------------------------------
// Manhack Conditions
//-----------------------------------------------------------------------------
enum ManhackConditions
{
COND_MANHACK_START_ATTACK = LAST_SHARED_CONDITION, // We are able to do a bombing run on the current enemy.
};
//-----------------------------------------------------------------------------
// Manhack schedules.
//-----------------------------------------------------------------------------
enum ManhackSchedules
{
SCHED_MANHACK_ATTACK_HOVER = LAST_SHARED_SCHEDULE,
SCHED_MANHACK_DEPLOY,
SCHED_MANHACK_REGROUP,
SCHED_MANHACK_SWARM_IDLE,
SCHED_MANHACK_SWARM,
SCHED_MANHACK_SWARM_FAILURE,
};
//-----------------------------------------------------------------------------
// Manhack tasks.
//-----------------------------------------------------------------------------
enum ManhackTasks
{
TASK_MANHACK_HOVER = LAST_SHARED_TASK,
TASK_MANHACK_UNPACK,
TASK_MANHACK_FIND_SQUAD_CENTER,
TASK_MANHACK_FIND_SQUAD_MEMBER,
TASK_MANHACK_MOVEAT_SAVEPOSITION,
};
BEGIN_DATADESC( CNPC_Manhack )
DEFINE_FIELD( m_vForceVelocity, FIELD_VECTOR),
DEFINE_FIELD( m_vTargetBanking, FIELD_VECTOR),
DEFINE_FIELD( m_vForceMoveTarget, FIELD_POSITION_VECTOR),
DEFINE_FIELD( m_fForceMoveTime, FIELD_TIME),
DEFINE_FIELD( m_vSwarmMoveTarget, FIELD_POSITION_VECTOR),
DEFINE_FIELD( m_fSwarmMoveTime, FIELD_TIME),
DEFINE_FIELD( m_fEnginePowerScale, FIELD_FLOAT),
DEFINE_FIELD( m_flNextEngineSoundTime, FIELD_TIME),
DEFINE_FIELD( m_flEngineStallTime, FIELD_TIME),
DEFINE_FIELD( m_flNextBurstTime, FIELD_TIME ),
DEFINE_FIELD( m_flWaterSuspendTime, FIELD_TIME),
DEFINE_FIELD( m_nLastSpinSound, FIELD_INTEGER ),
// Death
DEFINE_FIELD( m_fSparkTime, FIELD_TIME),
DEFINE_FIELD( m_fSmokeTime, FIELD_TIME),
DEFINE_FIELD( m_bDirtyPitch, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bGib, FIELD_BOOLEAN),
DEFINE_FIELD( m_bHeld, FIELD_BOOLEAN),
DEFINE_FIELD( m_bHackedByAlyx, FIELD_BOOLEAN),
DEFINE_FIELD( m_vecLoiterPosition, FIELD_POSITION_VECTOR),
DEFINE_FIELD( m_fTimeNextLoiterPulse, FIELD_TIME),
DEFINE_FIELD( m_flBumpSuppressTime, FIELD_TIME ),
DEFINE_FIELD( m_bBladesActive, FIELD_BOOLEAN),
DEFINE_FIELD( m_flBladeSpeed, FIELD_FLOAT),
DEFINE_KEYFIELD( m_bIgnoreClipbrushes, FIELD_BOOLEAN, "ignoreclipbrushes" ),
DEFINE_FIELD( m_hSmokeTrail, FIELD_EHANDLE),
// DEFINE_FIELD( m_pLightGlow, FIELD_CLASSPTR ),
// DEFINE_FIELD( m_pEyeGlow, FIELD_CLASSPTR ),
DEFINE_FIELD( m_iPanel1, FIELD_INTEGER ),
DEFINE_FIELD( m_iPanel2, FIELD_INTEGER ),
DEFINE_FIELD( m_iPanel3, FIELD_INTEGER ),
DEFINE_FIELD( m_iPanel4, FIELD_INTEGER ),
DEFINE_FIELD( m_nLastWaterLevel, FIELD_INTEGER ),
DEFINE_FIELD( m_bDoSwarmBehavior, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nEnginePitch1, FIELD_INTEGER ),
DEFINE_FIELD( m_flEnginePitch1Time, FIELD_TIME ),
DEFINE_FIELD( m_nEnginePitch2, FIELD_INTEGER ),
DEFINE_FIELD( m_flEnginePitch2Time, FIELD_TIME ),
// Physics Influence
DEFINE_FIELD( m_hPhysicsAttacker, FIELD_EHANDLE ),
DEFINE_FIELD( m_flLastPhysicsInfluenceTime, FIELD_TIME ),
DEFINE_FIELD( m_flBurstDuration, FIELD_FLOAT ),
DEFINE_FIELD( m_vecBurstDirection, FIELD_VECTOR ),
DEFINE_FIELD( m_bShowingHostile, FIELD_BOOLEAN ),
// Function Pointers
DEFINE_INPUTFUNC( FIELD_VOID, "DisableSwarm", InputDisableSwarm ),
DEFINE_INPUTFUNC( FIELD_VOID, "Unpack", InputUnpack ),
DEFINE_ENTITYFUNC( CrashTouch ),
DEFINE_BASENPCINTERACTABLE_DATADESC(),
END_DATADESC()
LINK_ENTITY_TO_CLASS( npc_manhack, CNPC_Manhack );
IMPLEMENT_SERVERCLASS_ST(CNPC_Manhack, DT_NPC_Manhack)
SendPropIntWithMinusOneFlag (SENDINFO(m_nEnginePitch1), 8 ),
SendPropFloat(SENDINFO(m_flEnginePitch1Time), 0, SPROP_NOSCALE),
SendPropIntWithMinusOneFlag(SENDINFO(m_nEnginePitch2), 8 )
END_SEND_TABLE()
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
CNPC_Manhack::CNPC_Manhack()
{
#ifdef _DEBUG
m_vForceMoveTarget.Init();
m_vSwarmMoveTarget.Init();
m_vTargetBanking.Init();
m_vForceVelocity.Init();
#endif
m_bDirtyPitch = true;
m_nLastWaterLevel = 0;
m_nEnginePitch1 = -1;
m_nEnginePitch2 = -1;
m_flEnginePitch1Time = 0;
m_flEnginePitch1Time = 0;
m_bDoSwarmBehavior = true;
m_flBumpSuppressTime = 0;
m_iCash = 20;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
CNPC_Manhack::~CNPC_Manhack()
{
}
//-----------------------------------------------------------------------------
// Purpose: Indicates this NPC's place in the relationship table.
//-----------------------------------------------------------------------------
Class_T CNPC_Manhack::Classify(void)
{
return (m_bHeld||m_bHackedByAlyx) ? CLASS_PLAYER_ALLY : CLASS_MANHACK;
}
//-----------------------------------------------------------------------------
// Purpose: Turns the manhack into a physics corpse when dying.
//-----------------------------------------------------------------------------
void CNPC_Manhack::Event_Dying(void)
{
DestroySmokeTrail();
SetHullSizeNormal();
BaseClass::Event_Dying();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Manhack::GatherConditions()
{
BaseClass::GatherConditions();
if( IsLoitering() && GetEnemy() )
{
StopLoitering();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::PrescheduleThink( void )
{
BaseClass::PrescheduleThink();
UpdatePanels();
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
// Stuck in water!
// Reduce engine power so that the manhack lifts out of the water slowly.
m_fEnginePowerScale = 0.75;
}
// ----------------------------------------
// Am I in water?
// ----------------------------------------
if ( GetWaterLevel() > 0 )
{
if( m_nLastWaterLevel == 0 )
{
Splash( WorldSpaceCenter() );
}
if( IsAlive() )
{
// If I've been out of water for 2 seconds or more, I'm eligible to be stuck in water again.
if( gpGlobals->curtime - m_flWaterSuspendTime > 2.0 )
{
m_flWaterSuspendTime = gpGlobals->curtime + 1.0;
}
}
}
else
{
if( m_nLastWaterLevel != 0 )
{
Splash( WorldSpaceCenter() );
}
}
m_nLastWaterLevel = GetWaterLevel();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator )
{
g_vecAttackDir = vecDir;
if ( info.GetDamageType() & DMG_BULLET)
{
g_pEffects->Ricochet(ptr->endpos,ptr->plane.normal);
}
if ( info.GetDamageType() & DMG_CLUB )
{
// Clubbed!
// UTIL_Smoke(GetAbsOrigin(), random->RandomInt(10, 15), 10);
g_pEffects->Sparks( ptr->endpos, 1, 1, &ptr->plane.normal );
}
BaseClass::TraceAttack( info, vecDir, ptr, pAccumulator );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::DeathSound( const CTakeDamageInfo &info )
{
StopSound("NPC_Manhack.Stunned");
CPASAttenuationFilter filter2( this, "NPC_Manhack.Die" );
EmitSound( filter2, entindex(), "NPC_Manhack.Die" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_Manhack::ShouldGib( const CTakeDamageInfo &info )
{
return ( m_bGib );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Event_Killed( const CTakeDamageInfo &info )
{
// turn off the blur!
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_OFF );
// Sparks
for (int i = 0; i < 3; i++)
{
Vector sparkPos = GetAbsOrigin();
sparkPos.x += random->RandomFloat(-12,12);
sparkPos.y += random->RandomFloat(-12,12);
sparkPos.z += random->RandomFloat(-12,12);
g_pEffects->Sparks( sparkPos, 2 );
}
// Light
CBroadcastRecipientFilter filter;
te->DynamicLight( filter, 0.0, &GetAbsOrigin(), 255, 180, 100, 0, 100, 0.1, 0 );
if ( m_nEnginePitch1 < 0 )
{
// Probably this manhack was killed immediately after spawning. Turn the sound
// on right now so that we can pitch it up for the crash!
SoundInit();
}
// Always gib when clubbed or blasted or crushed, or just randomly
if ( ( info.GetDamageType() & (DMG_CLUB|DMG_CRUSH|DMG_BLAST) ) || ( random->RandomInt( 0, 1 ) ) )
{
m_bGib = true;
}
else
{
m_bGib = false;
//FIXME: These don't stay with the ragdolls currently -- jdw
// Long fadeout on the sprites!!
KillSprites( 0.0f );
}
BaseClass::Event_Killed( info );
}
void CNPC_Manhack::HitPhysicsObject( CBaseEntity *pOther )
{
IPhysicsObject *pOtherPhysics = pOther->VPhysicsGetObject();
Vector pos, posOther;
// Put the force on the line between the manhack origin and hit object origin
VPhysicsGetObject()->GetPosition( &pos, NULL );
pOtherPhysics->GetPosition( &posOther, NULL );
Vector dir = posOther - pos;
VectorNormalize(dir);
// size/2 is approx radius
pos += dir * WorldAlignSize().x * 0.5;
Vector cross;
// UNDONE: Use actual manhack up vector so the fake blade is
// in the right plane?
// Get a vector in the x/y plane in the direction of blade spin (clockwise)
CrossProduct( dir, Vector(0,0,1), cross );
VectorNormalize( cross );
// force is a 30kg object going 100 in/s
pOtherPhysics->ApplyForceOffset( cross * 30 * 100, pos );
}
//-----------------------------------------------------------------------------
// Take damage from being thrown by a physcannon
//-----------------------------------------------------------------------------
#define MANHACK_SMASH_SPEED 500.0 // How fast a manhack must slam into something to take full damage
void CNPC_Manhack::TakeDamageFromPhyscannon( CBasePlayer *pPlayer )
{
CTakeDamageInfo info;
info.SetDamageType( DMG_GENERIC );
info.SetInflictor( this );
info.SetAttacker( pPlayer );
info.SetDamagePosition( GetAbsOrigin() );
info.SetDamageForce( Vector( 1.0, 1.0, 1.0 ) );
// Convert velocity into damage.
Vector vel;
VPhysicsGetObject()->GetVelocity( &vel, NULL );
float flSpeed = vel.Length();
float flFactor = flSpeed / MANHACK_SMASH_SPEED;
// Clamp. Don't inflict negative damage or massive damage!
flFactor = clamp( flFactor, 0.0f, 2.0f );
float flDamage = m_iMaxHealth * flFactor;
#if 0
Msg("Doing %f damage for %f speed!\n", flDamage, flSpeed );
#endif
info.SetDamage( flDamage );
TakeDamage( info );
}
//-----------------------------------------------------------------------------
// Take damage from a vehicle; it's like a really big crowbar
//-----------------------------------------------------------------------------
void CNPC_Manhack::TakeDamageFromVehicle( int index, gamevcollisionevent_t *pEvent )
{
// Use the vehicle velocity to determine the damage
int otherIndex = !index;
CBaseEntity *pOther = pEvent->pEntities[otherIndex];
float flSpeed = pEvent->preVelocity[ otherIndex ].Length();
flSpeed = clamp( flSpeed, 300.0f, 600.0f );
float flDamage = SimpleSplineRemapVal( flSpeed, 300.0f, 600.0f, 0.0f, 1.0f );
if ( flDamage == 0.0f )
return;
flDamage *= 20.0f;
Vector damagePos;
pEvent->pInternalData->GetContactPoint( damagePos );
Vector damageForce = 2.0f * pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass();
if ( damageForce == vec3_origin )
{
// This can happen if this entity is a func_breakable, and can't move.
// Use the velocity of the entity that hit us instead.
damageForce = 2.0f * pEvent->postVelocity[!index] * pEvent->pObjects[!index]->GetMass();
}
Assert( damageForce != vec3_origin );
CTakeDamageInfo dmgInfo( pOther, pOther, damageForce, damagePos, flDamage, DMG_CRUSH );
TakeDamage( dmgInfo );
}
//-----------------------------------------------------------------------------
// Take damage from combine ball
//-----------------------------------------------------------------------------
void CNPC_Manhack::TakeDamageFromPhysicsImpact( int index, gamevcollisionevent_t *pEvent )
{
CBaseEntity *pHitEntity = pEvent->pEntities[!index];
// NOTE: Bypass the normal impact energy scale here.
float flDamageScale = PlayerHasMegaPhysCannon() ? 10.0f : 1.0f;
int damageType = 0;
float damage = CalculateDefaultPhysicsDamage( index, pEvent, flDamageScale, true, damageType );
if ( damage == 0 )
return;
Vector damagePos;
pEvent->pInternalData->GetContactPoint( damagePos );
Vector damageForce = pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass();
if ( damageForce == vec3_origin )
{
// This can happen if this entity is motion disabled, and can't move.
// Use the velocity of the entity that hit us instead.
damageForce = pEvent->postVelocity[!index] * pEvent->pObjects[!index]->GetMass();
}
// FIXME: this doesn't pass in who is responsible if some other entity "caused" this collision
PhysCallbackDamage( this, CTakeDamageInfo( pHitEntity, pHitEntity, damageForce, damagePos, damage, damageType ), *pEvent, index );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
#define MANHACK_SMASH_TIME 0.35 // How long after being thrown from a physcannon that a manhack is eligible to die from impact
void CNPC_Manhack::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )
{
BaseClass::VPhysicsCollision( index, pEvent );
// Take no impact damage while being carried.
if ( IsHeldByPhyscannon() )
return;
// Wake us up
if ( m_spawnflags & SF_MANHACK_PACKED_UP )
{
SetCondition( COND_LIGHT_DAMAGE );
}
int otherIndex = !index;
CBaseEntity *pHitEntity = pEvent->pEntities[otherIndex];
CBasePlayer *pPlayer = HasPhysicsAttacker( MANHACK_SMASH_TIME );
if( pPlayer )
{
if (!pHitEntity)
{
TakeDamageFromPhyscannon( pPlayer );
StopBurst( true );
return;
}
// Don't take damage from NPCs or server ragdolls killed by the manhack
CRagdollProp *pRagdollProp = dynamic_cast<CRagdollProp*>(pHitEntity);
if (!pHitEntity->IsNPC() && (!pRagdollProp || pRagdollProp->GetKiller() != this))
{
TakeDamageFromPhyscannon( pPlayer );
StopBurst( true );
return;
}
}
if ( pHitEntity )
{
// It can take physics damage if it rams into a vehicle
if ( pHitEntity->GetServerVehicle() )
{
TakeDamageFromVehicle( index, pEvent );
}
else if ( pHitEntity->HasPhysicsAttacker( 0.5f ) )
{
// It also can take physics damage from things thrown by the player.
TakeDamageFromPhysicsImpact( index, pEvent );
}
else if ( FClassnameIs( pHitEntity, "prop_combine_ball" ) )
{
// It also can take physics damage from a combine ball.
TakeDamageFromPhysicsImpact( index, pEvent );
}
else if ( m_iHealth <= 0 )
{
TakeDamageFromPhysicsImpact( index, pEvent );
}
StopBurst( true );
}
}
void CNPC_Manhack::VPhysicsShadowCollision( int index, gamevcollisionevent_t *pEvent )
{
int otherIndex = !index;
CBaseEntity *pOther = pEvent->pEntities[otherIndex];
if ( pOther->GetMoveType() == MOVETYPE_VPHYSICS )
{
HitPhysicsObject( pOther );
}
BaseClass::VPhysicsShadowCollision( index, pEvent );
}
//-----------------------------------------------------------------------------
// Purpose: Manhack is out of control! (dying) Just explode as soon as you touch anything!
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::CrashTouch( CBaseEntity *pOther )
{
CTakeDamageInfo info( GetWorldEntity(), GetWorldEntity(), 25, DMG_CRUSH );
CorpseGib( info );
}
//-----------------------------------------------------------------------------
// Create smoke trail!
//-----------------------------------------------------------------------------
void CNPC_Manhack::CreateSmokeTrail()
{
if ( HasSpawnFlags( SF_MANHACK_NO_DAMAGE_EFFECTS ) )
return;
if ( m_hSmokeTrail != NULL )
return;
SmokeTrail *pSmokeTrail = SmokeTrail::CreateSmokeTrail();
if( !pSmokeTrail )
return;
pSmokeTrail->m_SpawnRate = 20;
pSmokeTrail->m_ParticleLifetime = 0.5f;
pSmokeTrail->m_StartSize = 8;
pSmokeTrail->m_EndSize = 32;
pSmokeTrail->m_SpawnRadius = 5;
pSmokeTrail->m_MinSpeed = 15;
pSmokeTrail->m_MaxSpeed = 25;
pSmokeTrail->m_StartColor.Init( 0.4f, 0.4f, 0.4f );
pSmokeTrail->m_EndColor.Init( 0, 0, 0 );
pSmokeTrail->SetLifetime(-1);
pSmokeTrail->FollowEntity(this);
m_hSmokeTrail = pSmokeTrail;
}
void CNPC_Manhack::DestroySmokeTrail()
{
if ( m_hSmokeTrail.Get() )
{
UTIL_Remove( m_hSmokeTrail );
m_hSmokeTrail = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
// Hafta make a copy of info cause we might need to scale damage.(sjb)
CTakeDamageInfo tdInfo = info;
if( tdInfo.GetAmmoType() == GetAmmoDef()->Index("SniperRound") )
{
// Unfortunately, this is the easiest way to stop the sniper killing manhacks in one shot.
tdInfo.SetDamage( m_iMaxHealth>>1 );
}
if (info.GetDamageType() & DMG_PHYSGUN )
{
m_flBladeSpeed = 20.0;
// respond to physics
// FIXME: shouldn't this happen in a base class? Anyway to prevent it from happening twice?
VPhysicsTakeDamage( info );
// reduce damage to nothing
tdInfo.SetDamage( 1.0 );
StopBurst( true );
}
else if ( info.GetDamageType() & DMG_AIRBOAT )
{
// Airboat gun kills me instantly.
tdInfo.SetDamage( GetHealth() );
}
else if (info.GetDamageType() & DMG_CLUB)
{
// Being hit by a club means a couple of things:
//
// -I'm going to be knocked away from the person that clubbed me.
// if fudging this vector a little bit could help me slam into a physics object,
// then make that adjustment. This is a simple heuristic. The manhack will be
// directed towards the physics object that is closest to g_vecAttackDir
//
// -Take 150% damage from club attacks. This makes crowbar duels take two hits.
tdInfo.ScaleDamage( 1.50 );
#define MANHACK_PHYS_SEARCH_SIZE 64
#define MANHACK_PHYSICS_SEARCH_RADIUS 128
CBaseEntity *pList[ MANHACK_PHYS_SEARCH_SIZE ];
Vector attackDir = info.GetDamageForce();
VectorNormalize( attackDir );
Vector testCenter = GetAbsOrigin() + ( attackDir * MANHACK_PHYSICS_SEARCH_RADIUS );
Vector vecDelta( MANHACK_PHYSICS_SEARCH_RADIUS, MANHACK_PHYSICS_SEARCH_RADIUS, MANHACK_PHYSICS_SEARCH_RADIUS );
int count = UTIL_EntitiesInBox( pList, MANHACK_PHYS_SEARCH_SIZE, testCenter - vecDelta, testCenter + vecDelta, 0 );
Vector vecBestDir = g_vecAttackDir;
float flBestDot = 0.90;
IPhysicsObject *pPhysObj;
int i;
for( i = 0 ; i < count ; i++ )
{
pPhysObj = pList[ i ]->VPhysicsGetObject();
if( !pPhysObj || pPhysObj->GetMass() > 200 )
{
// Not physics.
continue;
}
Vector center = pList[ i ]->WorldSpaceCenter();
Vector vecDirToObject;
VectorSubtract( center, WorldSpaceCenter(), vecDirToObject );
VectorNormalize( vecDirToObject );
float flDot;
flDot = DotProduct( g_vecAttackDir, vecDirToObject );
if( flDot > flBestDot )
{
flBestDot = flDot;
vecBestDir = vecDirToObject;
}
}
tdInfo.SetDamageForce( vecBestDir * info.GetDamage() * 200 );
// FIXME: shouldn't this happen in a base class? Anyway to prevent it from happening twice?
VPhysicsTakeDamage( tdInfo );
// Force us away (no more residual speed hits!)
m_vForceVelocity = vecBestDir * info.GetDamage() * 0.5f;
m_flBladeSpeed = 10.0;
EmitSound( "NPC_Manhack.Bat" );
// tdInfo.SetDamage( 1.0 );
m_flEngineStallTime = gpGlobals->curtime + 0.5f;
StopBurst( true );
}
else
{
m_flBladeSpeed = 20.0;
Vector vecDamageDir = tdInfo.GetDamageForce();
VectorNormalize( vecDamageDir );
m_flEngineStallTime = gpGlobals->curtime + 0.25f;
m_vForceVelocity = vecDamageDir * info.GetDamage() * 20.0f;
tdInfo.SetDamageForce( tdInfo.GetDamageForce() * 20 );
VPhysicsTakeDamage( info );
}
int nRetVal = BaseClass::OnTakeDamage_Alive( tdInfo );
if ( nRetVal )
{
if ( m_iHealth > 0 )
{
if ( info.GetDamageType() & DMG_CLUB )
{
SetEyeState( MANHACK_EYE_STATE_STUNNED );
}
if ( m_iHealth <= ( m_iMaxHealth / 2 ) )
{
CreateSmokeTrail();
}
}
else
{
DestroySmokeTrail();
}
}
return nRetVal;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool CNPC_Manhack::CorpseGib( const CTakeDamageInfo &info )
{
Vector vecGibVelocity;
AngularImpulse vecGibAVelocity;
if( info.GetDamageType() & DMG_CLUB )
{
// If clubbed to death, break apart before the attacker's eyes!
vecGibVelocity = g_vecAttackDir * -150;
vecGibAVelocity.x = random->RandomFloat( -2000, 2000 );
vecGibAVelocity.y = random->RandomFloat( -2000, 2000 );
vecGibAVelocity.z = random->RandomFloat( -2000, 2000 );
}
else
{
// Shower the pieces with my velocity.
vecGibVelocity = GetCurrentVelocity();
vecGibAVelocity.x = random->RandomFloat( -500, 500 );
vecGibAVelocity.y = random->RandomFloat( -500, 500 );
vecGibAVelocity.z = random->RandomFloat( -500, 500 );
}
PropBreakableCreateAll( GetModelIndex(), NULL, GetAbsOrigin(), GetAbsAngles(), vecGibVelocity, vecGibAVelocity, 1.0, 60, COLLISION_GROUP_DEBRIS );
RemoveDeferred();
KillSprites( 0.0f );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Explode the manhack if it's damaged while crashing
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::OnTakeDamage_Dying( const CTakeDamageInfo &info )
{
// Ignore damage for the first 1 second of crashing behavior.
// If we don't do this, manhacks always just explode under
// sustained fire.
VPhysicsTakeDamage( info );
return 0;
}
//-----------------------------------------------------------------------------
// Turn on the engine sound if we're gagged!
//-----------------------------------------------------------------------------
void CNPC_Manhack::OnStateChange( NPC_STATE OldState, NPC_STATE NewState )
{
if( m_vNoiseMod.z == MANHACK_NOISEMOD_HIDE && !(m_spawnflags & SF_NPC_WAIT_FOR_SCRIPT) && !(m_spawnflags & SF_MANHACK_PACKED_UP) )
{
// This manhack should get a normal noisemod now.
float flNoiseMod = random->RandomFloat( 1.7, 2.3 );
// Just bob up and down.
SetNoiseMod( 0, 0, flNoiseMod );
}
if( NewState != NPC_STATE_IDLE && (m_spawnflags & SF_NPC_GAG) && (m_nEnginePitch1 < 0) )
{
m_spawnflags &= ~SF_NPC_GAG;
SoundInit();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Type -
//-----------------------------------------------------------------------------
void CNPC_Manhack::HandleAnimEvent( animevent_t *pEvent )
{
Vector vecNewVelocity;
switch( pEvent->event )
{
case MANHACK_AE_START_ENGINE:
StartEye();
StartEngine( true );
m_spawnflags &= ~SF_MANHACK_PACKED_UP;
// No bursts until fully unpacked!
m_flNextBurstTime = gpGlobals->curtime + FLT_MAX;
break;
case MANHACK_AE_DONE_UNPACKING:
m_flNextBurstTime = gpGlobals->curtime + 2.0;
break;
case MANHACK_AE_OPEN_BLADE:
m_bBladesActive = true;
break;
default:
BaseClass::HandleAnimEvent( pEvent );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether or not the given activity would translate to flying.
//-----------------------------------------------------------------------------
bool CNPC_Manhack::IsFlyingActivity( Activity baseAct )
{
return ((baseAct == ACT_FLY || baseAct == ACT_IDLE || baseAct == ACT_RUN || baseAct == ACT_WALK) && m_bBladesActive);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Type -
//-----------------------------------------------------------------------------
Activity CNPC_Manhack::NPC_TranslateActivity( Activity baseAct )
{
if (IsFlyingActivity( baseAct ))
{
return (Activity)ACT_FLY;
}
return BaseClass::NPC_TranslateActivity( baseAct );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Type -
//-----------------------------------------------------------------------------
int CNPC_Manhack::TranslateSchedule( int scheduleType )
{
// Fail-safe for deployment if packed up and interrupted
if ( m_spawnflags & SF_MANHACK_PACKED_UP )
{
if ( scheduleType != SCHED_WAIT_FOR_SCRIPT )
return SCHED_MANHACK_DEPLOY;
}
switch ( scheduleType )
{
case SCHED_MELEE_ATTACK1:
{
return SCHED_MANHACK_ATTACK_HOVER;
break;
}
case SCHED_BACK_AWAY_FROM_ENEMY:
{
return SCHED_MANHACK_REGROUP;
break;
}
case SCHED_CHASE_ENEMY:
{
// If we're waiting for our next attack opportunity, just swarm
if ( m_flNextBurstTime > gpGlobals->curtime )
{
return SCHED_MANHACK_SWARM;
}
if ( !m_bDoSwarmBehavior || OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
{
return SCHED_CHASE_ENEMY;
}
else
{
return SCHED_MANHACK_SWARM;
}
}
case SCHED_COMBAT_FACE:
{
// Don't care about facing enemy, handled automatically
return TranslateSchedule( SCHED_CHASE_ENEMY );
break;
}
case SCHED_WAKE_ANGRY:
{
if( m_spawnflags & SF_MANHACK_PACKED_UP )
{
return SCHED_MANHACK_DEPLOY;
}
else
{
return TranslateSchedule( SCHED_CHASE_ENEMY );
}
break;
}
case SCHED_IDLE_STAND:
case SCHED_ALERT_STAND:
case SCHED_ALERT_FACE:
{
if ( m_pSquad && m_bDoSwarmBehavior )
{
return SCHED_MANHACK_SWARM_IDLE;
}
else
{
return BaseClass::TranslateSchedule(scheduleType);
}
}
case SCHED_CHASE_ENEMY_FAILED:
{
// Relentless bastard! Doesn't fail (fail not valid anyway)
return TranslateSchedule( SCHED_CHASE_ENEMY );
break;
}
}
return BaseClass::TranslateSchedule(scheduleType);
}
#define MAX_LOITER_DIST_SQR 144 // (12 inches sqr)
void CNPC_Manhack::Loiter()
{
//NDebugOverlay::Line( GetAbsOrigin(), m_vecLoiterPosition, 255, 255, 255, false, 0.1 );
// Friendly manhack is loitering.
if( !m_bHeld )
{
float distSqr = m_vecLoiterPosition.DistToSqr(GetAbsOrigin());
if( distSqr > MAX_LOITER_DIST_SQR )
{
Vector vecDir = m_vecLoiterPosition - GetAbsOrigin();
VectorNormalize( vecDir );
// Move back to our loiter position.
if( gpGlobals->curtime > m_fTimeNextLoiterPulse )
{
// Apply a pulse of force if allowed right now.
if( distSqr > MAX_LOITER_DIST_SQR * 4.0f )
{
//Msg("Big Pulse\n");
m_vForceVelocity = vecDir * 12.0f;
}
else
{
//Msg("Small Pulse\n");
m_vForceVelocity = vecDir * 6.0f;
}
m_fTimeNextLoiterPulse = gpGlobals->curtime + 1.0f;
}
else
{
m_vForceVelocity = vec3_origin;
}
}
else
{
// Counteract velocity to slow down.
Vector velocity = GetCurrentVelocity();
m_vForceVelocity = velocity * -0.5;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::MaintainGroundHeight( void )
{
float zSpeed = GetCurrentVelocity().z;
if ( zSpeed > 32.0f )
return;
const float minGroundHeight = 52.0f;
trace_t tr;
AI_TraceHull( GetAbsOrigin(),
GetAbsOrigin() - Vector( 0, 0, minGroundHeight ),
GetHullMins(),
GetHullMaxs(),
(MASK_NPCSOLID_BRUSHONLY),
this,
COLLISION_GROUP_NONE,
&tr );
if ( tr.fraction != 1.0f )
{
float speedAdj = MAX( 16, (-zSpeed*0.5f) );
m_vForceVelocity += Vector(0,0,1) * ( speedAdj * ( 1.0f - tr.fraction ) );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles movement towards the last move target.
// Input : flInterval -
//-----------------------------------------------------------------------------
bool CNPC_Manhack::OverrideMove( float flInterval )
{
SpinBlades( flInterval );
// Don't execute any move code if packed up.
if( HasSpawnFlags(SF_MANHACK_PACKED_UP|SF_MANHACK_CARRIED) )
return true;
if( IsLoitering() )
{
Loiter();
}
else
{
MaintainGroundHeight();
}
// So cops, etc. will try to avoid them
if ( !HasSpawnFlags( SF_MANHACK_NO_DANGER_SOUNDS ) && !m_bHeld )
{
CSoundEnt::InsertSound( SOUND_DANGER, GetAbsOrigin(), 75, flInterval, this );
}
// -----------------------------------------------------------------
// If I'm being forced to move somewhere
// ------------------------------------------------------------------
if (m_fForceMoveTime > gpGlobals->curtime)
{
MoveToTarget(flInterval, m_vForceMoveTarget);
}
// -----------------------------------------------------------------
// If I have a route, keep it updated and move toward target
// ------------------------------------------------------------------
else if (GetNavigator()->IsGoalActive())
{
bool bReducible = GetNavigator()->GetPath()->GetCurWaypoint()->IsReducible();
const float strictTolerance = 64.0;
//NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + Vector(0, 0, 10 ), 255, 0, 0, true, 0.1);
if ( ProgressFlyPath( flInterval, GetEnemy(), MoveCollisionMask(), bReducible, strictTolerance ) == AINPP_COMPLETE )
return true;
}
// -----------------------------------------------------------------
// If I'm supposed to swarm somewhere, try to go there
// ------------------------------------------------------------------
else if (m_fSwarmMoveTime > gpGlobals->curtime)
{
MoveToTarget(flInterval, m_vSwarmMoveTarget);
}
// -----------------------------------------------------------------
// If I don't have anything better to do, just decelerate
// -------------------------------------------------------------- ----
else
{
float myDecay = 9.5;
Decelerate( flInterval, myDecay );
m_vTargetBanking = vec3_origin;
// -------------------------------------
// If I have an enemy turn to face him
// -------------------------------------
if (GetEnemy())
{
TurnHeadToTarget(flInterval, GetEnemy()->EyePosition() );
}
}
if ( m_iHealth <= 0 )
{
// Crashing!!
MoveExecute_Dead(flInterval);
}
else
{
// Alive!
MoveExecute_Alive(flInterval);
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::TurnHeadRandomly(float flInterval )
{
float desYaw = random->RandomFloat(0,360);
float iRate = 0.8;
// Make frame rate independent
float timeToUse = flInterval;
while (timeToUse > 0)
{
m_fHeadYaw = (iRate * m_fHeadYaw) + (1-iRate)*desYaw;
timeToUse = -0.1;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::MoveToTarget(float flInterval, const Vector &vMoveTarget)
{
if (flInterval <= 0)
{
return;
}
// -----------------------------------------
// Don't steer if engine's have stalled
// -----------------------------------------
if ( gpGlobals->curtime < m_flEngineStallTime || m_iHealth <= 0 )
return;
if ( GetEnemy() != NULL )
{
TurnHeadToTarget( flInterval, GetEnemy()->EyePosition() );
}
else
{
TurnHeadToTarget( flInterval, vMoveTarget );
}
// -------------------------------------
// Move towards our target
// -------------------------------------
float myAccel;
float myZAccel = 300.0f;
float myDecay = 0.3f;
Vector targetDir;
float flDist;
// If we're bursting, just head straight
if ( m_flBurstDuration > gpGlobals->curtime )
{
float zDist = 500;
// Steer towards our enemy if we're able to
if ( GetEnemy() != NULL )
{
Vector steerDir = ( GetEnemy()->EyePosition() - GetAbsOrigin() );
zDist = fabs( steerDir.z );
VectorNormalize( steerDir );
float useTime = flInterval;
while ( useTime > 0.0f )
{
m_vecBurstDirection += ( steerDir * 4.0f );
useTime -= 0.1f;
}
m_vecBurstDirection.z = steerDir.z;
VectorNormalize( m_vecBurstDirection );
}
// Debug visualizations
/*
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( targetDir * 64.0f ), 255, 0, 0, true, 2.1f );
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( steerDir * 64.0f ), 0, 255, 0, true, 2.1f );
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( m_vecBurstDirection * 64.0f ), 0, 0, 255, true, 2.1f );
NDebugOverlay::Cross3D( GetAbsOrigin() , -Vector(8,8,8), Vector(8,8,8), 255, 0, 0, true, 2.1f );
*/
targetDir = m_vecBurstDirection;
flDist = FLT_MAX;
myDecay = 0.3f;
#ifdef _XBOX
myAccel = 500;
#else
myAccel = 400;
#endif // _XBOX
myZAccel = MIN( 500, zDist / flInterval );
}
else
{
Vector vecCurrentDir = GetCurrentVelocity();
VectorNormalize( vecCurrentDir );
targetDir = vMoveTarget - GetAbsOrigin();
flDist = VectorNormalize( targetDir );
float flDot = DotProduct( targetDir, vecCurrentDir );
// Otherwise we should steer towards our goal
if( flDot > 0.25 )
{
// If my target is in front of me, my flight model is a bit more accurate.
myAccel = 300;
}
else
{
// Have a harder time correcting my course if I'm currently flying away from my target.
myAccel = 200;
}
}
// Clamp lateral acceleration
if ( myAccel > ( flDist / flInterval ) )
{
myAccel = flDist / flInterval;
}
/*
// Boost vertical movement
if ( targetDir.z > 0 )
{
// Z acceleration is faster when we thrust upwards.
// This is to help keep manhacks out of water.
myZAccel *= 5.0;
}
*/
// Clamp vertical movement
if ( myZAccel > flDist / flInterval )
{
myZAccel = flDist / flInterval;
}
// Scale by our engine force
myAccel *= m_fEnginePowerScale;
myZAccel *= m_fEnginePowerScale;
MoveInDirection( flInterval, targetDir, myAccel, myZAccel, myDecay );
// calc relative banking targets
Vector forward, right;
GetVectors( &forward, &right, NULL );
m_vTargetBanking.x = 40 * DotProduct( forward, targetDir );
m_vTargetBanking.z = 40 * DotProduct( right, targetDir );
m_vTargetBanking.y = 0.0;
}
//-----------------------------------------------------------------------------
// Purpose: Ignore water if I'm close to my enemy
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::MoveCollisionMask(void)
{
return MASK_NPCSOLID;
}
//-----------------------------------------------------------------------------
// Purpose: Make a splash effect
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Splash( const Vector &vecSplashPos )
{
CEffectData data;
data.m_fFlags = 0;
data.m_vOrigin = vecSplashPos;
data.m_vNormal = Vector( 0, 0, 1 );
data.m_flScale = 8.0f;
int contents = GetWaterType();
// Verify we have valid contents
if ( !( contents & (CONTENTS_SLIME|CONTENTS_WATER)))
{
// We're leaving the water so we have to reverify what it was
trace_t tr;
UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() - Vector( 0, 0, 256 ), (CONTENTS_WATER|CONTENTS_SLIME), this, COLLISION_GROUP_NONE, &tr );
// Re-validate this
if ( !(tr.contents&(CONTENTS_WATER|CONTENTS_SLIME)) )
{
//NOTENOTE: We called a splash but we don't seem to be near water?
Assert( 0 );
return;
}
contents = tr.contents;
}
// Mark us if we're in slime
if ( contents & CONTENTS_SLIME )
{
data.m_fFlags |= FX_WATER_IN_SLIME;
}
DispatchEffect( "watersplash", data );
}
//-----------------------------------------------------------------------------
// Computes the slice bounce velocity
//-----------------------------------------------------------------------------
void CNPC_Manhack::ComputeSliceBounceVelocity( CBaseEntity *pHitEntity, trace_t &tr )
{
if( pHitEntity->IsAlive() && FClassnameIs( pHitEntity, "func_breakable_surf" ) )
{
// We want to see if the manhack hits a breakable pane of glass. To keep from checking
// The classname of the HitEntity on each impact, we only do this check if we hit
// something that's alive. Anyway, prevent the manhack bouncing off the pane of glass,
// since this impact will shatter the glass and let the manhack through.
return;
}
Vector vecDir;
// If the manhack isn't bouncing away from whatever he sliced, force it.
VectorSubtract( WorldSpaceCenter(), pHitEntity->WorldSpaceCenter(), vecDir );
VectorNormalize( vecDir );
vecDir *= 200;
vecDir[2] = 0.0f;
// Knock it away from us
if ( VPhysicsGetObject() != NULL )
{
VPhysicsGetObject()->ApplyForceOffset( vecDir * 4, GetAbsOrigin() );
}
// Also set our velocity
SetCurrentVelocity( vecDir );
}
//-----------------------------------------------------------------------------
// Is the manhack being held?
//-----------------------------------------------------------------------------
bool CNPC_Manhack::IsHeldByPhyscannon( )
{
return VPhysicsGetObject() && (VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD);
}
//-----------------------------------------------------------------------------
// Purpose: We've touched something that we can hurt. Slice it!
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Slice( CBaseEntity *pHitEntity, float flInterval, trace_t &tr )
{
// Don't hurt the player if I'm in water
if( GetWaterLevel() > 0 && pHitEntity->IsPlayer() )
return;
// Can't slice players holding it with the phys cannon
if ( IsHeldByPhyscannon() )
{
if ( pHitEntity && (pHitEntity == HasPhysicsAttacker( FLT_MAX )) )
return;
}
if ( pHitEntity->m_takedamage == DAMAGE_NO )
return;
// Damage must be scaled by flInterval so framerate independent
float flDamage = sk_manhack_melee_dmg.GetFloat() * flInterval;
if ( pHitEntity->IsPlayer() )
{
flDamage *= 2.0f;
}
// Held manhacks do more damage
if ( IsHeldByPhyscannon() )
{
// Deal 100 damage/sec
flDamage = 100.0f * flInterval;
}
else if ( pHitEntity->IsNPC() && HasPhysicsAttacker( MANHACK_SMASH_TIME ) )
{
extern ConVar sk_combine_guard_health;
// NOTE: The else here is essential.
// The physics attacker *will* be set even when the manhack is held
flDamage = sk_combine_guard_health.GetFloat(); // the highest healthed fleshy enemy
}
else if ( dynamic_cast<CBaseProp*>(pHitEntity) || dynamic_cast<CBreakable*>(pHitEntity) )
{
// If we hit a prop, we want it to break immediately
flDamage = pHitEntity->GetHealth();
}
else if ( pHitEntity->IsNPC() && IRelationType( pHitEntity ) == D_HT && FClassnameIs( pHitEntity, "npc_combine_s" ) )
{
flDamage *= 6.0f;
}
if (flDamage < 1.0f)
{
flDamage = 1.0f;
}
CTakeDamageInfo info( this, this, flDamage, DMG_SLASH );
// check for actual "ownership" of damage
CBasePlayer *pPlayer = HasPhysicsAttacker( MANHACK_SMASH_TIME );
if (pPlayer)
{
info.SetAttacker( pPlayer );
}
Vector dir = (tr.endpos - tr.startpos);
if ( dir == vec3_origin )
{
dir = tr.m_pEnt->GetAbsOrigin() - GetAbsOrigin();
}
CalculateMeleeDamageForce( &info, dir, tr.endpos );
pHitEntity->TakeDamage( info );
// Spawn some extra blood where we hit
if ( pHitEntity->BloodColor() == DONT_BLEED )
{
CEffectData data;
Vector velocity = GetCurrentVelocity();
data.m_vOrigin = tr.endpos;
data.m_vAngles = GetAbsAngles();
VectorNormalize( velocity );
data.m_vNormal = ( tr.plane.normal + velocity ) * 0.5;;
DispatchEffect( "ManhackSparks", data );
EmitSound( "NPC_Manhack.Grind" );
//TODO: What we really want to do is get a material reference and emit the proper sprayage! - jdw
}
else
{
SpawnBlood(tr.endpos, g_vecAttackDir, pHitEntity->BloodColor(), 6 );
EmitSound( "NPC_Manhack.Slice" );
}
// Pop back a little bit after hitting the player
ComputeSliceBounceVelocity( pHitEntity, tr );
// Save off when we last hit something
m_flLastDamageTime = gpGlobals->curtime;
// Reset our state and give the player time to react
StopBurst( true );
}
//-----------------------------------------------------------------------------
// Purpose: We've touched something solid. Just bump it.
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Bump( CBaseEntity *pHitEntity, float flInterval, trace_t &tr )
{
if ( !VPhysicsGetObject() )
return;
// Surpressing this behavior
if ( m_flBumpSuppressTime > gpGlobals->curtime )
return;
if ( pHitEntity->GetMoveType() == MOVETYPE_VPHYSICS && pHitEntity->Classify()!=CLASS_MANHACK )
{
HitPhysicsObject( pHitEntity );
}
// We've hit something so deflect our velocity based on the surface
// norm of what we've hit
if (flInterval > 0)
{
float moveLen = ( (GetCurrentVelocity() * flInterval) * (1.0 - tr.fraction) ).Length();
Vector moveVec = moveLen*tr.plane.normal/flInterval;
// If I'm totally dead, don't bounce me up
if (m_iHealth <=0 && moveVec.z > 0)
{
moveVec.z = 0;
}
// If I'm right over the ground don't push down
if (moveVec.z < 0)
{
float floorZ = GetFloorZ(GetAbsOrigin());
if (abs(GetAbsOrigin().z - floorZ) < 36)
{
moveVec.z = 0;
}
}
Vector myUp;
VPhysicsGetObject()->LocalToWorldVector( &myUp, Vector( 0.0, 0.0, 1.0 ) );
// plane must be something that could hit the blades
if (fabs( DotProduct( myUp, tr.plane.normal ) ) < 0.25 )
{
CEffectData data;
Vector velocity = GetCurrentVelocity();
data.m_vOrigin = tr.endpos;
data.m_vAngles = GetAbsAngles();
VectorNormalize( velocity );
data.m_vNormal = ( tr.plane.normal + velocity ) * 0.5;;
DispatchEffect( "ManhackSparks", data );
CBroadcastRecipientFilter filter;
te->DynamicLight( filter, 0.0, &GetAbsOrigin(), 255, 180, 100, 0, 50, 0.3, 150 );
// add some spin, but only if we're not already going fast..
Vector vecVelocity;
AngularImpulse vecAngVelocity;
VPhysicsGetObject()->GetVelocity( &vecVelocity, &vecAngVelocity );
float flDot = DotProduct( myUp, vecAngVelocity );
if ( fabs(flDot) < 100 )
{
//AngularImpulse torque = myUp * (1000 - flDot * 10);
AngularImpulse torque = myUp * (1000 - flDot * 2);
VPhysicsGetObject()->ApplyTorqueCenter( torque );
}
if (!(m_spawnflags & SF_NPC_GAG))
{
EmitSound( "NPC_Manhack.Grind" );
}
// For decals and sparks we must trace a line in the direction of the surface norm
// that we hit.
trace_t decalTrace;
AI_TraceLine( GetAbsOrigin(), GetAbsOrigin() - (tr.plane.normal * 24),MASK_SOLID, this, COLLISION_GROUP_NONE, &decalTrace );
if ( decalTrace.fraction != 1.0 )
{
// Leave decal only if colliding horizontally
if ((DotProduct(Vector(0,0,1),decalTrace.plane.normal)<0.5) && (DotProduct(Vector(0,0,-1),decalTrace.plane.normal)<0.5))
{
UTIL_DecalTrace( &decalTrace, "ManhackCut" );
}
}
}
// See if we will not have a valid surface
if ( tr.allsolid || tr.startsolid )
{
// Build a fake reflection back along our current velocity because we can't know how to reflect off
// a non-existant surface! -- jdw
Vector vecRandomDir = RandomVector( -1.0f, 1.0f );
SetCurrentVelocity( vecRandomDir * 50.0f );
m_flBumpSuppressTime = gpGlobals->curtime + 0.5f;
}
else
{
// This is a valid hit and we can deflect properly
VectorNormalize( moveVec );
float hitAngle = -DotProduct( tr.plane.normal, -moveVec );
Vector vReflection = 2.0 * tr.plane.normal * hitAngle + -moveVec;
float flSpeed = GetCurrentVelocity().Length();
SetCurrentVelocity( GetCurrentVelocity() + vReflection * flSpeed * 0.5f );
}
}
// -------------------------------------------------------------
// If I'm on a path check LOS to my next node, and fail on path
// if I don't have LOS. Note this is the only place I do this,
// so the manhack has to collide before failing on a path
// -------------------------------------------------------------
if (GetNavigator()->IsGoalActive() && !(GetNavigator()->GetPath()->CurWaypointFlags() & bits_WP_TO_PATHCORNER) )
{
AIMoveTrace_t moveTrace;
GetMoveProbe()->MoveLimit( NAV_GROUND, GetAbsOrigin(), GetNavigator()->GetCurWaypointPos(),
MoveCollisionMask(), GetEnemy(), &moveTrace );
if (IsMoveBlocked( moveTrace ) &&
!moveTrace.pObstruction->ClassMatches( GetClassname() ))
{
TaskFail(FAIL_NO_ROUTE);
GetNavigator()->ClearGoal();
return;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::CheckCollisions(float flInterval)
{
// Trace forward to see if I hit anything. But trace forward along the
// owner's view direction if you're being carried.
Vector vecTraceDir, vecCheckPos;
VPhysicsGetObject()->GetVelocity( &vecTraceDir, NULL );
vecTraceDir *= flInterval;
if ( IsHeldByPhyscannon() )
{
CBasePlayer *pCarrier = HasPhysicsAttacker( FLT_MAX );
if ( pCarrier )
{
if ( pCarrier->CollisionProp()->CalcDistanceFromPoint( WorldSpaceCenter() ) < 30 )
{
AngleVectors( pCarrier->EyeAngles(), &vecTraceDir, NULL, NULL );
vecTraceDir *= 40.0f;
}
}
}
VectorAdd( GetAbsOrigin(), vecTraceDir, vecCheckPos );
trace_t tr;
CBaseEntity* pHitEntity = NULL;
AI_TraceHull( GetAbsOrigin(),
vecCheckPos,
GetHullMins(),
GetHullMaxs(),
MoveCollisionMask(),
this,
COLLISION_GROUP_NONE,
&tr );
if ( (tr.fraction != 1.0 || tr.startsolid) && tr.m_pEnt)
{
PhysicsMarkEntitiesAsTouching( tr.m_pEnt, tr );
pHitEntity = tr.m_pEnt;
if( m_bHeld && tr.m_pEnt->MyNPCPointer() && tr.m_pEnt->MyNPCPointer()->IsPlayerAlly() )
{
// Don't slice Alyx when she approaches to hack. We need a better solution for this!!
//Msg("Ignoring!\n");
return;
}
if ( pHitEntity != NULL &&
pHitEntity->m_takedamage == DAMAGE_YES &&
pHitEntity->Classify() != CLASS_MANHACK &&
gpGlobals->curtime > m_flWaterSuspendTime )
{
// Slice this thing
Slice( pHitEntity, flInterval, tr );
m_flBladeSpeed = 20.0;
}
else
{
// Just bump into this thing.
Bump( pHitEntity, flInterval, tr );
m_flBladeSpeed = 20.0;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
#define tempTIME_STEP = 0.5;
void CNPC_Manhack::PlayFlySound(void)
{
float flEnemyDist;
if( GetEnemy() )
{
flEnemyDist = (GetAbsOrigin() - GetEnemy()->GetAbsOrigin()).Length();
}
else
{
flEnemyDist = FLT_MAX;
}
if( m_spawnflags & SF_NPC_GAG )
{
// Quiet!
return;
}
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
// Just went in water. Slow the motor!!
if( m_bDirtyPitch )
{
m_nEnginePitch1 = MANHACK_WATER_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.5f;
m_nEnginePitch2 = MANHACK_WATER_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.5f;
m_bDirtyPitch = false;
}
}
// Spin sound based on distance from enemy (unless we're crashing)
else if (GetEnemy() && IsAlive() )
{
if( flEnemyDist < MANHACK_PITCH_DIST1 )
{
// recalculate pitch.
int iPitch1, iPitch2;
float flDistFactor;
flDistFactor = MIN( 1.0, 1 - flEnemyDist / MANHACK_PITCH_DIST1 );
iPitch1 = MANHACK_MIN_PITCH1 + ( ( MANHACK_MAX_PITCH1 - MANHACK_MIN_PITCH1 ) * flDistFactor);
// NOTE: MANHACK_PITCH_DIST2 must be < MANHACK_PITCH_DIST1
flDistFactor = MIN( 1.0, 1 - flEnemyDist / MANHACK_PITCH_DIST2 );
iPitch2 = MANHACK_MIN_PITCH2 + ( ( MANHACK_MAX_PITCH2 - MANHACK_MIN_PITCH2 ) * flDistFactor);
m_nEnginePitch1 = iPitch1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.1f;
m_nEnginePitch2 = iPitch2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.1f;
m_bDirtyPitch = true;
}
else if( m_bDirtyPitch )
{
m_nEnginePitch1 = MANHACK_MIN_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.1f;
m_nEnginePitch2 = MANHACK_MIN_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.2f;
m_bDirtyPitch = false;
}
}
// If no enemy just play low sound
else if( IsAlive() && m_bDirtyPitch )
{
m_nEnginePitch1 = MANHACK_MIN_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.1f;
m_nEnginePitch2 = MANHACK_MIN_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.2f;
m_bDirtyPitch = false;
}
// Play special engine every once in a while
if (gpGlobals->curtime > m_flNextEngineSoundTime && flEnemyDist < 48)
{
m_flNextEngineSoundTime = gpGlobals->curtime + random->RandomFloat( 3.0, 10.0 );
EmitSound( "NPC_Manhack.EngineNoise" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::MoveExecute_Alive(float flInterval)
{
PhysicsCheckWaterTransition();
Vector vCurrentVelocity = GetCurrentVelocity();
// FIXME: move this
VPhysicsGetObject()->Wake();
if( m_fEnginePowerScale < GetMaxEnginePower() && gpGlobals->curtime > m_flWaterSuspendTime )
{
// Power is low, and we're no longer stuck in water, so bring power up.
m_fEnginePowerScale += 0.05;
}
// ----------------------------------------------------------------------------------------
// Add time-coherent noise to the current velocity so that it never looks bolted in place.
// ----------------------------------------------------------------------------------------
float noiseScale = 7.0f;
if ( (CBaseEntity*)GetEnemy() )
{
float flDist = (GetAbsOrigin() - GetEnemy()->GetAbsOrigin()).Length2D();
if( flDist < MANHACK_CHARGE_MIN_DIST )
{
// Less noise up close.
noiseScale = 2.0;
}
if ( IsInEffectiveTargetZone( GetEnemy() ) && flDist < MANHACK_CHARGE_MIN_DIST && gpGlobals->curtime > m_flNextBurstTime )
{
Vector vecCurrentDir = GetCurrentVelocity();
VectorNormalize( vecCurrentDir );
Vector vecToEnemy = ( GetEnemy()->EyePosition() - WorldSpaceCenter() );
VectorNormalize( vecToEnemy );
float flDot = DotProduct( vecCurrentDir, vecToEnemy );
if ( flDot > 0.75 )
{
Vector offsetDir = ( vecToEnemy - vecCurrentDir );
VectorNormalize( offsetDir );
Vector offsetSpeed = GetCurrentVelocity() * flDot;
//FIXME: This code sucks -- jdw
offsetDir.z = 0.0f;
m_vForceVelocity += ( offsetDir * ( offsetSpeed.Length2D() * 0.25f ) );
// Commit to the attack- no steering for about a second
StartBurst( vecToEnemy );
SetEyeState( MANHACK_EYE_STATE_CHARGE );
}
}
if ( gpGlobals->curtime > m_flBurstDuration )
{
ShowHostile( false );
}
}
// ----------------------------------------------------------------------------------------
// Add in any forced velocity
// ----------------------------------------------------------------------------------------
SetCurrentVelocity( vCurrentVelocity + m_vForceVelocity );
m_vForceVelocity = vec3_origin;
if( !m_bHackedByAlyx || GetEnemy() )
{
// If hacked and no enemy, don't drift!
AddNoiseToVelocity( noiseScale );
}
LimitSpeed( 200, ManhackMaxSpeed() );
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
if( UTIL_PointContents( GetAbsOrigin() ) & (CONTENTS_WATER|CONTENTS_SLIME) )
{
// Ooops, we're submerged somehow. Move upwards until our origin is out of the water.
m_vCurrentVelocity.z = 20.0;
}
else
{
// Skimming the surface. Forbid any movement on Z
m_vCurrentVelocity.z = 0.0;
}
}
else if( GetWaterLevel() > 0 )
{
// Allow the manhack to lift off, but not to go deeper.
m_vCurrentVelocity.z = MAX( m_vCurrentVelocity.z, 0 );
}
CheckCollisions(flInterval);
// Blend out desired velocity when launched by the physcannon
if ( HasPhysicsAttacker( MANHACK_SMASH_TIME ) && (!IsHeldByPhyscannon()) && VPhysicsGetObject() )
{
Vector vecCurrentVelocity;
VPhysicsGetObject()->GetVelocity( &vecCurrentVelocity, NULL );
float flLerpFactor = (gpGlobals->curtime - m_flLastPhysicsInfluenceTime) / MANHACK_SMASH_TIME;
flLerpFactor = clamp( flLerpFactor, 0.0f, 1.0f );
flLerpFactor = SimpleSplineRemapVal( flLerpFactor, 0.0f, 1.0f, 0.0f, 1.0f );
VectorLerp( vecCurrentVelocity, m_vCurrentVelocity, flLerpFactor, m_vCurrentVelocity );
}
QAngle angles = GetLocalAngles();
// ------------------------------------------
// Stalling
// ------------------------------------------
if (gpGlobals->curtime < m_flEngineStallTime)
{
/*
// If I'm stalled add random noise
angles.x += -20+(random->RandomInt(-10,10));
angles.z += -20+(random->RandomInt(0,40));
TurnHeadRandomly(flInterval);
*/
}
else
{
// Make frame rate independent
float iRate = 0.5;
float timeToUse = flInterval;
while (timeToUse > 0)
{
m_vCurrentBanking.x = (iRate * m_vCurrentBanking.x) + (1 - iRate)*(m_vTargetBanking.x);
m_vCurrentBanking.z = (iRate * m_vCurrentBanking.z) + (1 - iRate)*(m_vTargetBanking.z);
timeToUse = -0.1;
}
angles.x = m_vCurrentBanking.x;
angles.z = m_vCurrentBanking.z;
angles.y = 0;
#if 0
// Using our steering if we're not otherwise affecting our panels
if ( m_flEngineStallTime < gpGlobals->curtime && m_flBurstDuration < gpGlobals->curtime )
{
Vector delta( 10 * AngleDiff( m_vTargetBanking.x, m_vCurrentBanking.x ), -10 * AngleDiff( m_vTargetBanking.z, m_vCurrentBanking.z ), 0 );
//Vector delta( 3 * AngleNormalize( m_vCurrentBanking.x ), -4 * AngleNormalize( m_vCurrentBanking.z ), 0 );
VectorYawRotate( delta, -m_fHeadYaw, delta );
// DevMsg("%.0f %.0f\n", delta.x, delta.y );
SetPoseParameter( m_iPanel1, -delta.x - delta.y * 2);
SetPoseParameter( m_iPanel2, -delta.x + delta.y * 2);
SetPoseParameter( m_iPanel3, delta.x + delta.y * 2);
SetPoseParameter( m_iPanel4, delta.x - delta.y * 2);
//SetPoseParameter( m_iPanel1, -delta.x );
//SetPoseParameter( m_iPanel2, -delta.x );
//SetPoseParameter( m_iPanel3, delta.x );
//SetPoseParameter( m_iPanel4, delta.x );
}
#endif
}
// SetLocalAngles( angles );
if( m_lifeState != LIFE_DEAD )
{
PlayFlySound();
// SpinBlades( flInterval );
// WalkMove( GetCurrentVelocity() * flInterval, MASK_NPCSOLID );
}
// NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + Vector(0, 0, -10 ), 0, 255, 0, true, 0.1);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::SpinBlades(float flInterval)
{
if (!m_bBladesActive)
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_OFF );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_OFF );
m_flBladeSpeed = 0.0;
m_flPlaybackRate = 1.0;
return;
}
if ( IsFlyingActivity( GetActivity() ) )
{
// Blades may only ramp up while the engine is running
if ( m_flEngineStallTime < gpGlobals->curtime )
{
if (m_flBladeSpeed < 10)
{
m_flBladeSpeed = m_flBladeSpeed * 2 + 1;
}
else
{
// accelerate engine
m_flBladeSpeed = m_flBladeSpeed + 80 * flInterval;
}
}
if (m_flBladeSpeed > 100)
{
m_flBladeSpeed = 100;
}
// blend through blades, blades+blur, blur
if (m_flBladeSpeed < 20)
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_ON );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_OFF );
}
else if (m_flBladeSpeed < 40)
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_ON );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_ON );
}
else
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_OFF );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_ON );
}
m_flPlaybackRate = m_flBladeSpeed / 100.0;
}
else
{
m_flBladeSpeed = 0.0;
}
}
//-----------------------------------------------------------------------------
// Purpose: Smokes and sparks, exploding periodically. Eventually it goes away.
//-----------------------------------------------------------------------------
void CNPC_Manhack::MoveExecute_Dead(float flInterval)
{
if( GetWaterLevel() > 0 )
{
// No movement if sinking in water.
return;
}
// Periodically emit smoke.
if (gpGlobals->curtime > m_fSmokeTime && GetWaterLevel() == 0)
{
// UTIL_Smoke(GetAbsOrigin(), random->RandomInt(10, 15), 10);
m_fSmokeTime = gpGlobals->curtime + random->RandomFloat( 0.1, 0.3);
}
// Periodically emit sparks.
if (gpGlobals->curtime > m_fSparkTime)
{
g_pEffects->Sparks( GetAbsOrigin() );
m_fSparkTime = gpGlobals->curtime + random->RandomFloat(0.1, 0.3);
}
Vector newVelocity = GetCurrentVelocity();
// accelerate faster and faster when dying
newVelocity = newVelocity + (newVelocity * 1.5 * flInterval );
// Lose lift
newVelocity.z -= 0.02*flInterval*(GetCurrentGravity());
// ----------------------------------------------------------------------------------------
// Add in any forced velocity
// ----------------------------------------------------------------------------------------
newVelocity += m_vForceVelocity;
SetCurrentVelocity( newVelocity );
m_vForceVelocity = vec3_origin;
// Lots of noise!! Out of control!
AddNoiseToVelocity( 5.0 );
// ----------------------
// Limit overall speed
// ----------------------
LimitSpeed( -1, MANHACK_MAX_SPEED * 2.0 );
QAngle angles = GetLocalAngles();
// ------------------------------------------
// If I'm dying, add random banking noise
// ------------------------------------------
angles.x += -20+(random->RandomInt(0,40));
angles.z += -20+(random->RandomInt(0,40));
CheckCollisions(flInterval);
PlayFlySound();
// SetLocalAngles( angles );
WalkMove( GetCurrentVelocity() * flInterval,MASK_NPCSOLID );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::Precache(void)
{
//
// Model.
//
PrecacheModel("models/manhack.mdl");
PrecacheModel( MANHACK_GLOW_SPRITE );
PropBreakablePrecacheAll( MAKE_STRING("models/manhack.mdl") );
PrecacheScriptSound( "NPC_Manhack.Die" );
PrecacheScriptSound( "NPC_Manhack.Bat" );
PrecacheScriptSound( "NPC_Manhack.Grind" );
PrecacheScriptSound( "NPC_Manhack.Slice" );
PrecacheScriptSound( "NPC_Manhack.EngineNoise" );
PrecacheScriptSound( "NPC_Manhack.Unpack" );
PrecacheScriptSound( "NPC_Manhack.ChargeAnnounce" );
PrecacheScriptSound( "NPC_Manhack.ChargeEnd" );
PrecacheScriptSound( "NPC_Manhack.Stunned" );
// Sounds used on Client:
PrecacheScriptSound( "NPC_Manhack.EngineSound1" );
PrecacheScriptSound( "NPC_Manhack.EngineSound2" );
PrecacheScriptSound( "NPC_Manhack.BladeSound" );
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::GatherEnemyConditions( CBaseEntity *pEnemy )
{
// The Manhack "regroups" when its in attack range but to
// far above or below its enemy. Set the start attack
// condition if we are far enough away from the enemy
// or at the correct height
// Don't bother with Z if the enemy is in a vehicle
float fl2DDist = 60.0f;
float flZDist = 12.0f;
if ( GetEnemy()->IsPlayer() && assert_cast< CBasePlayer * >(GetEnemy())->IsInAVehicle() )
{
flZDist = 24.0f;
}
if ((GetAbsOrigin() - pEnemy->GetAbsOrigin()).Length2D() > fl2DDist)
{
SetCondition(COND_MANHACK_START_ATTACK);
}
else
{
float targetZ = pEnemy->EyePosition().z;
if (fabs(GetAbsOrigin().z - targetZ) < flZDist)
{
SetCondition(COND_MANHACK_START_ATTACK);
}
}
BaseClass::GatherEnemyConditions(pEnemy);
}
//-----------------------------------------------------------------------------
// Purpose: For innate melee attack
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::MeleeAttack1Conditions( float flDot, float flDist )
{
if ( GetEnemy() == NULL )
return COND_NONE;
//TODO: We could also decide if we want to back up here
if ( m_flNextBurstTime > gpGlobals->curtime )
return COND_NONE;
float flMaxDist = 45;
float flMinDist = 24;
bool bEnemyInVehicle = GetEnemy()->IsPlayer() && assert_cast< CBasePlayer * >(GetEnemy())->IsInAVehicle();
if ( GetEnemy()->IsPlayer() && assert_cast< CBasePlayer * >(GetEnemy())->IsInAVehicle() )
{
flMinDist = 0;
flMaxDist = 200.0f;
}
if (flDist > flMaxDist)
{
return COND_TOO_FAR_TO_ATTACK;
}
if (flDist < flMinDist)
{
return COND_TOO_CLOSE_TO_ATTACK;
}
// Check our current velocity and speed, if it's too far off, we need to settle
// Don't bother with Z if the enemy is in a vehicle
if ( bEnemyInVehicle )
{
return COND_CAN_MELEE_ATTACK1;
}
// Assume the this check is in regards to my current enemy
// for the Manhacks spetial condition
float deltaZ = GetAbsOrigin().z - GetEnemy()->EyePosition().z;
if ( (deltaZ > 12.0f) || (deltaZ < -24.0f) )
{
return COND_TOO_CLOSE_TO_ATTACK;
}
return COND_CAN_MELEE_ATTACK1;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CNPC_Manhack::RunTask( const Task_t *pTask )
{
switch ( pTask->iTask )
{
// Override this task so we go for the enemy at eye level
case TASK_MANHACK_HOVER:
{
break;
}
// If my enemy has moved significantly, update my path
case TASK_WAIT_FOR_MOVEMENT:
{
CBaseEntity *pEnemy = GetEnemy();
if (pEnemy &&
(GetCurSchedule()->GetId() == SCHED_CHASE_ENEMY) &&
GetNavigator()->IsGoalActive() )
{
Vector vecEnemyPosition;
vecEnemyPosition = pEnemy->EyePosition();
if ( GetNavigator()->GetGoalPos().DistToSqr(vecEnemyPosition) > 40 * 40 )
{
GetNavigator()->UpdateGoalPos( vecEnemyPosition );
}
}
BaseClass::RunTask(pTask);
break;
}
case TASK_MANHACK_MOVEAT_SAVEPOSITION:
{
// do the movement thingy
// NDebugOverlay::Line( GetAbsOrigin(), m_vSavePosition, 0, 255, 0, true, 0.1);
Vector dir = (m_vSavePosition - GetAbsOrigin());
float dist = VectorNormalize( dir );
float t = m_fSwarmMoveTime - gpGlobals->curtime;
if (t < 0.1)
{
if (dist > 256)
{
TaskFail( FAIL_NO_ROUTE );
}
else
{
TaskComplete();
}
}
else if (dist < 64)
{
m_vSwarmMoveTarget = GetAbsOrigin() - Vector( -dir.y, dir.x, 0 ) * 4;
}
else
{
m_vSwarmMoveTarget = GetAbsOrigin() + dir * 10;
}
break;
}
default:
{
BaseClass::RunTask(pTask);
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::Spawn(void)
{
Precache();
#ifdef _XBOX
// Always fade the corpse
AddSpawnFlags( SF_NPC_FADE_CORPSE );
#endif // _XBOX
SetModel( "models/manhack.mdl" );
SetHullType(HULL_TINY_CENTERED);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
if ( HasSpawnFlags( SF_MANHACK_CARRIED ) )
{
AddSolidFlags( FSOLID_NOT_SOLID );
SetMoveType( MOVETYPE_NONE );
}
else
{
SetMoveType( MOVETYPE_VPHYSICS );
}
m_iHealth = sk_manhack_health.GetFloat();
SetViewOffset( Vector(0, 0, 10) ); // Position of the eyes relative to NPC's origin.
m_flFieldOfView = VIEW_FIELD_FULL;
m_NPCState = NPC_STATE_NONE;
if ( m_spawnflags & SF_MANHACK_USE_AIR_NODES)
{
SetNavType(NAV_FLY);
}
else
{
SetNavType(NAV_GROUND);
}
AddEFlags( EFL_NO_DISSOLVE | EFL_NO_MEGAPHYSCANNON_RAGDOLL );
AddEffects( EF_NOSHADOW );
SetBloodColor( DONT_BLEED );
SetCurrentVelocity( vec3_origin );
m_vForceVelocity.Init();
m_vCurrentBanking.Init();
m_vTargetBanking.Init();
m_flNextBurstTime = gpGlobals->curtime;
CapabilitiesAdd( bits_CAP_INNATE_MELEE_ATTACK1 | bits_CAP_MOVE_FLY | bits_CAP_SQUAD );
m_flNextEngineSoundTime = gpGlobals->curtime;
m_flWaterSuspendTime = gpGlobals->curtime;
m_flEngineStallTime = gpGlobals->curtime;
m_fForceMoveTime = gpGlobals->curtime;
m_vForceMoveTarget = vec3_origin;
m_fSwarmMoveTime = gpGlobals->curtime;
m_vSwarmMoveTarget = vec3_origin;
m_nLastSpinSound = -1;
m_fSmokeTime = 0;
m_fSparkTime = 0;
// Set the noise mod to huge numbers right now, in case this manhack starts out waiting for a script
// for instance, we don't want him to bob whilst he's waiting for a script. This allows designers
// to 'hide' manhacks in small places. (sjb)
SetNoiseMod( MANHACK_NOISEMOD_HIDE, MANHACK_NOISEMOD_HIDE, MANHACK_NOISEMOD_HIDE );
// Start out with full power!
m_fEnginePowerScale = GetMaxEnginePower();
// find panels
m_iPanel1 = LookupPoseParameter( "Panel1" );
m_iPanel2 = LookupPoseParameter( "Panel2" );
m_iPanel3 = LookupPoseParameter( "Panel3" );
m_iPanel4 = LookupPoseParameter( "Panel4" );
m_fHeadYaw = 0;
NPCInit();
// Manhacks are designed to slam into things, so don't take much damage from it!
SetImpactEnergyScale( 0.001 );
// Manhacks get 30 seconds worth of free knowledge.
GetEnemies()->SetFreeKnowledgeDuration( 30.0 );
// don't be an NPC, we want to collide with debris stuff
SetCollisionGroup( COLLISION_GROUP_NONE );
m_bHeld = false;
m_bHackedByAlyx = false;
StopLoitering();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartEye( void )
{
//Create our Eye sprite
if ( m_pEyeGlow == NULL )
{
m_pEyeGlow = CSprite::SpriteCreate( MANHACK_GLOW_SPRITE, GetLocalOrigin(), false );
m_pEyeGlow->SetAttachment( this, LookupAttachment( "Eye" ) );
if( m_bHackedByAlyx )
{
m_pEyeGlow->SetTransparency( kRenderTransAdd, 0, 255, 0, 128, kRenderFxNoDissipation );
m_pEyeGlow->SetColor( 0, 255, 0 );
}
else
{
m_pEyeGlow->SetTransparency( kRenderTransAdd, 255, 0, 0, 128, kRenderFxNoDissipation );
m_pEyeGlow->SetColor( 255, 0, 0 );
}
m_pEyeGlow->SetBrightness( 164, 0.1f );
m_pEyeGlow->SetScale( 0.25f, 0.1f );
m_pEyeGlow->SetAsTemporary();
}
//Create our light sprite
if ( m_pLightGlow == NULL )
{
m_pLightGlow = CSprite::SpriteCreate( MANHACK_GLOW_SPRITE, GetLocalOrigin(), false );
m_pLightGlow->SetAttachment( this, LookupAttachment( "Light" ) );
if( m_bHackedByAlyx )
{
m_pLightGlow->SetTransparency( kRenderTransAdd, 0, 255, 0, 128, kRenderFxNoDissipation );
m_pLightGlow->SetColor( 0, 255, 0 );
}
else
{
m_pLightGlow->SetTransparency( kRenderTransAdd, 255, 0, 0, 128, kRenderFxNoDissipation );
m_pLightGlow->SetColor( 255, 0, 0 );
}
m_pLightGlow->SetBrightness( 164, 0.1f );
m_pLightGlow->SetScale( 0.25f, 0.1f );
m_pLightGlow->SetAsTemporary();
}
}
//-----------------------------------------------------------------------------
void CNPC_Manhack::Activate()
{
BaseClass::Activate();
if ( IsAlive() )
{
StartEye();
}
}
//-----------------------------------------------------------------------------
// Purpose: Get the engine sound started. Unless we're not supposed to have it on yet!
//-----------------------------------------------------------------------------
void CNPC_Manhack::PostNPCInit( void )
{
// SetAbsVelocity( vec3_origin );
m_bBladesActive = (m_spawnflags & (SF_MANHACK_PACKED_UP|SF_MANHACK_CARRIED)) ? false : true;
BladesInit();
}
void CNPC_Manhack::BladesInit()
{
if( !m_bBladesActive )
{
// manhack is packed up, so has no power of its own.
// don't start the engine sounds.
// make us fall a little slower than we should, for visual's sake
SetGravity( UTIL_ScaleForGravity( 400 ) );
SetActivity( ACT_IDLE );
}
else
{
bool engineSound = (m_spawnflags & SF_NPC_GAG) ? false : true;
StartEngine( engineSound );
SetActivity( ACT_FLY );
}
}
//-----------------------------------------------------------------------------
// Crank up the engine!
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartEngine( bool fStartSound )
{
if( fStartSound )
{
SoundInit();
}
// Make the blade appear.
SetBodygroup( 1, 1 );
// Pop up a little if falling fast!
Vector vecVelocity;
GetVelocity( &vecVelocity, NULL );
if( ( m_spawnflags & SF_MANHACK_PACKED_UP ) && vecVelocity.z < 0 )
{
// DevMsg(" POP UP \n" );
// ApplyAbsVelocityImpulse( Vector(0,0,-vecVelocity.z*0.75) );
}
// Under powered flight now.
// SetMoveType( MOVETYPE_STEP );
// SetGravity( MANHACK_GRAVITY );
AddFlag( FL_FLY );
}
//-----------------------------------------------------------------------------
// Purpose: Start the manhack's engine sound.
//-----------------------------------------------------------------------------
void CNPC_Manhack::SoundInit( void )
{
m_nEnginePitch1 = MANHACK_MIN_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime;
m_nEnginePitch2 = MANHACK_MIN_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StopLoopingSounds(void)
{
BaseClass::StopLoopingSounds();
m_nEnginePitch1 = -1;
m_flEnginePitch1Time = gpGlobals->curtime;
m_nEnginePitch2 = -1;
m_flEnginePitch2Time = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pTask -
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartTask( const Task_t *pTask )
{
switch (pTask->iTask)
{
case TASK_MANHACK_UNPACK:
{
// Just play a sound for now.
EmitSound( "NPC_Manhack.Unpack" );
TaskComplete();
}
break;
case TASK_MANHACK_HOVER:
break;
case TASK_MOVE_TO_TARGET_RANGE:
case TASK_GET_PATH_TO_GOAL:
case TASK_GET_PATH_TO_ENEMY_LKP:
case TASK_GET_PATH_TO_PLAYER:
{
BaseClass::StartTask( pTask );
/*
// FIXME: why were these tasks considered bad?
_asm
{
int 3;
int 5;
}
*/
}
break;
case TASK_FACE_IDEAL:
{
// this shouldn't ever happen, but if it does, don't choke
TaskComplete();
}
break;
case TASK_GET_PATH_TO_ENEMY:
{
if (IsUnreachable(GetEnemy()))
{
TaskFail(FAIL_NO_ROUTE);
return;
}
CBaseEntity *pEnemy = GetEnemy();
if ( pEnemy == NULL )
{
TaskFail(FAIL_NO_ENEMY);
return;
}
if ( GetNavigator()->SetGoal( GOALTYPE_ENEMY ) )
{
TaskComplete();
}
else
{
// no way to get there =(
DevWarning( 2, "GetPathToEnemy failed!!\n" );
RememberUnreachable(GetEnemy());
TaskFail(FAIL_NO_ROUTE);
}
break;
}
break;
case TASK_GET_PATH_TO_TARGET:
// DevMsg("TARGET\n");
BaseClass::StartTask( pTask );
break;
case TASK_MANHACK_FIND_SQUAD_CENTER:
{
if (!m_pSquad)
{
m_vSavePosition = GetAbsOrigin();
TaskComplete();
break;
}
// calc center of squad
int count = 0;
m_vSavePosition = Vector( 0, 0, 0 );
// give attacking members more influence
AISquadIter_t iter;
for (CAI_BaseNPC *pSquadMember = m_pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = m_pSquad->GetNextMember( &iter ) )
{
if (pSquadMember->HasStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ))
{
m_vSavePosition += pSquadMember->GetAbsOrigin() * 10;
count += 10;
}
else
{
m_vSavePosition += pSquadMember->GetAbsOrigin();
count++;
}
}
// pull towards enemy
if (GetEnemy() != NULL)
{
m_vSavePosition += GetEnemyLKP() * 4;
count += 4;
}
Assert( count != 0 );
m_vSavePosition = m_vSavePosition * (1.0 / count);
TaskComplete();
}
break;
case TASK_MANHACK_FIND_SQUAD_MEMBER:
{
if (m_pSquad)
{
CAI_BaseNPC *pSquadMember = m_pSquad->GetAnyMember();
m_vSavePosition = pSquadMember->GetAbsOrigin();
// find attacking members
AISquadIter_t iter;
for (pSquadMember = m_pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = m_pSquad->GetNextMember( &iter ) )
{
// are they attacking?
if (pSquadMember->HasStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ))
{
m_vSavePosition = pSquadMember->GetAbsOrigin();
break;
}
// do they have a goal?
if (pSquadMember->GetNavigator()->IsGoalActive())
{
m_vSavePosition = pSquadMember->GetAbsOrigin();
break;
}
}
}
else
{
m_vSavePosition = GetAbsOrigin();
}
TaskComplete();
}
break;
case TASK_MANHACK_MOVEAT_SAVEPOSITION:
{
trace_t tr;
AI_TraceLine( GetAbsOrigin(), m_vSavePosition, MASK_NPCWORLDSTATIC, this, COLLISION_GROUP_NONE, &tr );
if (tr.DidHitWorld())
{
TaskFail( FAIL_NO_ROUTE );
}
else
{
m_fSwarmMoveTime = gpGlobals->curtime + RandomFloat( pTask->flTaskData * 0.8, pTask->flTaskData * 1.2 );
}
}
break;
default:
BaseClass::StartTask(pTask);
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::UpdateOnRemove( void )
{
DestroySmokeTrail();
KillSprites( 0.0 );
BaseClass::UpdateOnRemove();
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CNPC_Manhack::HandleInteraction(int interactionType, void* data, CBaseCombatCharacter* sourceEnt)
{
if (interactionType == g_interactionVortigauntClaw)
{
// Freeze so vortigaunt and hit me easier
m_vForceMoveTarget.x = ((Vector *)data)->x;
m_vForceMoveTarget.y = ((Vector *)data)->y;
m_vForceMoveTarget.z = ((Vector *)data)->z;
m_fForceMoveTime = gpGlobals->curtime + 2.0;
return false;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float CNPC_Manhack::ManhackMaxSpeed( void )
{
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
// Slower in water!
return MANHACK_MAX_SPEED * 0.1;
}
if ( HasPhysicsAttacker( MANHACK_SMASH_TIME ) )
{
return MANHACK_NPC_BURST_SPEED;
}
return MANHACK_MAX_SPEED;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::ClampMotorForces( Vector &linear, AngularImpulse &angular )
{
float scale = m_flBladeSpeed / 100.0;
// Msg("%.0f %.0f %.0f\n", linear.x, linear.y, linear.z );
float fscale = 3000 * scale;
if ( m_flEngineStallTime > gpGlobals->curtime )
{
linear.x = 0.0f;
linear.y = 0.0f;
linear.z = clamp( linear.z, -fscale, fscale < 1200 ? 1200 : fscale );
}
else
{
// limit reaction forces
linear.x = clamp( linear.x, -fscale, fscale );
linear.y = clamp( linear.y, -fscale, fscale );
linear.z = clamp( linear.z, -fscale, fscale < 1200 ? 1200 : fscale );
}
angular.x *= scale;
angular.y *= scale;
angular.z *= scale;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::KillSprites( float flDelay )
{
if( m_pEyeGlow )
{
m_pEyeGlow->FadeAndDie( flDelay );
m_pEyeGlow = NULL;
}
if( m_pLightGlow )
{
m_pLightGlow->FadeAndDie( flDelay );
m_pLightGlow = NULL;
}
// Re-enable for light trails
/*
if ( m_hLightTrail )
{
m_hLightTrail->FadeAndDie( flDelay );
m_hLightTrail = NULL;
}
*/
}
//-----------------------------------------------------------------------------
// Purpose: Tests whether we're above the target's feet but also below their top
// Input : *pTarget - who we're testing against
//-----------------------------------------------------------------------------
bool CNPC_Manhack::IsInEffectiveTargetZone( CBaseEntity *pTarget )
{
Vector vecMaxPos, vecMinPos;
float ourHeight = WorldSpaceCenter().z;
// If the enemy is in a vehicle, we need to get those bounds
if ( pTarget && pTarget->IsPlayer() && assert_cast< CBasePlayer * >(pTarget)->IsInAVehicle() )
{
CBaseEntity *pVehicle = assert_cast< CBasePlayer * >(pTarget)->GetVehicleEntity();
pVehicle->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,1.0f), &vecMaxPos );
pVehicle->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,0.0f), &vecMinPos );
if ( ourHeight > vecMinPos.z && ourHeight < vecMaxPos.z )
return true;
return false;
}
// Get the enemies top and bottom point
pTarget->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,1.0f), &vecMaxPos );
#ifdef _XBOX
pTarget->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,0.5f), &vecMinPos ); // Only half the body is valid
#else
pTarget->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,0.0f), &vecMinPos );
#endif // _XBOX
// See if we're within that range
if ( ourHeight > vecMinPos.z && ourHeight < vecMaxPos.z )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pEnemy -
// &chasePosition -
// &tolerance -
//-----------------------------------------------------------------------------
void CNPC_Manhack::TranslateNavGoal( CBaseEntity *pEnemy, Vector &chasePosition )
{
if ( pEnemy && pEnemy->IsPlayer() && assert_cast< CBasePlayer * >(pEnemy)->IsInAVehicle() )
{
Vector vecNewPos;
CBaseEntity *pVehicle = assert_cast< CBasePlayer * >(pEnemy)->GetVehicleEntity();
pVehicle->CollisionProp()->NormalizedToWorldSpace( Vector(0.5,0.5,0.5f), &vecNewPos );
chasePosition.z = vecNewPos.z;
}
else
{
Vector vecTarget;
pEnemy->CollisionProp()->NormalizedToCollisionSpace( Vector(0,0,0.75f), &vecTarget );
chasePosition.z += vecTarget.z;
}
}
float CNPC_Manhack::GetDefaultNavGoalTolerance()
{
return GetHullWidth();
}
//-----------------------------------------------------------------------------
// Purpose: Input that disables the manhack's swarm behavior
//-----------------------------------------------------------------------------
void CNPC_Manhack::InputDisableSwarm( inputdata_t &inputdata )
{
m_bDoSwarmBehavior = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_Manhack::InputUnpack( inputdata_t &inputdata )
{
if ( HasSpawnFlags( SF_MANHACK_PACKED_UP ) == false )
return;
SetCondition( COND_LIGHT_DAMAGE );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pPhysGunUser -
// reason -
//-----------------------------------------------------------------------------
void CNPC_Manhack::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
{
m_hPhysicsAttacker = pPhysGunUser;
m_flLastPhysicsInfluenceTime = gpGlobals->curtime;
if ( reason == PUNTED_BY_CANNON )
{
StopLoitering();
m_bHeld = false;
// There's about to be a massive change in velocity.
// Think immediately so we can do our slice traces, etc.
SetNextThink( gpGlobals->curtime + 0.01f );
// Stall our engine for awhile
m_flEngineStallTime = gpGlobals->curtime + 2.0f;
SetEyeState( MANHACK_EYE_STATE_STUNNED );
}
else
{
// Suppress collisions between the manhack and the player; we're currently bumping
// almost certainly because it's not purely a physics object.
SetOwnerEntity( pPhysGunUser );
m_bHeld = true;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pPhysGunUser -
// Reason -
//-----------------------------------------------------------------------------
void CNPC_Manhack::OnPhysGunDrop( CBasePlayer *pPhysGunUser, PhysGunDrop_t Reason )
{
// Stop suppressing collisions between the manhack and the player
SetOwnerEntity( NULL );
m_bHeld = false;
if ( Reason == LAUNCHED_BY_CANNON )
{
m_hPhysicsAttacker = pPhysGunUser;
m_flLastPhysicsInfluenceTime = gpGlobals->curtime;
// There's about to be a massive change in velocity.
// Think immediately so we can do our slice traces, etc.
SetNextThink( gpGlobals->curtime + 0.01f );
// Stall our engine for awhile
m_flEngineStallTime = gpGlobals->curtime + 2.0f;
SetEyeState( MANHACK_EYE_STATE_STUNNED );
}
else
{
if( m_bHackedByAlyx && !GetEnemy() )
{
// If a hacked manhack is released in peaceable conditions,
// just loiter, don't zip off.
StartLoitering( GetAbsOrigin() );
}
m_hPhysicsAttacker = NULL;
m_flLastPhysicsInfluenceTime = 0;
}
}
void CNPC_Manhack::StartLoitering( const Vector &vecLoiterPosition )
{
//Msg("Start Loitering\n");
m_vTargetBanking = vec3_origin;
m_vecLoiterPosition = GetAbsOrigin();
m_vForceVelocity = vec3_origin;
SetCurrentVelocity( vec3_origin );
}
CBasePlayer *CNPC_Manhack::HasPhysicsAttacker( float dt )
{
// If the player is holding me now, or I've been recently thrown
// then return a pointer to that player
if ( IsHeldByPhyscannon() || (gpGlobals->curtime - dt <= m_flLastPhysicsInfluenceTime) )
{
return m_hPhysicsAttacker;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Manhacks that have been hacked by Alyx get more engine power (fly faster)
//-----------------------------------------------------------------------------
float CNPC_Manhack::GetMaxEnginePower()
{
if( m_bHackedByAlyx )
{
return 2.0f;
}
return 1.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::UpdatePanels( void )
{
if ( m_flEngineStallTime > gpGlobals->curtime )
{
SetPoseParameter( m_iPanel1, random->RandomFloat( 0.0f, 90.0f ) );
SetPoseParameter( m_iPanel2, random->RandomFloat( 0.0f, 90.0f ) );
SetPoseParameter( m_iPanel3, random->RandomFloat( 0.0f, 90.0f ) );
SetPoseParameter( m_iPanel4, random->RandomFloat( 0.0f, 90.0f ) );
return;
}
float panelPosition = GetPoseParameter( m_iPanel1 );
if ( m_bShowingHostile )
{
panelPosition = 90.0f;//UTIL_Approach( 90.0f, panelPosition, 90.0f );
}
else
{
panelPosition = UTIL_Approach( 0.0f, panelPosition, 25.0f );
}
//FIXME: If we're going to have all these be equal, there's no need for 4 poses..
SetPoseParameter( m_iPanel1, panelPosition );
SetPoseParameter( m_iPanel2, panelPosition );
SetPoseParameter( m_iPanel3, panelPosition );
SetPoseParameter( m_iPanel4, panelPosition );
//TODO: Make these waver randomly?
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : hostile -
//-----------------------------------------------------------------------------
void CNPC_Manhack::ShowHostile( bool hostile /*= true*/)
{
if ( m_bShowingHostile == hostile )
return;
//TODO: Open the manhack panels or close them, depending on the state
m_bShowingHostile = hostile;
if ( hostile )
{
EmitSound( "NPC_Manhack.ChargeAnnounce" );
}
else
{
EmitSound( "NPC_Manhack.ChargeEnd" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartBurst( const Vector &vecDirection )
{
if ( m_flBurstDuration > gpGlobals->curtime )
return;
ShowHostile();
// Don't burst attack again for a couple seconds
m_flNextBurstTime = gpGlobals->curtime + 2.0;
m_flBurstDuration = gpGlobals->curtime + 1.0;
// Save off where we were going towards and for how long
m_vecBurstDirection = vecDirection;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StopBurst( bool bInterruptSchedule /*= false*/ )
{
if ( m_flBurstDuration < gpGlobals->curtime )
return;
ShowHostile( false );
// Stop our burst timers
m_flNextBurstTime = gpGlobals->curtime + 2.0f; //FIXME: Skill level based
m_flBurstDuration = gpGlobals->curtime - 0.1f;
if ( bInterruptSchedule )
{
// We need to rethink our current schedule
ClearSchedule( "Stopping burst" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::SetEyeState( int state )
{
// Make sure we're active
StartEye();
switch( state )
{
case MANHACK_EYE_STATE_STUNNED:
{
if ( m_pEyeGlow )
{
//Toggle our state
m_pEyeGlow->SetColor( 255, 128, 0 );
m_pEyeGlow->SetScale( 0.15f, 0.1f );
m_pEyeGlow->SetBrightness( 164, 0.1f );
m_pEyeGlow->m_nRenderFX = kRenderFxStrobeFast;
}
if ( m_pLightGlow )
{
m_pLightGlow->SetColor( 255, 128, 0 );
m_pLightGlow->SetScale( 0.15f, 0.1f );
m_pLightGlow->SetBrightness( 164, 0.1f );
m_pLightGlow->m_nRenderFX = kRenderFxStrobeFast;
}
EmitSound("NPC_Manhack.Stunned");
break;
}
case MANHACK_EYE_STATE_CHARGE:
{
if ( m_pEyeGlow )
{
//Toggle our state
if( m_bHackedByAlyx )
{
m_pEyeGlow->SetColor( 0, 255, 0 );
}
else
{
m_pEyeGlow->SetColor( 255, 0, 0 );
}
m_pEyeGlow->SetScale( 0.25f, 0.5f );
m_pEyeGlow->SetBrightness( 164, 0.1f );
m_pEyeGlow->m_nRenderFX = kRenderFxNone;
}
if ( m_pLightGlow )
{
if( m_bHackedByAlyx )
{
m_pLightGlow->SetColor( 0, 255, 0 );
}
else
{
m_pLightGlow->SetColor( 255, 0, 0 );
}
m_pLightGlow->SetScale( 0.25f, 0.5f );
m_pLightGlow->SetBrightness( 164, 0.1f );
m_pLightGlow->m_nRenderFX = kRenderFxNone;
}
break;
}
default:
if ( m_pEyeGlow )
m_pEyeGlow->m_nRenderFX = kRenderFxNone;
break;
}
}
unsigned int CNPC_Manhack::PhysicsSolidMaskForEntity( void ) const
{
unsigned int mask = BaseClass::PhysicsSolidMaskForEntity();
if ( m_bIgnoreClipbrushes )
{
mask &= ~CONTENTS_MONSTERCLIP;
}
return mask;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_Manhack::CreateVPhysics( void )
{
if ( HasSpawnFlags( SF_MANHACK_CARRIED ) )
return false;
return BaseClass::CreateVPhysics();
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( npc_manhack, CNPC_Manhack )
DECLARE_TASK( TASK_MANHACK_HOVER );
DECLARE_TASK( TASK_MANHACK_UNPACK );
DECLARE_TASK( TASK_MANHACK_FIND_SQUAD_CENTER );
DECLARE_TASK( TASK_MANHACK_FIND_SQUAD_MEMBER );
DECLARE_TASK( TASK_MANHACK_MOVEAT_SAVEPOSITION );
DECLARE_CONDITION( COND_MANHACK_START_ATTACK );
DECLARE_ACTIVITY( ACT_MANHACK_UNPACK );
//=========================================================
// > SCHED_MANHACK_ATTACK_HOVER
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_ATTACK_HOVER,
" Tasks"
" TASK_SET_ACTIVITY ACTIVITY:ACT_FLY"
" TASK_MANHACK_HOVER 0"
" "
" Interrupts"
" COND_TOO_FAR_TO_ATTACK"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_ENEMY_OCCLUDED"
);
//=========================================================
// > SCHED_MANHACK_ATTACK_HOVER
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_DEPLOY,
" Tasks"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_MANHACK_UNPACK"
" TASK_SET_ACTIVITY ACTIVITY:ACT_FLY"
" "
// " Interrupts"
);
//=========================================================
// > SCHED_MANHACK_REGROUP
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_REGROUP,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_TOLERANCE_DISTANCE 24"
" TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION 0"
" TASK_FIND_BACKAWAY_FROM_SAVEPOSITION 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" "
" Interrupts"
" COND_MANHACK_START_ATTACK"
" COND_NEW_ENEMY"
" COND_CAN_MELEE_ATTACK1"
);
//=========================================================
// > SCHED_MANHACK_SWARN
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_SWARM_IDLE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MANHACK_SWARM_FAILURE"
" TASK_MANHACK_FIND_SQUAD_CENTER 0"
" TASK_MANHACK_MOVEAT_SAVEPOSITION 5"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_SEE_ENEMY"
" COND_SEE_FEAR"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_SMELL"
" COND_PROVOKED"
" COND_GIVE_WAY"
" COND_HEAR_PLAYER"
" COND_HEAR_DANGER"
" COND_HEAR_COMBAT"
" COND_HEAR_BULLET_IMPACT"
);
DEFINE_SCHEDULE
(
SCHED_MANHACK_SWARM,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MANHACK_SWARM_FAILURE"
" TASK_MANHACK_FIND_SQUAD_CENTER 0"
" TASK_MANHACK_MOVEAT_SAVEPOSITION 1"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_CAN_MELEE_ATTACK1"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
);
DEFINE_SCHEDULE
(
SCHED_MANHACK_SWARM_FAILURE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_WAIT 2"
" TASK_WAIT_RANDOM 2"
" TASK_MANHACK_FIND_SQUAD_MEMBER 0"
" TASK_GET_PATH_TO_SAVEPOSITION 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" "
" Interrupts"
" COND_SEE_ENEMY"
" COND_NEW_ENEMY"
);
AI_END_CUSTOM_NPC()
|
/*
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/shell/shell_options.h"
#include <iostream>
#include "mongo/util/options_parser/startup_option_init.h"
#include "mongo/util/options_parser/startup_options.h"
#include "mongo/util/quick_exit.h"
namespace mongo {
MONGO_GENERAL_STARTUP_OPTIONS_REGISTER(MongoShellOptions)(InitializerContext* context) {
return addMongoShellOptions(&moe::startupOptions);
}
MONGO_STARTUP_OPTIONS_VALIDATE(MongoShellOptions)(InitializerContext* context) {
if (!handlePreValidationMongoShellOptions(moe::startupOptionsParsed, context->args())) {
quickExit(EXIT_SUCCESS);
}
Status ret = moe::startupOptionsParsed.validate();
if (!ret.isOK()) {
return ret;
}
ret = validateMongoShellOptions(moe::startupOptionsParsed);
if (!ret.isOK()) {
return ret;
}
return Status::OK();
}
MONGO_STARTUP_OPTIONS_STORE(MongoShellOptions)(InitializerContext* context) {
Status ret = storeMongoShellOptions(moe::startupOptionsParsed, context->args());
if (!ret.isOK()) {
std::cerr << ret.toString() << std::endl;
std::cerr << "try '" << context->args()[0] << " --help' for more information" << std::endl;
quickExit(EXIT_BADOPTIONS);
}
return Status::OK();
}
}
|
#ifndef BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
#define BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: msvc_eti_base.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
#include <Awl/boost/mpl/aux_/is_msvc_eti_arg.hpp>
#include <Awl/boost/mpl/aux_/config/eti.hpp>
#include <Awl/boost/mpl/aux_/config/gcc.hpp>
#include <Awl/boost/mpl/aux_/config/workaround.hpp>
namespace boost { namespace mpl { namespace aux {
#if defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG)
template< bool > struct msvc_eti_base_impl
{
template< typename T > struct result_
: T
{
typedef T type;
};
};
template<> struct msvc_eti_base_impl<true>
{
template< typename T > struct result_
{
typedef result_ type;
typedef result_ first;
typedef result_ second;
typedef result_ tag;
enum { value = 0 };
};
};
template< typename T > struct msvc_eti_base
: msvc_eti_base_impl< is_msvc_eti_arg<T>::value >
::template result_<T>
{
};
#else // !BOOST_MPL_CFG_MSVC_70_ETI_BUG
template< typename T > struct msvc_eti_base
: T
{
#if BOOST_WORKAROUND(BOOST_MPL_CFG_GCC, BOOST_TESTED_AT(0x0304))
msvc_eti_base();
#endif
typedef T type;
};
#endif
template<> struct msvc_eti_base<int>
{
typedef msvc_eti_base type;
typedef msvc_eti_base first;
typedef msvc_eti_base second;
typedef msvc_eti_base tag;
enum { value = 0 };
};
}}}
#endif // BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int a, sum = 0;
for(int i = 0; i < 3; i++){
scanf("%d", &a);
sum = (sum * 10) + a;
}
printf("%s\n", (sum % 4 == 0) ? "YES" : "NO");
return 0;
}
|
// Copyright 2010-2018, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 <algorithm>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/logging.h"
#include "base/port.h"
#include "base/system_util.h"
#include "config/config_handler.h"
#include "converter/quality_regression_util.h"
#include "data_manager/data_manager.h"
#include "engine/engine.h"
#include "protocol/commands.pb.h"
#include "protocol/config.pb.h"
#include "session/request_test_util.h"
#include "testing/base/public/gunit.h"
#include "testing/base/public/mozctest.h"
namespace mozc {
// Test data is provided in external file.
struct TestCase {
const bool enabled;
const char *line;
};
extern TestCase kTestData[];
namespace {
using quality_regression::QualityRegressionUtil;
class QualityRegressionTest : public ::testing::Test {
protected:
static void RunTestForPlatform(uint32 platform, QualityRegressionUtil *util) {
CHECK(util);
std::map<string, std::vector<std::pair<float, string>>> results,
disabled_results;
int num_executed_cases = 0, num_disabled_cases = 0;
for (size_t i = 0; kTestData[i].line; ++i) {
const string &tsv_line = kTestData[i].line;
QualityRegressionUtil::TestItem item;
CHECK(item.ParseFromTSV(tsv_line));
if (!(item.platform & platform)) {
continue;
}
string actual_value;
const bool test_result = util->ConvertAndTest(item, &actual_value);
std::map<string, std::vector<std::pair<float, string>>> *table = nullptr;
if (kTestData[i].enabled) {
++num_executed_cases;
table = &results;
} else {
LOG(INFO) << "DISABLED: " << kTestData[i].line;
++num_disabled_cases;
table = &disabled_results;
}
const string &label = item.label;
string line = tsv_line;
line.append("\tActual: ").append(actual_value);
if (test_result) {
// use "-1.0" as a dummy expected ratio
(*table)[label].push_back(std::make_pair(-1.0, line));
} else {
(*table)[label].push_back(std::make_pair(item.accuracy, line));
}
}
ExamineResults(true, platform, &results);
ExamineResults(false, platform, &disabled_results);
const int total_cases = num_executed_cases + num_disabled_cases;
LOG(INFO) << "Tested " << num_executed_cases << " / "
<< total_cases << " entries.";
}
// If |enabled| parameter is true, then actual conversion results are tested
// and any failure is reported as test failure. If false, actual conversion
// results don't affect test results but closable issues are reported.
static void ExamineResults(
const bool enabled, uint32 platform,
std::map<string, std::vector<std::pair<float, string>>> *results) {
for (auto it = results->begin(); it != results->end(); ++it) {
std::vector<std::pair<float, string>> *values = &it->second;
std::sort(values->begin(), values->end());
size_t correct = 0;
bool all_passed = true;
for (const auto &value : *values) {
const float accuracy = value.first;
if (accuracy < 0) {
++correct;
continue;
}
// Print failed example for failed label
const float actual_ratio = 1.0 * correct / values->size();
if (enabled) {
EXPECT_LT(accuracy, actual_ratio) << value.second
<< " " << accuracy
<< " " << actual_ratio;
} else {
if (accuracy < actual_ratio) {
LOG(INFO) << "PASSED (DISABLED): "
<< it->first << ": " << value.second;
} else {
LOG(INFO) << "FAILED (DISABLED): "
<< it->first << ": " << value.second;
all_passed = false;
}
}
}
LOG(INFO) << "Accuracy: " << it->first << " "
<< 1.0 * correct / values->size();
if (!enabled && all_passed) {
LOG(INFO) << "CLOSED ISSUE [platform = "
<< QualityRegressionUtil::GetPlatformString(platform)
<< "]: " << it->first << " with "
<< it->second.size() << " cases";
}
}
}
private:
const testing::ScopedTmpUserProfileDirectory scoped_profile_dir_;
};
std::unique_ptr<EngineInterface> CreateEngine(const string &data_file_path,
const string &magic_number,
const string &engine_type) {
std::unique_ptr<DataManager> data_manager(new DataManager);
const auto status = data_manager->InitFromFile(data_file_path, magic_number);
if (status != DataManager::Status::OK) {
LOG(ERROR) << "Failed to load " << data_file_path
<< ": " << DataManager::StatusCodeToString(status);
return nullptr;
}
if (engine_type == "desktop") {
return Engine::CreateDesktopEngine(std::move(data_manager));
}
if (engine_type == "mobile") {
return Engine::CreateMobileEngine(std::move(data_manager));
}
LOG(ERROR) << "Invalid engine type: " << engine_type;
return nullptr;
}
} // namespace
} // namespace mozc
|
/* LSOracle: A learning based Oracle for Logic Synthesis
* MIT License
* Copyright 2019 Laboratory for Nano Integrated Systems (LNIS)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <memory>
#include <alice/alice.hpp>
#include <lorina/aiger.hpp>
#include <lorina/blif.hpp>
#include <lorina/verilog.hpp>
#include <mockturtle/mockturtle.hpp>
#include <fmt/format.h>
#include "algorithms/partitioning/partition_manager_junior.hpp"
namespace alice
{
using aig_names = mockturtle::names_view<mockturtle::aig_network>;
using aig_ntk = std::shared_ptr<aig_names>;
using part_man_aig = oracle::partition_manager<aig_names>;
using part_man_aig_ntk = std::shared_ptr<part_man_aig>;
using part_man_jr_aig = oracle::partition_manager_junior<mockturtle::aig_network>;
using part_man_jr_aig_ntk = std::shared_ptr<part_man_jr_aig>;
ALICE_ADD_STORE(aig_ntk, "aig", "a", "aig", "AIGs")
ALICE_DESCRIBE_STORE(aig_ntk, aig)
{
return fmt::format("i/o = {}/{} gates = {}", aig->num_pis(), aig->num_pos(),
aig->num_gates());
}
ALICE_LOG_STORE_STATISTICS(aig_ntk, aig)
{
mockturtle::depth_view depth{*aig};
return {
{"nodes", aig->size()},
{"inputs", aig->num_pis()},
{"latches", aig->num_latches()},
{"outputs", aig->num_pos()},
{"AIG nodes", aig->num_gates()},
{"AIG level", depth.depth()}};
}
ALICE_PRINT_STORE_STATISTICS(aig_ntk, os, aig)
{
mockturtle::depth_view depth{*aig};
os << "nodes: " << aig->size() << std::endl;
os << "inputs: " << aig->num_pis() << std::endl;
os << "latches: " << aig->num_latches() << std::endl;
os << "outputs: " << aig->num_pos() << std::endl;
os << "AIG nodes: " << aig->num_gates() << std::endl;
os << "AIG level: " << depth.depth() << std::endl;
}
ALICE_ADD_STORE(part_man_aig_ntk, "part_man_aig", "pm_a", "part_man_aig",
"PART_MAN_AIGs")
/* Implements the short string to describe a store element in store -a */
ALICE_DESCRIBE_STORE(part_man_aig_ntk, part_man)
{
const auto name = "partition manager for Named MIG networks";
const auto part_num = part_man->get_part_num();
return fmt::format("{} # partitions = {}", name, part_num);
}//end partition manager<mig_network> describe store
ALICE_LOG_STORE_STATISTICS(part_man_aig_ntk, part_man)
{
return {
{"partition number", part_man->get_part_num()}};
}//end partition manager<mig_network> log store statistics
/* Implements the functionality of ps -b */
ALICE_PRINT_STORE_STATISTICS(part_man_aig_ntk, os, part_man)
{
os << "partition number: " << part_man->get_part_num() << std::endl;
}//end partition manager<mig_network> print store statistics
ALICE_ADD_STORE(part_man_jr_aig_ntk, "part_man_jr_aig", "pm_a", "part_man_jr_aig",
"PART_MAN_JR_AIGs")
/* Implements the short string to describe a store element in store -a */
ALICE_DESCRIBE_STORE(part_man_jr_aig_ntk, part_man_jr)
{
const auto name = "partition manager for Named MIG networks";
const auto part_num = part_man_jr->count();
return fmt::format("{} # partitions = {}", name, part_num);
}//end partition manager<mig_network> describe store
ALICE_LOG_STORE_STATISTICS(part_man_jr_aig_ntk, part_man_jr)
{
return {
{"partition number", part_man_jr->count()}};
}//end partition manager<mig_network> log store statistics
/* Implements the functionality of ps -b */
ALICE_PRINT_STORE_STATISTICS(part_man_jr_aig_ntk, os, part_man_jr)
{
os << "partition number: " << part_man_jr->count() << std::endl;
}//end partition manager<mig_network> print store statistics
}
|
#ifndef BOOST_ARCHIVE_OSERIALIZER_HPP
#define BOOST_ARCHIVE_OSERIALIZER_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#pragma inline_depth(511)
#pragma inline_recursion(on)
#endif
#if defined(__MWERKS__)
#pragma inline_depth(511)
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// oserializer.hpp: interface for serialization system.
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <cassert>
#include <cstddef> // NULL
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/throw_exception.hpp>
#include <boost/smart_cast.hpp>
#include <boost/static_assert.hpp>
#include <boost/static_warning.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_enum.hpp>
//#include <boost/type_traits/is_volatile.hpp>
#include <boost/type_traits/is_const.hpp>
//#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
#include <boost/type_traits/remove_extent.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/and.hpp>
//#include <boost/mpl/less.hpp>
#include <boost/mpl/greater_equal.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/identity.hpp>
//#include <boost/mpl/list.hpp>
//#include <boost/mpl/empty.hpp>
#include <boost/mpl/not.hpp>
#ifndef BOOST_SERIALIZATION_DEFAULT_TYPE_INFO
#include <boost/serialization/extended_type_info_typeid.hpp>
#endif
// the following is need only for dynamic cast of polymorphic pointers
#include <boost/archive/detail/basic_oarchive.hpp>
#include <boost/archive/detail/basic_oserializer.hpp>
#include <boost/archive/detail/archive_pointer_oserializer.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/void_cast.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/singleton.hpp>
#include <boost/archive/archive_exception.hpp>
namespace boost {
namespace serialization {
class extended_type_info;
} // namespace serialization
namespace archive {
// an accessor to permit friend access to archives. Needed because
// some compilers don't handle friend templates completely
class save_access {
public:
template<class Archive>
static void end_preamble(Archive & ar){
ar.end_preamble();
}
template<class Archive, class T>
static void save_primitive(Archive & ar, const T & t){
ar.end_preamble();
ar.save(t);
}
};
namespace detail {
template<class Archive, class T>
class oserializer : public basic_oserializer
{
private:
// private constructor to inhibit any existence other than the
// static one
public:
explicit BOOST_DLLEXPORT oserializer() :
basic_oserializer(
boost::serialization::type_info_implementation<T>::type
::get_const_instance()
)
{}
virtual BOOST_DLLEXPORT void save_object_data(
basic_oarchive & ar,
const void *x
) const BOOST_USED;
virtual bool class_info() const {
return boost::serialization::implementation_level<T>::value
>= boost::serialization::object_class_info;
}
virtual bool tracking(const unsigned int /* flags */) const {
return boost::serialization::tracking_level<T>::value == boost::serialization::track_always
|| (boost::serialization::tracking_level<T>::value == boost::serialization::track_selectively
&& serialized_as_pointer());
}
virtual unsigned int version() const {
return ::boost::serialization::version<T>::value;
}
virtual bool is_polymorphic() const {
return boost::is_polymorphic<T>::value;
}
virtual ~oserializer(){}
};
template<class Archive, class T>
BOOST_DLLEXPORT void oserializer<Archive, T>::save_object_data(
basic_oarchive & ar,
const void *x
) const {
// make sure call is routed through the highest interface that might
// be specialized by the user.
BOOST_STATIC_ASSERT(boost::is_const<T>::value == false);
boost::serialization::serialize_adl(
boost::smart_cast_reference<Archive &>(ar),
* static_cast<T *>(const_cast<void *>(x)),
version()
);
}
template<class Archive, class T>
class pointer_oserializer
: public archive_pointer_oserializer<Archive>
{
const basic_oserializer & get_basic_serializer() const;
private:
virtual BOOST_DLLEXPORT void save_object_ptr(
basic_oarchive & ar,
const void * x
) const BOOST_USED;
public:
explicit BOOST_DLLEXPORT pointer_oserializer() BOOST_USED;
};
template<class Archive, class T>
const basic_oserializer &
pointer_oserializer<Archive, T>::get_basic_serializer() const {
return boost::serialization::singleton<
oserializer<Archive, T>
>::get_const_instance();
}
template<class Archive, class T>
BOOST_DLLEXPORT void pointer_oserializer<Archive, T>::save_object_ptr(
basic_oarchive & ar,
const void * x
) const {
assert(NULL != x);
// make sure call is routed through the highest interface that might
// be specialized by the user.
T * t = static_cast<T *>(const_cast<void *>(x));
const unsigned int file_version = boost::serialization::version<T>::value;
Archive & ar_impl = boost::smart_cast_reference<Archive &>(ar);
boost::serialization::save_construct_data_adl<Archive, T>(
ar_impl,
t,
file_version
);
ar_impl << boost::serialization::make_nvp(NULL, * t);
}
template<class Archive, class T>
BOOST_DLLEXPORT pointer_oserializer<Archive, T>::pointer_oserializer() :
archive_pointer_oserializer<Archive>(
boost::serialization::type_info_implementation<T>::type
::get_const_instance()
)
{
// make sure appropriate member function is instantiated
boost::serialization::singleton<
oserializer<Archive, T>
>::get_mutable_instance().set_bpos(this);
}
template<class Archive, class T>
struct save_non_pointer_type {
// note this bounces the call right back to the archive
// with no runtime overhead
struct save_primitive {
static void invoke(Archive & ar, const T & t){
save_access::save_primitive(ar, t);
}
};
// same as above but passes through serialization
struct save_only {
static void invoke(Archive & ar, const T & t){
// make sure call is routed through the highest interface that might
// be specialized by the user.
boost::serialization::serialize_adl(
ar,
const_cast<T &>(t),
::boost::serialization::version<T>::value
);
}
};
// adds class information to the archive. This includes
// serialization level and class version
struct save_standard {
static void invoke(Archive &ar, const T & t){
ar.save_object(
& t,
boost::serialization::singleton<
oserializer<Archive, T>
>::get_const_instance()
);
}
};
// adds class information to the archive. This includes
// serialization level and class version
struct save_conditional {
static void invoke(Archive &ar, const T &t){
//if(0 == (ar.get_flags() & no_tracking))
save_standard::invoke(ar, t);
//else
// save_only::invoke(ar, t);
}
};
typedef
BOOST_DEDUCED_TYPENAME mpl::eval_if<
// if its primitive
mpl::equal_to<
boost::serialization::implementation_level<T>,
mpl::int_<boost::serialization::primitive_type>
>,
mpl::identity<save_primitive>,
// else
BOOST_DEDUCED_TYPENAME mpl::eval_if<
// class info / version
mpl::greater_equal<
boost::serialization::implementation_level<T>,
mpl::int_<boost::serialization::object_class_info>
>,
// do standard save
mpl::identity<save_standard>,
// else
BOOST_DEDUCED_TYPENAME mpl::eval_if<
// no tracking
mpl::equal_to<
boost::serialization::tracking_level<T>,
mpl::int_<boost::serialization::track_never>
>,
// do a fast save
mpl::identity<save_only>,
// else
// do a fast save only tracking is turned off
mpl::identity<save_conditional>
> > >::type typex;
static void invoke(Archive & ar, const T & t){
// check that we're not trying to serialize something that
// has been marked not to be serialized. If this your program
// traps here, you've tried to serialize a class whose trait
// has been marked "non-serializable". Either reset the trait
// (see level.hpp) or change program not to serialize items of this class
BOOST_STATIC_ASSERT((
mpl::greater_equal<
boost::serialization::implementation_level<T>,
mpl::int_<boost::serialization::primitive_type>
>::value
));
typex::invoke(ar, t);
};
};
template<class Archive, class TPtr>
struct save_pointer_type {
template<class T>
struct abstract
{
static const basic_pointer_oserializer * register_type(Archive & /* ar */){
// it has? to be polymorphic
BOOST_STATIC_ASSERT(boost::is_polymorphic<T>::value);
return NULL;
}
};
template<class T>
struct non_abstract
{
static const basic_pointer_oserializer * register_type(Archive & ar){
return ar.register_type(static_cast<T *>(NULL));
}
};
template<class T>
static const basic_pointer_oserializer * register_type(Archive &ar, T & /*t*/){
// there should never be any need to save an abstract polymorphic
// class pointer. Inhibiting code generation for this
// permits abstract base classes to be used - note: exception
// virtual serialize functions used for plug-ins
typedef
BOOST_DEDUCED_TYPENAME mpl::eval_if<
boost::serialization::is_abstract<T>,
mpl::identity<abstract<T> >,
mpl::identity<non_abstract<T> >
>::type typex;
return typex::register_type(ar);
}
template<class T>
struct non_polymorphic
{
static void save(
Archive &ar,
T & t
){
const basic_pointer_oserializer & bpos =
boost::serialization::singleton<
pointer_oserializer<Archive, T>
>::get_const_instance();
// save the requested pointer type
ar.save_pointer(& t, & bpos);
}
};
template<class T>
struct polymorphic
{
static void save(
Archive &ar,
T & t
){
BOOST_DEDUCED_TYPENAME
boost::serialization::type_info_implementation<T>::type const
& i = boost::serialization::type_info_implementation<T>::type
::get_const_instance();
boost::serialization::extended_type_info const * const this_type = & i;
// retrieve the true type of the object pointed to
// if this assertion fails its an error in this library
assert(NULL != this_type);
const boost::serialization::extended_type_info * true_type =
i.get_derived_extended_type_info(t);
// note:if this exception is thrown, be sure that derived pointer
// is either registered or exported.
if(NULL == true_type){
boost::throw_exception(
archive_exception(archive_exception::unregistered_class)
);
}
// if its not a pointer to a more derived type
const void *vp = static_cast<const void *>(&t);
if(*this_type == *true_type){
const basic_pointer_oserializer * bpos = register_type(ar, t);
ar.save_pointer(vp, bpos);
return;
}
// convert pointer to more derived type. if this is thrown
// it means that the base/derived relationship hasn't be registered
vp = serialization::void_downcast(
*true_type,
*this_type,
static_cast<const void *>(&t)
);
if(NULL == vp){
boost::throw_exception(
archive_exception(archive_exception::unregistered_cast)
);
}
// since true_type is valid, and this only gets made if the
// pointer oserializer object has been created, this should never
// fail
const basic_pointer_oserializer * bpos
= archive_pointer_oserializer<Archive>::find(* true_type);
assert(NULL != bpos);
if(NULL == bpos)
boost::throw_exception(
archive_exception(archive_exception::unregistered_class)
);
ar.save_pointer(vp, bpos);
}
};
// out of line selector works around borland quirk
template<class T>
struct conditional {
typedef BOOST_DEDUCED_TYPENAME mpl::eval_if<
is_polymorphic<T>,
mpl::identity<polymorphic<T> >,
mpl::identity<non_polymorphic<T> >
>::type type;
};
// used to convert TPtr in to a pointer to a T
template<class T>
static void save(
Archive & ar,
const T & t
){
conditional<T>::type::save(ar, const_cast<T &>(t));
}
template<class T>
static void const_check(T & t){
BOOST_STATIC_ASSERT(! boost::is_const<T>::value);
}
static void invoke(Archive &ar, const TPtr t){
#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// if your program traps here, its because you tried to do
// something like ar << t where t is a pointer to a const value
// void f3(A const* a, text_oarchive& oa)
// {
// oa << a;
// }
// with a compiler which doesn't support remove_const
// const_check(* t);
#else
// otherwise remove the const
#endif
register_type(ar, * t);
if(NULL == t){
basic_oarchive & boa = boost::smart_cast_reference<basic_oarchive &>(ar);
boa.save_null_pointer();
save_access::end_preamble(ar);
return;
}
save(ar, * t);
};
};
template<class Archive, class T>
struct save_enum_type
{
static void invoke(Archive &ar, const T &t){
// convert enum to integers on save
const int i = static_cast<int>(t);
ar << boost::serialization::make_nvp(NULL, i);
}
};
template<class Archive, class T>
struct save_array_type
{
static void invoke(Archive &ar, const T &t){
typedef BOOST_DEDUCED_TYPENAME boost::remove_extent<T>::type value_type;
save_access::end_preamble(ar);
// consider alignment
int count = sizeof(t) / (
static_cast<const char *>(static_cast<const void *>(&t[1]))
- static_cast<const char *>(static_cast<const void *>(&t[0]))
);
ar << BOOST_SERIALIZATION_NVP(count);
ar << serialization::make_array(static_cast<value_type const*>(&t[0]),count);
}
};
} // detail
template<class Archive, class T>
inline void save(Archive & ar, const T &t){
typedef
BOOST_DEDUCED_TYPENAME mpl::eval_if<is_pointer<T>,
mpl::identity<detail::save_pointer_type<Archive, T> >,
//else
BOOST_DEDUCED_TYPENAME mpl::eval_if<is_enum<T>,
mpl::identity<detail::save_enum_type<Archive, T> >,
//else
BOOST_DEDUCED_TYPENAME mpl::eval_if<is_array<T>,
mpl::identity<detail::save_array_type<Archive, T> >,
//else
mpl::identity<detail::save_non_pointer_type<Archive, T> >
>
>
>::type typex;
typex::invoke(ar, t);
}
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<class T>
struct check_tracking {
typedef BOOST_DEDUCED_TYPENAME mpl::if_<
// if its never tracked.
BOOST_DEDUCED_TYPENAME mpl::equal_to<
serialization::tracking_level<T>,
mpl::int_<serialization::track_never>
>,
// it better not be a pointer
mpl::not_<is_pointer<T> >,
//else
// otherwise if it might be tracked. So there shouldn't
// be any problem making a const
is_const<T>
>::type typex;
BOOST_STATIC_CONSTANT(bool, value = typex::value);
};
template<class Archive, class T>
inline void save(Archive & ar, T &t){
// if your program traps here, it indicates that your doing one of the following:
// a) serializing an object of a type marked "track_never" through a pointer.
// b) saving an non-const object of a type not markd "track_never)
// Either of these conditions may be an indicator of an error usage of the
// serialization library and should be double checked. See documentation on
// object tracking. Also, see the "rationale" section of the documenation
// for motivation for this checking.
BOOST_STATIC_WARNING(check_tracking<T>::value);
save(ar, const_cast<const T &>(t));
}
#endif
} // namespace archive
} // namespace boost
#endif // BOOST_ARCHIVE_OSERIALIZER_HPP
|
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/iomgr/socket_mutator.h"
#include "src/core/lib/channel/channel_args.h"
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/sync.h>
#include <grpc/support/useful.h>
void grpc_socket_mutator_init(grpc_socket_mutator* mutator,
const grpc_socket_mutator_vtable* vtable) {
mutator->vtable = vtable;
gpr_ref_init(&mutator->refcount, 1);
}
grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator) {
gpr_ref(&mutator->refcount);
return mutator;
}
bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd) {
return mutator->vtable->mutate_fd(fd, mutator);
}
int grpc_socket_mutator_compare(grpc_socket_mutator* a,
grpc_socket_mutator* b) {
int c = GPR_ICMP(a, b);
if (c != 0) {
grpc_socket_mutator* sma = a;
grpc_socket_mutator* smb = b;
c = GPR_ICMP(sma->vtable, smb->vtable);
if (c == 0) {
c = sma->vtable->compare(sma, smb);
}
}
return c;
}
void grpc_socket_mutator_unref(grpc_socket_mutator* mutator) {
if (gpr_unref(&mutator->refcount)) {
mutator->vtable->destory(mutator);
}
}
static void* socket_mutator_arg_copy(void* p) {
return grpc_socket_mutator_ref((grpc_socket_mutator*)p);
}
static void socket_mutator_arg_destroy(grpc_exec_ctx* exec_ctx, void* p) {
grpc_socket_mutator_unref((grpc_socket_mutator*)p);
}
static int socket_mutator_cmp(void* a, void* b) {
return grpc_socket_mutator_compare((grpc_socket_mutator*)a,
(grpc_socket_mutator*)b);
}
static const grpc_arg_pointer_vtable socket_mutator_arg_vtable = {
socket_mutator_arg_copy, socket_mutator_arg_destroy, socket_mutator_cmp};
grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator) {
return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_MUTATOR,
mutator, &socket_mutator_arg_vtable);
}
|
#include <iostream>
#include <twinkle/twinkle.h>
using namespace std;
using namespace twinkle;
void client_main();
void server_main();
#define SERVER_PORT 9670
#define CLIENT_PORT 9000
int main()
{
twinkle::startup();
int choice = 0;
cout << "UDP Chat [0: Server, 1: Client]: ";
cin >> choice;
if (choice == 0)
server_main();
else client_main();
cout << "Premi un tasto per continuare...";
getchar();
twinkle::shutdown();
return 0;
}
void client_main()
{
UDPSocket sock({ Address::localAddress, CLIENT_PORT });
if (sock.isValid())
{
if (sock.bind())
{
cout << "Socket binded successfully!" << endl;
std::string message{};
Address fromAddress{};
if (sock.receive(message, fromAddress))
{
cout << "Message: " << message << endl;
}
else cout << "Unable to receive a message" << endl;
}
else
{
cout << "Invalid socket binding: " << twinkle::getErrorMessage() << endl;
}
}
else
{
cout << "Invalid socket creation: " << twinkle::getErrorMessage() << endl;
}
}
void server_main()
{
UDPSocket sock({ Address::localAddress, SERVER_PORT });
if (sock.isValid())
{
if (sock.bind())
{
cout << "Socket binded successfully!" << endl;
cout << "Press to send a message...";
getchar();
if (sock.send("ciao mondo", { Address::localAddress, CLIENT_PORT }))
{
cout << "Message sent!" << endl;
}
else cout << "Unable to send the message" << endl;
}
else
{
cout << "Invalid socket binding: " << twinkle::getErrorMessage() << endl;
}
}
else
{
cout << "Invalid socket creation: " << twinkle::getErrorMessage() << endl;
}
}
|
/* Generated by Cython 0.29.17 */
/* BEGIN: Cython Metadata
{
"distutils": {
"depends": [
"ssa_translation_c_w_lowmem_nostats.h"
],
"language": "c++",
"name": "ssa_translation_lowmem_nostats",
"sources": [
"ssa_translation_lowmem_nostats.pyx"
]
},
"module_name": "ssa_translation_lowmem_nostats"
}
END: Cython Metadata */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#ifndef Py_PYTHON_H
#error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)
#error Cython requires Python 2.6+ or Python 3.3+.
#else
#define CYTHON_ABI "0_29_17"
#define CYTHON_HEX_VERSION 0x001D11F0
#define CYTHON_FUTURE_DIVISION 0
#include <stddef.h>
#ifndef offsetof
#define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
#ifndef DL_IMPORT
#define DL_IMPORT(t) t
#endif
#ifndef DL_EXPORT
#define DL_EXPORT(t) t
#endif
#define __PYX_COMMA ,
#ifndef HAVE_LONG_LONG
#if PY_VERSION_HEX >= 0x02070000
#define HAVE_LONG_LONG
#endif
#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG LONG_LONG
#endif
#ifndef Py_HUGE_VAL
#define Py_HUGE_VAL HUGE_VAL
#endif
#ifdef PYPY_VERSION
#define CYTHON_COMPILING_IN_PYPY 1
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 0
#undef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 0
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#if PY_VERSION_HEX < 0x03050000
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#undef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#undef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 1
#undef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 0
#undef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 0
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#undef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT 0
#undef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 0
#undef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS 0
#undef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK 0
#elif defined(PYSTON_VERSION)
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 1
#define CYTHON_COMPILING_IN_CPYTHON 0
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#undef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT 0
#undef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 0
#undef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS 0
#undef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK 0
#else
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 1
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#elif !defined(CYTHON_USE_PYTYPE_LOOKUP)
#define CYTHON_USE_PYTYPE_LOOKUP 1
#endif
#if PY_MAJOR_VERSION < 3
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#elif !defined(CYTHON_USE_PYLONG_INTERNALS)
#define CYTHON_USE_PYLONG_INTERNALS 1
#endif
#ifndef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 1
#endif
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#if PY_VERSION_HEX < 0x030300F0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#elif !defined(CYTHON_USE_UNICODE_WRITER)
#define CYTHON_USE_UNICODE_WRITER 1
#endif
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#ifndef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 1
#endif
#ifndef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 1
#endif
#ifndef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000)
#endif
#ifndef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1)
#endif
#ifndef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1)
#endif
#ifndef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3)
#endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#undef SHIFT
#undef BASE
#undef MASK
#ifdef SIZEOF_VOID_P
enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) };
#endif
#endif
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
#ifndef CYTHON_RESTRICT
#if defined(__GNUC__)
#define CYTHON_RESTRICT __restrict__
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define CYTHON_RESTRICT __restrict
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_RESTRICT restrict
#else
#define CYTHON_RESTRICT
#endif
#endif
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
#endif
#ifndef CYTHON_MAYBE_UNUSED_VAR
# if defined(__cplusplus)
template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
# else
# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
# endif
#endif
#ifndef CYTHON_NCP_UNUSED
# if CYTHON_COMPILING_IN_CPYTHON
# define CYTHON_NCP_UNUSED
# else
# define CYTHON_NCP_UNUSED CYTHON_UNUSED
# endif
#endif
#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
#ifdef _MSC_VER
#ifndef _MSC_STDINT_H_
#if _MSC_VER < 1300
typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
#else
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
#endif
#endif
#else
#include <stdint.h>
#endif
#ifndef CYTHON_FALLTHROUGH
#if defined(__cplusplus) && __cplusplus >= 201103L
#if __has_cpp_attribute(fallthrough)
#define CYTHON_FALLTHROUGH [[fallthrough]]
#elif __has_cpp_attribute(clang::fallthrough)
#define CYTHON_FALLTHROUGH [[clang::fallthrough]]
#elif __has_cpp_attribute(gnu::fallthrough)
#define CYTHON_FALLTHROUGH [[gnu::fallthrough]]
#endif
#endif
#ifndef CYTHON_FALLTHROUGH
#if __has_attribute(fallthrough)
#define CYTHON_FALLTHROUGH __attribute__((fallthrough))
#else
#define CYTHON_FALLTHROUGH
#endif
#endif
#if defined(__clang__ ) && defined(__apple_build_version__)
#if __apple_build_version__ < 7000000
#undef CYTHON_FALLTHROUGH
#define CYTHON_FALLTHROUGH
#endif
#endif
#endif
#ifndef __cplusplus
#error "Cython files generated with the C++ option must be compiled with a C++ compiler."
#endif
#ifndef CYTHON_INLINE
#if defined(__clang__)
#define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
#else
#define CYTHON_INLINE inline
#endif
#endif
template<typename T>
void __Pyx_call_destructor(T& x) {
x.~T();
}
template<typename T>
class __Pyx_FakeReference {
public:
__Pyx_FakeReference() : ptr(NULL) { }
__Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { }
T *operator->() { return ptr; }
T *operator&() { return ptr; }
operator T&() { return *ptr; }
template<typename U> bool operator ==(U other) { return *ptr == other; }
template<typename U> bool operator !=(U other) { return *ptr != other; }
private:
T *ptr;
};
#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
#define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#if PY_MAJOR_VERSION < 3
#define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyClass_Type
#else
#define __Pyx_BUILTIN_MODULE_NAME "builtins"
#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#else
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#endif
#define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
#define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
#define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#ifndef METH_STACKLESS
#define METH_STACKLESS 0
#endif
#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL)
#ifndef METH_FASTCALL
#define METH_FASTCALL 0x80
#endif
typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs);
typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args,
Py_ssize_t nargs, PyObject *kwnames);
#else
#define __Pyx_PyCFunctionFast _PyCFunctionFast
#define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)))))
#else
#define __Pyx_PyFastCFunction_Check(func) 0
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
#define PyObject_Malloc(s) PyMem_Malloc(s)
#define PyObject_Free(p) PyMem_Free(p)
#define PyObject_Realloc(p) PyMem_Realloc(p)
#endif
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1
#define PyMem_RawMalloc(n) PyMem_Malloc(n)
#define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n)
#define PyMem_RawFree(p) PyMem_Free(p)
#endif
#if CYTHON_COMPILING_IN_PYSTON
#define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
#else
#define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
#endif
#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000
#define __Pyx_PyThreadState_Current PyThreadState_GET()
#elif PY_VERSION_HEX >= 0x03060000
#define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet()
#elif PY_VERSION_HEX >= 0x03000000
#define __Pyx_PyThreadState_Current PyThreadState_GET()
#else
#define __Pyx_PyThreadState_Current _PyThreadState_Current
#endif
#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT)
#include "pythread.h"
#define Py_tss_NEEDS_INIT 0
typedef int Py_tss_t;
static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) {
*key = PyThread_create_key();
return 0;
}
static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) {
Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t));
*key = Py_tss_NEEDS_INIT;
return key;
}
static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) {
PyObject_Free(key);
}
static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) {
return *key != Py_tss_NEEDS_INIT;
}
static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) {
PyThread_delete_key(*key);
*key = Py_tss_NEEDS_INIT;
}
static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) {
return PyThread_set_key_value(*key, value);
}
static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) {
return PyThread_get_key_value(*key);
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized)
#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n))
#else
#define __Pyx_PyDict_NewPresized(n) PyDict_New()
#endif
#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION
#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y)
#else
#define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y)
#endif
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS
#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash)
#else
#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name)
#endif
#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
#define CYTHON_PEP393_ENABLED 1
#define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\
0 : _PyUnicode_Ready((PyObject *)(op)))
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u)
#define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u)
#define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u)
#define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i)
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
#else
#define CYTHON_PEP393_ENABLED 0
#define PyUnicode_1BYTE_KIND 1
#define PyUnicode_2BYTE_KIND 2
#define PyUnicode_4BYTE_KIND 4
#define __Pyx_PyUnicode_READY(op) (0)
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
#define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE))
#define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u))
#define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u))
#endif
#if CYTHON_COMPILING_IN_PYPY
#define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b)
#else
#define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\
PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
#define PyUnicode_Contains(u, s) PySequence_Contains(u, s)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
#define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
#define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt)
#endif
#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b)
#else
#define __Pyx_PyString_Format(a, b) PyString_Format(a, b)
#endif
#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII)
#define PyObject_ASCII(o) PyObject_Repr(o)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBaseString_Type PyUnicode_Type
#define PyStringObject PyUnicodeObject
#define PyString_Type PyUnicode_Type
#define PyString_Check PyUnicode_Check
#define PyString_CheckExact PyUnicode_CheckExact
#ifndef PyObject_Unicode
#define PyObject_Unicode PyObject_Str
#endif
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
#define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
#else
#define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj))
#define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#ifndef PySet_CheckExact
#define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
#endif
#if CYTHON_ASSUME_SAFE_MACROS
#define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq)
#else
#define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyIntObject PyLongObject
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define PyNumber_Int PyNumber_Long
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBoolObject PyLongObject
#endif
#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
#ifndef PyUnicode_InternFromString
#define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
#endif
#endif
#if PY_VERSION_HEX < 0x030200A4
typedef long Py_hash_t;
#define __Pyx_PyInt_FromHash_t PyInt_FromLong
#define __Pyx_PyInt_AsHash_t PyInt_AsLong
#else
#define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
#define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : (Py_INCREF(func), func))
#else
#define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
#endif
#if CYTHON_USE_ASYNC_SLOTS
#if PY_VERSION_HEX >= 0x030500B1
#define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
#define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
#else
#define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
#endif
#else
#define __Pyx_PyType_AsAsync(obj) NULL
#endif
#ifndef __Pyx_PyAsyncMethodsStruct
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
} __Pyx_PyAsyncMethodsStruct;
#endif
#if defined(WIN32) || defined(MS_WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
float value;
memset(&value, 0xFF, sizeof(value));
return value;
}
#endif
#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
#define __Pyx_truncl trunc
#else
#define __Pyx_truncl truncl
#endif
#define __PYX_ERR(f_index, lineno, Ln_error) \
{ \
__pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \
}
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#define __PYX_HAVE__ssa_translation_lowmem_nostats
#define __PYX_HAVE_API__ssa_translation_lowmem_nostats
/* Early includes */
#include <string.h>
#include <stdio.h>
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
#include "ssa_translation_c_w_lowmem_nostats.h"
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)
#define CYTHON_WITHOUT_ASSERTIONS
#endif
typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;
#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8)
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_uchar_cast(c) ((unsigned char)c)
#define __Pyx_long_cast(x) ((long)x)
#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\
(sizeof(type) < sizeof(Py_ssize_t)) ||\
(sizeof(type) > sizeof(Py_ssize_t) &&\
likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX) &&\
(!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\
v == (type)PY_SSIZE_T_MIN))) ||\
(sizeof(type) == sizeof(Py_ssize_t) &&\
(is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX))) )
static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) {
return (size_t) i < (size_t) limit;
}
#if defined (__cplusplus) && __cplusplus >= 201103L
#include <cstdlib>
#define __Pyx_sst_abs(value) std::abs(value)
#elif SIZEOF_INT >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) abs(value)
#elif SIZEOF_LONG >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) labs(value)
#elif defined (_MSC_VER)
#define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value))
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_sst_abs(value) llabs(value)
#elif defined (__GNUC__)
#define __Pyx_sst_abs(value) __builtin_llabs(value)
#else
#define __Pyx_sst_abs(value) ((value<0) ? -value : value)
#endif
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
#define __Pyx_PyBytes_FromString PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*);
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#else
#define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
#endif
#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s))
#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s)
#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s)
#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s)
#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s)
#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) {
const Py_UNICODE *u_end = u;
while (*u_end++) ;
return (size_t)(u_end - u - 1);
}
#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode
#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj)
#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b);
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
#define __Pyx_PySequence_Tuple(obj)\
(likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj))
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_ASSUME_SAFE_MACROS
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#else
#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
#endif
#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
#else
#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
#endif
#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x))
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
static int __Pyx_sys_getdefaultencoding_not_ascii;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
PyObject* ascii_chars_u = NULL;
PyObject* ascii_chars_b = NULL;
const char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
if (strcmp(default_encoding_c, "ascii") == 0) {
__Pyx_sys_getdefaultencoding_not_ascii = 0;
} else {
char ascii_chars[128];
int c;
for (c = 0; c < 128; c++) {
ascii_chars[c] = c;
}
__Pyx_sys_getdefaultencoding_not_ascii = 1;
ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
if (!ascii_chars_u) goto bad;
ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
PyErr_Format(
PyExc_ValueError,
"This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
default_encoding_c);
goto bad;
}
Py_DECREF(ascii_chars_u);
Py_DECREF(ascii_chars_b);
}
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
Py_XDECREF(ascii_chars_u);
Py_XDECREF(ascii_chars_b);
return -1;
}
#endif
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
#else
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
static char* __PYX_DEFAULT_STRING_ENCODING;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
__PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1);
if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
return -1;
}
#endif
#endif
/* Test for GCC > 2.95 */
#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* !__GNUC__ or GCC < 2.95 */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }
static PyObject *__pyx_m = NULL;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_cython_runtime = NULL;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static PyObject *__pyx_empty_unicode;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;
/* Header.proto */
#if !defined(CYTHON_CCOMPLEX)
#if defined(__cplusplus)
#define CYTHON_CCOMPLEX 1
#elif defined(_Complex_I)
#define CYTHON_CCOMPLEX 1
#else
#define CYTHON_CCOMPLEX 0
#endif
#endif
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
#include <complex>
#else
#include <complex.h>
#endif
#endif
#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
#undef _Complex_I
#define _Complex_I 1.0fj
#endif
static const char *__pyx_f[] = {
"ssa_translation_lowmem_nostats.pyx",
"__init__.pxd",
"type.pxd",
};
/* BufferFormatStructs.proto */
#define IS_UNSIGNED(type) (((type) -1) > 0)
struct __Pyx_StructField_;
#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0)
typedef struct {
const char* name;
struct __Pyx_StructField_* fields;
size_t size;
size_t arraysize[8];
int ndim;
char typegroup;
char is_unsigned;
int flags;
} __Pyx_TypeInfo;
typedef struct __Pyx_StructField_ {
__Pyx_TypeInfo* type;
const char* name;
size_t offset;
} __Pyx_StructField;
typedef struct {
__Pyx_StructField* field;
size_t parent_offset;
} __Pyx_BufFmt_StackElem;
typedef struct {
__Pyx_StructField root;
__Pyx_BufFmt_StackElem* head;
size_t fmt_offset;
size_t new_count, enc_count;
size_t struct_alignment;
int is_complex;
char enc_type;
char new_packmode;
char enc_packmode;
char is_valid_array;
} __Pyx_BufFmt_Context;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":776
* # in Cython to enable them only on the right systems.
*
* ctypedef npy_int8 int8_t # <<<<<<<<<<<<<<
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t
*/
typedef npy_int8 __pyx_t_5numpy_int8_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":777
*
* ctypedef npy_int8 int8_t
* ctypedef npy_int16 int16_t # <<<<<<<<<<<<<<
* ctypedef npy_int32 int32_t
* ctypedef npy_int64 int64_t
*/
typedef npy_int16 __pyx_t_5numpy_int16_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":778
* ctypedef npy_int8 int8_t
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t # <<<<<<<<<<<<<<
* ctypedef npy_int64 int64_t
* #ctypedef npy_int96 int96_t
*/
typedef npy_int32 __pyx_t_5numpy_int32_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":779
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t
* ctypedef npy_int64 int64_t # <<<<<<<<<<<<<<
* #ctypedef npy_int96 int96_t
* #ctypedef npy_int128 int128_t
*/
typedef npy_int64 __pyx_t_5numpy_int64_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":783
* #ctypedef npy_int128 int128_t
*
* ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<<
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t
*/
typedef npy_uint8 __pyx_t_5numpy_uint8_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":784
*
* ctypedef npy_uint8 uint8_t
* ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<<
* ctypedef npy_uint32 uint32_t
* ctypedef npy_uint64 uint64_t
*/
typedef npy_uint16 __pyx_t_5numpy_uint16_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":785
* ctypedef npy_uint8 uint8_t
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<<
* ctypedef npy_uint64 uint64_t
* #ctypedef npy_uint96 uint96_t
*/
typedef npy_uint32 __pyx_t_5numpy_uint32_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":786
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t
* ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<<
* #ctypedef npy_uint96 uint96_t
* #ctypedef npy_uint128 uint128_t
*/
typedef npy_uint64 __pyx_t_5numpy_uint64_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":790
* #ctypedef npy_uint128 uint128_t
*
* ctypedef npy_float32 float32_t # <<<<<<<<<<<<<<
* ctypedef npy_float64 float64_t
* #ctypedef npy_float80 float80_t
*/
typedef npy_float32 __pyx_t_5numpy_float32_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":791
*
* ctypedef npy_float32 float32_t
* ctypedef npy_float64 float64_t # <<<<<<<<<<<<<<
* #ctypedef npy_float80 float80_t
* #ctypedef npy_float128 float128_t
*/
typedef npy_float64 __pyx_t_5numpy_float64_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":800
* # The int types are mapped a bit surprising --
* # numpy.int corresponds to 'l' and numpy.long to 'q'
* ctypedef npy_long int_t # <<<<<<<<<<<<<<
* ctypedef npy_longlong long_t
* ctypedef npy_longlong longlong_t
*/
typedef npy_long __pyx_t_5numpy_int_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":801
* # numpy.int corresponds to 'l' and numpy.long to 'q'
* ctypedef npy_long int_t
* ctypedef npy_longlong long_t # <<<<<<<<<<<<<<
* ctypedef npy_longlong longlong_t
*
*/
typedef npy_longlong __pyx_t_5numpy_long_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":802
* ctypedef npy_long int_t
* ctypedef npy_longlong long_t
* ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<<
*
* ctypedef npy_ulong uint_t
*/
typedef npy_longlong __pyx_t_5numpy_longlong_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":804
* ctypedef npy_longlong longlong_t
*
* ctypedef npy_ulong uint_t # <<<<<<<<<<<<<<
* ctypedef npy_ulonglong ulong_t
* ctypedef npy_ulonglong ulonglong_t
*/
typedef npy_ulong __pyx_t_5numpy_uint_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":805
*
* ctypedef npy_ulong uint_t
* ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<<
* ctypedef npy_ulonglong ulonglong_t
*
*/
typedef npy_ulonglong __pyx_t_5numpy_ulong_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":806
* ctypedef npy_ulong uint_t
* ctypedef npy_ulonglong ulong_t
* ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<<
*
* ctypedef npy_intp intp_t
*/
typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":808
* ctypedef npy_ulonglong ulonglong_t
*
* ctypedef npy_intp intp_t # <<<<<<<<<<<<<<
* ctypedef npy_uintp uintp_t
*
*/
typedef npy_intp __pyx_t_5numpy_intp_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":809
*
* ctypedef npy_intp intp_t
* ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<<
*
* ctypedef npy_double float_t
*/
typedef npy_uintp __pyx_t_5numpy_uintp_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":811
* ctypedef npy_uintp uintp_t
*
* ctypedef npy_double float_t # <<<<<<<<<<<<<<
* ctypedef npy_double double_t
* ctypedef npy_longdouble longdouble_t
*/
typedef npy_double __pyx_t_5numpy_float_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":812
*
* ctypedef npy_double float_t
* ctypedef npy_double double_t # <<<<<<<<<<<<<<
* ctypedef npy_longdouble longdouble_t
*
*/
typedef npy_double __pyx_t_5numpy_double_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":813
* ctypedef npy_double float_t
* ctypedef npy_double double_t
* ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<<
*
* ctypedef npy_cfloat cfloat_t
*/
typedef npy_longdouble __pyx_t_5numpy_longdouble_t;
/* Declarations.proto */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
typedef ::std::complex< float > __pyx_t_float_complex;
#else
typedef float _Complex __pyx_t_float_complex;
#endif
#else
typedef struct { float real, imag; } __pyx_t_float_complex;
#endif
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float);
/* Declarations.proto */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
typedef ::std::complex< double > __pyx_t_double_complex;
#else
typedef double _Complex __pyx_t_double_complex;
#endif
#else
typedef struct { double real, imag; } __pyx_t_double_complex;
#endif
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double);
/*--- Type declarations ---*/
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":815
* ctypedef npy_longdouble longdouble_t
*
* ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<<
* ctypedef npy_cdouble cdouble_t
* ctypedef npy_clongdouble clongdouble_t
*/
typedef npy_cfloat __pyx_t_5numpy_cfloat_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":816
*
* ctypedef npy_cfloat cfloat_t
* ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<<
* ctypedef npy_clongdouble clongdouble_t
*
*/
typedef npy_cdouble __pyx_t_5numpy_cdouble_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":817
* ctypedef npy_cfloat cfloat_t
* ctypedef npy_cdouble cdouble_t
* ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<<
*
* ctypedef npy_cdouble complex_t
*/
typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":819
* ctypedef npy_clongdouble clongdouble_t
*
* ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew1(a):
*/
typedef npy_cdouble __pyx_t_5numpy_complex_t;
/* --- Runtime support code (head) --- */
/* Refnanny.proto */
#ifndef CYTHON_REFNANNY
#define CYTHON_REFNANNY 0
#endif
#if CYTHON_REFNANNY
typedef struct {
void (*INCREF)(void*, PyObject*, int);
void (*DECREF)(void*, PyObject*, int);
void (*GOTREF)(void*, PyObject*, int);
void (*GIVEREF)(void*, PyObject*, int);
void* (*SetupContext)(const char*, int, const char*);
void (*FinishContext)(void**);
} __Pyx_RefNannyAPIStruct;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname);
#define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
#ifdef WITH_THREAD
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
if (acquire_gil) {\
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
PyGILState_Release(__pyx_gilstate_save);\
} else {\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
}
#else
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#endif
#define __Pyx_RefNannyFinishContext()\
__Pyx_RefNanny->FinishContext(&__pyx_refnanny)
#define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
#define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
#define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
#define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
#else
#define __Pyx_RefNannyDeclarations
#define __Pyx_RefNannySetupContext(name, acquire_gil)
#define __Pyx_RefNannyFinishContext()
#define __Pyx_INCREF(r) Py_INCREF(r)
#define __Pyx_DECREF(r) Py_DECREF(r)
#define __Pyx_GOTREF(r)
#define __Pyx_GIVEREF(r)
#define __Pyx_XINCREF(r) Py_XINCREF(r)
#define __Pyx_XDECREF(r) Py_XDECREF(r)
#define __Pyx_XGOTREF(r)
#define __Pyx_XGIVEREF(r)
#endif
#define __Pyx_XDECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_XDECREF(tmp);\
} while (0)
#define __Pyx_DECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_DECREF(tmp);\
} while (0)
#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)
/* RaiseArgTupleInvalid.proto */
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found);
/* RaiseDoubleKeywords.proto */
static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name);
/* ParseKeywords.proto */
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\
PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\
const char* function_name);
/* ArgTypeTest.proto */
#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\
((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\
__Pyx__ArgTypeTest(obj, type, name, exact))
static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact);
/* IsLittleEndian.proto */
static CYTHON_INLINE int __Pyx_Is_Little_Endian(void);
/* BufferFormatCheck.proto */
static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts);
static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
__Pyx_BufFmt_StackElem* stack,
__Pyx_TypeInfo* type);
/* BufferGetAndValidate.proto */
#define __Pyx_GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)\
((obj == Py_None || obj == NULL) ?\
(__Pyx_ZeroBuffer(buf), 0) :\
__Pyx__GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack))
static int __Pyx__GetBufferAndValidate(Py_buffer* buf, PyObject* obj,
__Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack);
static void __Pyx_ZeroBuffer(Py_buffer* buf);
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info);
static Py_ssize_t __Pyx_minusones[] = { -1, -1, -1, -1, -1, -1, -1, -1 };
static Py_ssize_t __Pyx_zeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0)
#define __Pyx_BufPtrCContig2d(type, buf, i0, s0, i1, s1) ((type)((char*)buf + i0 * s0) + i1)
/* PyThreadStateGet.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate;
#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current;
#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type
#else
#define __Pyx_PyThreadState_declare
#define __Pyx_PyThreadState_assign
#define __Pyx_PyErr_Occurred() PyErr_Occurred()
#endif
/* PyErrFetchRestore.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL)
#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb)
#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#if CYTHON_COMPILING_IN_CPYTHON
#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL))
#else
#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
#endif
#else
#define __Pyx_PyErr_Clear() PyErr_Clear()
#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb)
#endif
/* PyObjectGetAttrStr.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name);
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif
/* GetBuiltinName.proto */
static PyObject *__Pyx_GetBuiltinName(PyObject *name);
/* PyObjectCall.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif
/* RaiseException.proto */
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause);
/* PyCFunctionFastCall.proto */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs);
#else
#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL)
#endif
/* PyFunctionFastCall.proto */
#if CYTHON_FAST_PYCALL
#define __Pyx_PyFunction_FastCall(func, args, nargs)\
__Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL)
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs);
#else
#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs)
#endif
#define __Pyx_BUILD_ASSERT_EXPR(cond)\
(sizeof(char [1 - 2*!(cond)]) - 1)
#ifndef Py_MEMBER_SIZE
#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
#endif
static size_t __pyx_pyframe_localsplus_offset = 0;
#include "frameobject.h"
#define __Pxy_PyFrame_Initialize_Offsets()\
((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\
(void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus)))
#define __Pyx_PyFrame_GetLocalsplus(frame)\
(assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset))
#endif
/* PyObjectCallMethO.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg);
#endif
/* PyObjectCallOneArg.proto */
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg);
/* DictGetItem.proto */
#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY
static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key);
#define __Pyx_PyObject_Dict_GetItem(obj, name)\
(likely(PyDict_CheckExact(obj)) ?\
__Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name))
#else
#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key)
#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name)
#endif
/* RaiseTooManyValuesToUnpack.proto */
static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
/* RaiseNeedMoreValuesToUnpack.proto */
static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
/* RaiseNoneIterError.proto */
static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
/* ExtTypeTest.proto */
static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type);
/* GetTopmostException.proto */
#if CYTHON_USE_EXC_INFO_STACK
static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate);
#endif
/* SaveResetException.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
#else
#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb)
#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb)
#endif
/* PyErrExceptionMatches.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err)
static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err);
#else
#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err)
#endif
/* GetException.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb)
static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#else
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb);
#endif
/* TypeImport.proto */
#ifndef __PYX_HAVE_RT_ImportType_proto
#define __PYX_HAVE_RT_ImportType_proto
enum __Pyx_ImportType_CheckSize {
__Pyx_ImportType_CheckSize_Error = 0,
__Pyx_ImportType_CheckSize_Warn = 1,
__Pyx_ImportType_CheckSize_Ignore = 2
};
static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size);
#endif
/* Import.proto */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level);
/* PyDictVersioning.proto */
#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1)
#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag)
#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\
(version_var) = __PYX_GET_DICT_VERSION(dict);\
(cache_var) = (value);
#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\
static PY_UINT64_T __pyx_dict_version = 0;\
static PyObject *__pyx_dict_cached_value = NULL;\
if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\
(VAR) = __pyx_dict_cached_value;\
} else {\
(VAR) = __pyx_dict_cached_value = (LOOKUP);\
__pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\
}\
}
static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj);
static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj);
static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version);
#else
#define __PYX_GET_DICT_VERSION(dict) (0)
#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)
#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP);
#endif
/* CLineInTraceback.proto */
#ifdef CYTHON_CLINE_IN_TRACEBACK
#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0)
#else
static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line);
#endif
/* CodeObjectCache.proto */
typedef struct {
PyCodeObject* code_object;
int code_line;
} __Pyx_CodeObjectCacheEntry;
struct __Pyx_CodeObjectCache {
int count;
int max_count;
__Pyx_CodeObjectCacheEntry* entries;
};
static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
static PyCodeObject *__pyx_find_code_object(int code_line);
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);
/* AddTraceback.proto */
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename);
/* BufferStructDeclare.proto */
typedef struct {
Py_ssize_t shape, strides, suboffsets;
} __Pyx_Buf_DimInfo;
typedef struct {
size_t refcount;
Py_buffer pybuffer;
} __Pyx_Buffer;
typedef struct {
__Pyx_Buffer *rcbuffer;
char *data;
__Pyx_Buf_DimInfo diminfo[8];
} __Pyx_LocalBuf_ND;
#if PY_MAJOR_VERSION < 3
static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags);
static void __Pyx_ReleaseBuffer(Py_buffer *view);
#else
#define __Pyx_GetBuffer PyObject_GetBuffer
#define __Pyx_ReleaseBuffer PyBuffer_Release
#endif
/* RealImag.proto */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
#define __Pyx_CREAL(z) ((z).real())
#define __Pyx_CIMAG(z) ((z).imag())
#else
#define __Pyx_CREAL(z) (__real__(z))
#define __Pyx_CIMAG(z) (__imag__(z))
#endif
#else
#define __Pyx_CREAL(z) ((z).real)
#define __Pyx_CIMAG(z) ((z).imag)
#endif
#if defined(__cplusplus) && CYTHON_CCOMPLEX\
&& (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103)
#define __Pyx_SET_CREAL(z,x) ((z).real(x))
#define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
#else
#define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
#define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
#endif
/* Arithmetic.proto */
#if CYTHON_CCOMPLEX
#define __Pyx_c_eq_float(a, b) ((a)==(b))
#define __Pyx_c_sum_float(a, b) ((a)+(b))
#define __Pyx_c_diff_float(a, b) ((a)-(b))
#define __Pyx_c_prod_float(a, b) ((a)*(b))
#define __Pyx_c_quot_float(a, b) ((a)/(b))
#define __Pyx_c_neg_float(a) (-(a))
#ifdef __cplusplus
#define __Pyx_c_is_zero_float(z) ((z)==(float)0)
#define __Pyx_c_conj_float(z) (::std::conj(z))
#if 1
#define __Pyx_c_abs_float(z) (::std::abs(z))
#define __Pyx_c_pow_float(a, b) (::std::pow(a, b))
#endif
#else
#define __Pyx_c_is_zero_float(z) ((z)==0)
#define __Pyx_c_conj_float(z) (conjf(z))
#if 1
#define __Pyx_c_abs_float(z) (cabsf(z))
#define __Pyx_c_pow_float(a, b) (cpowf(a, b))
#endif
#endif
#else
static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex);
static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex);
#if 1
static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex);
#endif
#endif
/* Arithmetic.proto */
#if CYTHON_CCOMPLEX
#define __Pyx_c_eq_double(a, b) ((a)==(b))
#define __Pyx_c_sum_double(a, b) ((a)+(b))
#define __Pyx_c_diff_double(a, b) ((a)-(b))
#define __Pyx_c_prod_double(a, b) ((a)*(b))
#define __Pyx_c_quot_double(a, b) ((a)/(b))
#define __Pyx_c_neg_double(a) (-(a))
#ifdef __cplusplus
#define __Pyx_c_is_zero_double(z) ((z)==(double)0)
#define __Pyx_c_conj_double(z) (::std::conj(z))
#if 1
#define __Pyx_c_abs_double(z) (::std::abs(z))
#define __Pyx_c_pow_double(a, b) (::std::pow(a, b))
#endif
#else
#define __Pyx_c_is_zero_double(z) ((z)==0)
#define __Pyx_c_conj_double(z) (conj(z))
#if 1
#define __Pyx_c_abs_double(z) (cabs(z))
#define __Pyx_c_pow_double(a, b) (cpow(a, b))
#endif
#endif
#else
static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex);
static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex);
#if 1
static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex);
#endif
#endif
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value);
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value);
/* CIntFromPy.proto */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
/* CIntFromPy.proto */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
/* FastTypeChecks.proto */
#if CYTHON_COMPILING_IN_CPYTHON
#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type)
static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b);
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type);
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2);
#else
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type)
#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2))
#endif
#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
/* CheckBinaryVersion.proto */
static int __Pyx_check_binary_version(void);
/* InitStrings.proto */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);
/* Module declarations from 'cython' */
/* Module declarations from 'cpython.buffer' */
/* Module declarations from 'libc.string' */
/* Module declarations from 'libc.stdio' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.type' */
static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;
/* Module declarations from 'cpython' */
/* Module declarations from 'cpython.object' */
/* Module declarations from 'cpython.ref' */
/* Module declarations from 'cpython.mem' */
/* Module declarations from 'numpy' */
/* Module declarations from 'numpy' */
static PyTypeObject *__pyx_ptype_5numpy_dtype = 0;
static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0;
static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0;
static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0;
static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0;
static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/
/* Module declarations from 'ssa_translation_lowmem_nostats' */
static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 };
static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 };
#define __Pyx_MODULE_NAME "ssa_translation_lowmem_nostats"
extern int __pyx_module_is_main_ssa_translation_lowmem_nostats;
int __pyx_module_is_main_ssa_translation_lowmem_nostats = 0;
/* Implementation of 'ssa_translation_lowmem_nostats' */
static PyObject *__pyx_builtin_ValueError;
static PyObject *__pyx_builtin_range;
static PyObject *__pyx_builtin_RuntimeError;
static PyObject *__pyx_builtin_ImportError;
static const char __pyx_k_N[] = "N";
static const char __pyx_k_Nt[] = "Nt";
static const char __pyx_k_np[] = "np";
static const char __pyx_k_x0[] = "x0";
static const char __pyx_k_fNt[] = "fNt";
static const char __pyx_k_FRAP[] = "FRAP";
static const char __pyx_k_main[] = "__main__";
static const char __pyx_k_name[] = "__name__";
static const char __pyx_k_seed[] = "seed";
static const char __pyx_k_test[] = "__test__";
static const char __pyx_k_kbind[] = "kbind";
static const char __pyx_k_numpy[] = "numpy";
static const char __pyx_k_range[] = "range";
static const char __pyx_k_Ncolor[] = "Ncolor";
static const char __pyx_k_import[] = "__import__";
static const char __pyx_k_kcompl[] = "kcompl";
static const char __pyx_k_kelong[] = "kelong";
static const char __pyx_k_run_SSA[] = "run_SSA";
static const char __pyx_k_t_array[] = "t_array";
static const char __pyx_k_probevec[] = "probevec";
static const char __pyx_k_Inhibitor[] = "Inhibitor";
static const char __pyx_k_intensity[] = "intensity";
static const char __pyx_k_ValueError[] = "ValueError";
static const char __pyx_k_ImportError[] = "ImportError";
static const char __pyx_k_frap_result[] = "frap_result";
static const char __pyx_k_r_footprint[] = "r_footprint";
static const char __pyx_k_RuntimeError[] = "RuntimeError";
static const char __pyx_k_inhibit_time[] = "inhibit_time";
static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback";
static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous";
static const char __pyx_k_ssa_translation_lowmem_nostats[] = "ssa_translation_lowmem_nostats";
static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import";
static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)";
static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd";
static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported";
static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous";
static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import";
static const char __pyx_k_ssa_translation_lowmem_nostats_p[] = "ssa_translation_lowmem_nostats.pyx";
static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short.";
static PyObject *__pyx_n_s_FRAP;
static PyObject *__pyx_kp_u_Format_string_allocated_too_shor;
static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2;
static PyObject *__pyx_n_s_ImportError;
static PyObject *__pyx_n_s_Inhibitor;
static PyObject *__pyx_n_s_N;
static PyObject *__pyx_n_s_Ncolor;
static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor;
static PyObject *__pyx_n_s_Nt;
static PyObject *__pyx_n_s_RuntimeError;
static PyObject *__pyx_n_s_ValueError;
static PyObject *__pyx_n_s_cline_in_traceback;
static PyObject *__pyx_n_s_fNt;
static PyObject *__pyx_n_s_frap_result;
static PyObject *__pyx_n_s_import;
static PyObject *__pyx_n_s_inhibit_time;
static PyObject *__pyx_n_s_intensity;
static PyObject *__pyx_n_s_kbind;
static PyObject *__pyx_n_s_kcompl;
static PyObject *__pyx_n_s_kelong;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_name;
static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous;
static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou;
static PyObject *__pyx_n_s_np;
static PyObject *__pyx_n_s_numpy;
static PyObject *__pyx_kp_s_numpy_core_multiarray_failed_to;
static PyObject *__pyx_kp_s_numpy_core_umath_failed_to_impor;
static PyObject *__pyx_n_s_probevec;
static PyObject *__pyx_n_s_r_footprint;
static PyObject *__pyx_n_s_range;
static PyObject *__pyx_n_s_run_SSA;
static PyObject *__pyx_n_s_seed;
static PyObject *__pyx_n_s_ssa_translation_lowmem_nostats;
static PyObject *__pyx_kp_s_ssa_translation_lowmem_nostats_p;
static PyObject *__pyx_n_s_t_array;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd;
static PyObject *__pyx_n_s_x0;
static PyObject *__pyx_pf_30ssa_translation_lowmem_nostats_run_SSA(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_intensity, PyArrayObject *__pyx_v_kelong, PyArrayObject *__pyx_v_frap_result, PyArrayObject *__pyx_v_t_array, double __pyx_v_kbind, double __pyx_v_kcompl, int __pyx_v_FRAP, int __pyx_v_Inhibitor, double __pyx_v_inhibit_time, int __pyx_v_seed, PyArrayObject *__pyx_v_x0, int __pyx_v_r_footprint, PyArrayObject *__pyx_v_probevec, int __pyx_v_Ncolor); /* proto */
static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */
static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */
static PyObject *__pyx_tuple_;
static PyObject *__pyx_tuple__2;
static PyObject *__pyx_tuple__3;
static PyObject *__pyx_tuple__4;
static PyObject *__pyx_tuple__5;
static PyObject *__pyx_tuple__6;
static PyObject *__pyx_tuple__7;
static PyObject *__pyx_tuple__8;
static PyObject *__pyx_codeobj__9;
/* Late includes */
/* "ssa_translation_lowmem_nostats.pyx":16
* @cython.wraparound(False)
*
* def run_SSA(np.ndarray[int, ndim=2, mode="c"] intensity not None, np.ndarray[double, ndim=1, mode="c"] kelong not None, np.ndarray[int, ndim=1, mode="c"] frap_result not None, np.ndarray[double, ndim=1, mode="c"] t_array not None, double kbind, double kcompl, int FRAP, int Inhibitor, double inhibit_time, int seed, np.ndarray[int, ndim=1, mode="c"] x0 not None, int r_footprint, np.ndarray[int, ndim=2, mode="c"] probevec not None, int Ncolor): # <<<<<<<<<<<<<<
* """
* I need to write this.
*/
/* Python wrapper */
static PyObject *__pyx_pw_30ssa_translation_lowmem_nostats_1run_SSA(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_30ssa_translation_lowmem_nostats_run_SSA[] = "\n I need to write this. \n ";
static PyMethodDef __pyx_mdef_30ssa_translation_lowmem_nostats_1run_SSA = {"run_SSA", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_30ssa_translation_lowmem_nostats_1run_SSA, METH_VARARGS|METH_KEYWORDS, __pyx_doc_30ssa_translation_lowmem_nostats_run_SSA};
static PyObject *__pyx_pw_30ssa_translation_lowmem_nostats_1run_SSA(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyArrayObject *__pyx_v_intensity = 0;
PyArrayObject *__pyx_v_kelong = 0;
PyArrayObject *__pyx_v_frap_result = 0;
PyArrayObject *__pyx_v_t_array = 0;
double __pyx_v_kbind;
double __pyx_v_kcompl;
int __pyx_v_FRAP;
int __pyx_v_Inhibitor;
double __pyx_v_inhibit_time;
int __pyx_v_seed;
PyArrayObject *__pyx_v_x0 = 0;
int __pyx_v_r_footprint;
PyArrayObject *__pyx_v_probevec = 0;
int __pyx_v_Ncolor;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("run_SSA (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_intensity,&__pyx_n_s_kelong,&__pyx_n_s_frap_result,&__pyx_n_s_t_array,&__pyx_n_s_kbind,&__pyx_n_s_kcompl,&__pyx_n_s_FRAP,&__pyx_n_s_Inhibitor,&__pyx_n_s_inhibit_time,&__pyx_n_s_seed,&__pyx_n_s_x0,&__pyx_n_s_r_footprint,&__pyx_n_s_probevec,&__pyx_n_s_Ncolor,0};
PyObject* values[14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13);
CYTHON_FALLTHROUGH;
case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12);
CYTHON_FALLTHROUGH;
case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11);
CYTHON_FALLTHROUGH;
case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10);
CYTHON_FALLTHROUGH;
case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9);
CYTHON_FALLTHROUGH;
case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8);
CYTHON_FALLTHROUGH;
case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7);
CYTHON_FALLTHROUGH;
case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6);
CYTHON_FALLTHROUGH;
case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5);
CYTHON_FALLTHROUGH;
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
CYTHON_FALLTHROUGH;
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
CYTHON_FALLTHROUGH;
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
CYTHON_FALLTHROUGH;
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
CYTHON_FALLTHROUGH;
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
CYTHON_FALLTHROUGH;
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_intensity)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
CYTHON_FALLTHROUGH;
case 1:
if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kelong)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 1); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 2:
if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_frap_result)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 2); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 3:
if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_array)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 3); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 4:
if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kbind)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 4); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 5:
if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kcompl)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 5); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 6:
if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_FRAP)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 6); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 7:
if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Inhibitor)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 7); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 8:
if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_inhibit_time)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 8); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 9:
if (likely((values[9] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_seed)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 9); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 10:
if (likely((values[10] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_x0)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 10); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 11:
if (likely((values[11] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_r_footprint)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 11); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 12:
if (likely((values[12] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_probevec)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 12); __PYX_ERR(0, 16, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 13:
if (likely((values[13] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Ncolor)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, 13); __PYX_ERR(0, 16, __pyx_L3_error)
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "run_SSA") < 0)) __PYX_ERR(0, 16, __pyx_L3_error)
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 14) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
values[5] = PyTuple_GET_ITEM(__pyx_args, 5);
values[6] = PyTuple_GET_ITEM(__pyx_args, 6);
values[7] = PyTuple_GET_ITEM(__pyx_args, 7);
values[8] = PyTuple_GET_ITEM(__pyx_args, 8);
values[9] = PyTuple_GET_ITEM(__pyx_args, 9);
values[10] = PyTuple_GET_ITEM(__pyx_args, 10);
values[11] = PyTuple_GET_ITEM(__pyx_args, 11);
values[12] = PyTuple_GET_ITEM(__pyx_args, 12);
values[13] = PyTuple_GET_ITEM(__pyx_args, 13);
}
__pyx_v_intensity = ((PyArrayObject *)values[0]);
__pyx_v_kelong = ((PyArrayObject *)values[1]);
__pyx_v_frap_result = ((PyArrayObject *)values[2]);
__pyx_v_t_array = ((PyArrayObject *)values[3]);
__pyx_v_kbind = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_kbind == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_kcompl = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_kcompl == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_FRAP = __Pyx_PyInt_As_int(values[6]); if (unlikely((__pyx_v_FRAP == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_Inhibitor = __Pyx_PyInt_As_int(values[7]); if (unlikely((__pyx_v_Inhibitor == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_inhibit_time = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_inhibit_time == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_seed = __Pyx_PyInt_As_int(values[9]); if (unlikely((__pyx_v_seed == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_x0 = ((PyArrayObject *)values[10]);
__pyx_v_r_footprint = __Pyx_PyInt_As_int(values[11]); if (unlikely((__pyx_v_r_footprint == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_v_probevec = ((PyArrayObject *)values[12]);
__pyx_v_Ncolor = __Pyx_PyInt_As_int(values[13]); if (unlikely((__pyx_v_Ncolor == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L3_error)
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("run_SSA", 1, 14, 14, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 16, __pyx_L3_error)
__pyx_L3_error:;
__Pyx_AddTraceback("ssa_translation_lowmem_nostats.run_SSA", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intensity), __pyx_ptype_5numpy_ndarray, 0, "intensity", 0))) __PYX_ERR(0, 16, __pyx_L1_error)
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kelong), __pyx_ptype_5numpy_ndarray, 0, "kelong", 0))) __PYX_ERR(0, 16, __pyx_L1_error)
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_frap_result), __pyx_ptype_5numpy_ndarray, 0, "frap_result", 0))) __PYX_ERR(0, 16, __pyx_L1_error)
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_t_array), __pyx_ptype_5numpy_ndarray, 0, "t_array", 0))) __PYX_ERR(0, 16, __pyx_L1_error)
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x0), __pyx_ptype_5numpy_ndarray, 0, "x0", 0))) __PYX_ERR(0, 16, __pyx_L1_error)
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probevec), __pyx_ptype_5numpy_ndarray, 0, "probevec", 0))) __PYX_ERR(0, 16, __pyx_L1_error)
__pyx_r = __pyx_pf_30ssa_translation_lowmem_nostats_run_SSA(__pyx_self, __pyx_v_intensity, __pyx_v_kelong, __pyx_v_frap_result, __pyx_v_t_array, __pyx_v_kbind, __pyx_v_kcompl, __pyx_v_FRAP, __pyx_v_Inhibitor, __pyx_v_inhibit_time, __pyx_v_seed, __pyx_v_x0, __pyx_v_r_footprint, __pyx_v_probevec, __pyx_v_Ncolor);
/* function exit code */
goto __pyx_L0;
__pyx_L1_error:;
__pyx_r = NULL;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_30ssa_translation_lowmem_nostats_run_SSA(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_intensity, PyArrayObject *__pyx_v_kelong, PyArrayObject *__pyx_v_frap_result, PyArrayObject *__pyx_v_t_array, double __pyx_v_kbind, double __pyx_v_kcompl, int __pyx_v_FRAP, int __pyx_v_Inhibitor, double __pyx_v_inhibit_time, int __pyx_v_seed, PyArrayObject *__pyx_v_x0, int __pyx_v_r_footprint, PyArrayObject *__pyx_v_probevec, int __pyx_v_Ncolor) {
int __pyx_v_Nt;
int __pyx_v_N;
npy_intp __pyx_v_fNt;
__Pyx_LocalBuf_ND __pyx_pybuffernd_frap_result;
__Pyx_Buffer __pyx_pybuffer_frap_result;
__Pyx_LocalBuf_ND __pyx_pybuffernd_intensity;
__Pyx_Buffer __pyx_pybuffer_intensity;
__Pyx_LocalBuf_ND __pyx_pybuffernd_kelong;
__Pyx_Buffer __pyx_pybuffer_kelong;
__Pyx_LocalBuf_ND __pyx_pybuffernd_probevec;
__Pyx_Buffer __pyx_pybuffer_probevec;
__Pyx_LocalBuf_ND __pyx_pybuffernd_t_array;
__Pyx_Buffer __pyx_pybuffer_t_array;
__Pyx_LocalBuf_ND __pyx_pybuffernd_x0;
__Pyx_Buffer __pyx_pybuffer_x0;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
Py_ssize_t __pyx_t_2;
Py_ssize_t __pyx_t_3;
Py_ssize_t __pyx_t_4;
Py_ssize_t __pyx_t_5;
Py_ssize_t __pyx_t_6;
Py_ssize_t __pyx_t_7;
Py_ssize_t __pyx_t_8;
Py_ssize_t __pyx_t_9;
__Pyx_RefNannySetupContext("run_SSA", 0);
__pyx_pybuffer_intensity.pybuffer.buf = NULL;
__pyx_pybuffer_intensity.refcount = 0;
__pyx_pybuffernd_intensity.data = NULL;
__pyx_pybuffernd_intensity.rcbuffer = &__pyx_pybuffer_intensity;
__pyx_pybuffer_kelong.pybuffer.buf = NULL;
__pyx_pybuffer_kelong.refcount = 0;
__pyx_pybuffernd_kelong.data = NULL;
__pyx_pybuffernd_kelong.rcbuffer = &__pyx_pybuffer_kelong;
__pyx_pybuffer_frap_result.pybuffer.buf = NULL;
__pyx_pybuffer_frap_result.refcount = 0;
__pyx_pybuffernd_frap_result.data = NULL;
__pyx_pybuffernd_frap_result.rcbuffer = &__pyx_pybuffer_frap_result;
__pyx_pybuffer_t_array.pybuffer.buf = NULL;
__pyx_pybuffer_t_array.refcount = 0;
__pyx_pybuffernd_t_array.data = NULL;
__pyx_pybuffernd_t_array.rcbuffer = &__pyx_pybuffer_t_array;
__pyx_pybuffer_x0.pybuffer.buf = NULL;
__pyx_pybuffer_x0.refcount = 0;
__pyx_pybuffernd_x0.data = NULL;
__pyx_pybuffernd_x0.rcbuffer = &__pyx_pybuffer_x0;
__pyx_pybuffer_probevec.pybuffer.buf = NULL;
__pyx_pybuffer_probevec.refcount = 0;
__pyx_pybuffernd_probevec.data = NULL;
__pyx_pybuffernd_probevec.rcbuffer = &__pyx_pybuffer_probevec;
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intensity.rcbuffer->pybuffer, (PyObject*)__pyx_v_intensity, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 16, __pyx_L1_error)
}
__pyx_pybuffernd_intensity.diminfo[0].strides = __pyx_pybuffernd_intensity.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intensity.diminfo[0].shape = __pyx_pybuffernd_intensity.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_intensity.diminfo[1].strides = __pyx_pybuffernd_intensity.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_intensity.diminfo[1].shape = __pyx_pybuffernd_intensity.rcbuffer->pybuffer.shape[1];
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_kelong.rcbuffer->pybuffer, (PyObject*)__pyx_v_kelong, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 16, __pyx_L1_error)
}
__pyx_pybuffernd_kelong.diminfo[0].strides = __pyx_pybuffernd_kelong.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_kelong.diminfo[0].shape = __pyx_pybuffernd_kelong.rcbuffer->pybuffer.shape[0];
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_frap_result.rcbuffer->pybuffer, (PyObject*)__pyx_v_frap_result, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 16, __pyx_L1_error)
}
__pyx_pybuffernd_frap_result.diminfo[0].strides = __pyx_pybuffernd_frap_result.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_frap_result.diminfo[0].shape = __pyx_pybuffernd_frap_result.rcbuffer->pybuffer.shape[0];
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_t_array.rcbuffer->pybuffer, (PyObject*)__pyx_v_t_array, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 16, __pyx_L1_error)
}
__pyx_pybuffernd_t_array.diminfo[0].strides = __pyx_pybuffernd_t_array.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_t_array.diminfo[0].shape = __pyx_pybuffernd_t_array.rcbuffer->pybuffer.shape[0];
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x0.rcbuffer->pybuffer, (PyObject*)__pyx_v_x0, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 16, __pyx_L1_error)
}
__pyx_pybuffernd_x0.diminfo[0].strides = __pyx_pybuffernd_x0.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x0.diminfo[0].shape = __pyx_pybuffernd_x0.rcbuffer->pybuffer.shape[0];
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probevec.rcbuffer->pybuffer, (PyObject*)__pyx_v_probevec, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 16, __pyx_L1_error)
}
__pyx_pybuffernd_probevec.diminfo[0].strides = __pyx_pybuffernd_probevec.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probevec.diminfo[0].shape = __pyx_pybuffernd_probevec.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_probevec.diminfo[1].strides = __pyx_pybuffernd_probevec.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_probevec.diminfo[1].shape = __pyx_pybuffernd_probevec.rcbuffer->pybuffer.shape[1];
/* "ssa_translation_lowmem_nostats.pyx":25
*
* # subtract 2.
* N = len(kelong) # <<<<<<<<<<<<<<
* Nt = t_array.shape[0]
*
*/
__pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_kelong)); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 25, __pyx_L1_error)
__pyx_v_N = __pyx_t_1;
/* "ssa_translation_lowmem_nostats.pyx":26
* # subtract 2.
* N = len(kelong)
* Nt = t_array.shape[0] # <<<<<<<<<<<<<<
*
* fNt = t_array.shape[0]
*/
__pyx_v_Nt = (__pyx_v_t_array->dimensions[0]);
/* "ssa_translation_lowmem_nostats.pyx":28
* Nt = t_array.shape[0]
*
* fNt = t_array.shape[0] # <<<<<<<<<<<<<<
*
* translationSSA (&kelong[0], &t_array[0], Nt, kbind, kcompl, &intensity[0,0], N, FRAP, Inhibitor, inhibit_time,seed,fNt,&frap_result[0], &x0[0], r_footprint, &probevec[0,0],Ncolor)
*/
__pyx_v_fNt = (__pyx_v_t_array->dimensions[0]);
/* "ssa_translation_lowmem_nostats.pyx":30
* fNt = t_array.shape[0]
*
* translationSSA (&kelong[0], &t_array[0], Nt, kbind, kcompl, &intensity[0,0], N, FRAP, Inhibitor, inhibit_time,seed,fNt,&frap_result[0], &x0[0], r_footprint, &probevec[0,0],Ncolor) # <<<<<<<<<<<<<<
*
* return None
*/
__pyx_t_2 = 0;
__pyx_t_3 = 0;
__pyx_t_4 = 0;
__pyx_t_5 = 0;
__pyx_t_6 = 0;
__pyx_t_7 = 0;
__pyx_t_8 = 0;
__pyx_t_9 = 0;
translationSSA((&(*__Pyx_BufPtrCContig1d(double *, __pyx_pybuffernd_kelong.rcbuffer->pybuffer.buf, __pyx_t_2, __pyx_pybuffernd_kelong.diminfo[0].strides))), (&(*__Pyx_BufPtrCContig1d(double *, __pyx_pybuffernd_t_array.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_t_array.diminfo[0].strides))), __pyx_v_Nt, __pyx_v_kbind, __pyx_v_kcompl, (&(*__Pyx_BufPtrCContig2d(int *, __pyx_pybuffernd_intensity.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_intensity.diminfo[0].strides, __pyx_t_5, __pyx_pybuffernd_intensity.diminfo[1].strides))), __pyx_v_N, __pyx_v_FRAP, __pyx_v_Inhibitor, __pyx_v_inhibit_time, __pyx_v_seed, __pyx_v_fNt, (&(*__Pyx_BufPtrCContig1d(int *, __pyx_pybuffernd_frap_result.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_frap_result.diminfo[0].strides))), (&(*__Pyx_BufPtrCContig1d(int *, __pyx_pybuffernd_x0.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_x0.diminfo[0].strides))), __pyx_v_r_footprint, (&(*__Pyx_BufPtrCContig2d(int *, __pyx_pybuffernd_probevec.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_probevec.diminfo[0].strides, __pyx_t_9, __pyx_pybuffernd_probevec.diminfo[1].strides))), __pyx_v_Ncolor);
/* "ssa_translation_lowmem_nostats.pyx":32
* translationSSA (&kelong[0], &t_array[0], Nt, kbind, kcompl, &intensity[0,0], N, FRAP, Inhibitor, inhibit_time,seed,fNt,&frap_result[0], &x0[0], r_footprint, &probevec[0,0],Ncolor)
*
* return None # <<<<<<<<<<<<<<
*
* ## Numpy must be initialized. When using numpy from C or Cython you must
*/
__Pyx_XDECREF(__pyx_r);
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
/* "ssa_translation_lowmem_nostats.pyx":16
* @cython.wraparound(False)
*
* def run_SSA(np.ndarray[int, ndim=2, mode="c"] intensity not None, np.ndarray[double, ndim=1, mode="c"] kelong not None, np.ndarray[int, ndim=1, mode="c"] frap_result not None, np.ndarray[double, ndim=1, mode="c"] t_array not None, double kbind, double kcompl, int FRAP, int Inhibitor, double inhibit_time, int seed, np.ndarray[int, ndim=1, mode="c"] x0 not None, int r_footprint, np.ndarray[int, ndim=2, mode="c"] probevec not None, int Ncolor): # <<<<<<<<<<<<<<
* """
* I need to write this.
*/
/* function exit code */
__pyx_L1_error:;
{ PyObject *__pyx_type, *__pyx_value, *__pyx_tb;
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_frap_result.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intensity.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_kelong.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probevec.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_t_array.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x0.rcbuffer->pybuffer);
__Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);}
__Pyx_AddTraceback("ssa_translation_lowmem_nostats.run_SSA", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
goto __pyx_L2;
__pyx_L0:;
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_frap_result.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intensity.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_kelong.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probevec.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_t_array.rcbuffer->pybuffer);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x0.rcbuffer->pybuffer);
__pyx_L2:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":258
* # experimental exception made for __getbuffer__ and __releasebuffer__
* # -- the details of this may change.
* def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<<
* # This implementation of getbuffer is geared towards Cython
* # requirements, and does not yet fulfill the PEP.
*/
/* Python wrapper */
static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0);
__pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_v_i;
int __pyx_v_ndim;
int __pyx_v_endian_detector;
int __pyx_v_little_endian;
int __pyx_v_t;
char *__pyx_v_f;
PyArray_Descr *__pyx_v_descr = 0;
int __pyx_v_offset;
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
int __pyx_t_5;
int __pyx_t_6;
PyArray_Descr *__pyx_t_7;
PyObject *__pyx_t_8 = NULL;
char *__pyx_t_9;
if (__pyx_v_info == NULL) {
PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete");
return -1;
}
__Pyx_RefNannySetupContext("__getbuffer__", 0);
__pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None);
__Pyx_GIVEREF(__pyx_v_info->obj);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":265
*
* cdef int i, ndim
* cdef int endian_detector = 1 # <<<<<<<<<<<<<<
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
*
*/
__pyx_v_endian_detector = 1;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":266
* cdef int i, ndim
* cdef int endian_detector = 1
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<<
*
* ndim = PyArray_NDIM(self)
*/
__pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":268
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
*
* ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<<
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
*/
__pyx_v_ndim = PyArray_NDIM(__pyx_v_self);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":270
* ndim = PyArray_NDIM(self)
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous")
*/
__pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0);
if (__pyx_t_2) {
} else {
__pyx_t_1 = __pyx_t_2;
goto __pyx_L4_bool_binop_done;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":271
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): # <<<<<<<<<<<<<<
* raise ValueError(u"ndarray is not C contiguous")
*
*/
__pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_ARRAY_C_CONTIGUOUS) != 0)) != 0);
__pyx_t_1 = __pyx_t_2;
__pyx_L4_bool_binop_done:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":270
* ndim = PyArray_NDIM(self)
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous")
*/
if (unlikely(__pyx_t_1)) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":272
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<<
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 272, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__PYX_ERR(1, 272, __pyx_L1_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":270
* ndim = PyArray_NDIM(self)
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous")
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":274
* raise ValueError(u"ndarray is not C contiguous")
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous")
*/
__pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0);
if (__pyx_t_2) {
} else {
__pyx_t_1 = __pyx_t_2;
goto __pyx_L7_bool_binop_done;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":275
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): # <<<<<<<<<<<<<<
* raise ValueError(u"ndarray is not Fortran contiguous")
*
*/
__pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_ARRAY_F_CONTIGUOUS) != 0)) != 0);
__pyx_t_1 = __pyx_t_2;
__pyx_L7_bool_binop_done:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":274
* raise ValueError(u"ndarray is not C contiguous")
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous")
*/
if (unlikely(__pyx_t_1)) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":276
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<<
*
* info.buf = PyArray_DATA(self)
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 276, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__PYX_ERR(1, 276, __pyx_L1_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":274
* raise ValueError(u"ndarray is not C contiguous")
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous")
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":278
* raise ValueError(u"ndarray is not Fortran contiguous")
*
* info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<<
* info.ndim = ndim
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
*/
__pyx_v_info->buf = PyArray_DATA(__pyx_v_self);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":279
*
* info.buf = PyArray_DATA(self)
* info.ndim = ndim # <<<<<<<<<<<<<<
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
* # Allocate new buffer for strides and shape info.
*/
__pyx_v_info->ndim = __pyx_v_ndim;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":280
* info.buf = PyArray_DATA(self)
* info.ndim = ndim
* if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<<
* # Allocate new buffer for strides and shape info.
* # This is allocated as one block, strides first.
*/
__pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0);
if (__pyx_t_1) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":283
* # Allocate new buffer for strides and shape info.
* # This is allocated as one block, strides first.
* info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) # <<<<<<<<<<<<<<
* info.shape = info.strides + ndim
* for i in range(ndim):
*/
__pyx_v_info->strides = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * 2) * ((size_t)__pyx_v_ndim))));
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":284
* # This is allocated as one block, strides first.
* info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim)
* info.shape = info.strides + ndim # <<<<<<<<<<<<<<
* for i in range(ndim):
* info.strides[i] = PyArray_STRIDES(self)[i]
*/
__pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":285
* info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim)
* info.shape = info.strides + ndim
* for i in range(ndim): # <<<<<<<<<<<<<<
* info.strides[i] = PyArray_STRIDES(self)[i]
* info.shape[i] = PyArray_DIMS(self)[i]
*/
__pyx_t_4 = __pyx_v_ndim;
__pyx_t_5 = __pyx_t_4;
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_i = __pyx_t_6;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":286
* info.shape = info.strides + ndim
* for i in range(ndim):
* info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<<
* info.shape[i] = PyArray_DIMS(self)[i]
* else:
*/
(__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":287
* for i in range(ndim):
* info.strides[i] = PyArray_STRIDES(self)[i]
* info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<<
* else:
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
*/
(__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]);
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":280
* info.buf = PyArray_DATA(self)
* info.ndim = ndim
* if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<<
* # Allocate new buffer for strides and shape info.
* # This is allocated as one block, strides first.
*/
goto __pyx_L9;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":289
* info.shape[i] = PyArray_DIMS(self)[i]
* else:
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<<
* info.shape = <Py_ssize_t*>PyArray_DIMS(self)
* info.suboffsets = NULL
*/
/*else*/ {
__pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self));
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":290
* else:
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
* info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<<
* info.suboffsets = NULL
* info.itemsize = PyArray_ITEMSIZE(self)
*/
__pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self));
}
__pyx_L9:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":291
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
* info.shape = <Py_ssize_t*>PyArray_DIMS(self)
* info.suboffsets = NULL # <<<<<<<<<<<<<<
* info.itemsize = PyArray_ITEMSIZE(self)
* info.readonly = not PyArray_ISWRITEABLE(self)
*/
__pyx_v_info->suboffsets = NULL;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":292
* info.shape = <Py_ssize_t*>PyArray_DIMS(self)
* info.suboffsets = NULL
* info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<<
* info.readonly = not PyArray_ISWRITEABLE(self)
*
*/
__pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":293
* info.suboffsets = NULL
* info.itemsize = PyArray_ITEMSIZE(self)
* info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<<
*
* cdef int t
*/
__pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0));
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":296
*
* cdef int t
* cdef char* f = NULL # <<<<<<<<<<<<<<
* cdef dtype descr = <dtype>PyArray_DESCR(self)
* cdef int offset
*/
__pyx_v_f = NULL;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":297
* cdef int t
* cdef char* f = NULL
* cdef dtype descr = <dtype>PyArray_DESCR(self) # <<<<<<<<<<<<<<
* cdef int offset
*
*/
__pyx_t_7 = PyArray_DESCR(__pyx_v_self);
__pyx_t_3 = ((PyObject *)__pyx_t_7);
__Pyx_INCREF(__pyx_t_3);
__pyx_v_descr = ((PyArray_Descr *)__pyx_t_3);
__pyx_t_3 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":300
* cdef int offset
*
* info.obj = self # <<<<<<<<<<<<<<
*
* if not PyDataType_HASFIELDS(descr):
*/
__Pyx_INCREF(((PyObject *)__pyx_v_self));
__Pyx_GIVEREF(((PyObject *)__pyx_v_self));
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj);
__pyx_v_info->obj = ((PyObject *)__pyx_v_self);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":302
* info.obj = self
*
* if not PyDataType_HASFIELDS(descr): # <<<<<<<<<<<<<<
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or
*/
__pyx_t_1 = ((!(PyDataType_HASFIELDS(__pyx_v_descr) != 0)) != 0);
if (__pyx_t_1) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":303
*
* if not PyDataType_HASFIELDS(descr):
* t = descr.type_num # <<<<<<<<<<<<<<
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)):
*/
__pyx_t_4 = __pyx_v_descr->type_num;
__pyx_v_t = __pyx_t_4;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":304
* if not PyDataType_HASFIELDS(descr):
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
__pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0);
if (!__pyx_t_2) {
goto __pyx_L15_next_or;
} else {
}
__pyx_t_2 = (__pyx_v_little_endian != 0);
if (!__pyx_t_2) {
} else {
__pyx_t_1 = __pyx_t_2;
goto __pyx_L14_bool_binop_done;
}
__pyx_L15_next_or:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":305
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<<
* raise ValueError(u"Non-native byte order not supported")
* if t == NPY_BYTE: f = "b"
*/
__pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0);
if (__pyx_t_2) {
} else {
__pyx_t_1 = __pyx_t_2;
goto __pyx_L14_bool_binop_done;
}
__pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0);
__pyx_t_1 = __pyx_t_2;
__pyx_L14_bool_binop_done:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":304
* if not PyDataType_HASFIELDS(descr):
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
if (unlikely(__pyx_t_1)) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":306
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B"
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 306, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__PYX_ERR(1, 306, __pyx_L1_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":304
* if not PyDataType_HASFIELDS(descr):
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":307
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
* if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<<
* elif t == NPY_UBYTE: f = "B"
* elif t == NPY_SHORT: f = "h"
*/
switch (__pyx_v_t) {
case NPY_BYTE:
__pyx_v_f = ((char *)"b");
break;
case NPY_UBYTE:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":308
* raise ValueError(u"Non-native byte order not supported")
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<<
* elif t == NPY_SHORT: f = "h"
* elif t == NPY_USHORT: f = "H"
*/
__pyx_v_f = ((char *)"B");
break;
case NPY_SHORT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":309
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B"
* elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<<
* elif t == NPY_USHORT: f = "H"
* elif t == NPY_INT: f = "i"
*/
__pyx_v_f = ((char *)"h");
break;
case NPY_USHORT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":310
* elif t == NPY_UBYTE: f = "B"
* elif t == NPY_SHORT: f = "h"
* elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<<
* elif t == NPY_INT: f = "i"
* elif t == NPY_UINT: f = "I"
*/
__pyx_v_f = ((char *)"H");
break;
case NPY_INT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":311
* elif t == NPY_SHORT: f = "h"
* elif t == NPY_USHORT: f = "H"
* elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<<
* elif t == NPY_UINT: f = "I"
* elif t == NPY_LONG: f = "l"
*/
__pyx_v_f = ((char *)"i");
break;
case NPY_UINT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":312
* elif t == NPY_USHORT: f = "H"
* elif t == NPY_INT: f = "i"
* elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<<
* elif t == NPY_LONG: f = "l"
* elif t == NPY_ULONG: f = "L"
*/
__pyx_v_f = ((char *)"I");
break;
case NPY_LONG:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":313
* elif t == NPY_INT: f = "i"
* elif t == NPY_UINT: f = "I"
* elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<<
* elif t == NPY_ULONG: f = "L"
* elif t == NPY_LONGLONG: f = "q"
*/
__pyx_v_f = ((char *)"l");
break;
case NPY_ULONG:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":314
* elif t == NPY_UINT: f = "I"
* elif t == NPY_LONG: f = "l"
* elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<<
* elif t == NPY_LONGLONG: f = "q"
* elif t == NPY_ULONGLONG: f = "Q"
*/
__pyx_v_f = ((char *)"L");
break;
case NPY_LONGLONG:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":315
* elif t == NPY_LONG: f = "l"
* elif t == NPY_ULONG: f = "L"
* elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<<
* elif t == NPY_ULONGLONG: f = "Q"
* elif t == NPY_FLOAT: f = "f"
*/
__pyx_v_f = ((char *)"q");
break;
case NPY_ULONGLONG:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":316
* elif t == NPY_ULONG: f = "L"
* elif t == NPY_LONGLONG: f = "q"
* elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<<
* elif t == NPY_FLOAT: f = "f"
* elif t == NPY_DOUBLE: f = "d"
*/
__pyx_v_f = ((char *)"Q");
break;
case NPY_FLOAT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":317
* elif t == NPY_LONGLONG: f = "q"
* elif t == NPY_ULONGLONG: f = "Q"
* elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<<
* elif t == NPY_DOUBLE: f = "d"
* elif t == NPY_LONGDOUBLE: f = "g"
*/
__pyx_v_f = ((char *)"f");
break;
case NPY_DOUBLE:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":318
* elif t == NPY_ULONGLONG: f = "Q"
* elif t == NPY_FLOAT: f = "f"
* elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<<
* elif t == NPY_LONGDOUBLE: f = "g"
* elif t == NPY_CFLOAT: f = "Zf"
*/
__pyx_v_f = ((char *)"d");
break;
case NPY_LONGDOUBLE:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":319
* elif t == NPY_FLOAT: f = "f"
* elif t == NPY_DOUBLE: f = "d"
* elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<<
* elif t == NPY_CFLOAT: f = "Zf"
* elif t == NPY_CDOUBLE: f = "Zd"
*/
__pyx_v_f = ((char *)"g");
break;
case NPY_CFLOAT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":320
* elif t == NPY_DOUBLE: f = "d"
* elif t == NPY_LONGDOUBLE: f = "g"
* elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<<
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg"
*/
__pyx_v_f = ((char *)"Zf");
break;
case NPY_CDOUBLE:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":321
* elif t == NPY_LONGDOUBLE: f = "g"
* elif t == NPY_CFLOAT: f = "Zf"
* elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<<
* elif t == NPY_CLONGDOUBLE: f = "Zg"
* elif t == NPY_OBJECT: f = "O"
*/
__pyx_v_f = ((char *)"Zd");
break;
case NPY_CLONGDOUBLE:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":322
* elif t == NPY_CFLOAT: f = "Zf"
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<<
* elif t == NPY_OBJECT: f = "O"
* else:
*/
__pyx_v_f = ((char *)"Zg");
break;
case NPY_OBJECT:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":323
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg"
* elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<<
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
*/
__pyx_v_f = ((char *)"O");
break;
default:
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":325
* elif t == NPY_OBJECT: f = "O"
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<<
* info.format = f
* return
*/
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 325, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 325, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 325, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__PYX_ERR(1, 325, __pyx_L1_error)
break;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":326
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
* info.format = f # <<<<<<<<<<<<<<
* return
* else:
*/
__pyx_v_info->format = __pyx_v_f;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":327
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
* info.format = f
* return # <<<<<<<<<<<<<<
* else:
* info.format = <char*>PyObject_Malloc(_buffer_format_string_len)
*/
__pyx_r = 0;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":302
* info.obj = self
*
* if not PyDataType_HASFIELDS(descr): # <<<<<<<<<<<<<<
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":329
* return
* else:
* info.format = <char*>PyObject_Malloc(_buffer_format_string_len) # <<<<<<<<<<<<<<
* info.format[0] = c'^' # Native data types, manual alignment
* offset = 0
*/
/*else*/ {
__pyx_v_info->format = ((char *)PyObject_Malloc(0xFF));
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":330
* else:
* info.format = <char*>PyObject_Malloc(_buffer_format_string_len)
* info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<<
* offset = 0
* f = _util_dtypestring(descr, info.format + 1,
*/
(__pyx_v_info->format[0]) = '^';
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":331
* info.format = <char*>PyObject_Malloc(_buffer_format_string_len)
* info.format[0] = c'^' # Native data types, manual alignment
* offset = 0 # <<<<<<<<<<<<<<
* f = _util_dtypestring(descr, info.format + 1,
* info.format + _buffer_format_string_len,
*/
__pyx_v_offset = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":332
* info.format[0] = c'^' # Native data types, manual alignment
* offset = 0
* f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<<
* info.format + _buffer_format_string_len,
* &offset)
*/
__pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(1, 332, __pyx_L1_error)
__pyx_v_f = __pyx_t_9;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":335
* info.format + _buffer_format_string_len,
* &offset)
* f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<<
*
* def __releasebuffer__(ndarray self, Py_buffer* info):
*/
(__pyx_v_f[0]) = '\x00';
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":258
* # experimental exception made for __getbuffer__ and __releasebuffer__
* # -- the details of this may change.
* def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<<
* # This implementation of getbuffer is geared towards Cython
* # requirements, and does not yet fulfill the PEP.
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
if (__pyx_v_info->obj != NULL) {
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0;
}
goto __pyx_L2;
__pyx_L0:;
if (__pyx_v_info->obj == Py_None) {
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0;
}
__pyx_L2:;
__Pyx_XDECREF((PyObject *)__pyx_v_descr);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":337
* f[0] = c'\0' # Terminate format string
*
* def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<<
* if PyArray_HASFIELDS(self):
* PyObject_Free(info.format)
*/
/* Python wrapper */
static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/
static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0);
__pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info));
/* function exit code */
__Pyx_RefNannyFinishContext();
}
static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) {
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("__releasebuffer__", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":338
*
* def __releasebuffer__(ndarray self, Py_buffer* info):
* if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<<
* PyObject_Free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
*/
__pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0);
if (__pyx_t_1) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":339
* def __releasebuffer__(ndarray self, Py_buffer* info):
* if PyArray_HASFIELDS(self):
* PyObject_Free(info.format) # <<<<<<<<<<<<<<
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
* PyObject_Free(info.strides)
*/
PyObject_Free(__pyx_v_info->format);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":338
*
* def __releasebuffer__(ndarray self, Py_buffer* info):
* if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<<
* PyObject_Free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":340
* if PyArray_HASFIELDS(self):
* PyObject_Free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<<
* PyObject_Free(info.strides)
* # info.shape was stored after info.strides in the same block
*/
__pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0);
if (__pyx_t_1) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":341
* PyObject_Free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
* PyObject_Free(info.strides) # <<<<<<<<<<<<<<
* # info.shape was stored after info.strides in the same block
*
*/
PyObject_Free(__pyx_v_info->strides);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":340
* if PyArray_HASFIELDS(self):
* PyObject_Free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<<
* PyObject_Free(info.strides)
* # info.shape was stored after info.strides in the same block
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":337
* f[0] = c'\0' # Terminate format string
*
* def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<<
* if PyArray_HASFIELDS(self):
* PyObject_Free(info.format)
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":821
* ctypedef npy_cdouble complex_t
*
* cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(1, <void*>a)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":822
*
* cdef inline object PyArray_MultiIterNew1(a):
* return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew2(a, b):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 822, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":821
* ctypedef npy_cdouble complex_t
*
* cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(1, <void*>a)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":824
* return PyArray_MultiIterNew(1, <void*>a)
*
* cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":825
*
* cdef inline object PyArray_MultiIterNew2(a, b):
* return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew3(a, b, c):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 825, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":824
* return PyArray_MultiIterNew(1, <void*>a)
*
* cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":827
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
* cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":828
*
* cdef inline object PyArray_MultiIterNew3(a, b, c):
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 828, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":827
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
* cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":830
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":831
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d):
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 831, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":830
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":833
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":834
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<<
*
* cdef inline tuple PyDataType_SHAPE(dtype d):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 834, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":833
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":836
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
* cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<<
* if PyDataType_HASSUBARRAY(d):
* return <tuple>d.subarray.shape
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("PyDataType_SHAPE", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":837
*
* cdef inline tuple PyDataType_SHAPE(dtype d):
* if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<<
* return <tuple>d.subarray.shape
* else:
*/
__pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0);
if (__pyx_t_1) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":838
* cdef inline tuple PyDataType_SHAPE(dtype d):
* if PyDataType_HASSUBARRAY(d):
* return <tuple>d.subarray.shape # <<<<<<<<<<<<<<
* else:
* return ()
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape));
__pyx_r = ((PyObject*)__pyx_v_d->subarray->shape);
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":837
*
* cdef inline tuple PyDataType_SHAPE(dtype d):
* if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<<
* return <tuple>d.subarray.shape
* else:
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":840
* return <tuple>d.subarray.shape
* else:
* return () # <<<<<<<<<<<<<<
*
* cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL:
*/
/*else*/ {
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_empty_tuple);
__pyx_r = __pyx_empty_tuple;
goto __pyx_L0;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":836
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
* cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<<
* if PyDataType_HASSUBARRAY(d):
* return <tuple>d.subarray.shape
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":842
* return ()
*
* cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<<
* # Recursive utility function used in __getbuffer__ to get format
* # string. The new location in the format string is returned.
*/
static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) {
PyArray_Descr *__pyx_v_child = 0;
int __pyx_v_endian_detector;
int __pyx_v_little_endian;
PyObject *__pyx_v_fields = 0;
PyObject *__pyx_v_childname = NULL;
PyObject *__pyx_v_new_offset = NULL;
PyObject *__pyx_v_t = NULL;
char *__pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
Py_ssize_t __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
int __pyx_t_5;
int __pyx_t_6;
int __pyx_t_7;
long __pyx_t_8;
char *__pyx_t_9;
__Pyx_RefNannySetupContext("_util_dtypestring", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":847
*
* cdef dtype child
* cdef int endian_detector = 1 # <<<<<<<<<<<<<<
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
* cdef tuple fields
*/
__pyx_v_endian_detector = 1;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":848
* cdef dtype child
* cdef int endian_detector = 1
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<<
* cdef tuple fields
*
*/
__pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":851
* cdef tuple fields
*
* for childname in descr.names: # <<<<<<<<<<<<<<
* fields = descr.fields[childname]
* child, new_offset = fields
*/
if (unlikely(__pyx_v_descr->names == Py_None)) {
PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
__PYX_ERR(1, 851, __pyx_L1_error)
}
__pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0;
for (;;) {
if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break;
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
__pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(1, 851, __pyx_L1_error)
#else
__pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 851, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
#endif
__Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3);
__pyx_t_3 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":852
*
* for childname in descr.names:
* fields = descr.fields[childname] # <<<<<<<<<<<<<<
* child, new_offset = fields
*
*/
if (unlikely(__pyx_v_descr->fields == Py_None)) {
PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable");
__PYX_ERR(1, 852, __pyx_L1_error)
}
__pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 852, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(1, 852, __pyx_L1_error)
__Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3));
__pyx_t_3 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":853
* for childname in descr.names:
* fields = descr.fields[childname]
* child, new_offset = fields # <<<<<<<<<<<<<<
*
* if (end - f) - <int>(new_offset - offset[0]) < 15:
*/
if (likely(__pyx_v_fields != Py_None)) {
PyObject* sequence = __pyx_v_fields;
Py_ssize_t size = __Pyx_PySequence_SIZE(sequence);
if (unlikely(size != 2)) {
if (size > 2) __Pyx_RaiseTooManyValuesError(2);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
__PYX_ERR(1, 853, __pyx_L1_error)
}
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
__pyx_t_3 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_4 = PyTuple_GET_ITEM(sequence, 1);
__Pyx_INCREF(__pyx_t_3);
__Pyx_INCREF(__pyx_t_4);
#else
__pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 853, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 853, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
#endif
} else {
__Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 853, __pyx_L1_error)
}
if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 853, __pyx_L1_error)
__Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3));
__pyx_t_3 = 0;
__Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4);
__pyx_t_4 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":855
* child, new_offset = fields
*
* if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<<
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
*/
__pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 855, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 855, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 855, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0);
if (unlikely(__pyx_t_6)) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":856
*
* if (end - f) - <int>(new_offset - offset[0]) < 15:
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<<
*
* if ((child.byteorder == c'>' and little_endian) or
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 856, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__PYX_ERR(1, 856, __pyx_L1_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":855
* child, new_offset = fields
*
* if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<<
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":858
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
* if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
__pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0);
if (!__pyx_t_7) {
goto __pyx_L8_next_or;
} else {
}
__pyx_t_7 = (__pyx_v_little_endian != 0);
if (!__pyx_t_7) {
} else {
__pyx_t_6 = __pyx_t_7;
goto __pyx_L7_bool_binop_done;
}
__pyx_L8_next_or:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":859
*
* if ((child.byteorder == c'>' and little_endian) or
* (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<<
* raise ValueError(u"Non-native byte order not supported")
* # One could encode it in the format string and have Cython
*/
__pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0);
if (__pyx_t_7) {
} else {
__pyx_t_6 = __pyx_t_7;
goto __pyx_L7_bool_binop_done;
}
__pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0);
__pyx_t_6 = __pyx_t_7;
__pyx_L7_bool_binop_done:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":858
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
* if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
if (unlikely(__pyx_t_6)) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":860
* if ((child.byteorder == c'>' and little_endian) or
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* # One could encode it in the format string and have Cython
* # complain instead, BUT: < and > in format strings also imply
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 860, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__PYX_ERR(1, 860, __pyx_L1_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":858
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
* if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":870
*
* # Output padding bytes
* while offset[0] < new_offset: # <<<<<<<<<<<<<<
* f[0] = 120 # "x"; pad byte
* f += 1
*/
while (1) {
__pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 870, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 870, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 870, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (!__pyx_t_6) break;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":871
* # Output padding bytes
* while offset[0] < new_offset:
* f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<<
* f += 1
* offset[0] += 1
*/
(__pyx_v_f[0]) = 0x78;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":872
* while offset[0] < new_offset:
* f[0] = 120 # "x"; pad byte
* f += 1 # <<<<<<<<<<<<<<
* offset[0] += 1
*
*/
__pyx_v_f = (__pyx_v_f + 1);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":873
* f[0] = 120 # "x"; pad byte
* f += 1
* offset[0] += 1 # <<<<<<<<<<<<<<
*
* offset[0] += child.itemsize
*/
__pyx_t_8 = 0;
(__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1);
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":875
* offset[0] += 1
*
* offset[0] += child.itemsize # <<<<<<<<<<<<<<
*
* if not PyDataType_HASFIELDS(child):
*/
__pyx_t_8 = 0;
(__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":877
* offset[0] += child.itemsize
*
* if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<<
* t = child.type_num
* if end - f < 5:
*/
__pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0);
if (__pyx_t_6) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":878
*
* if not PyDataType_HASFIELDS(child):
* t = child.type_num # <<<<<<<<<<<<<<
* if end - f < 5:
* raise RuntimeError(u"Format string allocated too short.")
*/
__pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 878, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4);
__pyx_t_4 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":879
* if not PyDataType_HASFIELDS(child):
* t = child.type_num
* if end - f < 5: # <<<<<<<<<<<<<<
* raise RuntimeError(u"Format string allocated too short.")
*
*/
__pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0);
if (unlikely(__pyx_t_6)) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":880
* t = child.type_num
* if end - f < 5:
* raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<<
*
* # Until ticket #99 is fixed, use integers to avoid warnings
*/
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 880, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__PYX_ERR(1, 880, __pyx_L1_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":879
* if not PyDataType_HASFIELDS(child):
* t = child.type_num
* if end - f < 5: # <<<<<<<<<<<<<<
* raise RuntimeError(u"Format string allocated too short.")
*
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":883
*
* # Until ticket #99 is fixed, use integers to avoid warnings
* if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<<
* elif t == NPY_UBYTE: f[0] = 66 #"B"
* elif t == NPY_SHORT: f[0] = 104 #"h"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 883, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 883, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 883, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 98;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":884
* # Until ticket #99 is fixed, use integers to avoid warnings
* if t == NPY_BYTE: f[0] = 98 #"b"
* elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<<
* elif t == NPY_SHORT: f[0] = 104 #"h"
* elif t == NPY_USHORT: f[0] = 72 #"H"
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 884, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 884, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 884, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 66;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":885
* if t == NPY_BYTE: f[0] = 98 #"b"
* elif t == NPY_UBYTE: f[0] = 66 #"B"
* elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<<
* elif t == NPY_USHORT: f[0] = 72 #"H"
* elif t == NPY_INT: f[0] = 105 #"i"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 885, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 885, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 885, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x68;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":886
* elif t == NPY_UBYTE: f[0] = 66 #"B"
* elif t == NPY_SHORT: f[0] = 104 #"h"
* elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<<
* elif t == NPY_INT: f[0] = 105 #"i"
* elif t == NPY_UINT: f[0] = 73 #"I"
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 886, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 886, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 886, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 72;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":887
* elif t == NPY_SHORT: f[0] = 104 #"h"
* elif t == NPY_USHORT: f[0] = 72 #"H"
* elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<<
* elif t == NPY_UINT: f[0] = 73 #"I"
* elif t == NPY_LONG: f[0] = 108 #"l"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 887, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 887, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 887, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x69;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":888
* elif t == NPY_USHORT: f[0] = 72 #"H"
* elif t == NPY_INT: f[0] = 105 #"i"
* elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<<
* elif t == NPY_LONG: f[0] = 108 #"l"
* elif t == NPY_ULONG: f[0] = 76 #"L"
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 888, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 888, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 888, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 73;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":889
* elif t == NPY_INT: f[0] = 105 #"i"
* elif t == NPY_UINT: f[0] = 73 #"I"
* elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<<
* elif t == NPY_ULONG: f[0] = 76 #"L"
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 889, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 889, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 889, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x6C;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":890
* elif t == NPY_UINT: f[0] = 73 #"I"
* elif t == NPY_LONG: f[0] = 108 #"l"
* elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<<
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 890, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 890, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 890, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 76;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":891
* elif t == NPY_LONG: f[0] = 108 #"l"
* elif t == NPY_ULONG: f[0] = 76 #"L"
* elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<<
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
* elif t == NPY_FLOAT: f[0] = 102 #"f"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 891, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 891, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 891, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x71;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":892
* elif t == NPY_ULONG: f[0] = 76 #"L"
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<<
* elif t == NPY_FLOAT: f[0] = 102 #"f"
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 892, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 892, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 892, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 81;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":893
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
* elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<<
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 893, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 893, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 893, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x66;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":894
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
* elif t == NPY_FLOAT: f[0] = 102 #"f"
* elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<<
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 894, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 894, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 894, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x64;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":895
* elif t == NPY_FLOAT: f[0] = 102 #"f"
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<<
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 895, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 895, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 895, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 0x67;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":896
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<<
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 896, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 896, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 896, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 90;
(__pyx_v_f[1]) = 0x66;
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":897
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<<
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
* elif t == NPY_OBJECT: f[0] = 79 #"O"
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 897, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 897, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 897, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 90;
(__pyx_v_f[1]) = 0x64;
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":898
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<<
* elif t == NPY_OBJECT: f[0] = 79 #"O"
* else:
*/
__pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 898, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 898, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 898, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 90;
(__pyx_v_f[1]) = 0x67;
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":899
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
* elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<<
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
*/
__pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 899, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 899, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 899, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (likely(__pyx_t_6)) {
(__pyx_v_f[0]) = 79;
goto __pyx_L15;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":901
* elif t == NPY_OBJECT: f[0] = 79 #"O"
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<<
* f += 1
* else:
*/
/*else*/ {
__pyx_t_3 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 901, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 901, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__PYX_ERR(1, 901, __pyx_L1_error)
}
__pyx_L15:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":902
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
* f += 1 # <<<<<<<<<<<<<<
* else:
* # Cython ignores struct boundary information ("T{...}"),
*/
__pyx_v_f = (__pyx_v_f + 1);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":877
* offset[0] += child.itemsize
*
* if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<<
* t = child.type_num
* if end - f < 5:
*/
goto __pyx_L13;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":906
* # Cython ignores struct boundary information ("T{...}"),
* # so don't output it
* f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<<
* return f
*
*/
/*else*/ {
__pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(1, 906, __pyx_L1_error)
__pyx_v_f = __pyx_t_9;
}
__pyx_L13:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":851
* cdef tuple fields
*
* for childname in descr.names: # <<<<<<<<<<<<<<
* fields = descr.fields[childname]
* child, new_offset = fields
*/
}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":907
* # so don't output it
* f = _util_dtypestring(child, f, end, offset)
* return f # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = __pyx_v_f;
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":842
* return ()
*
* cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<<
* # Recursive utility function used in __getbuffer__ to get format
* # string. The new location in the format string is returned.
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_child);
__Pyx_XDECREF(__pyx_v_fields);
__Pyx_XDECREF(__pyx_v_childname);
__Pyx_XDECREF(__pyx_v_new_offset);
__Pyx_XDECREF(__pyx_v_t);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1022
* int _import_umath() except -1
*
* cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
* Py_INCREF(base) # important to do this before stealing the reference below!
* PyArray_SetBaseObject(arr, base)
*/
static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("set_array_base", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1023
*
* cdef inline void set_array_base(ndarray arr, object base):
* Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<<
* PyArray_SetBaseObject(arr, base)
*
*/
Py_INCREF(__pyx_v_base);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1024
* cdef inline void set_array_base(ndarray arr, object base):
* Py_INCREF(base) # important to do this before stealing the reference below!
* PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<<
*
* cdef inline object get_array_base(ndarray arr):
*/
(void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base));
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1022
* int _import_umath() except -1
*
* cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
* Py_INCREF(base) # important to do this before stealing the reference below!
* PyArray_SetBaseObject(arr, base)
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1026
* PyArray_SetBaseObject(arr, base)
*
* cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
* base = PyArray_BASE(arr)
* if base is NULL:
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) {
PyObject *__pyx_v_base;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("get_array_base", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1027
*
* cdef inline object get_array_base(ndarray arr):
* base = PyArray_BASE(arr) # <<<<<<<<<<<<<<
* if base is NULL:
* return None
*/
__pyx_v_base = PyArray_BASE(__pyx_v_arr);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1028
* cdef inline object get_array_base(ndarray arr):
* base = PyArray_BASE(arr)
* if base is NULL: # <<<<<<<<<<<<<<
* return None
* return <object>base
*/
__pyx_t_1 = ((__pyx_v_base == NULL) != 0);
if (__pyx_t_1) {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1029
* base = PyArray_BASE(arr)
* if base is NULL:
* return None # <<<<<<<<<<<<<<
* return <object>base
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1028
* cdef inline object get_array_base(ndarray arr):
* base = PyArray_BASE(arr)
* if base is NULL: # <<<<<<<<<<<<<<
* return None
* return <object>base
*/
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1030
* if base is NULL:
* return None
* return <object>base # <<<<<<<<<<<<<<
*
* # Versions of the import_* functions which are more suitable for
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_base));
__pyx_r = ((PyObject *)__pyx_v_base);
goto __pyx_L0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1026
* PyArray_SetBaseObject(arr, base)
*
* cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
* base = PyArray_BASE(arr)
* if base is NULL:
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1034
* # Versions of the import_* functions which are more suitable for
* # Cython code.
* cdef inline int import_array() except -1: # <<<<<<<<<<<<<<
* try:
* _import_array()
*/
static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
__Pyx_RefNannySetupContext("import_array", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1035
* # Cython code.
* cdef inline int import_array() except -1:
* try: # <<<<<<<<<<<<<<
* _import_array()
* except Exception:
*/
{
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_1);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
/*try:*/ {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1036
* cdef inline int import_array() except -1:
* try:
* _import_array() # <<<<<<<<<<<<<<
* except Exception:
* raise ImportError("numpy.core.multiarray failed to import")
*/
__pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1036, __pyx_L3_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1035
* # Cython code.
* cdef inline int import_array() except -1:
* try: # <<<<<<<<<<<<<<
* _import_array()
* except Exception:
*/
}
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L8_try_end;
__pyx_L3_error:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1037
* try:
* _import_array()
* except Exception: # <<<<<<<<<<<<<<
* raise ImportError("numpy.core.multiarray failed to import")
*
*/
__pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])));
if (__pyx_t_4) {
__Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1037, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1038
* _import_array()
* except Exception:
* raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_umath() except -1:
*/
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1038, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__PYX_ERR(1, 1038, __pyx_L5_except_error)
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1035
* # Cython code.
* cdef inline int import_array() except -1:
* try: # <<<<<<<<<<<<<<
* _import_array()
* except Exception:
*/
__Pyx_XGIVEREF(__pyx_t_1);
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3);
goto __pyx_L1_error;
__pyx_L8_try_end:;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1034
* # Versions of the import_* functions which are more suitable for
* # Cython code.
* cdef inline int import_array() except -1: # <<<<<<<<<<<<<<
* try:
* _import_array()
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1040
* raise ImportError("numpy.core.multiarray failed to import")
*
* cdef inline int import_umath() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
__Pyx_RefNannySetupContext("import_umath", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1041
*
* cdef inline int import_umath() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
{
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_1);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
/*try:*/ {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1042
* cdef inline int import_umath() except -1:
* try:
* _import_umath() # <<<<<<<<<<<<<<
* except Exception:
* raise ImportError("numpy.core.umath failed to import")
*/
__pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1042, __pyx_L3_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1041
*
* cdef inline int import_umath() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
}
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L8_try_end;
__pyx_L3_error:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1043
* try:
* _import_umath()
* except Exception: # <<<<<<<<<<<<<<
* raise ImportError("numpy.core.umath failed to import")
*
*/
__pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])));
if (__pyx_t_4) {
__Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1043, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1044
* _import_umath()
* except Exception:
* raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_ufunc() except -1:
*/
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1044, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__PYX_ERR(1, 1044, __pyx_L5_except_error)
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1041
*
* cdef inline int import_umath() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
__Pyx_XGIVEREF(__pyx_t_1);
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3);
goto __pyx_L1_error;
__pyx_L8_try_end:;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1040
* raise ImportError("numpy.core.multiarray failed to import")
*
* cdef inline int import_umath() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1046
* raise ImportError("numpy.core.umath failed to import")
*
* cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
__Pyx_RefNannySetupContext("import_ufunc", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1047
*
* cdef inline int import_ufunc() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
{
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_1);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
/*try:*/ {
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1048
* cdef inline int import_ufunc() except -1:
* try:
* _import_umath() # <<<<<<<<<<<<<<
* except Exception:
* raise ImportError("numpy.core.umath failed to import")
*/
__pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1048, __pyx_L3_error)
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1047
*
* cdef inline int import_ufunc() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
}
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L8_try_end;
__pyx_L3_error:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1049
* try:
* _import_umath()
* except Exception: # <<<<<<<<<<<<<<
* raise ImportError("numpy.core.umath failed to import")
*/
__pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])));
if (__pyx_t_4) {
__Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1049, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1050
* _import_umath()
* except Exception:
* raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<<
*/
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1050, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__PYX_ERR(1, 1050, __pyx_L5_except_error)
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1047
*
* cdef inline int import_ufunc() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
__Pyx_XGIVEREF(__pyx_t_1);
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3);
goto __pyx_L1_error;
__pyx_L8_try_end:;
}
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1046
* raise ImportError("numpy.core.umath failed to import")
*
* cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyMethodDef __pyx_methods[] = {
{0, 0, 0, 0}
};
#if PY_MAJOR_VERSION >= 3
#if CYTHON_PEP489_MULTI_PHASE_INIT
static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/
static int __pyx_pymod_exec_ssa_translation_lowmem_nostats(PyObject* module); /*proto*/
static PyModuleDef_Slot __pyx_moduledef_slots[] = {
{Py_mod_create, (void*)__pyx_pymod_create},
{Py_mod_exec, (void*)__pyx_pymod_exec_ssa_translation_lowmem_nostats},
{0, NULL}
};
#endif
static struct PyModuleDef __pyx_moduledef = {
PyModuleDef_HEAD_INIT,
"ssa_translation_lowmem_nostats",
0, /* m_doc */
#if CYTHON_PEP489_MULTI_PHASE_INIT
0, /* m_size */
#else
-1, /* m_size */
#endif
__pyx_methods /* m_methods */,
#if CYTHON_PEP489_MULTI_PHASE_INIT
__pyx_moduledef_slots, /* m_slots */
#else
NULL, /* m_reload */
#endif
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
#ifndef CYTHON_SMALL_CODE
#if defined(__clang__)
#define CYTHON_SMALL_CODE
#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
#define CYTHON_SMALL_CODE __attribute__((cold))
#else
#define CYTHON_SMALL_CODE
#endif
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_n_s_FRAP, __pyx_k_FRAP, sizeof(__pyx_k_FRAP), 0, 0, 1, 1},
{&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0},
{&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0},
{&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1},
{&__pyx_n_s_Inhibitor, __pyx_k_Inhibitor, sizeof(__pyx_k_Inhibitor), 0, 0, 1, 1},
{&__pyx_n_s_N, __pyx_k_N, sizeof(__pyx_k_N), 0, 0, 1, 1},
{&__pyx_n_s_Ncolor, __pyx_k_Ncolor, sizeof(__pyx_k_Ncolor), 0, 0, 1, 1},
{&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0},
{&__pyx_n_s_Nt, __pyx_k_Nt, sizeof(__pyx_k_Nt), 0, 0, 1, 1},
{&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1},
{&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1},
{&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1},
{&__pyx_n_s_fNt, __pyx_k_fNt, sizeof(__pyx_k_fNt), 0, 0, 1, 1},
{&__pyx_n_s_frap_result, __pyx_k_frap_result, sizeof(__pyx_k_frap_result), 0, 0, 1, 1},
{&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1},
{&__pyx_n_s_inhibit_time, __pyx_k_inhibit_time, sizeof(__pyx_k_inhibit_time), 0, 0, 1, 1},
{&__pyx_n_s_intensity, __pyx_k_intensity, sizeof(__pyx_k_intensity), 0, 0, 1, 1},
{&__pyx_n_s_kbind, __pyx_k_kbind, sizeof(__pyx_k_kbind), 0, 0, 1, 1},
{&__pyx_n_s_kcompl, __pyx_k_kcompl, sizeof(__pyx_k_kcompl), 0, 0, 1, 1},
{&__pyx_n_s_kelong, __pyx_k_kelong, sizeof(__pyx_k_kelong), 0, 0, 1, 1},
{&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
{&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1},
{&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0},
{&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0},
{&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1},
{&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1},
{&__pyx_kp_s_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 0, 1, 0},
{&__pyx_kp_s_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 0, 1, 0},
{&__pyx_n_s_probevec, __pyx_k_probevec, sizeof(__pyx_k_probevec), 0, 0, 1, 1},
{&__pyx_n_s_r_footprint, __pyx_k_r_footprint, sizeof(__pyx_k_r_footprint), 0, 0, 1, 1},
{&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1},
{&__pyx_n_s_run_SSA, __pyx_k_run_SSA, sizeof(__pyx_k_run_SSA), 0, 0, 1, 1},
{&__pyx_n_s_seed, __pyx_k_seed, sizeof(__pyx_k_seed), 0, 0, 1, 1},
{&__pyx_n_s_ssa_translation_lowmem_nostats, __pyx_k_ssa_translation_lowmem_nostats, sizeof(__pyx_k_ssa_translation_lowmem_nostats), 0, 0, 1, 1},
{&__pyx_kp_s_ssa_translation_lowmem_nostats_p, __pyx_k_ssa_translation_lowmem_nostats_p, sizeof(__pyx_k_ssa_translation_lowmem_nostats_p), 0, 0, 1, 0},
{&__pyx_n_s_t_array, __pyx_k_t_array, sizeof(__pyx_k_t_array), 0, 0, 1, 1},
{&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
{&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0},
{&__pyx_n_s_x0, __pyx_k_x0, sizeof(__pyx_k_x0), 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 0}
};
static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) {
__pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 272, __pyx_L1_error)
__pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(1, 285, __pyx_L1_error)
__pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 856, __pyx_L1_error)
__pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 1038, __pyx_L1_error)
return 0;
__pyx_L1_error:;
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":272
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<<
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
*/
__pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 272, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple_);
__Pyx_GIVEREF(__pyx_tuple_);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":276
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<<
*
* info.buf = PyArray_DATA(self)
*/
__pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 276, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__2);
__Pyx_GIVEREF(__pyx_tuple__2);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":306
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B"
*/
__pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 306, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__3);
__Pyx_GIVEREF(__pyx_tuple__3);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":856
*
* if (end - f) - <int>(new_offset - offset[0]) < 15:
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<<
*
* if ((child.byteorder == c'>' and little_endian) or
*/
__pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 856, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__4);
__Pyx_GIVEREF(__pyx_tuple__4);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":880
* t = child.type_num
* if end - f < 5:
* raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<<
*
* # Until ticket #99 is fixed, use integers to avoid warnings
*/
__pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 880, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__5);
__Pyx_GIVEREF(__pyx_tuple__5);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1038
* _import_array()
* except Exception:
* raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_umath() except -1:
*/
__pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 1038, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__6);
__Pyx_GIVEREF(__pyx_tuple__6);
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1044
* _import_umath()
* except Exception:
* raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_ufunc() except -1:
*/
__pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 1044, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__7);
__Pyx_GIVEREF(__pyx_tuple__7);
/* "ssa_translation_lowmem_nostats.pyx":16
* @cython.wraparound(False)
*
* def run_SSA(np.ndarray[int, ndim=2, mode="c"] intensity not None, np.ndarray[double, ndim=1, mode="c"] kelong not None, np.ndarray[int, ndim=1, mode="c"] frap_result not None, np.ndarray[double, ndim=1, mode="c"] t_array not None, double kbind, double kcompl, int FRAP, int Inhibitor, double inhibit_time, int seed, np.ndarray[int, ndim=1, mode="c"] x0 not None, int r_footprint, np.ndarray[int, ndim=2, mode="c"] probevec not None, int Ncolor): # <<<<<<<<<<<<<<
* """
* I need to write this.
*/
__pyx_tuple__8 = PyTuple_Pack(17, __pyx_n_s_intensity, __pyx_n_s_kelong, __pyx_n_s_frap_result, __pyx_n_s_t_array, __pyx_n_s_kbind, __pyx_n_s_kcompl, __pyx_n_s_FRAP, __pyx_n_s_Inhibitor, __pyx_n_s_inhibit_time, __pyx_n_s_seed, __pyx_n_s_x0, __pyx_n_s_r_footprint, __pyx_n_s_probevec, __pyx_n_s_Ncolor, __pyx_n_s_Nt, __pyx_n_s_N, __pyx_n_s_fNt); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 16, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__8);
__Pyx_GIVEREF(__pyx_tuple__8);
__pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(14, 0, 17, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ssa_translation_lowmem_nostats_p, __pyx_n_s_run_SSA, 16, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) __PYX_ERR(0, 16, __pyx_L1_error)
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_RefNannyFinishContext();
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {
if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
return 0;
__pyx_L1_error:;
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/
static int __Pyx_modinit_global_init_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0);
/*--- Global init code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_variable_export_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0);
/*--- Variable export code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_function_export_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0);
/*--- Function export code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_type_init_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0);
/*--- Type init code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_type_import_code(void) {
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0);
/*--- Type import code ---*/
__pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 9, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type",
#if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000
sizeof(PyTypeObject),
#else
sizeof(PyHeapTypeObject),
#endif
__Pyx_ImportType_CheckSize_Warn);
if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(2, 9, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 206, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_ptype_5numpy_dtype = __Pyx_ImportType(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(1, 206, __pyx_L1_error)
__pyx_ptype_5numpy_flatiter = __Pyx_ImportType(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __Pyx_ImportType_CheckSize_Warn);
if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(1, 229, __pyx_L1_error)
__pyx_ptype_5numpy_broadcast = __Pyx_ImportType(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __Pyx_ImportType_CheckSize_Warn);
if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(1, 233, __pyx_L1_error)
__pyx_ptype_5numpy_ndarray = __Pyx_ImportType(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(1, 242, __pyx_L1_error)
__pyx_ptype_5numpy_ufunc = __Pyx_ImportType(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __Pyx_ImportType_CheckSize_Warn);
if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(1, 918, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_RefNannyFinishContext();
return -1;
}
static int __Pyx_modinit_variable_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0);
/*--- Variable import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_function_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0);
/*--- Function import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
#if PY_MAJOR_VERSION < 3
#ifdef CYTHON_NO_PYINIT_EXPORT
#define __Pyx_PyMODINIT_FUNC void
#else
#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC
#endif
#else
#ifdef CYTHON_NO_PYINIT_EXPORT
#define __Pyx_PyMODINIT_FUNC PyObject *
#else
#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC
#endif
#endif
#if PY_MAJOR_VERSION < 3
__Pyx_PyMODINIT_FUNC initssa_translation_lowmem_nostats(void) CYTHON_SMALL_CODE; /*proto*/
__Pyx_PyMODINIT_FUNC initssa_translation_lowmem_nostats(void)
#else
__Pyx_PyMODINIT_FUNC PyInit_ssa_translation_lowmem_nostats(void) CYTHON_SMALL_CODE; /*proto*/
__Pyx_PyMODINIT_FUNC PyInit_ssa_translation_lowmem_nostats(void)
#if CYTHON_PEP489_MULTI_PHASE_INIT
{
return PyModuleDef_Init(&__pyx_moduledef);
}
static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) {
#if PY_VERSION_HEX >= 0x030700A1
static PY_INT64_T main_interpreter_id = -1;
PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp);
if (main_interpreter_id == -1) {
main_interpreter_id = current_id;
return (unlikely(current_id == -1)) ? -1 : 0;
} else if (unlikely(main_interpreter_id != current_id))
#else
static PyInterpreterState *main_interpreter = NULL;
PyInterpreterState *current_interpreter = PyThreadState_Get()->interp;
if (!main_interpreter) {
main_interpreter = current_interpreter;
} else if (unlikely(main_interpreter != current_interpreter))
#endif
{
PyErr_SetString(
PyExc_ImportError,
"Interpreter change detected - this module can only be loaded into one interpreter per process.");
return -1;
}
return 0;
}
static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) {
PyObject *value = PyObject_GetAttrString(spec, from_name);
int result = 0;
if (likely(value)) {
if (allow_none || value != Py_None) {
result = PyDict_SetItemString(moddict, to_name, value);
}
Py_DECREF(value);
} else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
} else {
result = -1;
}
return result;
}
static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) {
PyObject *module = NULL, *moddict, *modname;
if (__Pyx_check_single_interpreter())
return NULL;
if (__pyx_m)
return __Pyx_NewRef(__pyx_m);
modname = PyObject_GetAttrString(spec, "name");
if (unlikely(!modname)) goto bad;
module = PyModule_NewObject(modname);
Py_DECREF(modname);
if (unlikely(!module)) goto bad;
moddict = PyModule_GetDict(module);
if (unlikely(!moddict)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad;
return module;
bad:
Py_XDECREF(module);
return NULL;
}
static CYTHON_SMALL_CODE int __pyx_pymod_exec_ssa_translation_lowmem_nostats(PyObject *__pyx_pyinit_module)
#endif
#endif
{
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannyDeclarations
#if CYTHON_PEP489_MULTI_PHASE_INIT
if (__pyx_m) {
if (__pyx_m == __pyx_pyinit_module) return 0;
PyErr_SetString(PyExc_RuntimeError, "Module 'ssa_translation_lowmem_nostats' has already been imported. Re-initialisation is not supported.");
return -1;
}
#elif PY_MAJOR_VERSION >= 3
if (__pyx_m) return __Pyx_NewRef(__pyx_m);
#endif
#if CYTHON_REFNANNY
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
if (!__Pyx_RefNanny) {
PyErr_Clear();
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
if (!__Pyx_RefNanny)
Py_FatalError("failed to import 'refnanny' module");
}
#endif
__Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_ssa_translation_lowmem_nostats(void)", 0);
if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#ifdef __Pxy_PyFrame_Initialize_Offsets
__Pxy_PyFrame_Initialize_Offsets();
#endif
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error)
#ifdef __Pyx_CyFunction_USED
if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_FusedFunction_USED
if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_Coroutine_USED
if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_Generator_USED
if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_AsyncGen_USED
if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_StopAsyncIteration_USED
if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
/*--- Library function declarations ---*/
/*--- Threads initialization code ---*/
#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
#ifdef WITH_THREAD /* Python build with threading support? */
PyEval_InitThreads();
#endif
#endif
/*--- Module creation code ---*/
#if CYTHON_PEP489_MULTI_PHASE_INIT
__pyx_m = __pyx_pyinit_module;
Py_INCREF(__pyx_m);
#else
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4("ssa_translation_lowmem_nostats", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_d);
__pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_b);
__pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_cython_runtime);
if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
/*--- Initialize various global constants etc. ---*/
if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
if (__pyx_module_is_main_ssa_translation_lowmem_nostats) {
if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
}
#if PY_MAJOR_VERSION >= 3
{
PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error)
if (!PyDict_GetItemString(modules, "ssa_translation_lowmem_nostats")) {
if (unlikely(PyDict_SetItemString(modules, "ssa_translation_lowmem_nostats", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error)
}
}
#endif
/*--- Builtin init code ---*/
if (__Pyx_InitCachedBuiltins() < 0) goto __pyx_L1_error;
/*--- Constants init code ---*/
if (__Pyx_InitCachedConstants() < 0) goto __pyx_L1_error;
/*--- Global type/function init code ---*/
(void)__Pyx_modinit_global_init_code();
(void)__Pyx_modinit_variable_export_code();
(void)__Pyx_modinit_function_export_code();
(void)__Pyx_modinit_type_init_code();
if (unlikely(__Pyx_modinit_type_import_code() != 0)) goto __pyx_L1_error;
(void)__Pyx_modinit_variable_import_code();
(void)__Pyx_modinit_function_import_code();
/*--- Execution code ---*/
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
/* "ssa_translation_lowmem_nostats.pyx":5
* import cython
* cimport numpy as np
* import numpy as np # <<<<<<<<<<<<<<
*
* # make the c type
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "ssa_translation_lowmem_nostats.pyx":16
* @cython.wraparound(False)
*
* def run_SSA(np.ndarray[int, ndim=2, mode="c"] intensity not None, np.ndarray[double, ndim=1, mode="c"] kelong not None, np.ndarray[int, ndim=1, mode="c"] frap_result not None, np.ndarray[double, ndim=1, mode="c"] t_array not None, double kbind, double kcompl, int FRAP, int Inhibitor, double inhibit_time, int seed, np.ndarray[int, ndim=1, mode="c"] x0 not None, int r_footprint, np.ndarray[int, ndim=2, mode="c"] probevec not None, int Ncolor): # <<<<<<<<<<<<<<
* """
* I need to write this.
*/
__pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_30ssa_translation_lowmem_nostats_1run_SSA, NULL, __pyx_n_s_ssa_translation_lowmem_nostats); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_run_SSA, __pyx_t_1) < 0) __PYX_ERR(0, 16, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "ssa_translation_lowmem_nostats.pyx":1
* # distutils: language=c++ # <<<<<<<<<<<<<<
*
* import cython
*/
__pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "../../../../Anaconda2/envs/newpy36clone/lib/site-packages/Cython/Includes/numpy/__init__.pxd":1046
* raise ImportError("numpy.core.umath failed to import")
*
* cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
/*--- Wrapped vars code ---*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
if (__pyx_m) {
if (__pyx_d) {
__Pyx_AddTraceback("init ssa_translation_lowmem_nostats", __pyx_clineno, __pyx_lineno, __pyx_filename);
}
Py_CLEAR(__pyx_m);
} else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "init ssa_translation_lowmem_nostats");
}
__pyx_L0:;
__Pyx_RefNannyFinishContext();
#if CYTHON_PEP489_MULTI_PHASE_INIT
return (__pyx_m != NULL) ? 0 : -1;
#elif PY_MAJOR_VERSION >= 3
return __pyx_m;
#else
return;
#endif
}
/* --- Runtime support code --- */
/* Refnanny */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
PyObject *m = NULL, *p = NULL;
void *r = NULL;
m = PyImport_ImportModule(modname);
if (!m) goto end;
p = PyObject_GetAttrString(m, "RefNannyAPI");
if (!p) goto end;
r = PyLong_AsVoidPtr(p);
end:
Py_XDECREF(p);
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
#endif
/* RaiseArgTupleInvalid */
static void __Pyx_RaiseArgtupleInvalid(
const char* func_name,
int exact,
Py_ssize_t num_min,
Py_ssize_t num_max,
Py_ssize_t num_found)
{
Py_ssize_t num_expected;
const char *more_or_less;
if (num_found < num_min) {
num_expected = num_min;
more_or_less = "at least";
} else {
num_expected = num_max;
more_or_less = "at most";
}
if (exact) {
more_or_less = "exactly";
}
PyErr_Format(PyExc_TypeError,
"%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
func_name, more_or_less, num_expected,
(num_expected == 1) ? "" : "s", num_found);
}
/* RaiseDoubleKeywords */
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name,
PyObject* kw_name)
{
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"%s() got multiple values for keyword argument '%U'", func_name, kw_name);
#else
"%s() got multiple values for keyword argument '%s'", func_name,
PyString_AsString(kw_name));
#endif
}
/* ParseKeywords */
static int __Pyx_ParseOptionalKeywords(
PyObject *kwds,
PyObject **argnames[],
PyObject *kwds2,
PyObject *values[],
Py_ssize_t num_pos_args,
const char* function_name)
{
PyObject *key = 0, *value = 0;
Py_ssize_t pos = 0;
PyObject*** name;
PyObject*** first_kw_arg = argnames + num_pos_args;
while (PyDict_Next(kwds, &pos, &key, &value)) {
name = first_kw_arg;
while (*name && (**name != key)) name++;
if (*name) {
values[name-argnames] = value;
continue;
}
name = first_kw_arg;
#if PY_MAJOR_VERSION < 3
if (likely(PyString_Check(key))) {
while (*name) {
if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
&& _PyString_Eq(**name, key)) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
if ((**argname == key) || (
(CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
&& _PyString_Eq(**argname, key))) {
goto arg_passed_twice;
}
argname++;
}
}
} else
#endif
if (likely(PyUnicode_Check(key))) {
while (*name) {
int cmp = (**name == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 :
#endif
PyUnicode_Compare(**name, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
int cmp = (**argname == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 :
#endif
PyUnicode_Compare(**argname, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) goto arg_passed_twice;
argname++;
}
}
} else
goto invalid_keyword_type;
if (kwds2) {
if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
} else {
goto invalid_keyword;
}
}
return 0;
arg_passed_twice:
__Pyx_RaiseDoubleKeywordsError(function_name, key);
goto bad;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings", function_name);
goto bad;
invalid_keyword:
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION < 3
"%.200s() got an unexpected keyword argument '%.200s'",
function_name, PyString_AsString(key));
#else
"%s() got an unexpected keyword argument '%U'",
function_name, key);
#endif
bad:
return -1;
}
/* ArgTypeTest */
static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact)
{
if (unlikely(!type)) {
PyErr_SetString(PyExc_SystemError, "Missing type object");
return 0;
}
else if (exact) {
#if PY_MAJOR_VERSION == 2
if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1;
#endif
}
else {
if (likely(__Pyx_TypeCheck(obj, type))) return 1;
}
PyErr_Format(PyExc_TypeError,
"Argument '%.200s' has incorrect type (expected %.200s, got %.200s)",
name, type->tp_name, Py_TYPE(obj)->tp_name);
return 0;
}
/* IsLittleEndian */
static CYTHON_INLINE int __Pyx_Is_Little_Endian(void)
{
union {
uint32_t u32;
uint8_t u8[4];
} S;
S.u32 = 0x01020304;
return S.u8[0] == 4;
}
/* BufferFormatCheck */
static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
__Pyx_BufFmt_StackElem* stack,
__Pyx_TypeInfo* type) {
stack[0].field = &ctx->root;
stack[0].parent_offset = 0;
ctx->root.type = type;
ctx->root.name = "buffer dtype";
ctx->root.offset = 0;
ctx->head = stack;
ctx->head->field = &ctx->root;
ctx->fmt_offset = 0;
ctx->head->parent_offset = 0;
ctx->new_packmode = '@';
ctx->enc_packmode = '@';
ctx->new_count = 1;
ctx->enc_count = 0;
ctx->enc_type = 0;
ctx->is_complex = 0;
ctx->is_valid_array = 0;
ctx->struct_alignment = 0;
while (type->typegroup == 'S') {
++ctx->head;
ctx->head->field = type->fields;
ctx->head->parent_offset = 0;
type = type->fields->type;
}
}
static int __Pyx_BufFmt_ParseNumber(const char** ts) {
int count;
const char* t = *ts;
if (*t < '0' || *t > '9') {
return -1;
} else {
count = *t++ - '0';
while (*t >= '0' && *t <= '9') {
count *= 10;
count += *t++ - '0';
}
}
*ts = t;
return count;
}
static int __Pyx_BufFmt_ExpectNumber(const char **ts) {
int number = __Pyx_BufFmt_ParseNumber(ts);
if (number == -1)
PyErr_Format(PyExc_ValueError,\
"Does not understand character buffer dtype format string ('%c')", **ts);
return number;
}
static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) {
PyErr_Format(PyExc_ValueError,
"Unexpected format string character: '%c'", ch);
}
static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) {
switch (ch) {
case '?': return "'bool'";
case 'c': return "'char'";
case 'b': return "'signed char'";
case 'B': return "'unsigned char'";
case 'h': return "'short'";
case 'H': return "'unsigned short'";
case 'i': return "'int'";
case 'I': return "'unsigned int'";
case 'l': return "'long'";
case 'L': return "'unsigned long'";
case 'q': return "'long long'";
case 'Q': return "'unsigned long long'";
case 'f': return (is_complex ? "'complex float'" : "'float'");
case 'd': return (is_complex ? "'complex double'" : "'double'");
case 'g': return (is_complex ? "'complex long double'" : "'long double'");
case 'T': return "a struct";
case 'O': return "Python object";
case 'P': return "a pointer";
case 's': case 'p': return "a string";
case 0: return "end";
default: return "unparseable format string";
}
}
static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return 2;
case 'i': case 'I': case 'l': case 'L': return 4;
case 'q': case 'Q': return 8;
case 'f': return (is_complex ? 8 : 4);
case 'd': return (is_complex ? 16 : 8);
case 'g': {
PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g')..");
return 0;
}
case 'O': case 'P': return sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(short);
case 'i': case 'I': return sizeof(int);
case 'l': case 'L': return sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(float) * (is_complex ? 2 : 1);
case 'd': return sizeof(double) * (is_complex ? 2 : 1);
case 'g': return sizeof(long double) * (is_complex ? 2 : 1);
case 'O': case 'P': return sizeof(void*);
default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
}
typedef struct { char c; short x; } __Pyx_st_short;
typedef struct { char c; int x; } __Pyx_st_int;
typedef struct { char c; long x; } __Pyx_st_long;
typedef struct { char c; float x; } __Pyx_st_float;
typedef struct { char c; double x; } __Pyx_st_double;
typedef struct { char c; long double x; } __Pyx_st_longdouble;
typedef struct { char c; void *x; } __Pyx_st_void_p;
#ifdef HAVE_LONG_LONG
typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong;
#endif
static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short);
case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int);
case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(__Pyx_st_float) - sizeof(float);
case 'd': return sizeof(__Pyx_st_double) - sizeof(double);
case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double);
case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
/* These are for computing the padding at the end of the struct to align
on the first member of the struct. This will probably the same as above,
but we don't have any guarantees.
*/
typedef struct { short x; char c; } __Pyx_pad_short;
typedef struct { int x; char c; } __Pyx_pad_int;
typedef struct { long x; char c; } __Pyx_pad_long;
typedef struct { float x; char c; } __Pyx_pad_float;
typedef struct { double x; char c; } __Pyx_pad_double;
typedef struct { long double x; char c; } __Pyx_pad_longdouble;
typedef struct { void *x; char c; } __Pyx_pad_void_p;
#ifdef HAVE_LONG_LONG
typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong;
#endif
static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short);
case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int);
case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(__Pyx_pad_float) - sizeof(float);
case 'd': return sizeof(__Pyx_pad_double) - sizeof(double);
case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double);
case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) {
switch (ch) {
case 'c':
return 'H';
case 'b': case 'h': case 'i':
case 'l': case 'q': case 's': case 'p':
return 'I';
case '?': case 'B': case 'H': case 'I': case 'L': case 'Q':
return 'U';
case 'f': case 'd': case 'g':
return (is_complex ? 'C' : 'R');
case 'O':
return 'O';
case 'P':
return 'P';
default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
}
static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) {
if (ctx->head == NULL || ctx->head->field == &ctx->root) {
const char* expected;
const char* quote;
if (ctx->head == NULL) {
expected = "end";
quote = "";
} else {
expected = ctx->head->field->type->name;
quote = "'";
}
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch, expected %s%s%s but got %s",
quote, expected, quote,
__Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex));
} else {
__Pyx_StructField* field = ctx->head->field;
__Pyx_StructField* parent = (ctx->head - 1)->field;
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'",
field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex),
parent->type->name, field->name);
}
}
static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
char group;
size_t size, offset, arraysize = 1;
if (ctx->enc_type == 0) return 0;
if (ctx->head->field->type->arraysize[0]) {
int i, ndim = 0;
if (ctx->enc_type == 's' || ctx->enc_type == 'p') {
ctx->is_valid_array = ctx->head->field->type->ndim == 1;
ndim = 1;
if (ctx->enc_count != ctx->head->field->type->arraysize[0]) {
PyErr_Format(PyExc_ValueError,
"Expected a dimension of size %zu, got %zu",
ctx->head->field->type->arraysize[0], ctx->enc_count);
return -1;
}
}
if (!ctx->is_valid_array) {
PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d",
ctx->head->field->type->ndim, ndim);
return -1;
}
for (i = 0; i < ctx->head->field->type->ndim; i++) {
arraysize *= ctx->head->field->type->arraysize[i];
}
ctx->is_valid_array = 0;
ctx->enc_count = 1;
}
group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex);
do {
__Pyx_StructField* field = ctx->head->field;
__Pyx_TypeInfo* type = field->type;
if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') {
size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex);
} else {
size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex);
}
if (ctx->enc_packmode == '@') {
size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex);
size_t align_mod_offset;
if (align_at == 0) return -1;
align_mod_offset = ctx->fmt_offset % align_at;
if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset;
if (ctx->struct_alignment == 0)
ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type,
ctx->is_complex);
}
if (type->size != size || type->typegroup != group) {
if (type->typegroup == 'C' && type->fields != NULL) {
size_t parent_offset = ctx->head->parent_offset + field->offset;
++ctx->head;
ctx->head->field = type->fields;
ctx->head->parent_offset = parent_offset;
continue;
}
if ((type->typegroup == 'H' || group == 'H') && type->size == size) {
} else {
__Pyx_BufFmt_RaiseExpected(ctx);
return -1;
}
}
offset = ctx->head->parent_offset + field->offset;
if (ctx->fmt_offset != offset) {
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected",
(Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset);
return -1;
}
ctx->fmt_offset += size;
if (arraysize)
ctx->fmt_offset += (arraysize - 1) * size;
--ctx->enc_count;
while (1) {
if (field == &ctx->root) {
ctx->head = NULL;
if (ctx->enc_count != 0) {
__Pyx_BufFmt_RaiseExpected(ctx);
return -1;
}
break;
}
ctx->head->field = ++field;
if (field->type == NULL) {
--ctx->head;
field = ctx->head->field;
continue;
} else if (field->type->typegroup == 'S') {
size_t parent_offset = ctx->head->parent_offset + field->offset;
if (field->type->fields->type == NULL) continue;
field = field->type->fields;
++ctx->head;
ctx->head->field = field;
ctx->head->parent_offset = parent_offset;
break;
} else {
break;
}
}
} while (ctx->enc_count);
ctx->enc_type = 0;
ctx->is_complex = 0;
return 0;
}
static PyObject *
__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp)
{
const char *ts = *tsp;
int i = 0, number;
int ndim = ctx->head->field->type->ndim;
;
++ts;
if (ctx->new_count != 1) {
PyErr_SetString(PyExc_ValueError,
"Cannot handle repeated arrays in format string");
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
while (*ts && *ts != ')') {
switch (*ts) {
case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue;
default: break;
}
number = __Pyx_BufFmt_ExpectNumber(&ts);
if (number == -1) return NULL;
if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i])
return PyErr_Format(PyExc_ValueError,
"Expected a dimension of size %zu, got %d",
ctx->head->field->type->arraysize[i], number);
if (*ts != ',' && *ts != ')')
return PyErr_Format(PyExc_ValueError,
"Expected a comma in format string, got '%c'", *ts);
if (*ts == ',') ts++;
i++;
}
if (i != ndim)
return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d",
ctx->head->field->type->ndim, i);
if (!*ts) {
PyErr_SetString(PyExc_ValueError,
"Unexpected end of format string, expected ')'");
return NULL;
}
ctx->is_valid_array = 1;
ctx->new_count = 1;
*tsp = ++ts;
return Py_None;
}
static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) {
int got_Z = 0;
while (1) {
switch(*ts) {
case 0:
if (ctx->enc_type != 0 && ctx->head == NULL) {
__Pyx_BufFmt_RaiseExpected(ctx);
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
if (ctx->head != NULL) {
__Pyx_BufFmt_RaiseExpected(ctx);
return NULL;
}
return ts;
case ' ':
case '\r':
case '\n':
++ts;
break;
case '<':
if (!__Pyx_Is_Little_Endian()) {
PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler");
return NULL;
}
ctx->new_packmode = '=';
++ts;
break;
case '>':
case '!':
if (__Pyx_Is_Little_Endian()) {
PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler");
return NULL;
}
ctx->new_packmode = '=';
++ts;
break;
case '=':
case '@':
case '^':
ctx->new_packmode = *ts++;
break;
case 'T':
{
const char* ts_after_sub;
size_t i, struct_count = ctx->new_count;
size_t struct_alignment = ctx->struct_alignment;
ctx->new_count = 1;
++ts;
if (*ts != '{') {
PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'");
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_type = 0;
ctx->enc_count = 0;
ctx->struct_alignment = 0;
++ts;
ts_after_sub = ts;
for (i = 0; i != struct_count; ++i) {
ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts);
if (!ts_after_sub) return NULL;
}
ts = ts_after_sub;
if (struct_alignment) ctx->struct_alignment = struct_alignment;
}
break;
case '}':
{
size_t alignment = ctx->struct_alignment;
++ts;
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_type = 0;
if (alignment && ctx->fmt_offset % alignment) {
ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment);
}
}
return ts;
case 'x':
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->fmt_offset += ctx->new_count;
ctx->new_count = 1;
ctx->enc_count = 0;
ctx->enc_type = 0;
ctx->enc_packmode = ctx->new_packmode;
++ts;
break;
case 'Z':
got_Z = 1;
++ts;
if (*ts != 'f' && *ts != 'd' && *ts != 'g') {
__Pyx_BufFmt_RaiseUnexpectedChar('Z');
return NULL;
}
CYTHON_FALLTHROUGH;
case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I':
case 'l': case 'L': case 'q': case 'Q':
case 'f': case 'd': case 'g':
case 'O': case 'p':
if (ctx->enc_type == *ts && got_Z == ctx->is_complex &&
ctx->enc_packmode == ctx->new_packmode) {
ctx->enc_count += ctx->new_count;
ctx->new_count = 1;
got_Z = 0;
++ts;
break;
}
CYTHON_FALLTHROUGH;
case 's':
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_count = ctx->new_count;
ctx->enc_packmode = ctx->new_packmode;
ctx->enc_type = *ts;
ctx->is_complex = got_Z;
++ts;
ctx->new_count = 1;
got_Z = 0;
break;
case ':':
++ts;
while(*ts != ':') ++ts;
++ts;
break;
case '(':
if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL;
break;
default:
{
int number = __Pyx_BufFmt_ExpectNumber(&ts);
if (number == -1) return NULL;
ctx->new_count = (size_t)number;
}
}
}
}
/* BufferGetAndValidate */
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) {
if (unlikely(info->buf == NULL)) return;
if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL;
__Pyx_ReleaseBuffer(info);
}
static void __Pyx_ZeroBuffer(Py_buffer* buf) {
buf->buf = NULL;
buf->obj = NULL;
buf->strides = __Pyx_zeros;
buf->shape = __Pyx_zeros;
buf->suboffsets = __Pyx_minusones;
}
static int __Pyx__GetBufferAndValidate(
Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags,
int nd, int cast, __Pyx_BufFmt_StackElem* stack)
{
buf->buf = NULL;
if (unlikely(__Pyx_GetBuffer(obj, buf, flags) == -1)) {
__Pyx_ZeroBuffer(buf);
return -1;
}
if (unlikely(buf->ndim != nd)) {
PyErr_Format(PyExc_ValueError,
"Buffer has wrong number of dimensions (expected %d, got %d)",
nd, buf->ndim);
goto fail;
}
if (!cast) {
__Pyx_BufFmt_Context ctx;
__Pyx_BufFmt_Init(&ctx, stack, dtype);
if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail;
}
if (unlikely((size_t)buf->itemsize != dtype->size)) {
PyErr_Format(PyExc_ValueError,
"Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)",
buf->itemsize, (buf->itemsize > 1) ? "s" : "",
dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : "");
goto fail;
}
if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones;
return 0;
fail:;
__Pyx_SafeReleaseBuffer(buf);
return -1;
}
/* PyErrFetchRestore */
#if CYTHON_FAST_THREAD_STATE
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) {
PyObject *tmp_type, *tmp_value, *tmp_tb;
tmp_type = tstate->curexc_type;
tmp_value = tstate->curexc_value;
tmp_tb = tstate->curexc_traceback;
tstate->curexc_type = type;
tstate->curexc_value = value;
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) {
*type = tstate->curexc_type;
*value = tstate->curexc_value;
*tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
}
#endif
/* PyObjectGetAttrStr */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
PyTypeObject* tp = Py_TYPE(obj);
if (likely(tp->tp_getattro))
return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
if (likely(tp->tp_getattr))
return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
return PyObject_GetAttr(obj, attr_name);
}
#endif
/* GetBuiltinName */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
if (unlikely(!result)) {
PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
"name '%U' is not defined", name);
#else
"name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
}
return result;
}
/* PyObjectCall */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyObject *result;
ternaryfunc call = func->ob_type->tp_call;
if (unlikely(!call))
return PyObject_Call(func, arg, kw);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = (*call)(func, arg, kw);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* RaiseException */
#if PY_MAJOR_VERSION < 3
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb,
CYTHON_UNUSED PyObject *cause) {
__Pyx_PyThreadState_declare
Py_XINCREF(type);
if (!value || value == Py_None)
value = NULL;
else
Py_INCREF(value);
if (!tb || tb == Py_None)
tb = NULL;
else {
Py_INCREF(tb);
if (!PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto raise_error;
}
}
if (PyType_Check(type)) {
#if CYTHON_COMPILING_IN_PYPY
if (!value) {
Py_INCREF(Py_None);
value = Py_None;
}
#endif
PyErr_NormalizeException(&type, &value, &tb);
} else {
if (value) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto raise_error;
}
value = type;
type = (PyObject*) Py_TYPE(type);
Py_INCREF(type);
if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto raise_error;
}
}
__Pyx_PyThreadState_assign
__Pyx_ErrRestore(type, value, tb);
return;
raise_error:
Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(tb);
return;
}
#else
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) {
PyObject* owned_instance = NULL;
if (tb == Py_None) {
tb = 0;
} else if (tb && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto bad;
}
if (value == Py_None)
value = 0;
if (PyExceptionInstance_Check(type)) {
if (value) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto bad;
}
value = type;
type = (PyObject*) Py_TYPE(value);
} else if (PyExceptionClass_Check(type)) {
PyObject *instance_class = NULL;
if (value && PyExceptionInstance_Check(value)) {
instance_class = (PyObject*) Py_TYPE(value);
if (instance_class != type) {
int is_subclass = PyObject_IsSubclass(instance_class, type);
if (!is_subclass) {
instance_class = NULL;
} else if (unlikely(is_subclass == -1)) {
goto bad;
} else {
type = instance_class;
}
}
}
if (!instance_class) {
PyObject *args;
if (!value)
args = PyTuple_New(0);
else if (PyTuple_Check(value)) {
Py_INCREF(value);
args = value;
} else
args = PyTuple_Pack(1, value);
if (!args)
goto bad;
owned_instance = PyObject_Call(type, args, NULL);
Py_DECREF(args);
if (!owned_instance)
goto bad;
value = owned_instance;
if (!PyExceptionInstance_Check(value)) {
PyErr_Format(PyExc_TypeError,
"calling %R should have returned an instance of "
"BaseException, not %R",
type, Py_TYPE(value));
goto bad;
}
}
} else {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto bad;
}
if (cause) {
PyObject *fixed_cause;
if (cause == Py_None) {
fixed_cause = NULL;
} else if (PyExceptionClass_Check(cause)) {
fixed_cause = PyObject_CallObject(cause, NULL);
if (fixed_cause == NULL)
goto bad;
} else if (PyExceptionInstance_Check(cause)) {
fixed_cause = cause;
Py_INCREF(fixed_cause);
} else {
PyErr_SetString(PyExc_TypeError,
"exception causes must derive from "
"BaseException");
goto bad;
}
PyException_SetCause(value, fixed_cause);
}
PyErr_SetObject(type, value);
if (tb) {
#if CYTHON_COMPILING_IN_PYPY
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb);
Py_INCREF(tb);
PyErr_Restore(tmp_type, tmp_value, tb);
Py_XDECREF(tmp_tb);
#else
PyThreadState *tstate = __Pyx_PyThreadState_Current;
PyObject* tmp_tb = tstate->curexc_traceback;
if (tb != tmp_tb) {
Py_INCREF(tb);
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_tb);
}
#endif
}
bad:
Py_XDECREF(owned_instance);
return;
}
#endif
/* PyCFunctionFastCall */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) {
PyCFunctionObject *func = (PyCFunctionObject*)func_obj;
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
PyObject *self = PyCFunction_GET_SELF(func);
int flags = PyCFunction_GET_FLAGS(func);
assert(PyCFunction_Check(func));
assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)));
assert(nargs >= 0);
assert(nargs == 0 || args != NULL);
/* _PyCFunction_FastCallDict() must not be called with an exception set,
because it may clear it (directly or indirectly) and so the
caller loses its exception */
assert(!PyErr_Occurred());
if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) {
return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL);
} else {
return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs);
}
}
#endif
/* PyFunctionFastCall */
#if CYTHON_FAST_PYCALL
static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na,
PyObject *globals) {
PyFrameObject *f;
PyThreadState *tstate = __Pyx_PyThreadState_Current;
PyObject **fastlocals;
Py_ssize_t i;
PyObject *result;
assert(globals != NULL);
/* XXX Perhaps we should create a specialized
PyFrame_New() that doesn't take locals, but does
take builtins without sanity checking them.
*/
assert(tstate != NULL);
f = PyFrame_New(tstate, co, globals, NULL);
if (f == NULL) {
return NULL;
}
fastlocals = __Pyx_PyFrame_GetLocalsplus(f);
for (i = 0; i < na; i++) {
Py_INCREF(*args);
fastlocals[i] = *args++;
}
result = PyEval_EvalFrameEx(f,0);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
return result;
}
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) {
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject *closure;
#if PY_MAJOR_VERSION >= 3
PyObject *kwdefs;
#endif
PyObject *kwtuple, **k;
PyObject **d;
Py_ssize_t nd;
Py_ssize_t nk;
PyObject *result;
assert(kwargs == NULL || PyDict_Check(kwargs));
nk = kwargs ? PyDict_Size(kwargs) : 0;
if (Py_EnterRecursiveCall((char*)" while calling a Python object")) {
return NULL;
}
if (
#if PY_MAJOR_VERSION >= 3
co->co_kwonlyargcount == 0 &&
#endif
likely(kwargs == NULL || nk == 0) &&
co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
if (argdefs == NULL && co->co_argcount == nargs) {
result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals);
goto done;
}
else if (nargs == 0 && argdefs != NULL
&& co->co_argcount == Py_SIZE(argdefs)) {
/* function called with no arguments, but all parameters have
a default value: use default values as arguments .*/
args = &PyTuple_GET_ITEM(argdefs, 0);
result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals);
goto done;
}
}
if (kwargs != NULL) {
Py_ssize_t pos, i;
kwtuple = PyTuple_New(2 * nk);
if (kwtuple == NULL) {
result = NULL;
goto done;
}
k = &PyTuple_GET_ITEM(kwtuple, 0);
pos = i = 0;
while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) {
Py_INCREF(k[i]);
Py_INCREF(k[i+1]);
i += 2;
}
nk = i / 2;
}
else {
kwtuple = NULL;
k = NULL;
}
closure = PyFunction_GET_CLOSURE(func);
#if PY_MAJOR_VERSION >= 3
kwdefs = PyFunction_GET_KW_DEFAULTS(func);
#endif
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
else {
d = NULL;
nd = 0;
}
#if PY_MAJOR_VERSION >= 3
result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL,
args, (int)nargs,
k, (int)nk,
d, (int)nd, kwdefs, closure);
#else
result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL,
args, (int)nargs,
k, (int)nk,
d, (int)nd, closure);
#endif
Py_XDECREF(kwtuple);
done:
Py_LeaveRecursiveCall();
return result;
}
#endif
#endif
/* PyObjectCallMethO */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) {
PyObject *self, *result;
PyCFunction cfunc;
cfunc = PyCFunction_GET_FUNCTION(func);
self = PyCFunction_GET_SELF(func);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = cfunc(self, arg);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* PyObjectCallOneArg */
#if CYTHON_COMPILING_IN_CPYTHON
static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) {
PyObject *result;
PyObject *args = PyTuple_New(1);
if (unlikely(!args)) return NULL;
Py_INCREF(arg);
PyTuple_SET_ITEM(args, 0, arg);
result = __Pyx_PyObject_Call(func, args, NULL);
Py_DECREF(args);
return result;
}
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(func)) {
return __Pyx_PyFunction_FastCall(func, &arg, 1);
}
#endif
if (likely(PyCFunction_Check(func))) {
if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) {
return __Pyx_PyObject_CallMethO(func, arg);
#if CYTHON_FAST_PYCCALL
} else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) {
return __Pyx_PyCFunction_FastCall(func, &arg, 1);
#endif
}
}
return __Pyx__PyObject_CallOneArg(func, arg);
}
#else
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
PyObject *result;
PyObject *args = PyTuple_Pack(1, arg);
if (unlikely(!args)) return NULL;
result = __Pyx_PyObject_Call(func, args, NULL);
Py_DECREF(args);
return result;
}
#endif
/* DictGetItem */
#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY
static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) {
PyObject *value;
value = PyDict_GetItemWithError(d, key);
if (unlikely(!value)) {
if (!PyErr_Occurred()) {
if (unlikely(PyTuple_Check(key))) {
PyObject* args = PyTuple_Pack(1, key);
if (likely(args)) {
PyErr_SetObject(PyExc_KeyError, args);
Py_DECREF(args);
}
} else {
PyErr_SetObject(PyExc_KeyError, key);
}
}
return NULL;
}
Py_INCREF(value);
return value;
}
#endif
/* RaiseTooManyValuesToUnpack */
static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
PyErr_Format(PyExc_ValueError,
"too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected);
}
/* RaiseNeedMoreValuesToUnpack */
static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
PyErr_Format(PyExc_ValueError,
"need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack",
index, (index == 1) ? "" : "s");
}
/* RaiseNoneIterError */
static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) {
PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
}
/* ExtTypeTest */
static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
if (unlikely(!type)) {
PyErr_SetString(PyExc_SystemError, "Missing type object");
return 0;
}
if (likely(__Pyx_TypeCheck(obj, type)))
return 1;
PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s",
Py_TYPE(obj)->tp_name, type->tp_name);
return 0;
}
/* GetTopmostException */
#if CYTHON_USE_EXC_INFO_STACK
static _PyErr_StackItem *
__Pyx_PyErr_GetTopmostException(PyThreadState *tstate)
{
_PyErr_StackItem *exc_info = tstate->exc_info;
while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) &&
exc_info->previous_item != NULL)
{
exc_info = exc_info->previous_item;
}
return exc_info;
}
#endif
/* SaveResetException */
#if CYTHON_FAST_THREAD_STATE
static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) {
#if CYTHON_USE_EXC_INFO_STACK
_PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate);
*type = exc_info->exc_type;
*value = exc_info->exc_value;
*tb = exc_info->exc_traceback;
#else
*type = tstate->exc_type;
*value = tstate->exc_value;
*tb = tstate->exc_traceback;
#endif
Py_XINCREF(*type);
Py_XINCREF(*value);
Py_XINCREF(*tb);
}
static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) {
PyObject *tmp_type, *tmp_value, *tmp_tb;
#if CYTHON_USE_EXC_INFO_STACK
_PyErr_StackItem *exc_info = tstate->exc_info;
tmp_type = exc_info->exc_type;
tmp_value = exc_info->exc_value;
tmp_tb = exc_info->exc_traceback;
exc_info->exc_type = type;
exc_info->exc_value = value;
exc_info->exc_traceback = tb;
#else
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
tstate->exc_type = type;
tstate->exc_value = value;
tstate->exc_traceback = tb;
#endif
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
#endif
/* PyErrExceptionMatches */
#if CYTHON_FAST_THREAD_STATE
static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) {
Py_ssize_t i, n;
n = PyTuple_GET_SIZE(tuple);
#if PY_MAJOR_VERSION >= 3
for (i=0; i<n; i++) {
if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1;
}
#endif
for (i=0; i<n; i++) {
if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1;
}
return 0;
}
static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) {
PyObject *exc_type = tstate->curexc_type;
if (exc_type == err) return 1;
if (unlikely(!exc_type)) return 0;
if (unlikely(PyTuple_Check(err)))
return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err);
return __Pyx_PyErr_GivenExceptionMatches(exc_type, err);
}
#endif
/* GetException */
#if CYTHON_FAST_THREAD_STATE
static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb)
#else
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb)
#endif
{
PyObject *local_type, *local_value, *local_tb;
#if CYTHON_FAST_THREAD_STATE
PyObject *tmp_type, *tmp_value, *tmp_tb;
local_type = tstate->curexc_type;
local_value = tstate->curexc_value;
local_tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
#else
PyErr_Fetch(&local_type, &local_value, &local_tb);
#endif
PyErr_NormalizeException(&local_type, &local_value, &local_tb);
#if CYTHON_FAST_THREAD_STATE
if (unlikely(tstate->curexc_type))
#else
if (unlikely(PyErr_Occurred()))
#endif
goto bad;
#if PY_MAJOR_VERSION >= 3
if (local_tb) {
if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0))
goto bad;
}
#endif
Py_XINCREF(local_tb);
Py_XINCREF(local_type);
Py_XINCREF(local_value);
*type = local_type;
*value = local_value;
*tb = local_tb;
#if CYTHON_FAST_THREAD_STATE
#if CYTHON_USE_EXC_INFO_STACK
{
_PyErr_StackItem *exc_info = tstate->exc_info;
tmp_type = exc_info->exc_type;
tmp_value = exc_info->exc_value;
tmp_tb = exc_info->exc_traceback;
exc_info->exc_type = local_type;
exc_info->exc_value = local_value;
exc_info->exc_traceback = local_tb;
}
#else
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
tstate->exc_type = local_type;
tstate->exc_value = local_value;
tstate->exc_traceback = local_tb;
#endif
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
#else
PyErr_SetExcInfo(local_type, local_value, local_tb);
#endif
return 0;
bad:
*type = 0;
*value = 0;
*tb = 0;
Py_XDECREF(local_type);
Py_XDECREF(local_value);
Py_XDECREF(local_tb);
return -1;
}
/* TypeImport */
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name,
size_t size, enum __Pyx_ImportType_CheckSize check_size)
{
PyObject *result = 0;
char warning[200];
Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
PyObject *py_basicsize;
#endif
result = PyObject_GetAttrString(module, class_name);
if (!result)
goto bad;
if (!PyType_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%.200s.%.200s is not a type object",
module_name, class_name);
goto bad;
}
#ifndef Py_LIMITED_API
basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
if (!py_basicsize)
goto bad;
basicsize = PyLong_AsSsize_t(py_basicsize);
Py_DECREF(py_basicsize);
py_basicsize = 0;
if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
goto bad;
#endif
if ((size_t)basicsize < size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
goto bad;
}
if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
goto bad;
}
else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) {
PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
}
return (PyTypeObject *)result;
bad:
Py_XDECREF(result);
return NULL;
}
#endif
/* Import */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) {
PyObject *empty_list = 0;
PyObject *module = 0;
PyObject *global_dict = 0;
PyObject *empty_dict = 0;
PyObject *list;
#if PY_MAJOR_VERSION < 3
PyObject *py_import;
py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import);
if (!py_import)
goto bad;
#endif
if (from_list)
list = from_list;
else {
empty_list = PyList_New(0);
if (!empty_list)
goto bad;
list = empty_list;
}
global_dict = PyModule_GetDict(__pyx_m);
if (!global_dict)
goto bad;
empty_dict = PyDict_New();
if (!empty_dict)
goto bad;
{
#if PY_MAJOR_VERSION >= 3
if (level == -1) {
if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) {
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, 1);
if (!module) {
if (!PyErr_ExceptionMatches(PyExc_ImportError))
goto bad;
PyErr_Clear();
}
}
level = 0;
}
#endif
if (!module) {
#if PY_MAJOR_VERSION < 3
PyObject *py_level = PyInt_FromLong(level);
if (!py_level)
goto bad;
module = PyObject_CallFunctionObjArgs(py_import,
name, global_dict, empty_dict, list, py_level, (PyObject *)NULL);
Py_DECREF(py_level);
#else
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, level);
#endif
}
}
bad:
#if PY_MAJOR_VERSION < 3
Py_XDECREF(py_import);
#endif
Py_XDECREF(empty_list);
Py_XDECREF(empty_dict);
return module;
}
/* PyDictVersioning */
#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) {
PyObject *dict = Py_TYPE(obj)->tp_dict;
return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0;
}
static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) {
PyObject **dictptr = NULL;
Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset;
if (offset) {
#if CYTHON_COMPILING_IN_CPYTHON
dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj);
#else
dictptr = _PyObject_GetDictPtr(obj);
#endif
}
return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0;
}
static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) {
PyObject *dict = Py_TYPE(obj)->tp_dict;
if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict)))
return 0;
return obj_dict_version == __Pyx_get_object_dict_version(obj);
}
#endif
/* CLineInTraceback */
#ifndef CYTHON_CLINE_IN_TRACEBACK
static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) {
PyObject *use_cline;
PyObject *ptype, *pvalue, *ptraceback;
#if CYTHON_COMPILING_IN_CPYTHON
PyObject **cython_runtime_dict;
#endif
if (unlikely(!__pyx_cython_runtime)) {
return c_line;
}
__Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback);
#if CYTHON_COMPILING_IN_CPYTHON
cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime);
if (likely(cython_runtime_dict)) {
__PYX_PY_DICT_LOOKUP_IF_MODIFIED(
use_cline, *cython_runtime_dict,
__Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback))
} else
#endif
{
PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback);
if (use_cline_obj) {
use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True;
Py_DECREF(use_cline_obj);
} else {
PyErr_Clear();
use_cline = NULL;
}
}
if (!use_cline) {
c_line = 0;
PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False);
}
else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) {
c_line = 0;
}
__Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback);
return c_line;
}
#endif
/* CodeObjectCache */
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) {
int start = 0, mid = 0, end = count - 1;
if (end >= 0 && code_line > entries[end].code_line) {
return count;
}
while (start < end) {
mid = start + (end - start) / 2;
if (code_line < entries[mid].code_line) {
end = mid;
} else if (code_line > entries[mid].code_line) {
start = mid + 1;
} else {
return mid;
}
}
if (code_line <= entries[mid].code_line) {
return mid;
} else {
return mid + 1;
}
}
static PyCodeObject *__pyx_find_code_object(int code_line) {
PyCodeObject* code_object;
int pos;
if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) {
return NULL;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) {
return NULL;
}
code_object = __pyx_code_cache.entries[pos].code_object;
Py_INCREF(code_object);
return code_object;
}
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) {
int pos, i;
__Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries;
if (unlikely(!code_line)) {
return;
}
if (unlikely(!entries)) {
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry));
if (likely(entries)) {
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = 64;
__pyx_code_cache.count = 1;
entries[0].code_line = code_line;
entries[0].code_object = code_object;
Py_INCREF(code_object);
}
return;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) {
PyCodeObject* tmp = entries[pos].code_object;
entries[pos].code_object = code_object;
Py_DECREF(tmp);
return;
}
if (__pyx_code_cache.count == __pyx_code_cache.max_count) {
int new_max = __pyx_code_cache.max_count + 64;
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc(
__pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry));
if (unlikely(!entries)) {
return;
}
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = new_max;
}
for (i=__pyx_code_cache.count; i>pos; i--) {
entries[i] = entries[i-1];
}
entries[pos].code_line = code_line;
entries[pos].code_object = code_object;
__pyx_code_cache.count++;
Py_INCREF(code_object);
}
/* AddTraceback */
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static PyCodeObject* __Pyx_CreateCodeObjectForTraceback(
const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
#if PY_MAJOR_VERSION < 3
py_srcfile = PyString_FromString(filename);
#else
py_srcfile = PyUnicode_FromString(filename);
#endif
if (!py_srcfile) goto bad;
if (c_line) {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#else
py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#endif
}
else {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromString(funcname);
#else
py_funcname = PyUnicode_FromString(funcname);
#endif
}
if (!py_funcname) goto bad;
py_code = __Pyx_PyCode_New(
0,
0,
0,
0,
0,
__pyx_empty_bytes, /*PyObject *code,*/
__pyx_empty_tuple, /*PyObject *consts,*/
__pyx_empty_tuple, /*PyObject *names,*/
__pyx_empty_tuple, /*PyObject *varnames,*/
__pyx_empty_tuple, /*PyObject *freevars,*/
__pyx_empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
py_line,
__pyx_empty_bytes /*PyObject *lnotab*/
);
Py_DECREF(py_srcfile);
Py_DECREF(py_funcname);
return py_code;
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
return NULL;
}
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
PyThreadState *tstate = __Pyx_PyThreadState_Current;
if (c_line) {
c_line = __Pyx_CLineForTraceback(tstate, c_line);
}
py_code = __pyx_find_code_object(c_line ? -c_line : py_line);
if (!py_code) {
py_code = __Pyx_CreateCodeObjectForTraceback(
funcname, c_line, py_line, filename);
if (!py_code) goto bad;
__pyx_insert_code_object(c_line ? -c_line : py_line, py_code);
}
py_frame = PyFrame_New(
tstate, /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
__pyx_d, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
__Pyx_PyFrame_SetLineNumber(py_frame, py_line);
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
#if PY_MAJOR_VERSION < 3
static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) {
if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags);
if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags);
PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name);
return -1;
}
static void __Pyx_ReleaseBuffer(Py_buffer *view) {
PyObject *obj = view->obj;
if (!obj) return;
if (PyObject_CheckBuffer(obj)) {
PyBuffer_Release(view);
return;
}
if ((0)) {}
else if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view);
view->obj = NULL;
Py_DECREF(obj);
}
#endif
/* CIntFromPyVerify */
#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0)
#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1)
#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\
{\
func_type value = func_value;\
if (sizeof(target_type) < sizeof(func_type)) {\
if (unlikely(value != (func_type) (target_type) value)) {\
func_type zero = 0;\
if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\
return (target_type) -1;\
if (is_unsigned && unlikely(value < zero))\
goto raise_neg_overflow;\
else\
goto raise_overflow;\
}\
}\
return (target_type) value;\
}
/* Declarations */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
return ::std::complex< float >(x, y);
}
#else
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
return x + y*(__pyx_t_float_complex)_Complex_I;
}
#endif
#else
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
__pyx_t_float_complex z;
z.real = x;
z.imag = y;
return z;
}
#endif
/* Arithmetic */
#if CYTHON_CCOMPLEX
#else
static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
return (a.real == b.real) && (a.imag == b.imag);
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real + b.real;
z.imag = a.imag + b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real - b.real;
z.imag = a.imag - b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real * b.real - a.imag * b.imag;
z.imag = a.real * b.imag + a.imag * b.real;
return z;
}
#if 1
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
if (b.imag == 0) {
return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real);
} else if (fabsf(b.real) >= fabsf(b.imag)) {
if (b.real == 0 && b.imag == 0) {
return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag);
} else {
float r = b.imag / b.real;
float s = (float)(1.0) / (b.real + b.imag * r);
return __pyx_t_float_complex_from_parts(
(a.real + a.imag * r) * s, (a.imag - a.real * r) * s);
}
} else {
float r = b.real / b.imag;
float s = (float)(1.0) / (b.imag + b.real * r);
return __pyx_t_float_complex_from_parts(
(a.real * r + a.imag) * s, (a.imag * r - a.real) * s);
}
}
#else
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
if (b.imag == 0) {
return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real);
} else {
float denom = b.real * b.real + b.imag * b.imag;
return __pyx_t_float_complex_from_parts(
(a.real * b.real + a.imag * b.imag) / denom,
(a.imag * b.real - a.real * b.imag) / denom);
}
}
#endif
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) {
__pyx_t_float_complex z;
z.real = -a.real;
z.imag = -a.imag;
return z;
}
static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) {
return (a.real == 0) && (a.imag == 0);
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) {
__pyx_t_float_complex z;
z.real = a.real;
z.imag = -a.imag;
return z;
}
#if 1
static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) {
#if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return sqrtf(z.real*z.real + z.imag*z.imag);
#else
return hypotf(z.real, z.imag);
#endif
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
float r, lnr, theta, z_r, z_theta;
if (b.imag == 0 && b.real == (int)b.real) {
if (b.real < 0) {
float denom = a.real * a.real + a.imag * a.imag;
a.real = a.real / denom;
a.imag = -a.imag / denom;
b.real = -b.real;
}
switch ((int)b.real) {
case 0:
z.real = 1;
z.imag = 0;
return z;
case 1:
return a;
case 2:
return __Pyx_c_prod_float(a, a);
case 3:
z = __Pyx_c_prod_float(a, a);
return __Pyx_c_prod_float(z, a);
case 4:
z = __Pyx_c_prod_float(a, a);
return __Pyx_c_prod_float(z, z);
}
}
if (a.imag == 0) {
if (a.real == 0) {
return a;
} else if (b.imag == 0) {
z.real = powf(a.real, b.real);
z.imag = 0;
return z;
} else if (a.real > 0) {
r = a.real;
theta = 0;
} else {
r = -a.real;
theta = atan2f(0.0, -1.0);
}
} else {
r = __Pyx_c_abs_float(a);
theta = atan2f(a.imag, a.real);
}
lnr = logf(r);
z_r = expf(lnr * b.real - theta * b.imag);
z_theta = theta * b.real + lnr * b.imag;
z.real = z_r * cosf(z_theta);
z.imag = z_r * sinf(z_theta);
return z;
}
#endif
#endif
/* Declarations */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
return ::std::complex< double >(x, y);
}
#else
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
return x + y*(__pyx_t_double_complex)_Complex_I;
}
#endif
#else
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
__pyx_t_double_complex z;
z.real = x;
z.imag = y;
return z;
}
#endif
/* Arithmetic */
#if CYTHON_CCOMPLEX
#else
static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
return (a.real == b.real) && (a.imag == b.imag);
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real + b.real;
z.imag = a.imag + b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real - b.real;
z.imag = a.imag - b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real * b.real - a.imag * b.imag;
z.imag = a.real * b.imag + a.imag * b.real;
return z;
}
#if 1
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
if (b.imag == 0) {
return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real);
} else if (fabs(b.real) >= fabs(b.imag)) {
if (b.real == 0 && b.imag == 0) {
return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag);
} else {
double r = b.imag / b.real;
double s = (double)(1.0) / (b.real + b.imag * r);
return __pyx_t_double_complex_from_parts(
(a.real + a.imag * r) * s, (a.imag - a.real * r) * s);
}
} else {
double r = b.real / b.imag;
double s = (double)(1.0) / (b.imag + b.real * r);
return __pyx_t_double_complex_from_parts(
(a.real * r + a.imag) * s, (a.imag * r - a.real) * s);
}
}
#else
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
if (b.imag == 0) {
return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real);
} else {
double denom = b.real * b.real + b.imag * b.imag;
return __pyx_t_double_complex_from_parts(
(a.real * b.real + a.imag * b.imag) / denom,
(a.imag * b.real - a.real * b.imag) / denom);
}
}
#endif
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) {
__pyx_t_double_complex z;
z.real = -a.real;
z.imag = -a.imag;
return z;
}
static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) {
return (a.real == 0) && (a.imag == 0);
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) {
__pyx_t_double_complex z;
z.real = a.real;
z.imag = -a.imag;
return z;
}
#if 1
static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) {
#if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return sqrt(z.real*z.real + z.imag*z.imag);
#else
return hypot(z.real, z.imag);
#endif
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
double r, lnr, theta, z_r, z_theta;
if (b.imag == 0 && b.real == (int)b.real) {
if (b.real < 0) {
double denom = a.real * a.real + a.imag * a.imag;
a.real = a.real / denom;
a.imag = -a.imag / denom;
b.real = -b.real;
}
switch ((int)b.real) {
case 0:
z.real = 1;
z.imag = 0;
return z;
case 1:
return a;
case 2:
return __Pyx_c_prod_double(a, a);
case 3:
z = __Pyx_c_prod_double(a, a);
return __Pyx_c_prod_double(z, a);
case 4:
z = __Pyx_c_prod_double(a, a);
return __Pyx_c_prod_double(z, z);
}
}
if (a.imag == 0) {
if (a.real == 0) {
return a;
} else if (b.imag == 0) {
z.real = pow(a.real, b.real);
z.imag = 0;
return z;
} else if (a.real > 0) {
r = a.real;
theta = 0;
} else {
r = -a.real;
theta = atan2(0.0, -1.0);
}
} else {
r = __Pyx_c_abs_double(a);
theta = atan2(a.imag, a.real);
}
lnr = log(r);
z_r = exp(lnr * b.real - theta * b.imag);
z_theta = theta * b.real + lnr * b.imag;
z.real = z_r * cos(z_theta);
z.imag = z_r * sin(z_theta);
return z;
}
#endif
#endif
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) {
const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(int) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(int) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(int) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(int),
little, !is_unsigned);
}
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) {
const enum NPY_TYPES neg_one = (enum NPY_TYPES) ((enum NPY_TYPES) 0 - (enum NPY_TYPES) 1), const_zero = (enum NPY_TYPES) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(enum NPY_TYPES) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(enum NPY_TYPES) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES),
little, !is_unsigned);
}
}
/* CIntFromPy */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(int) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0])
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) {
return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) {
return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) {
return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (int) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0])
case -2:
if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
}
#endif
if (sizeof(int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
int val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (int) -1;
}
} else {
int val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (int) -1;
val = __Pyx_PyInt_As_int(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to int");
return (int) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(long) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(long) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(long) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(long),
little, !is_unsigned);
}
}
/* CIntFromPy */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(long) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (long) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0])
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) {
return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) {
return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) {
return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (long) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(long) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0])
case -2:
if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
}
#endif
if (sizeof(long) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
long val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (long) -1;
}
} else {
long val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (long) -1;
val = __Pyx_PyInt_As_long(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to long");
return (long) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
/* FastTypeChecks */
#if CYTHON_COMPILING_IN_CPYTHON
static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) {
while (a) {
a = a->tp_base;
if (a == b)
return 1;
}
return b == &PyBaseObject_Type;
}
static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) {
PyObject *mro;
if (a == b) return 1;
mro = a->tp_mro;
if (likely(mro)) {
Py_ssize_t i, n;
n = PyTuple_GET_SIZE(mro);
for (i = 0; i < n; i++) {
if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
return 1;
}
return 0;
}
return __Pyx_InBases(a, b);
}
#if PY_MAJOR_VERSION == 2
static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) {
PyObject *exception, *value, *tb;
int res;
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ErrFetch(&exception, &value, &tb);
res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0;
if (unlikely(res == -1)) {
PyErr_WriteUnraisable(err);
res = 0;
}
if (!res) {
res = PyObject_IsSubclass(err, exc_type2);
if (unlikely(res == -1)) {
PyErr_WriteUnraisable(err);
res = 0;
}
}
__Pyx_ErrRestore(exception, value, tb);
return res;
}
#else
static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) {
int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0;
if (!res) {
res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2);
}
return res;
}
#endif
static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) {
Py_ssize_t i, n;
assert(PyExceptionClass_Check(exc_type));
n = PyTuple_GET_SIZE(tuple);
#if PY_MAJOR_VERSION >= 3
for (i=0; i<n; i++) {
if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1;
}
#endif
for (i=0; i<n; i++) {
PyObject *t = PyTuple_GET_ITEM(tuple, i);
#if PY_MAJOR_VERSION < 3
if (likely(exc_type == t)) return 1;
#endif
if (likely(PyExceptionClass_Check(t))) {
if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1;
} else {
}
}
return 0;
}
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) {
if (likely(err == exc_type)) return 1;
if (likely(PyExceptionClass_Check(err))) {
if (likely(PyExceptionClass_Check(exc_type))) {
return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type);
} else if (likely(PyTuple_Check(exc_type))) {
return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type);
} else {
}
}
return PyErr_GivenExceptionMatches(err, exc_type);
}
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) {
assert(PyExceptionClass_Check(exc_type1));
assert(PyExceptionClass_Check(exc_type2));
if (likely(err == exc_type1 || err == exc_type2)) return 1;
if (likely(PyExceptionClass_Check(err))) {
return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2);
}
return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2));
}
#endif
/* CheckBinaryVersion */
static int __Pyx_check_binary_version(void) {
char ctversion[4], rtversion[4];
PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
char message[200];
PyOS_snprintf(message, sizeof(message),
"compiletime version %s of module '%.100s' "
"does not match runtime version %s",
ctversion, __Pyx_MODULE_NAME, rtversion);
return PyErr_WarnEx(NULL, message, 1);
}
return 0;
}
/* InitStrings */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
while (t->p) {
#if PY_MAJOR_VERSION < 3
if (t->is_unicode) {
*t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
} else if (t->intern) {
*t->p = PyString_InternFromString(t->s);
} else {
*t->p = PyString_FromStringAndSize(t->s, t->n - 1);
}
#else
if (t->is_unicode | t->is_str) {
if (t->intern) {
*t->p = PyUnicode_InternFromString(t->s);
} else if (t->encoding) {
*t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
} else {
*t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
}
} else {
*t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
}
#endif
if (!*t->p)
return -1;
if (PyObject_Hash(*t->p) == -1)
return -1;
++t;
}
return 0;
}
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) {
return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str));
}
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) {
Py_ssize_t ignore;
return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
#if !CYTHON_PEP393_ENABLED
static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
char* defenc_c;
PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
if (!defenc) return NULL;
defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
{
char* end = defenc_c + PyBytes_GET_SIZE(defenc);
char* c;
for (c = defenc_c; c < end; c++) {
if ((unsigned char) (*c) >= 128) {
PyUnicode_AsASCIIString(o);
return NULL;
}
}
}
#endif
*length = PyBytes_GET_SIZE(defenc);
return defenc_c;
}
#else
static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
if (likely(PyUnicode_IS_ASCII(o))) {
*length = PyUnicode_GET_LENGTH(o);
return PyUnicode_AsUTF8(o);
} else {
PyUnicode_AsASCIIString(o);
return NULL;
}
#else
return PyUnicode_AsUTF8AndSize(o, length);
#endif
}
#endif
#endif
static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
__Pyx_sys_getdefaultencoding_not_ascii &&
#endif
PyUnicode_Check(o)) {
return __Pyx_PyUnicode_AsStringAndSize(o, length);
} else
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
if (PyByteArray_Check(o)) {
*length = PyByteArray_GET_SIZE(o);
return PyByteArray_AS_STRING(o);
} else
#endif
{
char* result;
int r = PyBytes_AsStringAndSize(o, &result, length);
if (unlikely(r < 0)) {
return NULL;
} else {
return result;
}
}
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
int is_true = x == Py_True;
if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
else return PyObject_IsTrue(x);
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) {
int retval;
if (unlikely(!x)) return -1;
retval = __Pyx_PyObject_IsTrue(x);
Py_DECREF(x);
return retval;
}
static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) {
#if PY_MAJOR_VERSION >= 3
if (PyLong_Check(result)) {
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"__int__ returned non-int (type %.200s). "
"The ability to return an instance of a strict subclass of int "
"is deprecated, and may be removed in a future version of Python.",
Py_TYPE(result)->tp_name)) {
Py_DECREF(result);
return NULL;
}
return result;
}
#endif
PyErr_Format(PyExc_TypeError,
"__%.4s__ returned non-%.4s (type %.200s)",
type_name, type_name, Py_TYPE(result)->tp_name);
Py_DECREF(result);
return NULL;
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) {
#if CYTHON_USE_TYPE_SLOTS
PyNumberMethods *m;
#endif
const char *name = NULL;
PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x) || PyLong_Check(x)))
#else
if (likely(PyLong_Check(x)))
#endif
return __Pyx_NewRef(x);
#if CYTHON_USE_TYPE_SLOTS
m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
if (m && m->nb_int) {
name = "int";
res = m->nb_int(x);
}
else if (m && m->nb_long) {
name = "long";
res = m->nb_long(x);
}
#else
if (likely(m && m->nb_int)) {
name = "int";
res = m->nb_int(x);
}
#endif
#else
if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) {
res = PyNumber_Int(x);
}
#endif
if (likely(res)) {
#if PY_MAJOR_VERSION < 3
if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) {
#else
if (unlikely(!PyLong_CheckExact(res))) {
#endif
return __Pyx_PyNumber_IntOrLongWrongResultType(res, name);
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
Py_ssize_t ival;
PyObject *x;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_CheckExact(b))) {
if (sizeof(Py_ssize_t) >= sizeof(long))
return PyInt_AS_LONG(b);
else
return PyInt_AsSsize_t(b);
}
#endif
if (likely(PyLong_CheckExact(b))) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)b)->ob_digit;
const Py_ssize_t size = Py_SIZE(b);
if (likely(__Pyx_sst_abs(size) <= 1)) {
ival = likely(size) ? digits[0] : 0;
if (size == -1) ival = -ival;
return ival;
} else {
switch (size) {
case 2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
}
}
#endif
return PyLong_AsSsize_t(b);
}
x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) {
return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False);
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
return PyInt_FromSize_t(ival);
}
#endif /* Py_PYTHON_H */
|
//============================================================================
// MCKL/include/mckl/random/internal/aes_key_seq.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2018, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_INTERNAL_AES_KEY_SEQ_HPP
#define MCKL_RANDOM_INTERNAL_AES_KEY_SEQ_HPP
#include <mckl/random/internal/common.hpp>
MCKL_PUSH_GCC_WARNING("-Wignored-attributes")
namespace mckl {
namespace internal {
template <std::size_t Rounds, typename KeySeqGenerator>
class AESKeySeqImpl
{
public:
using key_type = typename KeySeqGenerator::key_type;
using rk_type = typename KeySeqGenerator::rk_type;
static constexpr std::size_t rounds() { return Rounds; }
key_type key() const { return KeySeqGenerator::key(rk_); }
void set(const key_type &key)
{
KeySeqGenerator generator;
generator(key, rk_);
}
const std::array<rk_type, rounds() + 1> &get() const { return rk_; }
template <std::size_t N>
const rk_type &get() const
{
return std::get<N>(rk_);
}
friend bool operator==(const AESKeySeqImpl<Rounds, KeySeqGenerator> &seq1,
const AESKeySeqImpl<Rounds, KeySeqGenerator> &seq2)
{
std::array<std::uint64_t, 2 * (rounds() + 1)> ks1;
std::array<std::uint64_t, 2 * (rounds() + 1)> ks2;
std::memcpy(ks1.data(), seq1.rk_.data(),
sizeof(std::uint64_t) * 2 * (rounds() + 1));
std::memcpy(ks2.data(), seq2.rk_.data(),
sizeof(std::uint64_t) * 2 * (rounds() + 1));
return ks1 == ks2;
}
friend bool operator!=(const AESKeySeqImpl<Rounds, KeySeqGenerator> &seq1,
const AESKeySeqImpl<Rounds, KeySeqGenerator> &seq2)
{
return !(seq1 == seq2);
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os,
const AESKeySeqImpl<Rounds, KeySeqGenerator> &seq)
{
if (!os) {
return os;
}
std::array<std::uint64_t, 2 * (rounds() + 1)> ks;
std::memcpy(ks.data(), seq.rk_.data(),
sizeof(std::uint64_t) * 2 * (rounds() + 1));
ostream(os, ks);
return os;
}
template <typename CharT, typename Traits>
friend std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is,
AESKeySeqImpl<Rounds, KeySeqGenerator> &seq)
{
if (!is) {
return is;
}
std::array<std::uint64_t, 2 * (rounds() + 1)> ks;
istream(is, ks);
if (is) {
std::memcpy(seq.rk_.data(), ks.data(),
sizeof(std::uint64_t) * 2 * (rounds() + 1));
}
return is;
}
private:
std::array<rk_type, rounds() + 1> rk_;
}; // class AESKeySeqImpl
template <std::size_t Rounds, typename KeySeqGenerator>
class ARSKeySeqImpl
{
public:
using key_type = typename KeySeqGenerator::key_type;
using rk_type = typename KeySeqGenerator::rk_type;
static constexpr std::size_t rounds() { return Rounds; }
const key_type &key() const { return key_; }
void set(const key_type &key) { key_ = key; }
std::array<rk_type, rounds() + 1> get() const
{
KeySeqGenerator generator;
std::array<rk_type, rounds() + 1> rk;
generator(key_, rk);
return rk;
}
friend bool operator==(const ARSKeySeqImpl<Rounds, KeySeqGenerator> &seq1,
const ARSKeySeqImpl<Rounds, KeySeqGenerator> &seq2)
{
return seq1.key_ == seq2.key_;
}
friend bool operator!=(const ARSKeySeqImpl<Rounds, KeySeqGenerator> &seq1,
const ARSKeySeqImpl<Rounds, KeySeqGenerator> &seq2)
{
return !(seq1 == seq2);
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os,
const ARSKeySeqImpl<Rounds, KeySeqGenerator> &seq)
{
if (!os) {
return os;
}
ostream(os, seq.key_);
return os;
}
template <typename CharT, typename Traits>
friend std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is,
ARSKeySeqImpl<Rounds, KeySeqGenerator> &seq)
{
if (!is) {
return is;
}
key_type k = {{0}};
istream(is, k);
if (is) {
seq.key_ = k;
}
return is;
}
private:
key_type key_;
}; // class ARSKeySeqImpl
} // namespace internal
} // namespace mckl
MCKL_POP_GCC_WARNING
#endif // MCKL_RANDOM_INTERNAL_AES_KEY_SEQ_HPP
|
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2016, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// PCProfileFilter.h
//
// Purpose:
// [The purpose of this file]
//
// Description:
// See, in particular, the comments associated with 'PCProfile'.
//
//***************************************************************************
#ifndef PCProfileFilter_H
#define PCProfileFilter_H
//************************* System Include Files ****************************
#include <vector>
#include <list>
#include <string>
//*************************** User Include Files ****************************
#include <include/uint.h>
#include <lib/isa/ISA.hpp>
#include <lib/binutils/LM.hpp>
//*************************** Forward Declarations ***************************
class PCProfileFilter;
class MetricFilter;
class PCFilter;
// Some useful containers
class PCProfileFilterList : public std::list<PCProfileFilter*> {
public:
typedef std::list<PCProfileFilter*> Base;
public:
PCProfileFilterList() { }
virtual ~PCProfileFilterList() { clear(); }
virtual void clear() { Base::clear(); } // does not delte contents
void destroyContents(); // deletes contents
};
class PCProfileMetric;
//****************************************************************************
// PCProfileFilter
//****************************************************************************
// 'PCProfileFilter' is a filter that implicitly defines a derived
// metric (e.g. 'ProfileMetric') by specifing some combination of raw
// metrics and pcs from a 'PCProfile'.
// Currently, filters are strictly divided between metric and pc filters.
class PCProfileFilter
{
public:
// PCProfileFilter: assumes ownership of the MetricFilter and PCFilter.
PCProfileFilter(MetricFilter* x = NULL, PCFilter* y = NULL)
: mfilt(x), pcfilt(y) { }
virtual ~PCProfileFilter();
// Name, Description: The name and a description of what this filter
// computes.
const std::string& GetName() const { return name; }
const std::string& GetDescription() const { return description; }
void SetName(const char* s) { name = (s) ? s : ""; }
void SetDescription(const char* s) { description = (s) ? s : ""; }
// Access to the various sub-filters. (These intentionally return
// non-const pointers!)
MetricFilter* GetMetricFilter() const { return mfilt; }
PCFilter* GetPCFilter() const { return pcfilt; }
void Dump(std::ostream& o = std::cerr);
void DDump();
private:
// Should not be used
PCProfileFilter(const PCProfileFilter& p) { }
PCProfileFilter& operator=(const PCProfileFilter& p) { return *this; }
protected:
private:
std::string name;
std::string description;
MetricFilter* mfilt;
PCFilter* pcfilt;
};
//****************************************************************************
// MetricFilter
//****************************************************************************
// MetricFilter: An abstract base class providing an interface for
// standard and user-defined metric filters. A MetricFilter divides
// metrics into two sets sets, 'in' and 'out'.
class MetricFilter {
public:
MetricFilter() { }
virtual ~MetricFilter() { }
// Returns true if 'm' is within the 'in' set; false otherwise.
virtual bool operator()(const PCProfileMetric* m) = 0;
private:
};
//****************************************************************************
// PCFilter
//****************************************************************************
// PCFilter: An abstract base class providing an interface for
// standard and user-defined PC filters. A PCFilter divides
// PC into two sets sets, 'in' and 'out'.
class PCFilter {
public:
PCFilter() { }
virtual ~PCFilter() { }
// Returns true if the operation at 'pc' and 'opIndex' is within the
// 'in' set; false otherwise.
virtual bool operator()(VMA pc, ushort opIndex) = 0;
private:
};
//****************************************************************************
// InsnClassExpr
//****************************************************************************
#define INSN_CLASS_ALL 0x00000001 /* cannot be part of disjunction! */
#define INSN_CLASS_FLOP 0x00000002
#define INSN_CLASS_INTOP 0x00000004
#define INSN_CLASS_MEMOP 0x00000008
#define INSN_CLASS_OTHER 0x00000010
// InsnClassExpr: A common 'PCFilter' will be an instruction class
// filter (cf. 'InsnFilter'). This represent a disjunctive expression
// of instruction classes that can be used with an 'InsnFilter'.
class InsnClassExpr {
public:
typedef uint32_t bitvec_t;
public:
// A 'InsnClassExpr' can be created using the bit definitions above.
InsnClassExpr(bitvec_t bv = 0) : bits(bv) { }
virtual ~InsnClassExpr() { }
InsnClassExpr(const InsnClassExpr& x) { *this = x; }
InsnClassExpr& operator=(const InsnClassExpr& x) {
bits = x.bits;
return *this;
}
// IsSatisfied: Test to see if this query expression is satisfied by
// the given instruction class description within 'bv'. (Only on
// bit (= class) in 'bv' is set.)
bool IsSatisfied(const bitvec_t bv) {
if (IsSet(INSN_CLASS_ALL)) {
return true;
} else {
return IsSet(bv); // only one bit (= class) in 'bv' is set
}
}
// IsValid: If no bits are set, this must be an invalid expression
bool IsValid() const { return bits != 0; }
// IsSet: Tests to see if all the specified bits are set
bool IsSet(const bitvec_t bv) const {
return (bits & bv) == bv;
}
bool IsSet(const InsnClassExpr& m) const {
return (bits & m.bits) == m.bits;
}
// IsSetAny: Tests to see if *any* of the specified bits are set
bool IsSetAny(const bitvec_t bv) const {
return (bits & bv) != 0;
}
bool IsSetAny(const InsnClassExpr& m) const {
return (bits & m.bits) != 0;
}
// Set: Set all the specified bits
void Set(const bitvec_t bv) {
bits = bits | bv;
}
void Set(const InsnClassExpr& m) {
bits = bits | m.bits;
}
// Unset: Clears all the specified bits
void Unset(const bitvec_t bv) {
bits = bits & ~bv;
}
void Unset(const InsnClassExpr& m) {
bits = bits & ~(m.bits);
}
void Dump(std::ostream& o = std::cerr);
void DDump();
private:
protected:
private:
bitvec_t bits;
};
// ConvertInsnDesc: Converts an InsnDesc to one of the above classes
InsnClassExpr::bitvec_t
ConvertToInsnClass(ISA::InsnDesc d);
//****************************************************************************
// InsnFilter
//****************************************************************************
// InsnFilter: Divides PCs into two sets by Alpha instruction class.
class InsnFilter : public PCFilter {
public:
InsnFilter(InsnClassExpr expr_, binutils::LM* lm_);
virtual ~InsnFilter();
// Returns true if the operation at 'pc' and 'opIndex' satisfies
// 'expr'; false otherwise.
virtual bool operator()(VMA pc, ushort opIndex);
private:
InsnClassExpr expr;
binutils::LM* lm; // we do not own
};
//****************************************************************************
#endif
|
#include <limits>
#include <sys/time.h>
#include "generate_splits_utils.h"
using namespace std;
unordered_map<struct ckpt,double> ckpt_times;
vector<struct ckpt> ckpts;
static int group_by = 0;
int filter_syscall = 0;
int use_ckpt = 0, do_split = 0, details = 0, do_repartition = 0;
int lowmem = 0;
double ut_arg = 0.0;
double ui_arg = 0.0;
my_map ninsts; //the number of instructions based on trace_id
static void
pop_ckpt_times(vector<struct timing_data> &td) {
auto c = ckpts.begin();
for (auto &t : td) {
if (t.start_clock >= c->rp_clock) {
ckpt_times[*c] = t.ftiming; //this is the time that the ckpt takes place
++c;
}
}
for (auto &c : ckpt_times) {
fprintf(stderr, "ckpt %lu has time %lf\n",c.first.rp_clock, c.second);
}
}
static void
combine_vect(my_set &base, my_vect &to_add) {
for(auto i : to_add) {
base.insert(i);
}
}
static void
combine_trace(my_set &base, u_long* traces) {
while (*traces) {
base.insert(*traces);
traces++;
}
}
static u_long
calc_unique_insts(my_set &traces) {
u_long count = 0;
for (auto t:traces) {
count += ninsts[t];
}
return count;
}
void format ()
{
fprintf (stderr, "Format: mkpartition <timing dir> <# of partitions> [-g group_by] [-f filter syscall] [-s split at user-level] [-v verbose] [--stop stop_tracking_clock] [-r pin_trace_dir pin_trace_epochs] [-fork fork_flags] <list of processes in replay>\n");
exit (22);
}
int analyze_parts(vector<struct timing_data> &td,
vector<struct partition> &epochs)
{
int count = 0;
u_int current = 0, start;
my_set uinsts;
my_set utraces;
u_long imisses;
// u_int tindex = 0;
bool user_level_split = false; //is there currently a run of user_level splits?
vector<u_long> user_split_clocks; //the clock values of the user level splits in a run
for (auto e: epochs) {
start = current;
//we hit a new user-level split block
if(!strncmp(e.stop_level,"u",1) && !user_level_split) {
user_level_split = true;
user_split_clocks.push_back(e.start_clock); //save off the start
}
//there's another epoch in this split!
else if(!strncmp(e.stop_level,"u",1) && user_level_split) {
user_split_clocks.push_back(e.start_clock);
}
//we've reached the end of a run!
else if (!strncmp(e.stop_level, "k",1) && user_level_split) {
user_split_clocks.push_back(e.start_clock);
while (current < td.size()) {
if (td[current].start_clock == e.stop_clock) {
break;
}
if (td[current].should_track) {
combine_vect(uinsts, td[current].sampled_insts);
combine_vect(utraces, td[current].pin_traces);
imisses += td[current].imisses;
}
current++;
}
double total_time = td[current].dtiming - td[start].dtiming;
u_int num_merges = td[current].num_merges - td[start].num_merges;
int usize = uinsts.size();
u_int pin_usize = calc_unique_insts(utraces);
double ftiming = td[start].ftiming;
//adjust ftiming for ckpt
if (e.ckpt != 0) {
struct ckpt c;
c.rp_clock = e.ckpt;
ftiming -= ckpt_times[c];
}
//we make simplifying assumption that each user-level split gets equal share
//of the stats
u_long prev_clock = user_split_clocks[0];
for (u_int i = 1; i < user_split_clocks.size(); ++i) {
printf("%lu %lu %lf %lf %lu %lu %lu %lu %lu\n",prev_clock,
user_split_clocks[i],
total_time / user_split_clocks.size(),
ftiming,
usize / user_split_clocks.size(),
imisses / user_split_clocks.size(),
pin_usize / user_split_clocks.size(),
utraces.size() / user_split_clocks.size(),
num_merges / user_split_clocks.size());
prev_clock = user_split_clocks[i];
}
//now print the current
printf("%lu %lu %lf %lf %lu %lu %lu %lu %lu\n",prev_clock,
e.stop_clock,
total_time / user_split_clocks.size(),
ftiming,
usize / user_split_clocks.size(),
imisses / user_split_clocks.size(),
pin_usize / user_split_clocks.size(),
utraces.size() / user_split_clocks.size(),
num_merges / user_split_clocks.size());
//finally, clear out the user_split data:
user_split_clocks.clear();
user_level_split = false;
uinsts.clear();
utraces.clear();
imisses = 0;
}
else {
while (current < td.size()) {
if (td[current].start_clock == e.stop_clock) {
break;
}
if (td[current].should_track) {
combine_vect(uinsts, td[current].sampled_insts);
combine_vect(utraces, td[current].pin_traces);
imisses += td[current].imisses;
}
current++;
}
double total_time = td[current].dtiming - td[start].dtiming;
u_int num_merges = td[current].num_merges - td[start].num_merges;
u_int num_saved = td[current].num_saved - td[start].num_saved;
int usize = uinsts.size();
u_int pin_usize = calc_unique_insts(utraces);
double ftiming = td[start].ftiming;
//adjust ftiming for ckpt
if (e.ckpt != 0) {
struct ckpt c;
c.rp_clock = e.ckpt;
ftiming -= ckpt_times[c];
}
printf("%d %lu %lu %lf %lf %d %lu %u %lu %u %u\n",count,
e.start_clock, e.stop_clock,total_time,ftiming, usize,imisses,
pin_usize, utraces.size(), num_merges, num_saved);
count++;
unordered_map<short, int> syscall_cnt;
//can't remember if current is included in this or not.. I don't think so
for (int i = start; i < current; ++i)
{
syscall_cnt[td[i].syscall]++;
}
for (auto i :syscall_cnt) {
printf("%hd:%d\n",i.first, i.second);
}
uinsts.clear();
utraces.clear();
imisses = 0;
}
}
return 0;
}
static double estimate_dift(vector<struct timing_data> td,
int i,
int j,
double ftiming,
int uinsts_cnt) {
double utime = td[j].dtiming - td[i].dtiming;
u_long num_merges = td[j].num_merges - td[i].num_merges;
return (2.5 * ftiming) + (211 * utime) + (.08 * uinsts_cnt) + (.000058 * num_merges);
}
int print_estimates(vector<struct timing_data> &td,
vector<struct partition> &epochs)
{
u_int current = 0, start;
my_set uinsts;
my_set utraces;
u_long imisses;
for (auto e: epochs) {
start = current;
while (current < td.size()) {
if (td[current].start_clock == e.stop_clock) {
break;
}
if (td[current].should_track) {
combine_vect(uinsts, td[current].sampled_insts);
combine_vect(utraces, td[current].pin_traces);
imisses += td[current].imisses;
}
current++;
}
double total_time = td[current].dtiming - td[start].dtiming;
u_int num_merges = td[current].num_merges - td[start].num_merges;
u_int num_saved = td[current].num_saved - td[start].num_saved;
int usize = uinsts.size();
u_int pin_usize = calc_unique_insts(utraces);
double ftiming = td[start].ftiming;
//adjust ftiming for ckpt
if (e.ckpt != 0) {
struct ckpt c;
c.rp_clock = e.ckpt;
ftiming -= ckpt_times[c];
}
printf("%lu %lu %lf %lf %u %u %lf\n",e.start_clock,
e.stop_clock,total_time,ftiming, pin_usize, num_merges,
estimate_dift(td,start, current,ftiming,pin_usize));
uinsts.clear();
utraces.clear();
imisses = 0;
}
return 0;
}
int main (int argc, char* argv[])
{
struct stat st;
int fd, rc, num, i;
char following[256];
FILE *file;
char timing_fname[256]; //filename where the timing data is stored
char parts_fname[256]; //filename where the timing data is stored
char inst_fname[256]; //filename where the instruction data is stored (recording metrics)
char ckpt_fname[256]; //filename where a list of ckpts are storedtion data is stored (recording metrics)
char trace_dir[256]; //directory where the pin gathered traces are stored
u_int trace_epochs = -1; //number of files for the pin gathered traces
vector<struct partition> parts;
vector<struct timing_data> td;
if (argc < 3) {
format ();
}
following[0] = 0; //assume this isn't provided, fix it if it is.
sprintf (timing_fname, "%s", argv[1]);
sprintf (parts_fname, "%s", argv[2]);
for (i = 2; i < argc; i++) {
if (!strcmp(argv[i], "-c")) {
i++;
if (i < argc) {
strcpy(ckpt_fname,argv[i]);
use_ckpt = 1;
} else {
format();
}
i++;
}
else if (!strcmp(argv[i],"-r")){
i++;
if (i < argc) {
strcpy(trace_dir,argv[i]);
i++;
if (i < argc) {
trace_epochs = atoi(argv[i]);
do_repartition = 1;
} else {
format();
}
} else {
format();
}
}
else if (!strcmp(argv[i],"-i")){
i++;
if (i < argc) {
strcpy(inst_fname,argv[i]);
i++;
} else {
format();
}
}
}
file = fopen (timing_fname, "r");
if (file == NULL) {
fprintf (stderr, "Cannot open timings file %s, errno=%d\n",
timing_fname, errno);
return -1;
}
rc = read_timing_data(td, file);
fclose(file);
file = fopen(parts_fname, "r");
if (file == NULL) {
fprintf (stderr, "Unable to open epoch description file %s, errno=%d\n", parts_fname, errno);
return -1;
}
char line[256];
if(!fgets(line, 255, file)) fprintf(stderr,"hmm.. failed to read first line?\n");
while (!feof(file)) {
if (fgets (line, 255, file)) {
struct partition e;
struct ckpt c;
u_int fork_flags;
u_int filter_syscall;
rc = sscanf (line, "%d %c %lu %c %lu %u %lu %u\n", &e.pid, e.start_level, &e.start_clock, e.stop_level, &e.stop_clock, &filter_syscall, &e.ckpt, &fork_flags);
if (rc != 8) {
fprintf (stderr, "Unable to parse line of epoch descrtion file: %s\n", line);
return -1;
}
parts.push_back(e);
//deal with the ckpts
if (e.ckpt != 0) {
c.rp_clock = e.ckpt;
ckpts.push_back(c);
}
}
}
fclose(file);
file = fopen (inst_fname, "r");
if (file == NULL) {
fprintf (stderr, "Cannot open instructions file %s, errno=%d\n",
inst_fname, errno);
return -1;
}
if (ckpts.size()) {
pop_ckpt_times(td); //populates the ckpt_times map
}
rc = parse_instructions(td, file); //parses the instruction logs
rc = parse_pin_instructions(ninsts,trace_dir, trace_epochs);
rc = parse_pin_traces(td,trace_dir, trace_epochs);
analyze_parts(td, parts);
// print_estimates(td, parts);
return 0;
}
|
/*
Copyright 2005-2008 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks.
Threading Building Blocks is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
Threading Building Blocks is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Threading Building Blocks; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software
library without restriction. Specifically, if other files instantiate
templates or use macros or inline functions from this file, or you compile
this file and link it with other files to produce an executable, this
file does not by itself cause the resulting executable to be covered by
the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
*/
// Test whether scalable_allocator complies with the requirements in 20.1.5 of ISO C++ Standard (1998).
/* to avoid dependency on TBB shared library, the following macro should be
defined to non-zero _before_ including any TBB or test harness headers.
Also tbb_assert_impl.h from src/tbb should be included right after */
#define __TBB_NO_IMPLICIT_LINKAGE 1
#include "../tbb/tbb_assert_impl.h"
#define HARNESS_NO_PARSE_COMMAND_LINE 1
#include "tbb/scalable_allocator.h"
// the actual body of the test is there:
#include "test_allocator.h"
#if _MSC_VER
#include <windows.h>
#endif /* _MSC_VER */
int main(void)
{
#if _MSC_VER && !__TBB_NO_IMPLICIT_LINKAGE
#ifdef _DEBUG
ASSERT(!GetModuleHandle("tbbmalloc.dll") && GetModuleHandle("tbbmalloc_debug.dll"),
"debug application links with non-debug tbbmalloc library");
#else
ASSERT(!GetModuleHandle("tbbmalloc_debug.dll") && GetModuleHandle("tbbmalloc.dll"),
"non-debug application links with debug tbbmalloc library");
#endif
#endif /* _MSC_VER && !__TBB_NO_IMPLICIT_LINKAGE */
int result = TestMain<tbb::scalable_allocator<void> >();
printf("done\n");
return result;
}
|
#include "Player.hpp"
Player::Player(int x, int y, int points, int life, int attack, double cooldown_shoot, char *symbol)
:Character(x, y, points, life, attack, cooldown_shoot, cooldown_movement=-1, symbol) {
name = new char[MAX_NAME_LENGTH];
offset = 0;
isInvincible = false;
default_cooldown_shoot = cooldown_shoot;
}
void Player::move(int input, int width, int height, double time, bool hasPlatformAbove, bool hasPlatformAboveOne, bool hasPlatformBelow, bool hasPlatformBelowOne, bool hasPlatformRight, bool hasPlatformLeft) {
Character::move(input, width, height, time, hasPlatformAbove, hasPlatformAboveOne, hasPlatformBelow, hasPlatformBelowOne, hasPlatformRight, hasPlatformLeft);
if ((offset > 0 && x < FIXED_X) || x > FIXED_X) {
offset += x-FIXED_X;
x = FIXED_X;
}
if (offset < 0)
offset = 0;
}
void Player::checkBonusesTimer(double time) {
if (time - invincibilityActivation_time > invincibility_timer)
isInvincible = false;
if (time - minigunActivation_time > minigun_timer)
cooldown_shoot = default_cooldown_shoot;
}
void Player::increaseLife(int bonus_life) {
life += bonus_life;
}
void Player::increasePoints(int bonus_points) {
points += bonus_points;
}
void Player::setCooldownShoot(double minigun_cooldown, double time, double timer) {
this->cooldown_shoot = minigun_cooldown;
minigun_timer = timer;
minigunActivation_time = time;
}
void Player::setInvincibility(double time, double timer) {
isInvincible = true;
invincibility_timer = timer;
invincibilityActivation_time = time;
}
void Player::setLastDamageTime(double time) {
lastdamage_time = time;
}
// GETTER
int Player::getMaxNameLenght() {
return MAX_NAME_LENGTH;
}
double Player::getInvincibilityTimer(double time) {
if (isInvincible)
return invincibility_timer - (time - invincibilityActivation_time);
else
return 0.0;
}
double Player::getMinigunTimer(double time) {
if (cooldown_shoot != default_cooldown_shoot)
return minigun_timer - (time - minigunActivation_time);
else
return 0.0;
}
bool Player::isDamaged(double time) {
return (time - lastdamage_time <= COOLDOWN_DAMAGE);
}
bool Player::hasInvincibility() {
return isInvincible;
}
char *Player::getName() {
return name;
}
int Player::getOffset() {
return offset;
}
int Player::noOffsetX() {
return x;
}
// OVERRIDE
int Player::getX() {
return offset+Character::getX();
}
int Player::getFixedX() {
return FIXED_X;
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <PhysX_precompiled.h>
#include <AzFramework/Physics/PhysicsComponentBus.h>
#include <AzFramework/Physics/RigidBodyBus.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/std/smart_ptr/make_shared.h>
#include <AzFramework/Physics/Utils.h>
#include <Source/BaseColliderComponent.h>
#include <Source/RigidBodyComponent.h>
#include <Source/StaticRigidBodyComponent.h>
#include <Source/SystemComponent.h>
#include <Source/Utils.h>
#include <PhysX/PhysXLocks.h>
namespace PhysX
{
// ShapeInfoCache
AZ::Aabb BaseColliderComponent::ShapeInfoCache::GetAabb(const AZStd::vector<AZStd::shared_ptr<Physics::Shape>>& shapes)
{
if (m_cacheOutdated)
{
UpdateCache(shapes);
}
return m_aabb;
}
void BaseColliderComponent::ShapeInfoCache::InvalidateCache()
{
m_cacheOutdated = true;
}
const AZ::Transform& BaseColliderComponent::ShapeInfoCache::GetWorldTransform()
{
return m_worldTransform;
}
void BaseColliderComponent::ShapeInfoCache::SetWorldTransform(const AZ::Transform& worldTransform)
{
m_worldTransform = worldTransform;
}
void BaseColliderComponent::ShapeInfoCache::UpdateCache(const AZStd::vector<AZStd::shared_ptr<Physics::Shape>>& shapes)
{
size_t numShapes = shapes.size();
if (numShapes > 0)
{
auto world = Utils::GetDefaultWorld();
PHYSX_SCENE_READ_LOCK(world->GetNativeWorld());
auto pxShape = static_cast<physx::PxShape*>(shapes[0]->GetNativePointer());
physx::PxTransform pxWorldTransform = PxMathConvert(m_worldTransform);
physx::PxBounds3 bounds = physx::PxGeometryQuery::getWorldBounds(pxShape->getGeometry().any(),
pxWorldTransform * pxShape->getLocalPose(), 1.0f);
for (size_t shapeIndex = 1; shapeIndex < numShapes; ++shapeIndex)
{
pxShape = static_cast<physx::PxShape*>(shapes[0]->GetNativePointer());
bounds.include(physx::PxGeometryQuery::getWorldBounds(pxShape->getGeometry().any(),
pxWorldTransform * pxShape->getLocalPose(), 1.0f));
}
m_aabb = PxMathConvert(bounds);
}
else
{
m_aabb = AZ::Aabb::CreateFromPoint(m_worldTransform.GetPosition());
}
m_cacheOutdated = false;
}
// BaseColliderComponent
const Physics::ColliderConfiguration BaseColliderComponent::s_defaultColliderConfig = Physics::ColliderConfiguration();
void BaseColliderComponent::Reflect(AZ::ReflectContext* context)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<BaseColliderComponent, AZ::Component>()
->Version(1)
->Field("ShapeConfigList", &BaseColliderComponent::m_shapeConfigList)
;
}
}
void BaseColliderComponent::SetShapeConfigurationList(const Physics::ShapeConfigurationList& shapeConfigList)
{
if (GetEntity()->GetState() == AZ::Entity::State::ES_ACTIVE)
{
AZ_Warning("PhysX", false, "Trying to call SetShapeConfigurationList for entity \"%s\" while entity is active.",
GetEntity()->GetName().c_str());
return;
}
m_shapeConfigList = shapeConfigList;
}
// ColliderComponentRequestBus
AZStd::shared_ptr<Physics::ShapeConfiguration> BaseColliderComponent::GetShapeConfigFromEntity()
{
AZ_Warning("PhysX", false, "Colliders now support multiple shapes. GetShapeConfigFromEntity is deprecated, "
"but will return the shape configuration of only the first shape for compatibility. "
"Please use GetShapeConfigurations instead.");
if (!m_shapeConfigList.empty())
{
return m_shapeConfigList[0].second;
}
AZ_Warning("PhysX", false, "Collider has no associated shape/collider configurations, returning nullptr "
"for entity \"%s\".", GetEntity()->GetName().c_str());
return nullptr;
}
const Physics::ColliderConfiguration& BaseColliderComponent::GetColliderConfig()
{
AZ_Warning("PhysX", false, "Colliders now support multiple shapes. GetColliderConfig is deprecated, but for "
"compatibility will return the collider configuration of the first shape only. Please use "
"GetShapeConfigurations instead.");
if (!m_shapeConfigList.empty())
{
return *m_shapeConfigList[0].first;
}
AZ_Warning("PhysX", false, "Collider has no associated shape/collider configurations, returning default "
"collider configuration for entity \"%s\".", GetEntity()->GetName().c_str());
return s_defaultColliderConfig;
}
AZStd::shared_ptr<Physics::Shape> BaseColliderComponent::GetShape()
{
AZ_Warning("PhysX", false, "Colliders now support multiple shapes. GetShape is deprecated, but for "
"compatibility will return the first shape only. Please use GetShapes instead.");
if (!m_shapes.empty())
{
return m_shapes[0];
}
AZ_Warning("PhysX", false, "No shapes found for entity \"%s\".", GetEntity()->GetName().c_str());
return nullptr;
}
void* BaseColliderComponent::GetNativePointer()
{
AZ_Warning("PhysX", false, "Colliders now support multiple shapes. GetNativePointer is deprecated, but for "
"compatibility will return the native pointer for the first shape only. Please use GetShapes instead.");
if (!m_shapes.empty())
{
return m_shapes[0]->GetNativePointer();
}
AZ_Warning("PhysX", false, "No shapes found for entity \"%s\".", GetEntity()->GetName().c_str());
return nullptr;
}
Physics::ShapeConfigurationList BaseColliderComponent::GetShapeConfigurations()
{
return m_shapeConfigList;
}
AZStd::vector<AZStd::shared_ptr<Physics::Shape>> BaseColliderComponent::GetShapes()
{
return m_shapes;
}
bool BaseColliderComponent::IsStaticRigidBody()
{
const auto* component = GetEntity()->FindComponent<StaticRigidBodyComponent>();
return component != nullptr;
}
PhysX::RigidBodyStatic* BaseColliderComponent::GetStaticRigidBody()
{
auto* component = GetEntity()->FindComponent<StaticRigidBodyComponent>();
return component ? component->GetStaticRigidBody() : nullptr;
}
// TransformNotificationsBus
void BaseColliderComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world)
{
m_shapeInfoCache.SetWorldTransform(world);
m_shapeInfoCache.InvalidateCache();
}
// PhysX::ColliderShapeBus
AZ::Aabb BaseColliderComponent::GetColliderShapeAabb()
{
if (m_shapes.empty())
{
return AZ::Aabb::CreateFromPoint(m_shapeInfoCache.GetWorldTransform().GetPosition());
}
return m_shapeInfoCache.GetAabb(m_shapes);
}
bool BaseColliderComponent::IsTrigger()
{
AZ_Error("PhysX", !m_shapes.empty(), "Tried to call IsTrigger before any shapes were initialized for entity %s.",
GetEntity()->GetName().c_str());
// Colliders now support multiple shapes. This will return true if any of the shapes is a trigger.
for (const auto& shapeConfigPair : m_shapeConfigList)
{
if (shapeConfigPair.first->m_isTrigger)
{
return true;
}
}
return false;
}
void BaseColliderComponent::SetCollisionLayer(const AZStd::string& layerName, AZ::Crc32 colliderTag)
{
for(auto& shape : m_shapes)
{
if (Physics::Utils::FilterTag(shape->GetTag(), colliderTag))
{
bool success = false;
Physics::CollisionLayer layer;
Physics::CollisionRequestBus::BroadcastResult(success, &Physics::CollisionRequests::TryGetCollisionLayerByName, layerName, layer);
if (success)
{
shape->SetCollisionLayer(layer);
}
}
}
}
AZStd::string BaseColliderComponent::GetCollisionLayerName()
{
AZStd::string layerName;
if (!m_shapes.empty())
{
Physics::CollisionRequestBus::BroadcastResult(layerName, &Physics::CollisionRequests::GetCollisionLayerName, m_shapes[0]->GetCollisionLayer());
}
return layerName;
}
void BaseColliderComponent::SetCollisionGroup(const AZStd::string& groupName, AZ::Crc32 colliderTag)
{
for (auto& shape : m_shapes)
{
if (Physics::Utils::FilterTag(shape->GetTag(), colliderTag))
{
bool success = false;
Physics::CollisionGroup group;
Physics::CollisionRequestBus::BroadcastResult(success, &Physics::CollisionRequests::TryGetCollisionGroupByName, groupName, group);
if (success)
{
shape->SetCollisionGroup(group);
}
}
}
}
AZStd::string BaseColliderComponent::GetCollisionGroupName()
{
AZStd::string groupName;
if (!m_shapes.empty())
{
Physics::CollisionRequestBus::BroadcastResult(groupName, &Physics::CollisionRequests::GetCollisionGroupName, m_shapes[0]->GetCollisionGroup());
}
return groupName;
}
void BaseColliderComponent::ToggleCollisionLayer(const AZStd::string& layerName, AZ::Crc32 colliderTag, bool enabled)
{
for (const auto& shape : m_shapes)
{
if (Physics::Utils::FilterTag(shape->GetTag(), colliderTag))
{
bool success = false;
Physics::CollisionLayer layer;
Physics::CollisionRequestBus::BroadcastResult(success, &Physics::CollisionRequests::TryGetCollisionLayerByName, layerName, layer);
if (success)
{
auto group = shape->GetCollisionGroup();
group.SetLayer(layer, enabled);
shape->SetCollisionGroup(group);
}
}
}
}
// AZ::Component
void BaseColliderComponent::Activate()
{
const AZ::EntityId entityId = GetEntityId();
ColliderComponentRequestBus::Handler::BusConnect(entityId);
AZ::TransformNotificationBus::Handler::BusConnect(entityId);
ColliderShapeRequestBus::Handler::BusConnect(GetEntityId());
Physics::CollisionFilteringRequestBus::Handler::BusConnect(GetEntityId());
AZ::Transform worldTransform = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(worldTransform, entityId, &AZ::TransformBus::Events::GetWorldTM);
m_shapeInfoCache.SetWorldTransform(worldTransform);
InitShapes();
}
void BaseColliderComponent::Deactivate()
{
m_shapes.clear();
Physics::CollisionFilteringRequestBus::Handler::BusDisconnect();
ColliderShapeRequestBus::Handler::BusDisconnect();
AZ::TransformNotificationBus::Handler::BusDisconnect();
ColliderComponentRequestBus::Handler::BusDisconnect();
}
void BaseColliderComponent::UpdateScaleForShapeConfigs()
{
// Overridden by each collider component
}
bool BaseColliderComponent::InitShapes()
{
UpdateScaleForShapeConfigs();
if (IsMeshCollider())
{
return InitMeshCollider();
}
else
{
const AZ::Vector3 nonUniformScale = Utils::GetNonUniformScale(GetEntityId());
m_shapes.reserve(m_shapeConfigList.size());
for (const auto& shapeConfigPair : m_shapeConfigList)
{
const AZStd::shared_ptr<Physics::ShapeConfiguration>& shapeConfiguration = shapeConfigPair.second;
if (!shapeConfiguration)
{
AZ_Error("PhysX", false, "Unable to create a physics shape because shape configuration is null. Entity: %s",
GetEntity()->GetName().c_str());
return false;
}
Physics::ColliderConfiguration colliderConfiguration = *shapeConfigPair.first;
colliderConfiguration.m_position *= nonUniformScale;
AZStd::shared_ptr<Physics::Shape> shape;
Physics::SystemRequestBus::BroadcastResult(shape, &Physics::SystemRequests::CreateShape, colliderConfiguration, *shapeConfiguration);
if (!shape)
{
AZ_Error("PhysX", false, "Failed to create a PhysX shape. Entity: %s", GetEntity()->GetName().c_str());
return false;
}
m_shapes.push_back(shape);
}
return true;
}
}
bool BaseColliderComponent::IsMeshCollider() const
{
return m_shapeConfigList.size() == 1 && m_shapeConfigList.begin()->second &&
m_shapeConfigList.begin()->second->GetShapeType() == Physics::ShapeType::PhysicsAsset;
}
bool BaseColliderComponent::InitMeshCollider()
{
AZ_Assert(IsMeshCollider(), "InitMeshCollider called for a non-mesh collider.");
const Physics::ShapeConfigurationPair& shapeConfigurationPair = *(m_shapeConfigList.begin());
const Physics::ColliderConfiguration& componentColliderConfiguration = *(shapeConfigurationPair.first.get());
const Physics::PhysicsAssetShapeConfiguration& physicsAssetConfiguration =
*(static_cast<const Physics::PhysicsAssetShapeConfiguration*>(shapeConfigurationPair.second.get()));
if (!physicsAssetConfiguration.m_asset.IsReady())
{
return false;
}
Utils::GetShapesFromAsset(physicsAssetConfiguration, componentColliderConfiguration, m_shapes);
return true;
}
}
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/script.h"
#include "test/test_avian.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(script_P2PK_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(ispaytopublickey_test)
{
BOOST_TEST_MESSAGE("Running IsPayToPublicKey Test");
// Test CScript::IsPayToPublicKey()
static const unsigned char p2pkcompressedeven[] = {
0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG
};
BOOST_CHECK(CScript(p2pkcompressedeven, p2pkcompressedeven + sizeof(p2pkcompressedeven)).IsPayToPublicKey());
static const unsigned char p2pkcompressedodd[] = {
0x41, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG
};
BOOST_CHECK(CScript(p2pkcompressedodd, p2pkcompressedodd + sizeof(p2pkcompressedodd)).IsPayToPublicKey());
static const unsigned char p2pkuncompressed[] = {
0x41, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG
};
BOOST_CHECK(CScript(p2pkuncompressed, p2pkuncompressed + sizeof(p2pkuncompressed)).IsPayToPublicKey());
static const unsigned char missingop[] = {
0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
BOOST_CHECK(!CScript(missingop, missingop + sizeof(missingop)).IsPayToPublicKey());
static const unsigned char wrongop[] = {
0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_EQUALVERIFY
};
BOOST_CHECK(!CScript(wrongop, wrongop + sizeof(wrongop)).IsPayToPublicKey());
static const unsigned char tooshort[] = {
0x41, 0x02, 0, 0, OP_CHECKSIG
};
BOOST_CHECK(!CScript(tooshort, tooshort + sizeof(tooshort)).IsPayToPublicKey());
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2011 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 "components/autofill/browser/autofill_common_test.h"
#include "base/guid.h"
#include "base/prefs/pref_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "components/autofill/browser/autofill_profile.h"
#include "components/autofill/browser/credit_card.h"
#include "components/autofill/common/autofill_pref_names.h"
#include "components/autofill/common/form_field_data.h"
#include "components/user_prefs/user_prefs.h"
#include "components/webdata/encryptor/encryptor.h"
namespace autofill_test {
void CreateTestFormField(const char* label,
const char* name,
const char* value,
const char* type,
FormFieldData* field) {
field->label = ASCIIToUTF16(label);
field->name = ASCIIToUTF16(name);
field->value = ASCIIToUTF16(value);
field->form_control_type = type;
}
inline void check_and_set(
FormGroup* profile, AutofillFieldType type, const char* value) {
if (value)
profile->SetRawInfo(type, UTF8ToUTF16(value));
}
AutofillProfile GetFullProfile() {
AutofillProfile profile(base::GenerateGUID());
SetProfileInfo(&profile,
"John",
"H.",
"Doe",
"johndoe@hades.com",
"Underworld",
"666 Erebus St.",
"Apt 8",
"Elysium", "CA",
"91111",
"US",
"16502111111");
return profile;
}
void SetProfileInfo(AutofillProfile* profile,
const char* first_name, const char* middle_name,
const char* last_name, const char* email, const char* company,
const char* address1, const char* address2, const char* city,
const char* state, const char* zipcode, const char* country,
const char* phone) {
check_and_set(profile, NAME_FIRST, first_name);
check_and_set(profile, NAME_MIDDLE, middle_name);
check_and_set(profile, NAME_LAST, last_name);
check_and_set(profile, EMAIL_ADDRESS, email);
check_and_set(profile, COMPANY_NAME, company);
check_and_set(profile, ADDRESS_HOME_LINE1, address1);
check_and_set(profile, ADDRESS_HOME_LINE2, address2);
check_and_set(profile, ADDRESS_HOME_CITY, city);
check_and_set(profile, ADDRESS_HOME_STATE, state);
check_and_set(profile, ADDRESS_HOME_ZIP, zipcode);
check_and_set(profile, ADDRESS_HOME_COUNTRY, country);
check_and_set(profile, PHONE_HOME_WHOLE_NUMBER, phone);
}
void SetProfileInfoWithGuid(AutofillProfile* profile,
const char* guid, const char* first_name, const char* middle_name,
const char* last_name, const char* email, const char* company,
const char* address1, const char* address2, const char* city,
const char* state, const char* zipcode, const char* country,
const char* phone) {
if (guid)
profile->set_guid(guid);
SetProfileInfo(profile, first_name, middle_name, last_name, email,
company, address1, address2, city, state, zipcode, country,
phone);
}
void SetCreditCardInfo(CreditCard* credit_card,
const char* name_on_card, const char* card_number,
const char* expiration_month, const char* expiration_year) {
check_and_set(credit_card, CREDIT_CARD_NAME, name_on_card);
check_and_set(credit_card, CREDIT_CARD_NUMBER, card_number);
check_and_set(credit_card, CREDIT_CARD_EXP_MONTH, expiration_month);
check_and_set(credit_card, CREDIT_CARD_EXP_4_DIGIT_YEAR, expiration_year);
}
void DisableSystemServices(Profile* profile) {
// Use a mock Keychain rather than the OS one to store credit card data.
#if defined(OS_MACOSX)
Encryptor::UseMockKeychain(true);
#endif
// Disable auxiliary profiles for unit testing. These reach out to system
// services on the Mac.
if (profile) {
components::UserPrefs::Get(profile)->SetBoolean(
prefs::kAutofillAuxiliaryProfilesEnabled, false);
}
}
} // namespace autofill_test
|
// @HEADER
// ************************************************************************
//
// Intrepid Package
// Copyright (2007) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Pavel Bochev (pbboche@sandia.gov)
// Denis Ridzal (dridzal@sandia.gov), or
// Kara Peterson (kjpeter@sandia.gov)
//
// ************************************************************************
// @HEADER
/** \file test_01.cpp
\brief Unit tests for the Intrepid::HDIV_QUAD_I1_FEM class.
\author Created by R. Kirby, P. Bochev, D. Ridzal, and K. Peterson.
*/
#include "Intrepid_FieldContainer.hpp"
#include "Intrepid_HDIV_QUAD_In_FEM.hpp"
#include "Intrepid_PointTools.hpp"
#include "Teuchos_oblackholestream.hpp"
#include "Teuchos_RCP.hpp"
#include "Teuchos_GlobalMPISession.hpp"
using namespace std;
using namespace Intrepid;
#define INTREPID_TEST_COMMAND( S , throwCounter, nException ) \
{ \
++nException; \
try { \
S ; \
} \
catch (std::logic_error err) { \
++throwCounter; \
*outStream << "Expected Error " << nException << " -------------------------------------------------------------\n"; \
*outStream << err.what() << '\n'; \
*outStream << "-------------------------------------------------------------------------------" << "\n\n"; \
}; \
}
int main(int argc, char *argv[]) {
Teuchos::GlobalMPISession mpiSession(&argc, &argv);
// This little trick lets us print to std::cout only if
// a (dummy) command-line argument is provided.
int iprint = argc - 1;
Teuchos::RCP<std::ostream> outStream;
Teuchos::oblackholestream bhs; // outputs nothing
if (iprint > 0)
outStream = Teuchos::rcp(&std::cout, false);
else
outStream = Teuchos::rcp(&bhs, false);
// Save the format state of the original std::cout.
Teuchos::oblackholestream oldFormatState;
oldFormatState.copyfmt(std::cout);
*outStream \
<< "===============================================================================\n" \
<< "| |\n" \
<< "| Unit Test (Basis_HDIV_QUAD_In_FEM) |\n" \
<< "| |\n" \
<< "| 1) Conversion of Dof tags into Dof ordinals and back |\n" \
<< "| 2) Basis values for VALUE and DIV operators |\n" \
<< "| |\n" \
<< "| Questions? Contact Pavel Bochev (pbboche@sandia.gov), |\n" \
<< "| Denis Ridzal (dridzal@sandia.gov), |\n" \
<< "| Kara Peterson (kjpeter@sandia.gov). |\n" \
<< "| |\n" \
<< "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
<< "| Trilinos website: http://trilinos.sandia.gov |\n" \
<< "| |\n" \
<< "===============================================================================\n"\
<< "| TEST 1: Basis creation, exception testing |\n"\
<< "===============================================================================\n";
// Define basis and error flag
// get points first
const int deg = 1;
shards::CellTopology line(shards::getCellTopologyData< shards::Line<> >());
FieldContainer<double> closedPts(PointTools::getLatticeSize(line,deg),1);
FieldContainer<double> openPts(PointTools::getLatticeSize(line,deg+1,1),1);
PointTools::getLattice<double,FieldContainer<double> >(closedPts,line,deg);
PointTools::getLattice<double,FieldContainer<double> >(openPts,line,deg+1,1);
Basis_HDIV_QUAD_In_FEM<double, FieldContainer<double> > quadBasis(deg,closedPts,openPts);
int errorFlag = 0;
// Initialize throw counter for exception testing
int nException = 0;
int throwCounter = 0;
// Array with a lattice of 9 points on the quad
FieldContainer<double> quadNodes(9, 2);
quadNodes(0,0) = -1.0; quadNodes(0,1) = -1.0;
quadNodes(1,0) = 0.0; quadNodes(1,1) = -1.0;
quadNodes(2,0) = 1.0; quadNodes(2,1) = -1.0;
quadNodes(3,0) = -1.0; quadNodes(3,1) = 0.0;
quadNodes(4,0) = 0.0; quadNodes(4,1) = 0.0;
quadNodes(5,0) = 1.0; quadNodes(5,1) = 0.0;
quadNodes(6,0) = -1.0; quadNodes(6,1) = 1.0;
quadNodes(7,0) = 0.0; quadNodes(7,1) = 1.0;
quadNodes(8,0) = 1.0; quadNodes(8,1) = 1.0;
// Generic array for the output values; needs to be properly resized depending on the operator type
FieldContainer<double> vals;
try{
int spaceDim = quadBasis.getBaseCellTopology().getDimension();
// exception #1: GRAD cannot be applied to HDIV functions
// resize vals to rank-3 container with dimensions (num. basis functions, num. points, arbitrary)
vals.resize(quadBasis.getCardinality(), quadNodes.dimension(0), spaceDim );
INTREPID_TEST_COMMAND( quadBasis.getValues(vals, quadNodes, OPERATOR_GRAD), throwCounter, nException );
// exception #2: CURL cannot be applied to HDIV functions
INTREPID_TEST_COMMAND( quadBasis.getValues(vals, quadNodes, OPERATOR_CURL), throwCounter, nException );
// Exceptions 3-7: all bf tags/bf Ids below are wrong and should cause getDofOrdinal() and
// getDofTag() to access invalid array elements thereby causing bounds check exception
// exception #3
INTREPID_TEST_COMMAND( quadBasis.getDofOrdinal(3,0,0), throwCounter, nException );
// exception #4
INTREPID_TEST_COMMAND( quadBasis.getDofOrdinal(1,1,1), throwCounter, nException );
// exception #5
INTREPID_TEST_COMMAND( quadBasis.getDofOrdinal(0,4,1), throwCounter, nException );
// exception #6
INTREPID_TEST_COMMAND( quadBasis.getDofTag(12), throwCounter, nException );
// exception #7
INTREPID_TEST_COMMAND( quadBasis.getDofTag(-1), throwCounter, nException );
#ifdef HAVE_INTREPID_DEBUG
// Exceptions 8- test exception handling with incorrectly dimensioned input/output arrays
// exception #8: input points array must be of rank-2
FieldContainer<double> badPoints1(4, 5, 3);
INTREPID_TEST_COMMAND( quadBasis.getValues(vals, badPoints1, OPERATOR_VALUE), throwCounter, nException );
// exception #9 dimension 1 in the input point array must equal space dimension of the cell
FieldContainer<double> badPoints2(4, spaceDim + 1);
INTREPID_TEST_COMMAND( quadBasis.getValues(vals, badPoints2, OPERATOR_VALUE), throwCounter, nException );
// exception #10 output values must be of rank-3 for OPERATOR_VALUE
FieldContainer<double> badVals1(4, 5);
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals1, quadNodes, OPERATOR_VALUE), throwCounter, nException );
// exception #11 output values must be of rank-2 for OPERATOR_DIV
FieldContainer<double> badVals2(4, 5, spaceDim);
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals2, quadNodes, OPERATOR_DIV), throwCounter, nException );
// exception #12 incorrect 0th dimension of output array (must equal number of basis functions)
FieldContainer<double> badVals3(quadBasis.getCardinality() + 1, quadNodes.dimension(0), spaceDim);
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals3, quadNodes, OPERATOR_VALUE), throwCounter, nException );
// exception #13 incorrect 0th dimension of output array (must equal number of basis functions)
FieldContainer<double> badVals4(quadBasis.getCardinality() + 1, quadNodes.dimension(0));
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals4, quadNodes, OPERATOR_DIV), throwCounter, nException );
// exception #14 incorrect 1st dimension of output array (must equal number of points)
FieldContainer<double> badVals5(quadBasis.getCardinality(), quadNodes.dimension(0) + 1, spaceDim);
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals5, quadNodes, OPERATOR_VALUE), throwCounter, nException );
// exception #15 incorrect 1st dimension of output array (must equal number of points)
FieldContainer<double> badVals6(quadBasis.getCardinality(), quadNodes.dimension(0) + 1);
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals6, quadNodes, OPERATOR_DIV), throwCounter, nException );
// exception #16: incorrect 2nd dimension of output array (must equal the space dimension)
FieldContainer<double> badVals7(quadBasis.getCardinality(), quadNodes.dimension(0), spaceDim + 1);
INTREPID_TEST_COMMAND( quadBasis.getValues(badVals7, quadNodes, OPERATOR_VALUE), throwCounter, nException );
#endif
}
catch (std::logic_error err) {
*outStream << "UNEXPECTED ERROR !!! ----------------------------------------------------------\n";
*outStream << err.what() << '\n';
*outStream << "-------------------------------------------------------------------------------" << "\n\n";
errorFlag = -1000;
};
// Check if number of thrown exceptions matches the one we expect
if (throwCounter != nException) {
errorFlag++;
*outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
}
*outStream \
<< "\n"
<< "===============================================================================\n"\
<< "| TEST 2: correctness of tag to enum and enum to tag lookups |\n"\
<< "===============================================================================\n";
try{
std::vector<std::vector<int> > allTags = quadBasis.getAllDofTags();
// Loop over all tags, lookup the associated dof enumeration and then lookup the tag again
for (unsigned i = 0; i < allTags.size(); i++) {
int bfOrd = quadBasis.getDofOrdinal(allTags[i][0], allTags[i][1], allTags[i][2]);
std::vector<int> myTag = quadBasis.getDofTag(bfOrd);
if( !( (myTag[0] == allTags[i][0]) &&
(myTag[1] == allTags[i][1]) &&
(myTag[2] == allTags[i][2]) &&
(myTag[3] == allTags[i][3]) ) ) {
errorFlag++;
*outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
*outStream << " getDofOrdinal( {"
<< allTags[i][0] << ", "
<< allTags[i][1] << ", "
<< allTags[i][2] << ", "
<< allTags[i][3] << "}) = " << bfOrd <<" but \n";
*outStream << " getDofTag(" << bfOrd << ") = { "
<< myTag[0] << ", "
<< myTag[1] << ", "
<< myTag[2] << ", "
<< myTag[3] << "}\n";
}
}
// Now do the same but loop over basis functions
for( int bfOrd = 0; bfOrd < quadBasis.getCardinality(); bfOrd++) {
std::vector<int> myTag = quadBasis.getDofTag(bfOrd);
int myBfOrd = quadBasis.getDofOrdinal(myTag[0], myTag[1], myTag[2]);
if( bfOrd != myBfOrd) {
errorFlag++;
*outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
*outStream << " getDofTag(" << bfOrd << ") = { "
<< myTag[0] << ", "
<< myTag[1] << ", "
<< myTag[2] << ", "
<< myTag[3] << "} but getDofOrdinal({"
<< myTag[0] << ", "
<< myTag[1] << ", "
<< myTag[2] << ", "
<< myTag[3] << "} ) = " << myBfOrd << "\n";
}
}
}
catch (std::logic_error err){
*outStream << err.what() << "\n\n";
errorFlag = -1000;
};
*outStream \
<< "\n"
<< "===============================================================================\n"\
<< "| TEST 3: correctness of basis function values |\n"\
<< "===============================================================================\n";
outStream -> precision(20);
// VALUE:
double basisValues[] = {
// first bf, first row of points
1.0, 0.0, 0.5, 0.0, 0.0, 0.0,
// first bf, second row of points
1.0, 0.0, 0.5, 0.0, 0.0, 0.0,
// first bf, third row of points
1.0, 0.0, 0.5, 0.0, 0.0, 0.0,
// second bf, first row of points
0.0, 0.0, 0.5, 0.0, 1.0, 0.0,
// second bf, second row of points
0.0, 0.0, 0.5, 0.0, 1.0, 0.0,
// second bf, third row of points
0.0, 0.0, 0.5, 0.0, 1.0, 0.0,
// third bf, first row of points
0.0, 1.0, 0.0, 1.0, 0.0, 1.0,
// third bf, second row of points
0.0, 0.5, 0.0, 0.5, 0.0, 0.5,
// third bf, third row of points
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
// fourth bf, first row of points
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
// fourth bf, second row of points
0.0, 0.5, 0.0, 0.5, 0.0, 0.5,
// fourth bf, third row of points
0.0, 1.0, 0.0, 1.0, 0.0, 1.0
};
// DIV: each row gives the 6 correct values of the divergence of the 6 basis functions: (P,F) layout
double basisDivs[] = {
// bf0 has -0.5 divergence
-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5,
// bf1 has 0.5 divergencece
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
// bf2 has -0.5 divergence
-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5,
// bf3 has 0.5 divergence
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
};
try{
// Dimensions for the output arrays:
int numPoints = quadNodes.dimension(0);
int numFields = quadBasis.getCardinality();
int spaceDim = quadBasis.getBaseCellTopology().getDimension();
// Generic array for values and curls that will be properly sized before each call
FieldContainer<double> vals;
// Check VALUE of basis functions: resize vals to rank-3 container:
vals.resize(numFields, numPoints, spaceDim);
quadBasis.getValues(vals, quadNodes, OPERATOR_VALUE);
for (int i = 0; i < numFields; i++) {
for (int j = 0; j < numPoints; j++) {
for (int k = 0; k < spaceDim; k++) {
// compute offset for (F,P,D) data layout: indices are F->i, P-> j, D->k
int l = i * numPoints * spaceDim + j * spaceDim + k;
if (std::abs(vals(i,j,k) - basisValues[l]) > INTREPID_TOL) {
errorFlag++;
*outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
// Output the multi-index of the value where the error is:
*outStream << " At multi-index { ";
*outStream << i << " ";*outStream << j << " ";*outStream << k << " ";
*outStream << "} computed value: " << vals(i,j,k)
<< " but reference value: " << basisValues[l] << "\n";
}
}
}
}
// Check DIV of basis function: resize vals to rank-2 container
vals.resize(numFields, numPoints);
quadBasis.getValues(vals, quadNodes, OPERATOR_DIV);
for (int i = 0; i < numFields; i++) {
for (int j = 0; j < numPoints; j++) {
int l = j + i * numPoints;
if (std::abs(vals(i,j) - basisDivs[l]) > INTREPID_TOL) {
errorFlag++;
*outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
// Output the multi-index of the value where the error is:
*outStream << " At multi-index { ";
*outStream << i << " ";*outStream << j << " ";
*outStream << "} computed divergence component: " << vals(i,j)
<< " but reference divergence component: " << basisDivs[l] << "\n";
}
}
}
}
// Catch unexpected errors
catch (std::logic_error err) {
*outStream << err.what() << "\n\n";
errorFlag = -1000;
};
if (errorFlag != 0)
std::cout << "End Result: TEST FAILED\n";
else
std::cout << "End Result: TEST PASSED\n";
// reset format state of std::cout
std::cout.copyfmt(oldFormatState);
return errorFlag;
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "SerialPort.h"
//#include "NetworkCommunication/UsageReporting.h"
#include "HAL/HAL.hpp"
#include <stdarg.h>
//static ViStatus _VI_FUNCH ioCompleteHandler (ViSession vi, ViEventType eventType, ViEvent event, ViAddr userHandle);
/**
* Create an instance of a Serial Port class.
*
* @param baudRate The baud rate to configure the serial port.
* @param port The physical port to use
* @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits.
* @param parity Select the type of parity checking to use.
* @param stopBits The number of stop bits to use as defined by the enum StopBits.
*/
SerialPort::SerialPort(uint32_t baudRate, Port port, uint8_t dataBits, SerialPort::Parity parity, SerialPort::StopBits stopBits)
: m_resourceManagerHandle (0)
, m_portHandle (0)
, m_consoleModeEnabled (false)
{
int32_t status = 0;
m_port = port;
serialInitializePort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
serialSetBaudRate(port, baudRate, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
serialSetDataBits(port, dataBits, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
serialSetParity(port, parity, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
serialSetStopBits(port, stopBits, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
// Set the default timeout to 5 seconds.
SetTimeout(5.0f);
// Don't wait until the buffer is full to transmit.
SetWriteBufferMode(kFlushOnAccess);
EnableTermination();
//viInstallHandler(m_portHandle, VI_EVENT_IO_COMPLETION, ioCompleteHandler, this);
//viEnableEvent(m_portHandle, VI_EVENT_IO_COMPLETION, VI_HNDLR, VI_NULL);
HALReport(HALUsageReporting::kResourceType_SerialPort, 0);
}
/**
* Destructor.
*/
SerialPort::~SerialPort()
{
int32_t status = 0;
serialClose(m_port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Set the type of flow control to enable on this port.
*
* By default, flow control is disabled.
*/
void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl)
{
int32_t status = 0;
serialSetFlowControl(m_port, flowControl, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Enable termination and specify the termination character.
*
* Termination is currently only implemented for receive.
* When the the terminator is recieved, the Read() or Scanf() will return
* fewer bytes than requested, stopping after the terminator.
*
* @param terminator The character to use for termination.
*/
void SerialPort::EnableTermination(char terminator)
{
int32_t status = 0;
serialEnableTermination(m_port, terminator, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Disable termination behavior.
*/
void SerialPort::DisableTermination()
{
int32_t status = 0;
serialDisableTermination(m_port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Get the number of bytes currently available to read from the serial port.
*
* @return The number of bytes available to read
*/
int32_t SerialPort::GetBytesReceived()
{
int32_t status = 0;
int32_t retVal = serialGetBytesReceived(m_port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
return retVal;
}
/**
* Read raw bytes out of the buffer.
*
* @param buffer Pointer to the buffer to store the bytes in.
* @param count The maximum number of bytes to read.
* @return The number of bytes actually read into the buffer.
*/
uint32_t SerialPort::Read(char *buffer, int32_t count)
{
int32_t status = 0;
int32_t retVal = serialRead(m_port, buffer, count, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
return retVal;
}
/**
* Write raw bytes to the buffer.
*
* @param buffer Pointer to the buffer to read the bytes from.
* @param count The maximum number of bytes to write.
* @return The number of bytes actually written into the port.
*/
uint32_t SerialPort::Write(const char *buffer, int32_t count)
{
int32_t status = 0;
int32_t retVal = serialWrite(m_port, buffer, count, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
return retVal;
}
/**
* Configure the timeout of the serial port.
*
* This defines the timeout for transactions with the hardware.
* It will affect reads and very large writes.
*
* @param timeout The number of seconds to to wait for I/O.
*/
void SerialPort::SetTimeout(float timeout)
{
int32_t status = 0;
serialSetTimeout(m_port, timeout, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Specify the size of the input buffer.
*
* Specify the amount of data that can be stored before data
* from the device is returned to Read or Scanf. If you want
* data that is recieved to be returned immediately, set this to 1.
*
* It the buffer is not filled before the read timeout expires, all
* data that has been received so far will be returned.
*
* @param size The read buffer size.
*/
void SerialPort::SetReadBufferSize(uint32_t size)
{
int32_t status = 0;
serialSetReadBufferSize(m_port, size, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Specify the size of the output buffer.
*
* Specify the amount of data that can be stored before being
* transmitted to the device.
*
* @param size The write buffer size.
*/
void SerialPort::SetWriteBufferSize(uint32_t size)
{
int32_t status = 0;
serialSetWriteBufferSize(m_port, size, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Specify the flushing behavior of the output buffer.
*
* When set to kFlushOnAccess, data is synchronously written to the serial port
* after each call to either Printf() or Write().
*
* When set to kFlushWhenFull, data will only be written to the serial port when
* the buffer is full or when Flush() is called.
*
* @param mode The write buffer mode.
*/
void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode)
{
int32_t status = 0;
serialSetWriteMode(m_port, mode, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Force the output buffer to be written to the port.
*
* This is used when SetWriteBufferMode() is set to kFlushWhenFull to force a
* flush before the buffer is full.
*/
void SerialPort::Flush()
{
int32_t status = 0;
serialFlush(m_port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Reset the serial port driver to a known state.
*
* Empty the transmit and receive buffers in the device and formatted I/O.
*/
void SerialPort::Reset()
{
int32_t status = 0;
serialClear(m_port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_OPTIMIZERS_HYPERGRADIENT_ADAM_HPP_INCLUDED
#define LBANN_OPTIMIZERS_HYPERGRADIENT_ADAM_HPP_INCLUDED
#include "lbann/optimizers/data_type_optimizer.hpp"
#include "lbann/io/persist.hpp"
#include <optimizers.pb.h>
namespace lbann {
/** @class hypergradient_adam
* @brief Hypergradient Adam optimizer.
*
* Reference:
*
* Baydin et al. "Online Learning Rate Adaptation with Hypergradient
* Descent", 2017.
*/
template <typename TensorDataType>
class hypergradient_adam
: public Cloneable<hypergradient_adam<TensorDataType>,
data_type_optimizer<TensorDataType>> {
using BaseType = Cloneable<hypergradient_adam<TensorDataType>,
data_type_optimizer<TensorDataType>>;
public:
/** @name Public Types */
///@{
/** @brief The tensor type expected in this object. */
using AbsDistMatrixType = El::AbstractDistMatrix<TensorDataType>;
/** @brief The concrete weights type used by this object. */
using WeightsType = data_type_weights<TensorDataType>;
/** @brief The base optimizer type for this class. */
using OptimizerType = data_type_optimizer<TensorDataType>;
///@}
public:
/** @brief Construct a Hypergradient Adam optimizer object
*
* @param init_learning_rate Initial Adam learning rate (0.001 is
* reasonable).
* @param hyper_learning_rate Hypergradient learning rate.
* @param beta1 Decay rate for the first moment
* moving average.
* @param beta2 Decay rate for the second moment
* moving average.
* @param eps Small factor to avoid division by
* zero.
*/
hypergradient_adam(
TensorDataType init_learning_rate = El::To<TensorDataType>(1e-3),
TensorDataType hyper_learning_rate = El::To<TensorDataType>(1e-7),
TensorDataType beta1 = El::To<TensorDataType>(0.9),
TensorDataType beta2 = El::To<TensorDataType>(0.99),
TensorDataType eps = El::To<TensorDataType>(1e-8));
hypergradient_adam(const hypergradient_adam& other);
hypergradient_adam& operator=(const hypergradient_adam& other);
~hypergradient_adam() override = default;
/** Archive for checkpoint and restart */
template <class Archive> void serialize(Archive & ar);
/** @brief Human-readable type name. */
std::string get_type() const override { return "hypergradient Adam"; }
/** @brief Human-readable description. */
description get_description() const override;
using OptimizerType::setup;
void setup(WeightsType* w = nullptr) override;
protected:
/** @brief Computation for an optimization step. */
void step_compute(AbsDistMatrixType& values,
const AbsDistMatrixType& gradient) override;
private:
/** @brief Hypergradient learning rate. */
TensorDataType m_hyper_learning_rate;
/** @brief Update factor for first moment estimate. */
TensorDataType m_beta1;
/** @brief Update factor for second moment estimate. */
TensorDataType m_beta2;
/** @brief Small factor to avoid division by zero. */
TensorDataType m_eps;
/** @brief beta1 ^ iteration. */
TensorDataType m_current_beta1;
/** @brief beta2 ^ iteration. */
TensorDataType m_current_beta2;
/** @brief First moment estimates. */
std::unique_ptr<AbsDistMatrixType> m_moment1;
/** @brief Second moment estimates. */
std::unique_ptr<AbsDistMatrixType> m_moment2;
/** @brief Gradient estimate from the prior step (for hypergradient). */
std::unique_ptr<AbsDistMatrixType> m_old_gradient;
};
template <typename TensorDataType>
std::unique_ptr<optimizer>
build_hypergradient_adam_optimizer_from_pbuf(
google::protobuf::Message const&);
} // namespace lbann
#endif // LBANN_OPTIMIZER_HYPERGRADIENT_ADAM_HPP_INCLUDED
|
// bdlt_epochutil.cpp -*-C++-*-
#include <bdlt_epochutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_epochutil_cpp,"$Id$ $CSID$")
namespace BloombergLP {
namespace bdlt {
// ----------------
// struct EpochUtil
// ----------------
// CLASS DATA
#ifndef BDE_OPENSOURCE_PUBLICATION
#ifdef BDE_USE_PROLEPTIC_DATES
#error 'BDE_USE_PROLEPTIC_DATES' option disallowed for Bloomberg code.
#endif
#endif
#ifdef BDE_USE_PROLEPTIC_DATES
const EpochUtil::TimeT64 EpochUtil::s_earliestAsTimeT64 = -62135596800LL;
// January 1, 0001 00:00:00
#else
const EpochUtil::TimeT64 EpochUtil::s_earliestAsTimeT64 = -62135769600LL;
// January 1, 0001 00:00:00
#endif
const EpochUtil::TimeT64 EpochUtil::s_latestAsTimeT64 = 253402300799LL;
// December 31, 9999 23:59:59
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2016 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
/**
* Copyright 2020 Huawei Technologies Co., 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.
*/
#include "frontend/optimizer/irpass/grad_var_prepare.h"
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <memory>
#include "frontend/operator/composite/composite.h"
#include "frontend/operator/ops.h"
#include "frontend/optimizer/irpass.h"
#include "frontend/optimizer/anf_visitor.h"
#include "ir/func_graph.h"
namespace mindspore {
namespace opt {
namespace irpass {
static AnfNodePtr GenerateUnpackGraphNode(const AnfNodePtr &origin_node, std::vector<AnfNodePtr> inputs_y,
const AnfNodePtr &func_node, bool is_unpack, bool sens_param) {
MS_EXCEPTION_IF_NULL(func_node);
FuncGraphPtr func_graph = origin_node->func_graph();
MS_EXCEPTION_IF_NULL(func_graph);
std::vector<AnfNodePtr> nodes;
AnfNodePtr unpack_graph_node = nullptr;
if (is_unpack) {
auto unpack_graph = std::make_shared<prim::UnpackGraphPrimitive>("unpack_graph", sens_param, true);
nodes.push_back(NewValueNode(unpack_graph));
nodes.push_back(func_node);
// {unpackcall, {GradOperation, ...}, args...}
const size_t inputs_begin_index = 2;
(void)std::transform(inputs_y.begin() + inputs_begin_index, inputs_y.end(), std::back_inserter(nodes),
[](const AnfNodePtr &node) { return node; });
unpack_graph_node = func_graph->NewCNodeBefore(origin_node, nodes);
} else {
auto unpack_graph = std::make_shared<prim::UnpackGraphPrimitive>("unpack_graph", sens_param, false);
nodes.push_back(NewValueNode(unpack_graph));
nodes.push_back(func_node);
// {{GradOperation, ...}, args...}
const size_t inputs_begin_index = 1;
(void)std::transform(inputs_y.begin() + inputs_begin_index, inputs_y.end(), std::back_inserter(nodes),
[](const AnfNodePtr &node) { return node; });
unpack_graph_node = func_graph->NewCNodeBefore(origin_node, nodes);
}
return unpack_graph_node;
}
// get metagraph of value node
MetaFuncGraphPtr GetMetaFuncGraphOfValueNode(const AnfNodePtr &node) {
ValuePtr value;
if (IsValueNode<prim::DoSignaturePrimitive>(node)) {
value = GetValueNode(node)->cast<prim::DoSignaturePrimitivePtr>()->function();
} else {
value = GetValueNode(node);
}
if (value == nullptr) {
return nullptr;
}
return value->cast<MetaFuncGraphPtr>();
}
// check if node is a specific metafuncgraph op
bool IsMetaFuncGraph(const AnfNodePtr &node, const MetaFuncGraphPtr meta_func_graph) {
if (node != nullptr) {
auto meta_func_graph_ptr = GetMetaFuncGraphOfValueNode(node);
if (meta_func_graph_ptr == nullptr) {
return false;
}
if (meta_func_graph_ptr->type_name() == meta_func_graph->type_name()) {
return true;
}
}
return false;
}
// {{GradOperation, g, w}, Ys}
// {UnPackCall, {GradOperation, g, w}, Ys}
AnfNodePtr GradVarPrepare::operator()(const OptimizerPtr &, const AnfNodePtr &node) {
auto cnode = node->cast<CNodePtr>();
if (cnode == nullptr) {
return nullptr;
}
auto func_graph = cnode->func_graph();
if (func_graph == nullptr) {
return nullptr;
}
// {{...}, Ys}
auto inputs_y = cnode->inputs();
std::vector<AnfNodePtr> inputs_x;
if (IsCNode(inputs_y[0])) {
inputs_x = inputs_y[0]->cast<CNodePtr>()->inputs();
} else if (IsMetaFuncGraph(inputs_y[0], unpack_op_) && IsCNode(inputs_y[1])) {
inputs_x = inputs_y[1]->cast<CNodePtr>()->inputs();
} else {
return nullptr;
}
// {{...}, Xs}
if (inputs_x.size() < 2) {
return nullptr;
}
// {GradOperation, g, w} or {GradOperation, g}
if (!IsMetaFuncGraph(inputs_x[0], grad_op_)) {
return nullptr;
}
auto meta_func = GetMetaFuncGraphOfValueNode(inputs_x[0]);
if (meta_func == nullptr) {
return nullptr;
}
auto grad_op_ptr = meta_func->cast<prim::GradOperationPtr>();
auto func_node = inputs_x[1];
if (!IsValueNode<FuncGraph>(func_node)) {
return nullptr;
}
const bool is_unpack = IsMetaFuncGraph(inputs_y[0], unpack_op_);
const bool sens_param = grad_op_ptr->sens_param();
inputs_x[1] = GenerateUnpackGraphNode(node, inputs_y, func_node, is_unpack, sens_param);
// construct new grad_opration
auto grad_op_cnode = func_graph->NewCNodeBefore(node, inputs_x);
if (IsMetaFuncGraph(inputs_y[0], unpack_op_)) {
inputs_y[1] = grad_op_cnode;
} else {
inputs_y[0] = grad_op_cnode;
}
return func_graph->NewCNodeBefore(node, inputs_y);
}
} // namespace irpass
} // namespace opt
} // namespace mindspore
|
#include <QDebug>
#include <QApplication>
#include <QMimeData>
#include <QClipboard>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.connect (QApplication::clipboard (), &QClipboard::changed, [=] () {
const QMimeData* mimeData = qApp->clipboard()->mimeData();
qDebug() << mimeData->formats();
qDebug() << qApp->clipboard ()->text ();
qDebug() << mimeData->text();
if (mimeData->hasFormat("peony-qt/is-cut")) {
qDebug() << "==> is-cut? :" << mimeData->data("peony-qt/is-cut");
}
qDebug() << "\n\n\n\n\n\n\n";
});
a.connect (QApplication::clipboard (), &QClipboard::findBufferChanged, [=] () {
qDebug() << "find buffer changed";
});
a.connect (QApplication::clipboard (), &QClipboard::selectionChanged, [=] () {
qDebug() << "selection changed";
});
return a.exec();
}
|
#include "css/composite/grammar.h"
#include "TypeName.h"
using smtk::common::typeName;
#include "css/token/grammar.h"
#include "css/composite/grammar.h"
#include "css/parser/actions.h"
#include <chrono>
#include <memory>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <typeinfo>
std::string read_file(const std::string& filename)
{
std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
std::ifstream::pos_type filesize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::vector<char> bytes(filesize);
ifs.read(bytes.data(), filesize);
return std::string(bytes.data(), filesize);
}
/// A namespace for cascading style sheets (CSS)
namespace css
{
/// A grammar
struct grammar : composite::stylesheet
{
};
template<typename Rule> using action = parser::action<Rule>;
using stylesheet = parser::stylesheet;
} // css namepace
int main(int argc, char* argv[])
{
using namespace tao::css_pegtl;
#ifdef CSS_DBG_GRAMMAR
if (analyze<css::grammar>() != 0 )
{
std::cerr << "CSS grammar: cycles without progress detected!\n";
return 1;
}
std::cout << "CSS grammar: no cycles without progress.\n";
#endif
std::string filename = argc > 1 ? argv[1] : "example.css";
std::string filedata = read_file(filename);
auto source = tao::css_pegtl::memory_input(filedata, filename);
const auto start = std::chrono::steady_clock::now();
css::stylesheet sheet;
try
{
bool parsed = tao::css_pegtl::parse<css::grammar, css::action>(source, sheet);
std::cout
<< "\n\n"
<< "Encoding \"" << sheet.encoding << "\"\n"
<< "Parse result: " << (parsed ? "T" : "F")
<< "\n";
sheet.valid &= parsed;
}
catch (parse_error& e)
{
std::cout << "***\n\n\n***\n\n\n";
(void)e;
const auto p = e.positions.front();
std::cerr
<< e.what() << "\n"
<< source.line_as_string(p) << "\n"
<< std::setw( p.byte ) << '^' << "\n";
sheet.valid = false;
}
const auto end = std::chrono::steady_clock::now();
auto dt = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::size_t numRulesets = 0;
// Print summary and increment counters.
if (sheet.valid)
{
#if !CSS_DBG_PARSE
std::cout << "\n\n# Summary\n\n";
#endif // !CSS_DBG_PARSE
for (const auto& sel : sheet.properties)
{
numRulesets += sel.second.size();
#if !CSS_DBG_PARSE
std::cout << "Selector <" << sel.first << ">\n";
sel.second.visit(
[](const css::parser::property& p) {
std::cout << " " << p << ";\n";
}
);
#endif // !CSS_DBG_PARSE
}
}
std::cout
<< "Parse took " << dt << "µs";
#if !CSS_DBG_PARSE
if (sheet.valid)
{
std::cout
<< " for " << sheet.properties.size() << " selectors"
<< " and " << numRulesets << " rulesets.";
}
#endif // !CSS_DBG_PARSE
std::cout << "\n";
return sheet.valid ? 0 : 1;
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "connection.h"
#include "dummypacket.h"
#include "channel.h"
#include "controlpacket.h"
#include "ipacketstreamer.h"
#include "iserveradapter.h"
#include "config.h"
#include "transport_thread.h"
#include "transport.h"
#include <vespa/log/log.h>
LOG_SETUP(".fnet");
namespace {
class SyncPacket : public FNET_DummyPacket {
private:
std::mutex _lock;
std::condition_variable _cond;
bool _done;
bool _waiting;
public:
SyncPacket()
: _lock(),
_cond(),
_done(false),
_waiting(false) {}
~SyncPacket() {}
void WaitFree() {
std::unique_lock<std::mutex> guard(_lock);
_waiting = true;
while (!_done)
_cond.wait(guard);
_waiting = false;
}
void Free() override;
};
void
SyncPacket::Free()
{
std::lock_guard<std::mutex> guard(_lock);
_done = true;
if (_waiting) {
_cond.notify_one();
}
}
}
FNET_Connection::ResolveHandler::ResolveHandler(FNET_Connection *conn)
: connection(conn),
address()
{
connection->AddRef();
}
void
FNET_Connection::ResolveHandler::handle_result(vespalib::SocketAddress result)
{
address = result;
connection->Owner()->Add(connection);
}
FNET_Connection::ResolveHandler::~ResolveHandler()
{
connection->SubRef();
}
///////////////////////
// PROTECTED METHODS //
///////////////////////
const char*
FNET_Connection::GetStateString(State state)
{
switch(state) {
case FNET_CONNECTING:
return "CONNECTING";
case FNET_CONNECTED:
return "CONNECTED";
case FNET_CLOSING:
return "CLOSING";
case FNET_CLOSED:
return "CLOSED";
default:
return "ILLEGAL";
}
}
void
FNET_Connection::SetState(State state)
{
State oldstate;
std::vector<FNET_Channel::UP> toDelete;
std::unique_lock<std::mutex> guard(_ioc_lock);
oldstate = _state;
_state = state;
if (LOG_WOULD_LOG(debug) && state != oldstate) {
LOG(debug, "Connection(%s): State transition: %s -> %s", GetSpec(),
GetStateString(oldstate), GetStateString(state));
}
if (oldstate < FNET_CLOSING && state >= FNET_CLOSING) {
if (_flags._writeLock) {
_flags._discarding = true;
while (_flags._writeLock)
_ioc_cond.wait(guard);
_flags._discarding = false;
}
while (!_queue.IsEmpty_NoLock() || !_myQueue.IsEmpty_NoLock()) {
_flags._discarding = true;
_queue.FlushPackets_NoLock(&_myQueue);
guard.unlock();
_myQueue.DiscardPackets_NoLock();
guard.lock();
_flags._discarding = false;
}
BeforeCallback(guard, nullptr);
toDelete = _channels.Broadcast(&FNET_ControlPacket::ChannelLost);
AfterCallback(guard);
}
if ( ! toDelete.empty() ) {
FNET_Channel *ach = _adminChannel;
for (const FNET_Channel::UP & ch : toDelete) {
if (ch.get() == ach) {
_adminChannel = nullptr;
} else {
SubRef_NoLock();
}
}
}
}
void
FNET_Connection::HandlePacket(uint32_t plen, uint32_t pcode,
uint32_t chid)
{
FNET_Packet *packet;
FNET_Channel *channel;
FNET_IPacketHandler::HP_RetCode hp_rc;
std::unique_lock<std::mutex> guard(_ioc_lock);
channel = _channels.Lookup(chid);
if (channel != nullptr) { // deliver packet on open channel
channel->prefetch(); // Prefetch in the shadow of the lock operation in BeforeCallback.
__builtin_prefetch(&_streamer);
__builtin_prefetch(&_input);
BeforeCallback(guard, channel);
__builtin_prefetch(channel->GetHandler(), 0); // Prefetch the handler while packet is being decoded.
packet = _streamer->Decode(&_input, plen, pcode, channel->GetContext());
hp_rc = (packet != nullptr) ? channel->Receive(packet)
: channel->Receive(&FNET_ControlPacket::BadPacket);
AfterCallback(guard);
FNET_Channel::UP toDelete;
if (hp_rc > FNET_IPacketHandler::FNET_KEEP_CHANNEL) {
_channels.Unregister(channel);
if (hp_rc == FNET_IPacketHandler::FNET_FREE_CHANNEL) {
if (channel == _adminChannel) {
_adminChannel = nullptr;
} else {
SubRef_NoLock();
}
toDelete.reset(channel);
}
}
} else if (CanAcceptChannels() && IsFromPeer(chid)) { // open new channel
FNET_Channel::UP newChannel(new FNET_Channel(chid, this));
channel = newChannel.get();
AddRef_NoLock();
BeforeCallback(guard, channel);
if (_serverAdapter->InitChannel(channel, pcode)) {
packet = _streamer->Decode(&_input, plen, pcode, channel->GetContext());
hp_rc = (packet != nullptr) ? channel->Receive(packet)
: channel->Receive(&FNET_ControlPacket::BadPacket);
AfterCallback(guard);
if (hp_rc == FNET_IPacketHandler::FNET_FREE_CHANNEL) {
SubRef_NoLock();
} else if (hp_rc == FNET_IPacketHandler::FNET_KEEP_CHANNEL) {
_channels.Register(newChannel.release());
} else {
newChannel.release(); // It has already been taken care of, so we should not free it here.
}
} else {
AfterCallback(guard);
SubRef_NoLock();
guard.unlock();
LOG(debug, "Connection(%s): channel init failed", GetSpec());
_input.DataToDead(plen);
}
} else { // skip unhandled packet
guard.unlock();
LOG(spam, "Connection(%s): skipping unhandled packet", GetSpec());
_input.DataToDead(plen);
}
}
bool
FNET_Connection::Read()
{
uint32_t readData = 0; // total data read
uint32_t readPackets = 0; // total packets read
int readCnt = 0; // read count
bool broken = false; // is this conn broken ?
ssize_t res; // single read result
_input.EnsureFree(FNET_READ_SIZE);
res = _socket.read(_input.GetFree(), _input.GetFreeLen());
readCnt++;
while (res > 0) {
_input.FreeToData((uint32_t)res);
readData += (uint32_t)res;
for (;;) { // handle each complete packet in the buffer.
if (!_flags._gotheader)
_flags._gotheader = _streamer->GetPacketInfo(&_input, &_packetLength,
&_packetCode, &_packetCHID,
&broken);
if (_flags._gotheader && _input.GetDataLen() >= _packetLength) {
readPackets++;
HandlePacket(_packetLength, _packetCode, _packetCHID);
_flags._gotheader = false; // reset header flag.
} else {
if (broken)
goto done_read;
break;
}
}
_input.resetIfEmpty();
if (_input.GetFreeLen() > 0
|| readCnt >= FNET_READ_REDO) // prevent starvation
goto done_read;
_input.EnsureFree(FNET_READ_SIZE);
res = _socket.read(_input.GetFree(), _input.GetFreeLen());
readCnt++;
}
done_read:
if (readData > 0) {
UpdateTimeOut();
CountDataRead(readData);
CountPacketRead(readPackets);
uint32_t maxSize = GetConfig()->_maxInputBufferSize;
if (maxSize > 0 && _input.GetBufSize() > maxSize)
{
if (!_flags._gotheader || _packetLength < maxSize) {
_input.Shrink(maxSize);
}
}
}
if (res <= 0) {
if (res == 0) {
broken = true; // handle EOF
} else { // res < 0
broken = ((errno != EWOULDBLOCK) && (errno != EAGAIN));
if (broken && (errno != ECONNRESET)) {
LOG(debug, "Connection(%s): read error: %d", GetSpec(), errno);
}
}
}
return !broken;
}
bool
FNET_Connection::Write(bool direct)
{
uint32_t writtenData = 0; // total data written
uint32_t writtenPackets = 0; // total packets written
int writeCnt = 0; // write count
bool broken = false; // is this conn broken ?
ssize_t res; // single write result
FNET_Packet *packet;
FNET_Context context;
do {
// fill output buffer
while (_output.GetDataLen() < FNET_WRITE_SIZE) {
if (_myQueue.IsEmpty_NoLock())
break;
packet = _myQueue.DequeuePacket_NoLock(&context);
if (packet->IsRegularPacket()) { // ignore non-regular packets
_streamer->Encode(packet, context._value.INT, &_output);
writtenPackets++;
}
packet->Free();
}
if (_output.GetDataLen() == 0) {
res = 0;
break;
}
// write data
res = _socket.write(_output.GetData(), _output.GetDataLen());
writeCnt++;
if (res > 0) {
_output.DataToDead((uint32_t)res);
writtenData += (uint32_t)res;
_output.resetIfEmpty();
}
} while (res > 0 &&
_output.GetDataLen() == 0 &&
!_myQueue.IsEmpty_NoLock() &&
writeCnt < FNET_WRITE_REDO);
if (writtenData > 0) {
uint32_t maxSize = GetConfig()->_maxOutputBufferSize;
if (maxSize > 0 && _output.GetBufSize() > maxSize) {
_output.Shrink(maxSize);
}
}
if (res < 0) {
broken = ((errno != EWOULDBLOCK) && (errno != EAGAIN));
if (broken && (errno != ECONNRESET)) {
LOG(debug, "Connection(%s): write error: %d", GetSpec(), errno);
}
}
std::unique_lock<std::mutex> guard(_ioc_lock);
_writeWork = _queue.GetPacketCnt_NoLock()
+ _myQueue.GetPacketCnt_NoLock()
+ ((_output.GetDataLen() > 0) ? 1 : 0);
_flags._writeLock = false;
if (_flags._discarding) {
_ioc_cond.notify_all();
}
bool writePending = (_writeWork > 0);
if (direct) { // direct write (from post packet)
if (writtenData > 0) {
CountDirectDataWrite(writtenData);
CountDirectPacketWrite(writtenPackets);
}
if (writePending) {
AddRef_NoLock();
guard.unlock();
if (broken) {
Owner()->Close(this, /* needRef = */ false);
} else {
Owner()->EnableWrite(this, /* needRef = */ false);
}
}
} else { // normal write (from event loop)
guard.unlock();
if (writtenData > 0) {
CountDataWrite(writtenData);
CountPacketWrite(writtenPackets);
}
if (!writePending)
EnableWriteEvent(false);
}
return !broken;
}
////////////////////
// PUBLIC METHODS //
////////////////////
FNET_Connection::FNET_Connection(FNET_TransportThread *owner,
FNET_IPacketStreamer *streamer,
FNET_IServerAdapter *serverAdapter,
vespalib::SocketHandle socket,
const char *spec)
: FNET_IOComponent(owner, socket.get(), spec, /* time-out = */ true),
_streamer(streamer),
_serverAdapter(serverAdapter),
_adminChannel(nullptr),
_socket(std::move(socket)),
_resolve_handler(nullptr),
_context(),
_state(FNET_CONNECTED), // <-- NB
_flags(),
_packetLength(0),
_packetCode(0),
_packetCHID(0),
_writeWork(0),
_currentID(1), // <-- NB
_input(FNET_READ_SIZE * 2),
_queue(256),
_myQueue(256),
_output(FNET_WRITE_SIZE * 2),
_channels(),
_callbackTarget(nullptr),
_cleanup(nullptr)
{
assert(_socket.valid());
LOG(debug, "Connection(%s): State transition: %s -> %s", GetSpec(),
GetStateString(FNET_CONNECTING), GetStateString(FNET_CONNECTED));
}
FNET_Connection::FNET_Connection(FNET_TransportThread *owner,
FNET_IPacketStreamer *streamer,
FNET_IServerAdapter *serverAdapter,
FNET_IPacketHandler *adminHandler,
FNET_Context adminContext,
FNET_Context context,
const char *spec)
: FNET_IOComponent(owner, -1, spec, /* time-out = */ true),
_streamer(streamer),
_serverAdapter(serverAdapter),
_adminChannel(nullptr),
_socket(),
_resolve_handler(nullptr),
_context(context),
_state(FNET_CONNECTING),
_flags(),
_packetLength(0),
_packetCode(0),
_packetCHID(0),
_writeWork(0),
_currentID(0),
_input(FNET_READ_SIZE * 2),
_queue(256),
_myQueue(256),
_output(FNET_WRITE_SIZE * 2),
_channels(),
_callbackTarget(nullptr),
_cleanup(nullptr)
{
if (adminHandler != nullptr) {
FNET_Channel::UP admin(new FNET_Channel(FNET_NOID, this, adminHandler, adminContext));
_adminChannel = admin.get();
_channels.Register(admin.release());
}
}
FNET_Connection::~FNET_Connection()
{
if (_adminChannel != nullptr) {
_channels.Unregister(_adminChannel);
delete _adminChannel;
}
assert(_cleanup == nullptr);
assert(!_flags._writeLock);
}
bool
FNET_Connection::Init()
{
// set up relevant events
EnableReadEvent(true);
if (IsClient()) {
EnableWriteEvent(true);
}
// init server admin channel
if (CanAcceptChannels() && _adminChannel == nullptr) {
FNET_Channel::UP ach(new FNET_Channel(FNET_NOID, this));
if (_serverAdapter->InitAdminChannel(ach.get())) {
AddRef_NoLock();
_channels.Register(ach.release());
}
}
// handle close by admin channel init
if (_state == FNET_CLOSED) {
return false;
}
// initiate async resolve
if (IsClient()) {
_resolve_handler = std::make_shared<ResolveHandler>(this);
Owner()->owner().resolve_async(GetSpec(), _resolve_handler);
}
return true;
}
bool
FNET_Connection::handle_add_event()
{
if (_resolve_handler) {
auto tweak = [this](vespalib::SocketHandle &handle) { return Owner()->tune(handle); };
_socket = _resolve_handler->address.connect(tweak);
_ioc_socket_fd = _socket.get();
_resolve_handler.reset();
}
return _socket.valid();
}
void
FNET_Connection::SetCleanupHandler(FNET_IConnectionCleanupHandler *handler)
{
_cleanup = handler;
}
FNET_Channel*
FNET_Connection::OpenChannel(FNET_IPacketHandler *handler,
FNET_Context context,
uint32_t *chid)
{
FNET_Channel::UP newChannel(new FNET_Channel(FNET_NOID, this, handler, context));
FNET_Channel * ret = nullptr;
std::unique_lock<std::mutex> guard(_ioc_lock);
if (__builtin_expect(_state < FNET_CLOSING, true)) {
newChannel->SetID(GetNextID());
if (chid != nullptr) {
*chid = newChannel->GetID();
}
WaitCallback(guard, nullptr);
AddRef_NoLock();
ret = newChannel.release();
_channels.Register(ret);
}
return ret;
}
FNET_Channel*
FNET_Connection::OpenChannel()
{
uint32_t chid;
{
std::lock_guard<std::mutex> guard(_ioc_lock);
chid = GetNextID();
AddRef_NoLock();
}
return new FNET_Channel(chid, this);
}
bool
FNET_Connection::CloseChannel(FNET_Channel *channel)
{
std::unique_lock<std::mutex> guard(_ioc_lock);
WaitCallback(guard, channel);
return _channels.Unregister(channel);
}
void
FNET_Connection::FreeChannel(FNET_Channel *channel)
{
delete channel;
SubRef_HasLock(std::unique_lock<std::mutex>(_ioc_lock));
}
void
FNET_Connection::CloseAndFreeChannel(FNET_Channel *channel)
{
std::unique_lock<std::mutex> guard(_ioc_lock);
WaitCallback(guard, channel);
_channels.Unregister(channel);
SubRef_HasLock(std::move(guard));
delete channel;
}
void
FNET_Connection::CloseAdminChannel()
{
FNET_Channel::UP toDelete;
std::unique_lock<std::mutex> guard(_ioc_lock);
if (_adminChannel != nullptr) {
WaitCallback(guard, _adminChannel);
if (_adminChannel != nullptr) {
_channels.Unregister(_adminChannel);
toDelete.reset(_adminChannel);
_adminChannel = nullptr;
}
}
}
bool
FNET_Connection::PostPacket(FNET_Packet *packet, uint32_t chid)
{
uint32_t writeWork;
assert(packet != nullptr);
std::unique_lock<std::mutex> guard(_ioc_lock);
if (_state >= FNET_CLOSING) {
if (_flags._discarding) {
_queue.QueuePacket_NoLock(packet, FNET_Context(chid));
} else {
guard.unlock();
packet->Free(); // discard packet
}
return false; // connection is down
}
writeWork = _writeWork;
_writeWork++;
_queue.QueuePacket_NoLock(packet, FNET_Context(chid));
if (writeWork == 0 && !_flags._writeLock &&
_state == FNET_CONNECTED)
{
if (GetConfig()->_directWrite) {
_flags._writeLock = true;
_queue.FlushPackets_NoLock(&_myQueue);
guard.unlock();
Write(true);
} else {
AddRef_NoLock();
guard.unlock();
Owner()->EnableWrite(this, /* needRef = */ false);
}
}
return true;
}
uint32_t
FNET_Connection::GetQueueLen()
{
std::lock_guard<std::mutex> guard(_ioc_lock);
return _queue.GetPacketCnt_NoLock() + _myQueue.GetPacketCnt_NoLock();
}
void
FNET_Connection::Sync()
{
SyncPacket sp;
PostPacket(&sp, FNET_NOID);
sp.WaitFree();
}
void
FNET_Connection::CleanupHook()
{
if (_cleanup != nullptr) {
_cleanup->Cleanup(this);
_cleanup = nullptr;
}
}
void
FNET_Connection::Close()
{
_resolve_handler.reset();
detach_selector();
SetState(FNET_CLOSED);
_ioc_socket_fd = -1;
_socket.reset();
}
bool
FNET_Connection::HandleReadEvent()
{
bool broken = false; // is connection broken ?
switch(_state) {
case FNET_CONNECTING: // ignore read events while connecting
break;
case FNET_CONNECTED:
broken = !Read();
break;
case FNET_CLOSING:
case FNET_CLOSED:
default:
broken = true;
}
return !broken;
}
bool
FNET_Connection::writePendingAfterConnect()
{
std::lock_guard<std::mutex> guard(_ioc_lock);
_state = FNET_CONNECTED; // SetState(FNET_CONNECTED)
LOG(debug, "Connection(%s): State transition: %s -> %s", GetSpec(),
GetStateString(FNET_CONNECTING), GetStateString(FNET_CONNECTED));
return (_writeWork > 0);
}
bool
FNET_Connection::HandleWriteEvent()
{
int error; // socket error code
bool broken = false; // is connection broken ?
switch(_state) {
case FNET_CONNECTING:
error = _socket.get_so_error();
if (error == 0) { // connect ok
if (!writePendingAfterConnect()) {
EnableWriteEvent(false);
}
} else {
LOG(debug, "Connection(%s): connect error: %d", GetSpec(), error);
SetState(FNET_CLOSED); // connect failed.
broken = true;
}
break;
case FNET_CONNECTED:
{
std::unique_lock<std::mutex> guard(_ioc_lock);
if (_flags._writeLock) {
guard.unlock();
EnableWriteEvent(false);
return true;
}
_flags._writeLock = true;
_queue.FlushPackets_NoLock(&_myQueue);
}
broken = !Write(false);
break;
case FNET_CLOSING:
case FNET_CLOSED:
default:
broken = true;
}
return !broken;
}
|
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkMorphologyImageFilter.h"
#define WIDTH 700
#define HEIGHT 560
namespace skiagm {
class MorphologyGM : public GM {
public:
MorphologyGM() {
this->setBGColor(0xFF000000);
fOnce = false;
}
protected:
virtual SkString onShortName() {
return SkString("morphology");
}
void make_bitmap() {
fBitmap.allocN32Pixels(135, 135);
SkCanvas canvas(fBitmap);
canvas.clear(0x0);
SkPaint paint;
paint.setAntiAlias(true);
const char* str1 = "ABC";
const char* str2 = "XYZ";
paint.setColor(0xFFFFFFFF);
paint.setTextSize(64);
canvas.drawText(str1, strlen(str1), 10, 55, paint);
canvas.drawText(str2, strlen(str2), 10, 110, paint);
}
virtual SkISize onISize() {
return SkISize::Make(WIDTH, HEIGHT);
}
void drawClippedBitmap(SkCanvas* canvas, const SkPaint& paint, int x, int y) {
canvas->save();
canvas->translate(SkIntToScalar(x), SkIntToScalar(y));
canvas->clipRect(SkRect::MakeWH(
SkIntToScalar(fBitmap.width()), SkIntToScalar(fBitmap.height())));
canvas->drawBitmap(fBitmap, 0, 0, &paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
if (!fOnce) {
make_bitmap();
fOnce = true;
}
struct {
int fWidth, fHeight;
int fRadiusX, fRadiusY;
} samples[] = {
{ 140, 140, 0, 0 },
{ 140, 140, 0, 2 },
{ 140, 140, 2, 0 },
{ 140, 140, 2, 2 },
{ 24, 24, 25, 25 },
};
SkPaint paint;
SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(25, 20, 100, 80));
for (unsigned j = 0; j < 4; ++j) {
for (unsigned i = 0; i < SK_ARRAY_COUNT(samples); ++i) {
const SkImageFilter::CropRect* cr = j & 0x02 ? &cropRect : NULL;
if (j & 0x01) {
paint.setImageFilter(SkErodeImageFilter::Create(
samples[i].fRadiusX,
samples[i].fRadiusY,
NULL,
cr))->unref();
} else {
paint.setImageFilter(SkDilateImageFilter::Create(
samples[i].fRadiusX,
samples[i].fRadiusY,
NULL,
cr))->unref();
}
drawClippedBitmap(canvas, paint, i * 140, j * 140);
}
}
}
private:
typedef GM INHERITED;
SkBitmap fBitmap;
bool fOnce;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new MorphologyGM; }
static GMRegistry reg(MyFactory);
}
|
/*
Tests assignment of generic cells of different types.
Copyright 2015, 2016 Ilja Honkonen
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 copyright holders nor the names of their 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 "cstdlib"
#include "gensimcell.hpp"
using namespace std;
struct test_variable1 {
using data_type = int;
};
struct test_variable2 {
using data_type = int;
};
using cell_n1_t = gensimcell::Cell<
gensimcell::Never_Transfer,
test_variable1
>;
using cell_n2_t = gensimcell::Cell<
gensimcell::Never_Transfer,
test_variable2
>;
using cell_n_t = gensimcell::Cell<
gensimcell::Never_Transfer,
test_variable1,
test_variable2
>;
using cell_a1_t = gensimcell::Cell<
gensimcell::Always_Transfer,
test_variable1
>;
using cell_a2_t = gensimcell::Cell<
gensimcell::Always_Transfer,
test_variable2
>;
using cell_a_t = gensimcell::Cell<
gensimcell::Always_Transfer,
test_variable1,
test_variable2
>;
using cell_o1_t = gensimcell::Cell<
gensimcell::Optional_Transfer,
test_variable1
>;
using cell_o2_t = gensimcell::Cell<
gensimcell::Optional_Transfer,
test_variable2
>;
using cell_o_t = gensimcell::Cell<
gensimcell::Optional_Transfer,
test_variable1,
test_variable2
>;
int main(int, char**)
{
using gensimcell::assign;
cell_n1_t n1;
cell_n2_t n2;
cell_n_t n;
cell_a1_t a1;
cell_a2_t a2;
cell_a_t a;
cell_o1_t o1;
cell_o2_t o2;
cell_o_t o;
// different transfer policy
assign(n1, a1);
n1.assign(a1);
assign(n1, o1);
n1.assign(o1);
assign(n2, a2);
n2.assign(a2);
assign(n2, o2);
n2.assign(o2);
assign(n, a);
n.assign(a);
assign(n, o);
n.assign(o);
// different variables
assign(n1, n2);
n1.assign(n2);
assign(a1, a2);
a1.assign(a2);
assign(o1, o2);
o1.assign(o2);
// different variables and transfer policies
assign(n1, a2);
n1.assign(a2);
assign(n1, o2);
n1.assign(o2);
// subset of common variables
assign(n, n1);
n.assign(n1);
assign(a, a1);
a.assign(a1);
assign(o, o1);
o.assign(o1);
return EXIT_SUCCESS;
}
|
// ---------------------------------------------------------------------
// pion: a Boost C++ framework for building lightweight HTTP interfaces
// ---------------------------------------------------------------------
// Copyright (C) 2007-2014 Splunk Inc. (https://github.com/splunk/pion)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_TCP_SERVER_HEADER__
#define __PION_TCP_SERVER_HEADER__
#include <set>
#include <boost/asio.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <pion/config.hpp>
#include <pion/logger.hpp>
#include <pion/scheduler.hpp>
#include <pion/tcp/connection.hpp>
namespace pion { // begin namespace pion
namespace tcp { // begin namespace tcp
///
/// tcp::server: a multi-threaded, asynchronous TCP server
///
class PION_API server :
private boost::noncopyable
{
public:
/// default destructor
virtual ~server() { if (m_is_listening) stop(false); }
/// starts listening for new connections
void start(void);
/**
* stops listening for new connections
*
* @param wait_until_finished if true, blocks until all pending connections have closed
*/
void stop(bool wait_until_finished = false);
/// the calling thread will sleep until the server has stopped listening for connections
void join(void);
/**
* configures server for SSL using a PEM-encoded RSA private key file
*
* @param pem_key_file name of the file containing a PEM-encoded private key
*/
void set_ssl_key_file(const std::string& pem_key_file);
/// returns the number of active tcp connections
std::size_t get_connections(void) const;
/// returns tcp port number that the server listens for connections on
inline unsigned int get_port(void) const { return m_endpoint.port(); }
/// sets tcp port number that the server listens for connections on
inline void set_port(unsigned int p) { m_endpoint.port(p); }
/// returns IP address that the server listens for connections on
inline boost::asio::ip::address get_address(void) const { return m_endpoint.address(); }
/// sets IP address that the server listens for connections on
inline void set_address(const boost::asio::ip::address& addr) { m_endpoint.address(addr); }
/// returns tcp endpoint that the server listens for connections on
inline const boost::asio::ip::tcp::endpoint& get_endpoint(void) const { return m_endpoint; }
/// sets tcp endpoint that the server listens for connections on
inline void set_endpoint(const boost::asio::ip::tcp::endpoint& ep) { m_endpoint = ep; }
/// returns true if the server uses SSL to encrypt connections
inline bool get_ssl_flag(void) const { return m_ssl_flag; }
/// sets value of SSL flag (true if the server uses SSL to encrypt connections)
inline void set_ssl_flag(bool b = true) { m_ssl_flag = b; }
/// returns the SSL context for configuration
inline connection::ssl_context_type& get_ssl_context_type(void) { return m_ssl_context; }
/// returns true if the server is listening for connections
inline bool is_listening(void) const { return m_is_listening; }
/// sets the logger to be used
inline void set_logger(logger log_ptr) { m_logger = log_ptr; }
/// returns the logger currently in use
inline logger get_logger(void) { return m_logger; }
/// returns mutable reference to the TCP connection acceptor
inline boost::asio::ip::tcp::acceptor& get_acceptor(void) { return m_tcp_acceptor; }
/// returns const reference to the TCP connection acceptor
inline const boost::asio::ip::tcp::acceptor& get_acceptor(void) const { return m_tcp_acceptor; }
protected:
/**
* protected constructor so that only derived objects may be created
*
* @param tcp_port port number used to listen for new connections (IPv4)
*/
explicit server(const unsigned int tcp_port);
/**
* protected constructor so that only derived objects may be created
*
* @param endpoint TCP endpoint used to listen for new connections (see ASIO docs)
*/
explicit server(const boost::asio::ip::tcp::endpoint& endpoint);
/**
* protected constructor so that only derived objects may be created
*
* @param sched the scheduler that will be used to manage worker threads
* @param tcp_port port number used to listen for new connections (IPv4)
*/
explicit server(scheduler& sched, const unsigned int tcp_port = 0);
/**
* protected constructor so that only derived objects may be created
*
* @param sched the scheduler that will be used to manage worker threads
* @param endpoint TCP endpoint used to listen for new connections (see ASIO docs)
*/
server(scheduler& sched, const boost::asio::ip::tcp::endpoint& endpoint);
/**
* handles a new TCP connection; derived classes SHOULD override this
* since the default behavior does nothing
*
* @param tcp_conn the new TCP connection to handle
*/
virtual void handle_connection(const tcp::connection_ptr& tcp_conn) {
tcp_conn->set_lifecycle(connection::LIFECYCLE_CLOSE); // make sure it will get closed
tcp_conn->finish();
}
/// called before the TCP server starts listening for new connections
virtual void before_starting(void) {}
/// called after the TCP server has stopped listing for new connections
virtual void after_stopping(void) {}
/// returns an async I/O service used to schedule work
inline boost::asio::io_service& get_io_service(void) { return m_active_scheduler.get_io_service(); }
/// primary logging interface used by this class
logger m_logger;
private:
/// handles a request to stop the server
void handle_stop_request(void);
/// listens for a new connection
void listen(void);
/**
* handles new connections (checks if there was an accept error)
*
* @param tcp_conn the new TCP connection (if no error occurred)
* @param accept_error true if an error occurred while accepting connections
*/
void handle_accept(const tcp::connection_ptr& tcp_conn,
const boost::system::error_code& accept_error);
/**
* handles new connections following an SSL handshake (checks for errors)
*
* @param tcp_conn the new TCP connection (if no error occurred)
* @param handshake_error true if an error occurred during the SSL handshake
*/
void handle_ssl_handshake(const tcp::connection_ptr& tcp_conn,
const boost::system::error_code& handshake_error);
/// This will be called by connection::finish() after a server has
/// finished handling a connection. If the keep_alive flag is true,
/// it will call handle_connection(); otherwise, it will close the
/// connection and remove it from the server's management pool
void finish_connection(const tcp::connection_ptr& tcp_conn);
/// prunes orphaned connections that did not close cleanly
/// and returns the remaining number of connections in the pool
std::size_t prune_connections(void);
/// data type for a pool of TCP connections
typedef std::set<tcp::connection_ptr> ConnectionPool;
/// the default scheduler object used to manage worker threads
single_service_scheduler m_default_scheduler;
/// reference to the active scheduler object used to manage worker threads
scheduler & m_active_scheduler;
/// manages async TCP connections
boost::asio::ip::tcp::acceptor m_tcp_acceptor;
/// context used for SSL configuration
connection::ssl_context_type m_ssl_context;
/// condition triggered when the server has stopped listening for connections
boost::condition m_server_has_stopped;
/// condition triggered when the connection pool is empty
boost::condition m_no_more_connections;
/// pool of active connections associated with this server
ConnectionPool m_conn_pool;
/// tcp endpoint used to listen for new connections
boost::asio::ip::tcp::endpoint m_endpoint;
/// true if the server uses SSL to encrypt connections
bool m_ssl_flag;
/// set to true when the server is listening for new connections
bool m_is_listening;
/// mutex to make class thread-safe
mutable boost::mutex m_mutex;
};
/// data type for a server pointer
typedef boost::shared_ptr<server> server_ptr;
} // end namespace tcp
} // end namespace pion
#endif
|
#include <sstream>
#include <Common/CurrentThread.h>
#include <Common/Exception.h>
#include <Common/ThreadProfileEvents.h>
#include <Common/TaskStatsInfoGetter.h>
#include <Common/QueryProfiler.h>
#include <Common/ThreadStatus.h>
#include <Poco/Logger.h>
#include <common/getThreadNumber.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int PTHREAD_ERROR;
}
thread_local ThreadStatus * current_thread = nullptr;
TasksStatsCounters TasksStatsCounters::current()
{
TasksStatsCounters res;
CurrentThread::get().taskstats_getter->getStat(res.stat, CurrentThread::get().os_thread_id);
return res;
}
ThreadStatus::ThreadStatus()
{
thread_number = getThreadNumber();
os_thread_id = TaskStatsInfoGetter::getCurrentTID();
last_rusage = std::make_unique<RUsageCounters>();
last_taskstats = std::make_unique<TasksStatsCounters>();
memory_tracker.setDescription("(for thread)");
log = &Poco::Logger::get("ThreadStatus");
current_thread = this;
/// NOTE: It is important not to do any non-trivial actions (like updating ProfileEvents or logging) before ThreadStatus is created
/// Otherwise it could lead to SIGSEGV due to current_thread dereferencing
}
ThreadStatus::~ThreadStatus()
{
try
{
if (untracked_memory > 0)
memory_tracker.alloc(untracked_memory);
else
memory_tracker.free(-untracked_memory);
}
catch (const DB::Exception &)
{
/// It's a minor tracked memory leak here (not the memory itself but it's counter).
/// We've already allocated a little bit more then the limit and cannot track it in the thread memory tracker or its parent.
}
if (deleter)
deleter();
current_thread = nullptr;
}
void ThreadStatus::initPerformanceCounters()
{
performance_counters_finalized = false;
/// Clear stats from previous query if a new query is started
/// TODO: make separate query_thread_performance_counters and thread_performance_counters
performance_counters.resetCounters();
memory_tracker.resetCounters();
memory_tracker.setDescription("(for thread)");
query_start_time_nanoseconds = getCurrentTimeNanoseconds();
query_start_time = time(nullptr);
++queries_started;
*last_rusage = RUsageCounters::current(query_start_time_nanoseconds);
try
{
if (TaskStatsInfoGetter::checkPermissions())
{
if (!taskstats_getter)
taskstats_getter = std::make_unique<TaskStatsInfoGetter>();
*last_taskstats = TasksStatsCounters::current();
}
}
catch (...)
{
taskstats_getter.reset();
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
void ThreadStatus::updatePerformanceCounters()
{
try
{
RUsageCounters::updateProfileEvents(*last_rusage, performance_counters);
if (taskstats_getter)
TasksStatsCounters::updateProfileEvents(*last_taskstats, performance_counters);
}
catch (...)
{
tryLogCurrentException(log);
}
}
void ThreadStatus::assertState(const std::initializer_list<int> & permitted_states, const char * description)
{
for (auto permitted_state : permitted_states)
{
if (getCurrentState() == permitted_state)
return;
}
std::stringstream ss;
ss << "Unexpected thread state " << getCurrentState();
if (description)
ss << ": " << description;
throw Exception(ss.str(), ErrorCodes::LOGICAL_ERROR);
}
void ThreadStatus::attachInternalTextLogsQueue(const InternalTextLogsQueuePtr & logs_queue,
LogsLevel client_logs_level)
{
logs_queue_ptr = logs_queue;
if (!thread_group)
return;
std::lock_guard lock(thread_group->mutex);
thread_group->logs_queue_ptr = logs_queue;
thread_group->client_logs_level = client_logs_level;
}
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkMeanSampleFilter.h"
#include "itkListSample.h"
int
itkMeanSampleFilterTest(int, char *[])
{
std::cout << "MeanSampleFilter test \n \n";
bool pass = true;
std::string failureMeassage = "";
constexpr unsigned int MeasurementVectorSize = 2;
constexpr unsigned int numberOfMeasurementVectors = 5;
unsigned int counter;
using MeasurementVectorType = itk::FixedArray<float, MeasurementVectorSize>;
using SampleType = itk::Statistics::ListSample<MeasurementVectorType>;
auto sample = SampleType::New();
sample->SetMeasurementVectorSize(MeasurementVectorSize);
MeasurementVectorType measure;
// reset counter
counter = 0;
while (counter < numberOfMeasurementVectors)
{
for (unsigned int i = 0; i < MeasurementVectorSize; ++i)
{
measure[i] = counter;
}
sample->PushBack(measure);
counter++;
}
using FilterType = itk::Statistics::MeanSampleFilter<SampleType>;
auto filter = FilterType::New();
std::cout << filter->GetNameOfClass() << std::endl;
filter->Print(std::cout);
// Invoke update before adding an input. An exception should be
// thrown.
try
{
filter->Update();
failureMeassage = "Exception should have been thrown since \
Update() is invoked without setting an input ";
pass = false;
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << "Exception caught: " << excp << std::endl;
}
if (filter->GetInput() != nullptr)
{
pass = false;
failureMeassage = "GetInput() should return nullptr if the input \
has not been set";
}
filter->ResetPipeline();
filter->SetInput(sample);
try
{
filter->Update();
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << "Exception caught: " << excp << std::endl;
}
const FilterType::MeasurementVectorDecoratedType * decorator = filter->GetOutput();
FilterType::MeasurementVectorType meanOutput = decorator->Get();
FilterType::MeasurementVectorType mean;
mean[0] = 2.0;
mean[1] = 2.0;
std::cout << meanOutput[0] << " " << mean[0] << " " << meanOutput[1] << " " << mean[1] << " " << std::endl;
FilterType::MeasurementVectorType::ValueType epsilon = 1e-6;
if ((std::fabs(meanOutput[0] - mean[0]) > epsilon) || (std::fabs(meanOutput[1] - mean[1]) > epsilon))
{
pass = false;
failureMeassage = "The result is not what is expected";
}
if (!pass)
{
std::cout << "Test failed." << failureMeassage << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
#include "h265_common.h"
#ifdef WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <stdio.h>
#include <cstdint>
#include <memory>
#include <vector>
namespace h265nal {
bool IsSliceSegment(uint32_t nal_unit_type) {
// payload (Table 7-1, Section 7.4.2.2)
switch (nal_unit_type) {
case TRAIL_N:
case TRAIL_R:
case TSA_N:
case TSA_R:
case STSA_N:
case STSA_R:
case RADL_N:
case RADL_R:
case RASL_N:
case RASL_R:
case BLA_W_LP:
case BLA_W_RADL:
case BLA_N_LP:
case IDR_W_RADL:
case IDR_N_LP:
case CRA_NUT:
// slice_segment_layer_rbsp()
return true;
break;
}
return false;
}
bool IsNalUnitTypeVcl(uint32_t nal_unit_type) {
// payload (Table 7-1, Section 7.4.2.2)
switch (nal_unit_type) {
case TRAIL_N:
case TRAIL_R:
case TSA_N:
case TSA_R:
case STSA_N:
case STSA_R:
case RADL_N:
case RADL_R:
case RASL_N:
case RASL_R:
case RSV_VCL_N10:
case RSV_VCL_R11:
case RSV_VCL_N12:
case RSV_VCL_R13:
case RSV_VCL_N14:
case RSV_VCL_R15:
case BLA_W_LP:
case BLA_W_RADL:
case BLA_N_LP:
case IDR_W_RADL:
case IDR_N_LP:
case CRA_NUT:
case RSV_IRAP_VCL22:
case RSV_IRAP_VCL23:
case RSV_VCL24:
case RSV_VCL25:
case RSV_VCL26:
case RSV_VCL27:
case RSV_VCL28:
case RSV_VCL29:
case RSV_VCL30:
case RSV_VCL31:
return true;
default:
break;
}
return false;
}
bool IsNalUnitTypeNonVcl(uint32_t nal_unit_type) {
// payload (Table 7-1, Section 7.4.2.2)
switch (nal_unit_type) {
case VPS_NUT:
case SPS_NUT:
case PPS_NUT:
case AUD_NUT:
case EOS_NUT:
case EOB_NUT:
case FD_NUT:
case PREFIX_SEI_NUT:
case SUFFIX_SEI_NUT:
case RSV_NVCL41:
case RSV_NVCL42:
case RSV_NVCL43:
case RSV_NVCL44:
case RSV_NVCL45:
case RSV_NVCL46:
case RSV_NVCL47:
case AP:
case FU:
case UNSPEC50:
case UNSPEC51:
case UNSPEC52:
case UNSPEC53:
case UNSPEC54:
case UNSPEC55:
case UNSPEC56:
case UNSPEC57:
case UNSPEC58:
case UNSPEC59:
case UNSPEC60:
case UNSPEC61:
case UNSPEC62:
case UNSPEC63:
return true;
default:
break;
}
return false;
}
bool IsNalUnitTypeUnspecified(uint32_t nal_unit_type) {
// payload (Table 7-1, Section 7.4.2.2)
switch (nal_unit_type) {
case AP:
case FU:
case UNSPEC50:
case UNSPEC51:
case UNSPEC52:
case UNSPEC53:
case UNSPEC54:
case UNSPEC55:
case UNSPEC56:
case UNSPEC57:
case UNSPEC58:
case UNSPEC59:
case UNSPEC60:
case UNSPEC61:
case UNSPEC62:
case UNSPEC63:
return true;
default:
break;
}
return false;
}
std::vector<uint8_t> UnescapeRbsp(const uint8_t *data, size_t length) {
std::vector<uint8_t> out;
out.reserve(length);
for (size_t i = 0; i < length;) {
// Be careful about over/underflow here. byte_length_ - 3 can underflow, and
// i + 3 can overflow, but byte_length_ - i can't, because i < byte_length_
// above, and that expression will produce the number of bytes left in
// the stream including the byte at i.
if (length - i >= 3 && data[i] == 0x00 && data[i + 1] == 0x00 &&
data[i + 2] == 0x03) {
// Two RBSP bytes.
out.push_back(data[i++]);
out.push_back(data[i++]);
// Skip the emulation byte.
i++;
} else {
// Single rbsp byte.
out.push_back(data[i++]);
}
}
return out;
}
// Syntax functions and descriptors) (Section 7.2)
bool byte_aligned(rtc::BitBuffer *bit_buffer) {
// If the current position in the bitstream is on a byte boundary, i.e.,
// the next bit in the bitstream is the first bit in a byte, the return
// value of byte_aligned() is equal to TRUE.
// Otherwise, the return value of byte_aligned() is equal to FALSE.
size_t out_byte_offset, out_bit_offset;
bit_buffer->GetCurrentOffset(&out_byte_offset, &out_bit_offset);
return (out_bit_offset == 0);
}
int get_current_offset(rtc::BitBuffer *bit_buffer) {
size_t out_byte_offset, out_bit_offset;
bit_buffer->GetCurrentOffset(&out_byte_offset, &out_bit_offset);
return out_byte_offset + ((out_bit_offset == 0) ? 0 : 1);
}
bool more_rbsp_data(rtc::BitBuffer *bit_buffer) {
// > If there is no more data in the raw byte sequence payload (RBSP), the
// > return value of more_rbsp_data() is equal to FALSE.
uint64_t remaining_bitcount = bit_buffer->RemainingBitCount();
if (remaining_bitcount == 0) {
return false;
}
// > Otherwise, the RBSP data is searched for the last (least significant,
// > right-most) bit equal to 1 that is present in the RBSP. Given the
// > position of this bit, which is the first bit (rbsp_stop_one_bit) of
// > the rbsp_trailing_bits() syntax structure, the following applies:
// > - If there is more data in an RBSP before the rbsp_trailing_bits()
// > syntax structure, the return value of more_rbsp_data() is equal to
// > TRUE.
// > - Otherwise, the return value of more_rbsp_data() is equal to FALSE.
// > The method for enabling determination of whether there is more data
// > in the RBSP is specified by the application (or in Annex B for
// > applications that use the byte stream format).
// Here we do the following simplification:
// (1) We know that rbsp_trailing_bits() is limited to at most 1 byte. Its
// definition is:
// > rbsp_trailing_bits() {
// > rbsp_stop_one_bit // equal to 1
// > while( !byte_aligned() )
// > rbsp_alignment_zero_bit // equal to 0
// > }
// where byte_aligned() is a Bool stating whether the position of the
// bitstream is in a byte boundary. So, if there is more than 1 byte
// left (8 bits left), clearly "there is more data in the RBSP before the
// rbsp_trailing_bits()"
if (remaining_bitcount > 8) {
return true;
}
// (2) if we are indeed in the last byte, we just need to know whether the
// rest of the byte is [1, 0, ..., 0]. For that, we want to peek in the
// bit buffer (not read).
// So we first read (peek) the remaining bits.
uint32_t remaining_bits;
if (!bit_buffer->PeekBits(&remaining_bits, remaining_bitcount)) {
// this should not happen: we do not have remaining_bits bits left.
return false;
}
// and then check for the actual values to be 100..000
bool is_rbsp_trailing_bits =
(remaining_bits == (1 << (remaining_bitcount - 1)));
// if the actual values to be 100..000, we are already at the
// rbsp_trailing_bits, which means there is no more RBSP data
return !is_rbsp_trailing_bits;
}
bool rbsp_trailing_bits(rtc::BitBuffer *bit_buffer) {
uint32_t bits_tmp;
// rbsp_stop_one_bit f(1) // equal to 1
if (!bit_buffer->ReadBits(&bits_tmp, 1)) {
return false;
}
if (bits_tmp != 1) {
return false;
}
while (!byte_aligned(bit_buffer)) {
// rbsp_alignment_zero_bit f(1) // equal to 0
if (!bit_buffer->ReadBits(&bits_tmp, 1)) {
return false;
}
if (bits_tmp != 0) {
return false;
}
}
return true;
}
#if defined(FDUMP_DEFINE)
int indent_level_incr(int indent_level) {
return (indent_level == -1) ? -1 : (indent_level + 1);
}
int indent_level_decr(int indent_level) {
return (indent_level == -1) ? -1 : (indent_level - 1);
}
void fdump_indent_level(FILE *outfp, int indent_level) {
if (indent_level == -1) {
// no indent
fprintf(outfp, " ");
return;
}
fprintf(outfp, "\n");
fprintf(outfp, "%*s", 2 * indent_level, "");
}
#endif // FDUMP_DEFINE
std::shared_ptr<NaluChecksum> NaluChecksum::GetNaluChecksum(
rtc::BitBuffer *bit_buffer) noexcept {
// save the bit buffer current state
size_t byte_offset = 0;
size_t bit_offset = 0;
bit_buffer->GetCurrentOffset(&byte_offset, &bit_offset);
auto checksum = std::make_shared<NaluChecksum>();
// implement simple IP-like checksum (extended from 16/32 to 32/64 bits)
// Inspired in https://stackoverflow.com/questions/26774761
// Our algorithm is simple, using a 64 bit accumulator (sum), we add
// sequential 32 bit words to it, and at the end, fold back all the
// carry bits from the top 32 bits into the lower 32 bits.
uint64_t sum = 0;
uint32_t val = 0;
while (bit_buffer->ReadUInt32(&val)) {
sum += val;
}
// check if there are unread bytes
int i = 0;
uint8_t val8 = 0;
val = 0;
while (bit_buffer->RemainingBitCount() > 0) {
(void)bit_buffer->ReadUInt8(&val8);
val |= (val8 << (8 * (3 - i)));
i += 1;
}
if (i > 0) {
sum += val;
}
// add back carry outs from top 32 bits to low 32 bits
// add hi 32 to low 32
sum = (sum >> 32) + (sum & 0xffffffff);
// add carry
sum += (sum >> 32);
// truncate to 32 bits and get one's complement
uint32_t answer = ~sum;
// write sum into (generic) checksum buffer (network order)
*(reinterpret_cast<uint32_t *>(checksum->checksum)) = htonl(answer);
checksum->length = 4;
// return the bit buffer to the original state
bit_buffer->Seek(byte_offset, bit_offset);
return checksum;
}
void NaluChecksum::fdump(char *output, int output_len) const {
int i = 0;
int oi = 0;
while (i < length) {
// make sure there is space in the output buffer
if (oi + 2 >= output_len) {
output[output_len - 1] = '\0';
break;
}
oi += sprintf(output + oi, "%02x", static_cast<unsigned char>(checksum[i++]));
}
}
} // namespace h265nal
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.