text:
//Qmitk
#include "QmitkRegistrationManipulationWidget.h"

//MatchPoint
#include <mapRegistrationManipulator.h>
#include <mapPreCachedRegistrationKernel.h>
#include <mapCombinedRegistrationKernel.h>
#include <mapNullRegistrationKernel.h>
#include <mapRegistrationCombinator.h>

#include <itkCompositeTransform.h>

#include <boost/math/constants/constants.hpp>

QmitkRegistrationManipulationWidget::QmitkRegistrationManipulationWidget(QWidget *parent)
  : QWidget(parent), m_CenterOfRotationIsRelativeToTarget(false), m_internalUpdate(false)
{
  this->setupUi(this);

  connect(this->slideRotX, SIGNAL(valueChanged(int)), this, SLOT(OnRotXSlideChanged(int)));
  connect(this->sbRotX, SIGNAL(valueChanged(double)), this, SLOT(OnRotXChanged(double)));
  connect(this->slideRotY, SIGNAL(valueChanged(int)), this, SLOT(OnRotYSlideChanged(int)));
  connect(this->sbRotY, SIGNAL(valueChanged(double)), this, SLOT(OnRotYChanged(double)));
  connect(this->slideRotZ, SIGNAL(valueChanged(int)), this, SLOT(OnRotZSlideChanged(int)));
  connect(this->sbRotZ, SIGNAL(valueChanged(double)), this, SLOT(OnRotZChanged(double)));

  connect(this->slideTransX, SIGNAL(valueChanged(int)), this, SLOT(OnTransXSlideChanged(int)));
  connect(this->sbTransX, SIGNAL(valueChanged(double)), this, SLOT(OnTransXChanged(double)));
  connect(this->slideTransY, SIGNAL(valueChanged(int)), this, SLOT(OnTransYSlideChanged(int)));
  connect(this->sbTransY, SIGNAL(valueChanged(double)), this, SLOT(OnTransYChanged(double)));
  connect(this->slideTransZ, SIGNAL(valueChanged(int)), this, SLOT(OnTransZSlideChanged(int)));
  connect(this->sbTransZ, SIGNAL(valueChanged(double)), this, SLOT(OnTransZChanged(double)));

  this->groupScale->setVisible(false);
}

QmitkRegistrationManipulationWidget::~QmitkRegistrationManipulationWidget()
= default;

void QmitkRegistrationManipulationWidget::Initialize()
{
  this->ResetTransforms();
  this->InitControls();
};

void QmitkRegistrationManipulationWidget::Initialize(MAPRegistrationType* precedingRegistration)
{
  this->ResetTransforms();
  this->m_PreRegistration = precedingRegistration;

  ::map::core::RegistrationManipulator<MAPRegistrationType> manipulator(m_CurrentRegistration);
  ::map::core::PreCachedRegistrationKernel<3, 3>::Pointer kernel = ::map::core::PreCachedRegistrationKernel<3, 3>::New();

  const map::core::RegistrationKernel<3, 3>* preKernel = dynamic_cast<const map::core::RegistrationKernel<3, 3>*>(&this->m_PreRegistration->getInverseMapping());
  itk::CompositeTransform < ::map::core::continuous::ScalarType, 3>::Pointer compTransform = itk::CompositeTransform < ::map::core::continuous::ScalarType, 3>::New();
  compTransform->AddTransform(preKernel->getTransformModel()->Clone());
  compTransform->AddTransform(this->m_InverseCurrentTransform);

  kernel->setTransformModel(compTransform);
  manipulator.setInverseMapping(kernel);

  this->InitControls();
};

void QmitkRegistrationManipulationWidget::Initialize(const mitk::Point3D& movingReference, const mitk::Point3D& targetReference)
{
  this->ResetTransforms();

  auto offset = targetReference - movingReference;
  m_DirectCurrentTransform->SetOffset(offset);
  m_DirectCurrentTransform->GetInverse(m_InverseCurrentTransform);

  this->InitControls();
};

void QmitkRegistrationManipulationWidget::ResetTransforms()
{
  this->m_CenterOfRotation.Fill(0.0);
  this->m_PreRegistration = nullptr;

  this->m_InverseCurrentTransform = TransformType::New();
  this->m_InverseCurrentTransform->SetIdentity();
  this->m_DirectCurrentTransform = TransformType::New();
  this->m_DirectCurrentTransform->SetIdentity();

  m_CurrentRegistration = MAPRegistrationType::New();

  ::map::core::RegistrationManipulator<MAPRegistrationType> manipulator(m_CurrentRegistration);
  ::map::core::PreCachedRegistrationKernel<3, 3>::Pointer kernel = ::map::core::PreCachedRegistrationKernel<3, 3>::New();
  kernel->setTransformModel(m_InverseCurrentTransform);
  manipulator.setInverseMapping(kernel);

  manipulator.setDirectMapping(::map::core::NullRegistrationKernel < 3, 3 >::New());
};

void QmitkRegistrationManipulationWidget::SetCenterOfRotation(const mitk::Point3D& center)
{
  this->m_CenterOfRotation = center;
  this->ConfigureTransformCenter();
  this->UpdateTransformWidgets();
};

/** Sets the internal m_CenterOfRotationIsRelativeToTarget. see below.*/
void QmitkRegistrationManipulationWidget::SetCenterOfRotationIsRelativeToTarget(bool targetRelative)
{
  this->m_CenterOfRotationIsRelativeToTarget = targetRelative;
  this->ConfigureTransformCenter();
  this->UpdateTransformWidgets();
};

void QmitkRegistrationManipulationWidget::InitControls()
{
  this->ConfigureTransformCenter();

  //set bounds of the translation slider widget to have sensible ranges
  this->m_internalUpdate = true;
  auto currenttrans = m_DirectCurrentTransform->GetTranslation();
  this->slideTransX->setMinimum(currenttrans[0] - 250);
  this->slideTransY->setMinimum(currenttrans[1] - 250);
  this->slideTransZ->setMinimum(currenttrans[2] - 250);
  this->slideTransX->setMaximum(currenttrans[0] + 250);
  this->slideTransY->setMaximum(currenttrans[1] + 250);
  this->slideTransZ->setMaximum(currenttrans[2] + 250);
  this->m_internalUpdate = false;

  this->UpdateTransformWidgets();
};

void QmitkRegistrationManipulationWidget::UpdateTransformWidgets()
{
  this->m_internalUpdate = true;
  this->sbTransX->setValue(this->m_DirectCurrentTransform->GetTranslation()[0]);
  this->sbTransY->setValue(this->m_DirectCurrentTransform->GetTranslation()[1]);
  this->sbTransZ->setValue(this->m_DirectCurrentTransform->GetTranslation()[2]);
  this->slideTransX->setValue(this->m_DirectCurrentTransform->GetTranslation()[0]);
  this->slideTransY->setValue(this->m_DirectCurrentTransform->GetTranslation()[1]);
  this->slideTransZ->setValue(this->m_DirectCurrentTransform->GetTranslation()[2]);

  this->sbRotX->setValue(this->m_DirectCurrentTransform->GetAngleX()*(180 / boost::math::double_constants::pi));
  this->sbRotY->setValue(this->m_DirectCurrentTransform->GetAngleY()*(180 / boost::math::double_constants::pi));
  this->sbRotZ->setValue(this->m_DirectCurrentTransform->GetAngleZ()*(180 / boost::math::double_constants::pi));
  this->slideRotX->setValue(this->m_DirectCurrentTransform->GetAngleX()*(180 / boost::math::double_constants::pi));
  this->slideRotY->setValue(this->m_DirectCurrentTransform->GetAngleY()*(180 / boost::math::double_constants::pi));
  this->slideRotZ->setValue(this->m_DirectCurrentTransform->GetAngleZ()*(180 / boost::math::double_constants::pi));
  this->m_internalUpdate = false;
};

void QmitkRegistrationManipulationWidget::UpdateTransform(bool updateRotation)
{
  if (updateRotation)
  {
    if (this->m_CenterOfRotationIsRelativeToTarget)
    {
     ConfigureTransformCenter();
    }

    this->m_DirectCurrentTransform->SetRotation(this->sbRotX->value()*(boost::math::double_constants::pi / 180),
      this->sbRotY->value()*(boost::math::double_constants::pi / 180),
      this->sbRotZ->value()*(boost::math::double_constants::pi / 180));
  }
  else
  {
    TransformType::OutputVectorType trans;
    trans[0] = this->sbTransX->value();
    trans[1] = this->sbTransY->value();
    trans[2] = this->sbTransZ->value();

    this->m_DirectCurrentTransform->SetTranslation(trans);
  }

  this->m_DirectCurrentTransform->GetInverse(this->m_InverseCurrentTransform);

  this->UpdateTransformWidgets();

  emit RegistrationChanged(this->m_CurrentRegistration);
};

map::core::RegistrationBase* QmitkRegistrationManipulationWidget::GetInterimRegistration() const
{
  return this->m_CurrentRegistration.GetPointer();
};

map::core::RegistrationBase::Pointer QmitkRegistrationManipulationWidget::GenerateRegistration() const
{
  MAPRegistrationType::Pointer newReg = MAPRegistrationType::New();

  ::map::core::RegistrationManipulator<MAPRegistrationType> manipulator(newReg);

  ::map::core::PreCachedRegistrationKernel<3, 3>::Pointer kernel = ::map::core::PreCachedRegistrationKernel<3, 3>::New();
  kernel->setTransformModel(m_InverseCurrentTransform);

  ::map::core::PreCachedRegistrationKernel<3, 3>::Pointer kernel2 = ::map::core::PreCachedRegistrationKernel<3, 3>::New();
  kernel2->setTransformModel(m_InverseCurrentTransform->GetInverseTransform());

  manipulator.setInverseMapping(kernel);
  manipulator.setDirectMapping(kernel2);

  if (this->m_PreRegistration.IsNotNull())
  { //compine registration with selected pre registration as baseline
    typedef ::map::core::RegistrationCombinator<MAPRegistrationType, MAPRegistrationType> CombinatorType;
    CombinatorType::Pointer combinator = CombinatorType::New();
    newReg = combinator->process(*m_PreRegistration, *newReg);
  }

  return newReg.GetPointer();
};

void QmitkRegistrationManipulationWidget::OnRotXChanged(double x)
{
  if (!m_internalUpdate)
  {
    m_internalUpdate = true;
    this->slideRotX->setValue(x);
    m_internalUpdate = false;
    this->UpdateTransform(true);
  }
};

void QmitkRegistrationManipulationWidget::OnRotXSlideChanged(int x)
{
  if (!m_internalUpdate)
  {
    this->sbRotX->setValue(x);
  }
};

void QmitkRegistrationManipulationWidget::OnRotYChanged(double y)
{
  if (!m_internalUpdate)
  {
    m_internalUpdate = true;
    this->slideRotY->setValue(y);
    m_internalUpdate = false;
    this->UpdateTransform(true);
  }
};

void QmitkRegistrationManipulationWidget::OnRotYSlideChanged(int y)
{
  if (!m_internalUpdate)
  {
    this->sbRotY->setValue(y);
  }
};

void QmitkRegistrationManipulationWidget::OnRotZChanged(double z)
{
  if (!m_internalUpdate)
  {
    m_internalUpdate = true;
    this->slideRotZ->setValue(z);
    m_internalUpdate = false;
    this->UpdateTransform(true);
  }
};

void QmitkRegistrationManipulationWidget::OnRotZSlideChanged(int z)
{
  if (!m_internalUpdate)
  {
    this->sbRotZ->setValue(z);
  }
};

void QmitkRegistrationManipulationWidget::OnTransXChanged(double x)
{
  if (!m_internalUpdate)
  {
    m_internalUpdate = true;
    this->slideTransX->setValue(x);
    m_internalUpdate = false;
    this->UpdateTransform();
  }
};

void QmitkRegistrationManipulationWidget::OnTransXSlideChanged(int x)
{
  if (!m_internalUpdate)
  {
    this->sbTransX->setValue(x);
  }
};

void QmitkRegistrationManipulationWidget::OnTransYChanged(double y)
{
  if (!m_internalUpdate)
  {
    m_internalUpdate = true;
    this->slideTransY->setValue(y);
    m_internalUpdate = false;
    this->UpdateTransform();
  }
};

void QmitkRegistrationManipulationWidget::OnTransYSlideChanged(int y)
{
  if (!m_internalUpdate)
  {
    this->sbTransY->setValue(y);
  }
};

void QmitkRegistrationManipulationWidget::OnTransZChanged(double z)
{
  if (!m_internalUpdate)
  {
    m_internalUpdate = true;
    this->slideTransZ->setValue(z);
    m_internalUpdate = false;
    this->UpdateTransform();
  }
};

void QmitkRegistrationManipulationWidget::OnTransZSlideChanged(int z)
{
  if (!m_internalUpdate)
  {
    this->sbTransZ->setValue(z);
  }
};

void QmitkRegistrationManipulationWidget::ConfigureTransformCenter()
{
  auto offset = m_DirectCurrentTransform->GetOffset();

  if (this->m_CenterOfRotationIsRelativeToTarget)
  {
    auto newCenter = m_InverseCurrentTransform->TransformPoint(m_CenterOfRotation);
    m_DirectCurrentTransform->SetCenter(newCenter);
  }
  else
  {
    m_DirectCurrentTransform->SetCenter(m_CenterOfRotation);
  }

  m_DirectCurrentTransform->SetOffset(offset);
  m_DirectCurrentTransform->GetInverse(m_InverseCurrentTransform);
};


text:
SRCS=ctest.c
PROG=ctest
BINDIR=/testbin

include ../../defs.mk
include ../../mk/prog.mk

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>AADC: C:/Development/3510_AADC_ADTF/trunk/src/adtfBase/AADC_ADTF_BaseFilters/src/converter/AADC_AttitudeConverter/EulerAngles.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AADC

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

 All Classes Namespaces Files Functions Variables Enumerations

EulerAngles.hpp

    1 //Beschreibung der Lage eines Objektes im Raum im Euler Winkel System

    2 //Leider gibt es nicht nur eine Art Euler Winkel darzustellen

    3 //Dieser Code implementiert alle Möglichkeiten

    4

    5 /**** EulerAngles.h - Support for 24 angle schemes ****/

    6 /* Code aus Buch "Graphic Germs IV" von Ken Shoemake, 1993 */

    7 #ifndef _H_EulerAngles

    8 #define _H_EulerAngles

    9 #include "QuatTypes.h"

   10 /*** Order type constants, constructors, extractors ***/

   11     /* There are 24 possible conventions, designated by:    */

   12     /*    o EulAxI = axis used initially            */

   13     /*    o EulPar = parity of axis permutation         */

   14     /*    o EulRep = repetition of initial axis as last     */

   15     /*    o EulFrm = frame from which axes are taken        */

   16     /* Axes I,J,K will be a permutation of X,Y,Z.       */

   17     /* Axis H will be either I or K, depending on EulRep.   */

   18     /* Frame S takes axes from initial static frame.        */

   19     /* If ord = (AxI=X, Par=Even, Rep=No, Frm=S), then      */

   20     /* {a,b,c,ord} means Rz(c)Ry(b)Rx(a), where Rz(c)v      */

   21     /* rotates v around Z by c radians.             */

   22 #define EulFrmS      0

   23 #define EulFrmR      1

   24 #define EulFrm(ord)  ((unsigned)(ord)&1)

   25 #define EulRepNo     0

   26 #define EulRepYes    1

   27 #define EulRep(ord)  (((unsigned)(ord)>>1)&1)

   28 #define EulParEven   0

   29 #define EulParOdd    1

   30 #define EulPar(ord)  (((unsigned)(ord)>>2)&1)

   31 #define EulSafe      "\000\001\002\000"

   32 #define EulNext      "\001\002\000\001"

   33 #define EulAxI(ord)  ((int)(EulSafe[(((unsigned)(ord)>>3)&3)]))

   34 #define EulAxJ(ord)  ((int)(EulNext[EulAxI(ord)+(EulPar(ord)==EulParOdd)]))

   35 #define EulAxK(ord)  ((int)(EulNext[EulAxI(ord)+(EulPar(ord)!=EulParOdd)]))

   36 #define EulAxH(ord)  ((EulRep(ord)==EulRepNo)?EulAxK(ord):EulAxI(ord))

   37     /* EulGetOrd unpacks all useful information about order simultaneously. */

   38 #define EulGetOrd(ord,i,j,k,h,n,s,f) {unsigned o=ord;f=o&1;o>>=1;s=o&1;o>>=1;\

   39     n=o&1;o>>=1;i=EulSafe[o&3];j=EulNext[i+n];k=EulNext[i+1-n];h=s?k:i;}

   40     /* EulOrd creates an order value between 0 and 23 from 4-tuple choices. */

   41 #define EulOrd(i,p,r,f)    (((((((i)<<1)+(p))<<1)+(r))<<1)+(f))

   42     /* Static axes */

   43 #define EulOrdXYZs    EulOrd(X,EulParEven,EulRepNo,EulFrmS)

   44 #define EulOrdXYXs    EulOrd(X,EulParEven,EulRepYes,EulFrmS)

   45 #define EulOrdXZYs    EulOrd(X,EulParOdd,EulRepNo,EulFrmS)

   46 #define EulOrdXZXs    EulOrd(X,EulParOdd,EulRepYes,EulFrmS)

   47 #define EulOrdYZXs    EulOrd(Y,EulParEven,EulRepNo,EulFrmS)

   48 #define EulOrdYZYs    EulOrd(Y,EulParEven,EulRepYes,EulFrmS)

   49 #define EulOrdYXZs    EulOrd(Y,EulParOdd,EulRepNo,EulFrmS)

   50 #define EulOrdYXYs    EulOrd(Y,EulParOdd,EulRepYes,EulFrmS)

   51 #define EulOrdZXYs    EulOrd(Z,EulParEven,EulRepNo,EulFrmS)

   52 #define EulOrdZXZs    EulOrd(Z,EulParEven,EulRepYes,EulFrmS)

   53 #define EulOrdZYXs    EulOrd(Z,EulParOdd,EulRepNo,EulFrmS)

   54 #define EulOrdZYZs    EulOrd(Z,EulParOdd,EulRepYes,EulFrmS)

   55     /* Rotating axes */

   56 #define EulOrdZYXr    EulOrd(X,EulParEven,EulRepNo,EulFrmR)

   57 #define EulOrdXYXr    EulOrd(X,EulParEven,EulRepYes,EulFrmR)

   58 #define EulOrdYZXr    EulOrd(X,EulParOdd,EulRepNo,EulFrmR)

   59 #define EulOrdXZXr    EulOrd(X,EulParOdd,EulRepYes,EulFrmR)

   60 #define EulOrdXZYr    EulOrd(Y,EulParEven,EulRepNo,EulFrmR)

   61 #define EulOrdYZYr    EulOrd(Y,EulParEven,EulRepYes,EulFrmR)

   62 #define EulOrdZXYr    EulOrd(Y,EulParOdd,EulRepNo,EulFrmR)

   63 #define EulOrdYXYr    EulOrd(Y,EulParOdd,EulRepYes,EulFrmR)

   64 #define EulOrdYXZr    EulOrd(Z,EulParEven,EulRepNo,EulFrmR)

   65 #define EulOrdZXZr    EulOrd(Z,EulParEven,EulRepYes,EulFrmR)

   66 #define EulOrdXYZr    EulOrd(Z,EulParOdd,EulRepNo,EulFrmR)

   67 #define EulOrdZYZr    EulOrd(Z,EulParOdd,EulRepYes,EulFrmR)

   68

   69 EulerAngles Eul_(float ai, float aj, float ah, int order);

   70 Quat Eul_ToQuat(EulerAngles ea);

   71 void Eul_ToHMatrix(EulerAngles ea, HMatrix M);

   72 EulerAngles Eul_FromHMatrix(HMatrix M, int order);

   73 EulerAngles Eul_FromQuat(Quat q, int order);

   74 #endif

Quat

Definition: QuatTypes.h:8

src

adtfBase

AADC_ADTF_BaseFilters

src

converter

AADC_AttitudeConverter

EulerAngles.hpp

Generated on Tue Sep 16 2014 14:13:25 for AADC by

     1.8.8


text:
using BlueSheep.Common.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace BlueSheep.Common.Data.D2o
{
    internal sealed class Class16
    {
        // Methods
        internal Class16(string string_1, string string_2)
        {
            this.string_0 = string_1;
        }

        internal DataClass method_0(string string_1, BigEndianReader dofusReader_0)
	{
		DataClass class2 = new DataClass { Name = this.string_0 };
		//Class17 class3 = default(Class17);
		foreach (Class17 class3 in this.list_0) {
			class2.Fields.Add(class3.string_0, RuntimeHelpers.GetObjectValue(class3.delegate0_0.Invoke(string_1, dofusReader_0)));
		}
		return class2;
	}

        internal void method_1(string string_1, BigEndianReader dofusReader_0)
        {
            Class17 item = new Class17(string_1, dofusReader_0);
            this.list_0.Add(item);
        }

        // Fields
        private List<Class17> list_0 = new List<Class17>();
        private string string_0;
    }
}


text:
/**
 * Exponential smoothing - smooth a series of points
 * Points passed in via the .data() function
 * Calculates the forecast points, the residuals, the sum of squares of the residuals and the factor
 */
ssci.fore.expon = function(){
    var data = [];
    var numPoints = 0;
    var output = [];
    var resids = [];
    var sumsq=0;
    var factor = 0.3;
    var x_conv = function(d){ return d[0]; };
    var y_conv = function(d){ return d[1]; };

    function retVar(){
        var i;
        var dataArray = [];

        //Clear output array - needed to stop output growing when function called repeatedly
		output = [];

        //Create array of data using accessors
        dataArray = data.map( function(d){
            return [x_conv(d), y_conv(d)];
        });
        numPoints = dataArray.length;

        //Calculate forecasts
        for(i=1;i<(numPoints+1);i++){
            if(i<2){
                output.push([dataArray[i][0], dataArray[i-1][1]]);
            } else if(i===numPoints){
                //Should I check for a date in the x-axis?
                //x value is one period on from the last period
                output.push([+dataArray[i-1][0]+(+dataArray[i-1][0]-dataArray[i-2][0]), dataArray[i-1][1]*factor + output[i-2][1]*(1-factor)]);
            } else {
                output.push([dataArray[i][0], dataArray[i-1][1]*factor + output[i-2][1]*(1-factor)]);
            }
        }

        //Calculate residuals
        for(i=1;i<numPoints;i++){
            resids.push(dataArray[i][1]-output[i-1][1]);
            sumsq += Math.pow(dataArray[i][1]-output[i-1][1],2);
        }
    }

    /**
     * Define a function to convert the x data passed in to the function. The default function just takes the first number in the arrays of array of data points
     * @param {function} [value] - A function to convert the x data for use in the function
     * @returns The conversion function if no parameter is passed in
     */
    retVar.x = function(value){
        if(!arguments.length){ return x_conv; }
        x_conv = value;
        return retVar;
    };

    /**
     * Define a function to convert the y data passed in to the function. The default function just takes the second number in the arrays of array of data points
     * @param {function} [value] - A function to convert the y data for use in the function
     * @returns The conversion function if no parameter is passed in
     */
    retVar.y = function(value){
        if(!arguments.length){ return y_conv; }
        y_conv = value;
        return retVar;
    };

    /**
     * Input the data. The default format is as an array of arrays of x and y values i.e. [['x1','y1']['x2','y2']]
     * @param value - the data
     * @returns The enclosing function
     */
    retVar.data = function(value){
        data = value;
        return retVar;
    };

    /**
     * Define or get the factor to smooth the data by
     * @param {number} [value=0.3] - A number between 0 and 1 to smooth the data by
     * @returns Either the factor or the enclosing object
     */
    retVar.factor = function(value){
        if(!arguments.length){ return factor; }

        //Check that factor is in range and of the right type
        if(typeof value !== 'number'){
            console.log('Factor appears to not be a number - changed to 0.3');
            factor=0.3;
            return retVar;
        }
        if(value>1 || value<0){
            console.log('Factor >1 or <0 - changed to 0.3');
            factor=0.3;
            return retVar;
        }

        factor = value;

        return retVar;
    };

    /**
     * Returns the smoothed data
     * @returns The smoothed data
     */
    retVar.output = function(){
        return output;
    };

    /**
     * Returns the residuals
     * @returns The residuals
     */
    retVar.residuals = function(){
        return resids;
    };
    retVar.sumSquares = function(){
        return sumsq;
    };

    return retVar;
};


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\DepartmentsSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Departments';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Departments', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'attribute'=>'companies_company_id',
                'value'=>'companiesCompany.company_name'
            ],
            [
                'attribute'=>'branches_branch_id',
                'value'=>'branchesBranch.branch_name'
            ],
            'department_name',
            'department_created_date',
            // 'department_status',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
package info.mornlight.gw2s.android.model;

import java.io.Serializable;

/**
 * Created by alfred on 5/22/13.
 */
public class StringName implements Serializable {
    String id;
    String name;

    public StringName() {
    }

    public StringName(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}


text:
import java.sql.*;
public class ConnectVertica {

	public static Connection conn;
	public ConnectVertica(){}
	public static Connection Getconnection() throws ClassNotFoundException,SQLException
	{
			Class.forName("com.vertica.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:vertica://localhost:5433/VMart", "dbadmin","dbadmin");
			return conn;
	}
}


text:
package cf.service;

import java.util.UUID;

import cf.common.JsonObject;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Mike Heath
 * @deprecated Use the V2 services.
 */
@Deprecated
public class BindRequest extends JsonObject {

	private final String serviceInstanceId;
	private final String label;
	private final String email;
	private final UUID appId;
	// Ignore bind_options field, it is always empty in v2

	public BindRequest(
			@JsonProperty("service_id") String serviceInstanceId,
			@JsonProperty("label") String label,
			@JsonProperty("email") String email,
			@JsonProperty("app_id") UUID appId) {
		this.serviceInstanceId = serviceInstanceId;
		this.label = label;
		this.email = email;
		this.appId = appId;
	}

	public String getServiceInstanceId() {
		return serviceInstanceId;
	}

	public String getLabel() {
		return label;
	}

	public String getEmail() {
		return email;
	}

	public UUID getAppId() {
		return appId;
	}
}


text:
export * from 'shared/routes';
export * from 'soundboard/routes';


text:
<?php

// Protect from unauthorized access
defined('FOF_INCLUDED') or die;

class FOFDownload
{
	/**
	 * Parameters passed from the GUI when importing from URL
	 *
	 * @var  array
	 */
	private $params = array();

	/**
	 * The download adapter which will be used by this class
	 *
	 * @var  FOFDownloadInterface
	 */
	private $adapter = null;

	/**
	 * Additional params that will be passed to the adapter while performing the download
	 *
	 * @var  array
	 */
	private $adapterOptions = array();

	/**
	 * Creates a new download object and assigns it the most fitting download adapter
	 */
	public function __construct()
	{
		// Find the best fitting adapter
		$allAdapters = self::getFiles(__DIR__ . '/adapter', array(), array('abstract.php'));
		$priority    = 0;

		foreach ($allAdapters as $adapterInfo)
		{
			if (!class_exists($adapterInfo['classname'], true))
			{
				continue;
			}

			/** @var FOFDownloadAdapterAbstract $adapter */
			$adapter = new $adapterInfo['classname'];

			if ( !$adapter->isSupported())
			{
				continue;
			}

			if ($adapter->priority > $priority)
			{
				$this->adapter = $adapter;
				$priority      = $adapter->priority;
			}
		}

		// Load the language strings
		FOFPlatform::getInstance()->loadTranslations('lib_fof');
	}

	/**
	 * Forces the use of a specific adapter
	 *
	 * @param  string $className   The name of the class or the name of the adapter, e.g. 'FOFDownloadAdapterCurl' or
	 *                             'curl'
	 */
	public function setAdapter($className)
	{
		$adapter = null;

		if (class_exists($className, true))
		{
			$adapter = new $className;
		}
		elseif (class_exists('FOFDownloadAdapter' . ucfirst($className)))
		{
			$className = 'FOFDownloadAdapter' . ucfirst($className);
			$adapter   = new $className;
		}

		if (is_object($adapter) && ($adapter instanceof FOFDownloadInterface))
		{
			$this->adapter = $adapter;
		}
	}

	/**
	 * Returns the name of the current adapter
	 *
	 * @return string
	 */
	public function getAdapterName()
	{
		if(is_object($this->adapter))
		{
			$class = get_class($this->adapter);

			return strtolower(str_ireplace('FOFDownloadAdapter', '', $class));
		}

		return '';
	}

	/**
	 * Sets the additional options for the adapter
	 *
	 * @param array $options
	 */
	public function setAdapterOptions(array $options)
	{
		$this->adapterOptions = $options;
	}

	/**
	 * Returns the additional options for the adapter
	 *
	 * @return array
	 */
	public function getAdapterOptions()
	{
		return $this->adapterOptions;
	}

	/**
	 * Used to decode the $params array
	 *
	 * @param   string $key     The parameter key you want to retrieve the value for
	 * @param   mixed  $default The default value, if none is specified
	 *
	 * @return  mixed  The value for this parameter key
	 */
	private function getParam($key, $default = null)
	{
		if (array_key_exists($key, $this->params))
		{
			return $this->params[$key];
		}
		else
		{
			return $default;
		}
	}

	/**
	 * Download data from a URL and return it
	 *
	 * @param   string $url The URL to download from
	 *
	 * @return  bool|string  The downloaded data or false on failure
	 */
	public function getFromURL($url)
	{
		try
		{
			return $this->adapter->downloadAndReturn($url, null, null, $this->adapterOptions);
		}
		catch (Exception $e)
		{
			return false;
		}
	}

	/**
	 * Performs the staggered download of file. The downloaded file will be stored in Joomla!'s temp-path using the
	 * basename of the URL as a filename
	 *
	 * The $params array can have any of the following keys
	 * url			The file being downloaded
	 * frag			Rolling counter of the file fragment being downloaded
	 * totalSize	The total size of the file being downloaded, in bytes
	 * doneSize		How many bytes we have already downloaded
	 * maxExecTime	Maximum execution time downloading file fragments, in seconds
	 * length		How many bytes to download at once
	 *
	 * The array returned is in the following format:
	 *
	 * status		True if there are no errors, false if there are errors
	 * error		A string with the error message if there are errors
	 * frag			The next file fragment to download
	 * totalSize	The total size of the downloaded file in bytes, if the server supports HEAD requests
	 * doneSize		How many bytes have already been downloaded
	 * percent		% of the file already downloaded (if totalSize could be determined)
	 * localfile	The name of the local file, without the path
	 *
	 * @param   array $params A parameters array, as sent by the user interface
	 *
	 * @return  array  A return status array
	 */
	public function importFromURL($params)
	{
		$this->params = $params;

		// Fetch data
		$url         	= $this->getParam('url');
		$localFilename	= $this->getParam('localFilename');
		$frag        	= $this->getParam('frag', -1);
		$totalSize   	= $this->getParam('totalSize', -1);
		$doneSize    	= $this->getParam('doneSize', -1);
		$maxExecTime 	= $this->getParam('maxExecTime', 5);
		$runTimeBias 	= $this->getParam('runTimeBias', 75);
		$length      	= $this->getParam('length', 1048576);

		if (empty($localFilename))
		{
			$localFilename = basename($url);

			if (strpos($localFilename, '?') !== false)
			{
				$paramsPos = strpos($localFilename, '?');
				$localFilename = substr($localFilename, 0, $paramsPos - 1);
			}
		}

		$tmpDir        = JFactory::getConfig()->get('tmp_path', JPATH_ROOT . '/tmp');
		$tmpDir        = rtrim($tmpDir, '/\\');

		// Init retArray
		$retArray = array(
			"status"    => true,
			"error"     => '',
			"frag"      => $frag,
			"totalSize" => $totalSize,
			"doneSize"  => $doneSize,
			"percent"   => 0,
			"localfile"	=> $localFilename
		);

		try
		{
			$timer = new FOFUtilsTimer($maxExecTime, $runTimeBias);
			$start = $timer->getRunningTime(); // Mark the start of this download
			$break = false; // Don't break the step

			// Figure out where on Earth to put that file
			$local_file = $tmpDir . '/' . $localFilename;

			while (($timer->getTimeLeft() > 0) && !$break)
			{
				// Do we have to initialize the file?
				if ($frag == -1)
				{
					// Currently downloaded size
					$doneSize = 0;

					if (@file_exists($local_file))
					{
						@unlink($local_file);
					}

					// Delete and touch the output file
					$fp = @fopen($local_file, 'wb');

					if ($fp !== false)
					{
						@fclose($fp);
					}

					// Init
					$frag = 0;

					//debugMsg("-- First frag, getting the file size");
					$retArray['totalSize'] = $this->adapter->getFileSize($url);
					$totalSize             = $retArray['totalSize'];
				}

				// Calculate from and length
				$from = $frag * $length;
				$to   = $length + $from - 1;

				// Try to download the first frag
				$required_time = 1.0;

				try
				{
					$result = $this->adapter->downloadAndReturn($url, $from, $to, $this->adapterOptions);

					if ($result === false)
					{
						throw new Exception(JText::sprintf('LIB_FOF_DOWNLOAD_ERR_COULDNOTDOWNLOADFROMURL', $url), 500);
					}
				}
				catch (Exception $e)
				{
					$result = false;
					$error  = $e->getMessage();
				}

				if ($result === false)
				{
					// Failed download
					if ($frag == 0)
					{
						// Failure to download first frag = failure to download. Period.
						$retArray['status'] = false;
						$retArray['error']  = $error;

						//debugMsg("-- Download FAILED");

						return $retArray;
					}
					else
					{
						// Since this is a staggered download, consider this normal and finish
						$frag = -1;
						//debugMsg("-- Import complete");
						$totalSize = $doneSize;
						$break     = true;
					}
				}

				// Add the currently downloaded frag to the total size of downloaded files
				if ($result)
				{
					$filesize = strlen($result);
					//debugMsg("-- Successful download of $filesize bytes");
					$doneSize += $filesize;

					// Append the file
					$fp = @fopen($local_file, 'ab');

					if ($fp === false)
					{
						//debugMsg("-- Can't open local file $local_file for writing");
						// Can't open the file for writing
						$retArray['status'] = false;
						$retArray['error']  = JText::sprintf('LIB_FOF_DOWNLOAD_ERR_COULDNOTWRITELOCALFILE', $local_file);

						return $retArray;
					}

					fwrite($fp, $result);
					fclose($fp);

					//debugMsg("-- Appended data to local file $local_file");

					$frag++;

					//debugMsg("-- Proceeding to next fragment, frag $frag");

					if (($filesize < $length) || ($filesize > $length))
					{
						// A partial download or a download larger than the frag size means we are done
						$frag = -1;
						//debugMsg("-- Import complete (partial download of last frag)");
						$totalSize = $doneSize;
						$break     = true;
					}
				}

				// Advance the frag pointer and mark the end
				$end = $timer->getRunningTime();

				// Do we predict that we have enough time?
				$required_time = max(1.1 * ($end - $start), $required_time);

				if ($required_time > (10 - $end + $start))
				{
					$break = true;
				}

				$start = $end;
			}

			if ($frag == -1)
			{
				$percent = 100;
			}
			elseif ($doneSize <= 0)
			{
				$percent = 0;
			}
			else
			{
				if ($totalSize > 0)
				{
					$percent = 100 * ($doneSize / $totalSize);
				}
				else
				{
					$percent = 0;
				}
			}

			// Update $retArray
			$retArray = array(
				"status"    => true,
				"error"     => '',
				"frag"      => $frag,
				"totalSize" => $totalSize,
				"doneSize"  => $doneSize,
				"percent"   => $percent,
			);
		}
		catch (Exception $e)
		{
			//debugMsg("EXCEPTION RAISED:");
			//debugMsg($e->getMessage());
			$retArray['status'] = false;
			$retArray['error']  = $e->getMessage();
		}

		return $retArray;
	}

	/**
	 * This method will crawl a starting directory and get all the valid files
	 * that will be analyzed by __construct. Then it organizes them into an
	 * associative array.
	 *
	 * @param   string $path          Folder where we should start looking
	 * @param   array  $ignoreFolders Folder ignore list
	 * @param   array  $ignoreFiles   File ignore list
	 *
	 * @return  array   Associative array, where the `fullpath` key contains the path to the file,
	 *                  and the `classname` key contains the name of the class
	 */
	protected static function getFiles($path, array $ignoreFolders = array(), array $ignoreFiles = array())
	{
		$return = array();

		$files = self::scanDirectory($path, $ignoreFolders, $ignoreFiles);

		// Ok, I got the files, now I have to organize them
		foreach ($files as $file)
		{
			$clean = str_replace($path, '', $file);
			$clean = trim(str_replace('\\', '/', $clean), '/');

			$parts = explode('/', $clean);

			$return[] = array(
				'fullpath'  => $file,
				'classname' => 'FOFDownloadAdapter' . ucfirst(basename($parts[0], '.php'))
			);
		}

		return $return;
	}

	/**
	 * Recursive function that will scan every directory unless it's in the
	 * ignore list. Files that aren't in the ignore list are returned.
	 *
	 * @param   string $path          Folder where we should start looking
	 * @param   array  $ignoreFolders Folder ignore list
	 * @param   array  $ignoreFiles   File ignore list
	 *
	 * @return  array   List of all the files
	 */
	protected static function scanDirectory($path, array $ignoreFolders = array(), array $ignoreFiles = array())
	{
		$return = array();

		$handle = @opendir($path);

		if ( !$handle)
		{
			return $return;
		}

		while (($file = readdir($handle)) !== false)
		{
			if ($file == '.' || $file == '..')
			{
				continue;
			}

			$fullpath = $path . '/' . $file;

			if ((is_dir($fullpath) && in_array($file, $ignoreFolders)) || (is_file($fullpath) && in_array($file, $ignoreFiles)))
			{
				continue;
			}

			if (is_dir($fullpath))
			{
				$return = array_merge(self::scanDirectory($fullpath, $ignoreFolders, $ignoreFiles), $return);
			}
			else
			{
				$return[] = $path . '/' . $file;
			}
		}

		return $return;
	}
}


text:
Jak tylko utworzysz galerię, możesz dostosować ją dla odwiedzających

Domyślne wyswietlanie w zakładce Administracja » Konfiguracja » Opcje Ustawienia dla gości

Domyślny temat w Administracja » Konfiguracja » Tematy

Domyślny język w Administracja » Konfiguracja » Języki

Domyślnie, każdy nowy użytkownik otrzyma te ustawienia po rejestracji.

Jeżeli masz pytania, społeczność Piwigo zaprasza Cię na swoje forum.


text:
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""

import numpy as np
import os
import scipy as sci
from scipy import stats

from matplotlib import pylab as plt
from mpl_toolkits.axes_grid import make_axes_locatable
import matplotlib.axes as maxes
import matplotlib.cm as cm
import matplotlib.colors as col
import matplotlib as mpl
from scipy import linalg, dot
import matplotlib.gridspec as gridspec
import pickle

from pycmbs.plots import pm_bar, add_nice_legend
from pycmbs.mapping import map_plot
from pycmbs.data import Data
from pycmbs.anova import *
from pycmbs.taylor import Taylor
from pycmbs.benchmarking.report import Report

from pycmbs.plots.violin import ViolinPlot

class RegionalAnalysis(object):

    """
    a class to perform comparisons between two datasets on a regional basis
    """

    def __init__(self, x, y, region, f_correlation=True, f_statistic=True, f_aggregated_violin=False, report=None):
        """

        Parameters
        ----------
        x : Data
            first dataset (is assumed to be the reference dataset!)
        y : Data
            second dataset
        region : Data
            region to analyze in both datasets; needs to have same geometry
            as the datasets
        f_statistic : bool
            calculate standard first and second moment statistics
        f_correlation : bool
            calculate correlation statistics between datasets
        f_aggregated_violin : bool
            generate a violin plot for the whole statistics over
            all timesteps
        report : Report
            Report class. When provided, figures are integrated
            into the report on the fly
        """

        self.region = region
        self._preprocessed = False
        self.f_correlation = f_correlation
        self.f_statistic = f_statistic
        self.f_aggregated_violin = f_aggregated_violin
        self.statistics = {}
        self.report = report

        if x is not None:
            if not isinstance(x, Data):
                raise ValueError('Error: RegionalAnalysis - X \
                                    is not of type Data!')
        if y is not None:
            if not isinstance(y, Data):
                raise ValueError('Error: RegionalAnalysis - Y \
                               is not of type Data!')

        if (x is None) or (y is None):
            # in case of dummy data, do not perform data check
            if x is None:
                self.x = None
            else:
                self.x = x.copy()
            if y is None:
                self.y = None
            else:
                self.y = y.copy()
        else:
            self.x = x.copy()
            self.y = y.copy()
            self._check()  # check input data

#---

    def _check(self):
        """
        check consistency of data
        """
        if self.report is not None:
            if not isinstance(self.report, Report):
                raise ValueError('Report is of invalid object type')
        if not isinstance(self.region, Data):
            raise ValueError('Region needs to be of instance C{Data}!')
        if self.x is not None:
            if self.x.ndim == 2:
                if self.x.shape != self.region.shape:
                    print self.x.shape, self.region.shape
                    raise ValueError('Inconsistent shape of \
                                       X-data with Region')
            elif self.x.ndim == 3:
                if self.x.data[0, :, :].shape != self.region.shape:
                    print self.x.data[0, :, :].shape, self.region.shape
                    raise ValueError('Inconsistent shape of \
                                       X-data with Region')
            else:
                raise ValueError('Unknown geometry!')

        if self.y is not None:
            if self.y.ndim == 2:
                if self.y.shape != self.region.shape:
                    print self.y.shape, self.region.shape
                    raise ValueError('Inconsistent shape of \
                                       Y-data with Region')
            elif self.y.ndim == 3:
                if self.y.data[0, :, :].shape != self.region.shape:
                    print self.y.data[0, :, :].shape, self.region.shape
                    raise ValueError('Inconsistent shape of \
                                      Y-data with Region')
            else:
                raise ValueError('Unknown geometry!')

        # check geometries
        if self.x.shape != self.y.shape:
            print self.x.shape, self.y.shape
            raise ValueError('ERROR: RegionalAnalyis - \
                               inconsistent geometries!')

    def _get_correlation(self, pthres=1.01):
        """
        calculate correlation between two fields

        in general one can think of three ways to calculate the correlation between X and Y
        a) correlate per pixel --> map of correlation measures; calculate then regional mean of this skill score (e.g. R)
        b) use multidimensional array [time,ny,nx] and correlate whole dataset for a region, without averaging
        c) calculate spatial mean field for each region and then correlate the means

        Here we implement all three approaches to allow for comparability

        Parameters
        ----------
        pthres : float
            threshold to mask insignificant correlations (default>1. ==> no masking)
        """

        if (self.x is None) or (self.y is None):
            return {'analysis_A': None, 'analysis_B': None, 'analysis_C': None}

        #======================================================================
        # A) calculate once correlation and then calculate regional statistics
        RO, PO = self.x.correlate(self.y, pthres=pthres,
                                  spearman=False, detrend=False)
        corrstat1 = RO.condstat(self.region)  # gives a dictionary already

        correlations = []
        correlations1 = []
        slopes = []
        slopes1 = []
        pvalues = []
        pvalues1 = []
        intercepts = []
        intercepts1 = []
        ids = []
        stdx = []
        stdy = []
        vals = self._get_unique_region_ids()
        for v in vals:
            x = self._get_masked_data(self.x, v)
            y = self._get_masked_data(self.y, v)

            #==================================================================
            # B) calculate regional statistics based on entire dataset for a
            # region
            xvec = x.data.flatten()
            yvec = y.data.flatten()
            slope, intercept, r_value, p_value, std_err = stats.mstats.linregress(
                xvec, yvec)
            ids.append(v)
            slopes.append(slope)
            correlations.append(r_value)
            pvalues.append(p_value)
            intercepts.append(intercept)
            stdx.append(xvec.std())
            stdy.append(yvec.std())
            del xvec, yvec, slope, intercept, r_value, p_value, std_err

            #==================================================================
            # C) fldmean() for each region and then correlate
            xm = x.fldmean(return_data=True)
            ym = y.fldmean(return_data=True)
            sh = xm.shape
            if xm.ndim != 3:
                raise ValueError('Invalid shape: %s' % sh)
            if sh[0] != xm.nt:
                raise ValueError(
                    'Timeseries should be of dimension [nt,1,1], %s' % str(sh))
            if sh[1] != 1:
                raise ValueError(
                    'Timeseries should be of dimension [nt,1,1], %s' % str(sh))
            if sh[2] != 1:
                raise ValueError(
                    'Timeseries should be of dimension [nt,1,1], %s' % str(sh))
            slope1, intercept1, r_value1, p_value1, std_err1 = stats.mstats.linregress(
                xm.data[:, 0, 0],
                ym.data[:, 0, 0])

            slopes1.append(slope1)
            correlations1.append(r_value1)
            pvalues1.append(p_value1)
            intercepts1.append(intercept1)

            # TODO
            print(
                'TODO: how to deal with area weighting in global correlation analyis ????')

            del x, y, xm, ym
        ids = np.asarray(ids)
        slopes = np.asarray(slopes)
        slopes1 = np.asarray(slopes1)
        correlations = np.asarray(correlations)
        correlations1 = np.asarray(correlations1)
        pvalues = np.asarray(pvalues)
        pvalues1 = np.asarray(pvalues1)
        intercepts = np.asarray(intercepts)
        intercepts1 = np.asarray(intercepts1)
        stdx = np.asarray(stdx)
        stdy = np.asarray(stdy)

        def _reshuffle(d):
            """reshuffle structure of output dictionary"""
            r = {}
            for i in xrange(len(d['id'])):
                id = d['id'][i]
                r.update(
                    {id: {'slope': d['slope'][i], 'intercept': d['intercept'][i],
                          'correlation': d['correlation'][i], 'pvalue': d['pvalue'][i]}})
                # stdx, stdy are not remapped at the moment
            return r

        corrstat2 = {'id': vals, 'slope': slopes,
                     'correlation': correlations,
                     'pvalue': pvalues,
                     'intercept': intercepts,
                     'stdx': stdx,
                     'stdy': stdy}

        corrstat3 = {'id': vals, 'slope': slopes1,
                     'correlation': correlations1,
                     'pvalue': pvalues1,
                     'intercept': intercepts1}

        #--- return result ---
        return {'analysis_A': corrstat1, 'analysis_B': _reshuffle(corrstat2), 'analysis_C': _reshuffle(corrstat3)}

    def calculate(self, pthres=1.01):
        """
        perform calculation of regional statistics

        Parameters
        ----------
        pthres : float
            threshold for significance level
            e.g. 0.05 corresponds to the 95% level
            values > 1. mean that no masking is applied to
            insignificant results

        Returns
        -------
        returns a dictionary with details on regional statistics
        """

        if self.f_statistic:  # calculate general statistic
            self._calc_general_statistic()
        if self.f_correlation:
            self._calc_correlation(pthres=pthres)
        if self.f_aggregated_violin:
            self._calc_global_violin()

    def _get_unique_region_ids(self):
        return np.unique(self.region.data.flatten())

    def _get_masked_data(self, x, id):
        """
        mask dataobject for a particular region
        and return masked object. The geometry is not changed.

        Parameters
        ----------
        x : Data
            data to be masked
        id : int
            region ID
        """

        # TODO cut bounding box for better performance when
        # bug in cut_bouding_box has been fixed

        if id not in self._get_unique_region_ids():
            print('WARNING: ID %s not found in data!')
            return x

        msk = self.region.data == id
        d = x.copy()
        d._apply_mask(msk)
        del msk
        return d

    def _calc_pdf_analysis(self):
        """
        do PDF analysis for regions
        """
        vals = self._get_unique_region_ids()
        for v in vals:
            x = self._get_masked_data(self.x, v)
            y = self._get_masked_data(self.y, v)
            x.label = x._get_label() + '-' + ' Region ' + str(v).zfill(5)
            y.label = y._get_label() + '-' + ' Region ' + str(v).zfill(5)
            pdf = PDFAnalysis(x, Y=y, report=self.report,
                              qq=False, labels=None)
            pdf.plot()
            del pdf

    def _calc_global_violin(self):
        """
        generate single violin plot that summarizes information
        for all regions
        """

        assert False  # not finally implemented

        xdata = []
        labels = []
        if self.y is not None:
            ydata = []
        else:
            ydata = None

        vals = self._get_unique_region_ids()
        for v in vals:
            x = self._get_masked_data(self.x, v)
            xdata.append(x.data.flatten())
            # todo replace by original region labels
            labels.append(str(v).zfill(5))
            del x

            if self.y is not None:
                y = self._get_masked_data(self.y, v)
                ydata.append(y.data.flatten())
                del y

        print 'Generating Violin plot ...'
        V = ViolinPlot(xdata, ydata, labels=labels)
        V.plot()

        print 'Done !'
        if self.report is not None:
            self.report.figure(
                V.ax.figure, caption='Violin plot for ' + self.variable.upper())
            plt.close(V.ax.figure.number)
        del V

#~ [ngroups, nsamp]
#~
    #~ def __init__(self, data, data2=None, labels=None, ax=None,
                 #~ boxplot=True, figsize=(10, 6)):
#~
#~
#~
#~
#~ Calculate Violin plot for each region
#~ generate a list with all regions as ID/label and generate a single plot
#~ that plots a vilon plot for each region
#~
#~ In best case the CTRL and EXPERIMENT data is plotted together in the Violin plot!

    def _calc_general_statistic(self):
        """
        calculate standard statistics for each region
        """
        xstat = None
        ystat = None
        if self.x is not None:
            xstat = self.x.condstat(self.region)
        if self.y is not None:
            ystat = self.y.condstat(self.region)
        self.statistics.update({'xstat': xstat})
        self.statistics.update({'ystat': ystat})

    def _calc_correlation(self, pthres=1.01):
        """
        calculate correlation between X and Y in different ways
        """
        # TODO weighting when calculating correlation
        self.statistics.update(
            {'corrstat': self._get_correlation(pthres=pthres)})

    def save(self, prefix='', format='txt', dir=None):
        """
        save statistic results to ASCII files

        Parameters
        ----------
        prefix : str
            prefix for output filenames
        format : str
            output format ['pkl','txt']
        dir : str
            directory where results shall be written to
        """

        if format not in ['txt', 'pkl', 'tex']:
            raise ValueError('Invalid format for output [txt,pkl]: %s' %
                             format)
        else:
            self.format = format
        if dir is None:
            raise ValueError('You need to specify an output directory!')
        if not os.path.exists(dir):
            os.makedirs(dir)  # try to generate directory
        if not os.path.exists(dir):
            raise ValueError(
                'ERROR: output directory not existing and it also can not be created!')
        if dir[-1] != os.sep:
            dir += os.sep

        if format == 'pkl':
            oname = dir + prefix + '_regional_statistics.pkl'
            if os.path.exists(oname):
                os.remove(oname)
            pickle.dump(self.statistics, open(oname, 'w'))
        elif format in ['txt', 'tex']:
            self._save_standard_statistics(
                dir + prefix + '_regional_statistics_standard.' + format)
            self._save_correlation_statistics_A(
                dir + prefix + '_regional_statistics_correlation_A.' + format)
            self._save_correlation_statistics_B(
                dir + prefix + '_regional_statistics_correlation_B.' + format)
            self._save_correlation_statistics_C(
                dir + prefix + '_regional_statistics_correlation_C.' + format)
        else:
            raise ValueError('Unsupported output format!')

    def _save_correlation_statistics_B(self, fname, tok='B'):
        """
        save correlation B results to ASCII file

        | id | slope | intercept | correlation | pvalue |

        """
        if self.format == 'txt':
            sep = '\t'
            eol = '\n'
        elif self.format == 'tex':
            sep = ' & '
            eol = ' \\\\  \n'

        if os.path.exists(fname):
            os.remove(fname)
        if os.path.splitext(fname)[1] != '.' + self.format:
            fname += '.' + self.format
        o = open(fname, 'w')
        # header
        if self.format == 'tex':
            if self.report is not None:
                self.report.open_table()
            o.write('\\begin{tabular}{lcccc}' + eol)
        o.write('id' + sep + 'slope' + sep + 'intercept' +
                sep + 'correlation' + sep + 'pvalue' + eol)
        # data
        corrstat = self.statistics['corrstat']['analysis_' + tok]
        for k in corrstat.keys():
            s = str(k) \
                + sep + str(corrstat[k]['slope']) \
                + sep + str(corrstat[k]['intercept']) \
                + sep + str(corrstat[k]['correlation']) \
                + sep + str(corrstat[k]['pvalue']) + eol
            o.write(s)
        if self.format == 'tex':
            if self.report is not None:
                self.report.write('    \\input{' + fname + '}')
                self.report.close_table(
                    caption='Regional statistics, correlation ' + tok)
            o.write('\end{tabular}')
            if self.report is not None:
                self.report.barrier()

        o.close()

    def _save_correlation_statistics_C(self, fname):
        """
        save correlation B results to ASCII file

        | id | slope | intercept | correlation | pvalue |

        This routine just acts as a wrapper
        """
        self._save_correlation_statistics_B(fname, tok='C')

    def _save_correlation_statistics_A(self, fname):
        """
        save correlation A results to ASCII file
        The results correspond to e.g the *mean* correlation coefficient for a particular region

        | id | rmean | rstd | rsum | rmin | rmax |
        """

        if self.format == 'txt':
            sep = '\t'
            eol = '\n'
        elif self.format == 'tex':
            sep = ' & '
            eol = ' \\\\  \n'

        if os.path.exists(fname):
            os.remove(fname)
        if os.path.splitext(fname)[1] != '.' + self.format:
            fname += '.' + self.format
        o = open(fname, 'w')
        # header
        if self.format == 'tex':
            if self.report is not None:
                self.report.open_table()
            o.write('\\begin{tabular}{lccccc}' + eol)
        o.write('id' + sep + 'r-mean' + sep + 'r-std' + sep +
                'r-sum' + sep + 'r-min' + sep + 'r-max' + eol)

        # data
        corrstat = self.statistics['corrstat']['analysis_A']
        for k in corrstat.keys():
            s = str(k) \
                + sep + str(corrstat[k]['mean'][0]) \
                + sep + str(corrstat[k]['std'][0]) \
                + sep + str(corrstat[k]['sum'][0]) \
                + sep + str(corrstat[k]['min'][0]) \
                + sep + str(corrstat[k]['max'][0]) + eol
            o.write(s)
        if self.format == 'tex':
            if self.report is not None:
                self.report.write('    \\input{' + fname + '}')
                self.report.close_table(
                    caption='Regional statistics, correlation A')
            o.write('\end{tabular}')
            if self.report is not None:
                self.report.barrier()

        o.close()

    def _save_standard_statistics(self, fname):
        """
        save standard (first and second order) statistics to ASCII files as follows

        time | xmean | ymean | xstd | ystd | xmin | ymin | xmax | ymax

        This information is stored separatley for each region ID in a separate file!

        The output is written dependent on the format.

        Parameters
        ----------
        fname : str
            filename for storing results
        """
        root = os.path.splitext(fname)[0]
        if self.format == 'txt':
            sep = '\t'
            eol = '\n'
        elif self.format == 'tex':
            sep = ' & '
            eol = ' \\\\  \n'
        else:
            raise ValueError('Invalid format')

        ids = self.statistics['xstat'].keys()
        for id in ids:
            fname = root + '_' + str(id).zfill(16) + '.' + self.format
            if os.path.exists(fname):
                os.remove(fname)
            o = open(fname, 'w')

            # header
            if self.format == 'tex':
                if self.report is not None:
                    self.report.open_table()
                o.write('\\begin{tabular}{lcccccccc}' + eol)
            o.write('time' + sep + 'xmean' + sep + 'ymean' + sep + 'xstd' + sep +
                    'ystd' + sep + 'xmin' + sep + 'ymin' + sep + 'xmax' + sep + 'ymax' + eol)

            # data
            for i in xrange(len(self.statistics['xstat'][id]['mean'])):
                s = str(i) + sep \
                    + str(self.statistics['xstat'][id]['mean'][i]) + sep \
                    + str(self.statistics['ystat'][id]['mean'][i]) + sep \
                    + str(self.statistics['xstat'][id]['std'][i]) + sep \
                    + str(self.statistics['ystat'][id]['std'][i]) + sep \
                    + str(self.statistics['xstat'][id]['min'][i]) + sep \
                    + str(self.statistics['ystat'][id]['min'][i]) + sep \
                    + str(self.statistics['xstat'][id]['max'][i]) + sep \
                    + str(self.statistics['ystat'][id]['max'][i]) + eol
                o.write(s)
            if self.format == 'tex':
                if self.report is not None:
                    self.report.write('    \\input{' + fname + '}')
                    self.report.close_table(
                        caption='General regional statistics')
                o.write('\end{tabular}')
                if self.report is not None:
                    self.report.barrier()

            o.close()

    def plot_taylor(self, dia=None, color='red'):
        """
        Taylor plot of statistics

        The plot produced contains the IDs of each region as default.
        todo: as an alternative one should be able to provide a dictionary that specifies how to plot results
        (e.hg. labels, markerstyles etc.)

        requires that statistics have alredy been calculated

        Parameters
        ----------
        color : str
            color for specifiying the current plot
        dia : Taylor
            Taylor plot instance
        """

        # check
        keys = np.unique(self.region.data.flatten())
        keys.sort()

        r = self.statistics['corrstat']['corrstat2']['correlation']
        sx = self.statistics['corrstat']['corrstat2']['stdx']
        sy = self.statistics['corrstat']['corrstat2']['stdy']

        ratio = sy / sx

        if dia is None:
            tay = Taylor(stdmax=max(ratio.max() * 1.2, 2.))
        else:
            if not isinstance(dia, Taylor):
                print type(dia)
                raise ValueError('Provided argument is no taylor class! ')
            else:
                tay = dia
                # preserve stdmax information when possible
                tay.stdmax = max(max(ratio.max() * 1.2, 2.), dia.stdmax)

        sid = map(str, self.statistics['corrstat']['corrstat2']['id'])
        tay.plot(r, ratio, labels=sid, color=color)
        return tay


text:
/**
 * Base class for ccui.UICCTextField
 * @class
 * @extends cc.TextFieldTTF
 *
 * @property {Boolean}  maxLengthEnabled    - Indicate whether max length limit is enabled
 * @property {Number}   maxLength           - The max length of the text field
 * @property {Boolean}  passwordEnabled     - Indicate whether the text field is for entering password
 */
ccui.UICCTextField = cc.TextFieldTTF.extend(/** @lends ccui.UICCTextField# */{
    maxLengthEnabled: false,
    maxLength: 0,
    passwordEnabled: false,
    _passwordStyleText: "",
    _attachWithIME: false,
    _detachWithIME: false,
    _insertText: false,
    _deleteBackward: false,
    _className: "UICCTextField",
    _textFieldRendererAdaptDirty: true,
    ctor: function () {
        cc.TextFieldTTF.prototype.ctor.call(this);
        this.maxLengthEnabled = false;
        this.maxLength = 0;
        this.passwordEnabled = false;
        this._passwordStyleText = "*";
        this._attachWithIME = false;
        this._detachWithIME = false;
        this._insertText = false;
        this._deleteBackward = false;
    },
    onEnter: function () {
        cc.TextFieldTTF.prototype.setDelegate.call(this, this);
    },
    //CCTextFieldDelegate
    onTextFieldAttachWithIME: function (sender) {
        this.setAttachWithIME(true);
        return false;
    },
    onTextFieldInsertText: function (sender, text, len) {
        if (len == 1 && text == "\n") {
            return false;
        }
        this.setInsertText(true);
        if (this.maxLengthEnabled) {
            if (cc.TextFieldTTF.prototype.getCharCount.call(this) >= this.maxLength) {
                return true;
            }
        }

        return false;
    },
    onTextFieldDeleteBackward: function (sender, delText, nLen) {
        this.setDeleteBackward(true);
        return false;
    },
    onTextFieldDetachWithIME: function (sender) {
        this.setDetachWithIME(true);
        return false;
    },
    insertText: function (text, len) {        //todo need to delete
        var input_text = text;

        if (text != "\n")
        {
            if (this.maxLengthEnabled)
            {
                var text_count = this.getString().length;
                if (text_count >= this.maxLength)
                {
                    // password
                    if (this.passwordEnabled)
                    {
                        this.setPasswordText(this.getString());
                    }
                    return;
                }
            }
        }
        cc.TextFieldTTF.prototype.insertText.call(this, input_text, len);

        // password
        if (this.passwordEnabled)
        {
            if (cc.TextFieldTTF.prototype.getCharCount.call(this) > 0)
            {
                this.setPasswordText(this.getString());
            }
        }
    },
    deleteBackward: function () {
        cc.TextFieldTTF.prototype.deleteBackward.call(this);

        if (cc.TextFieldTTF.prototype.getCharCount.call(this) > 0) {
            // password
            if (this.passwordEnabled) {
                this.setPasswordText(this._inputText);
            }
        }
    },
    openIME: function () {
        cc.TextFieldTTF.prototype.attachWithIME.call(this);
    },
    closeIME: function () {
        cc.TextFieldTTF.prototype.detachWithIME.call(this);
    },
    setMaxLengthEnabled: function (enable) {
        this.maxLengthEnabled = enable;
    },
    isMaxLengthEnabled: function () {
        return this.maxLengthEnabled;
    },
    setMaxLength: function (length) {
        this.maxLength = length;
    },
    getMaxLength: function () {
        return this.maxLength;
    },
    getCharCount: function () {
        return cc.TextFieldTTF.prototype.getCharCount.call(this);
    },
    setPasswordEnabled: function (enable) {
        this.passwordEnabled = enable;
    },
    isPasswordEnabled: function () {
        return this.passwordEnabled;
    },
    setPasswordStyleText: function (styleText) {
        if (styleText.length > 1) {
            return;
        }
        var header = styleText.charCodeAt(0);
        if (header < 33 || header > 126) {
            return;
        }
        this._passwordStyleText = styleText;
    },
    setPasswordText: function (text) {
        var tempStr = "";
        var text_count = text.length;
        var max = text_count;

        if (this.maxLengthEnabled)
        {
            if (text_count > this.maxLength)
            {
                max = this.maxLength;
            }
        }

        for (var i = 0; i < max; ++i)
        {
            tempStr += this._passwordStyleText;
        }

        cc.LabelTTF.prototype.setString.call(this, tempStr);
    },
    setAttachWithIME: function (attach) {
        this._attachWithIME = attach;
    },
    getAttachWithIME: function () {
        return this._attachWithIME;
    },
    setDetachWithIME: function (detach) {
        this._detachWithIME = detach;
    },
    getDetachWithIME: function () {
        return this._detachWithIME;
    },
    setInsertText: function (insert) {
        this._insertText = insert;
    },
    getInsertText: function () {
        return this._insertText;
    },
    setDeleteBackward: function (deleteBackward) {
        this._deleteBackward = deleteBackward;
    },
    getDeleteBackward: function () {
        return this._deleteBackward;
    },
    init: function () {
        if (ccui.Widget.prototype.init.call(this)) {
            this.setTouchEnabled(true);
            return true;
        }
        return false;
    },
    onDraw: function (sender) {
        return false;
    }
});

ccui.UICCTextField.create = function (placeholder, fontName, fontSize) {
    var ret = new ccui.UICCTextField();
    if (ret && ret.initWithString("", fontName, fontSize)) {
        if (placeholder) {
            ret.setPlaceHolder(placeholder);
        }
        return ret;
    }
    return null;
};

/**
 * Base class for ccui.TextField
 * @class
 * @extends ccui.Widget
 *
 * @property {String}   string              - The content string of the label
 * @property {Number}   placeHolder         - The place holder of the text field
 * @property {String}   font                - The text field font with a style string: e.g. "18px Verdana"
 * @property {String}   fontName            - The text field font name
 * @property {Number}   fontSize            - The text field font size
 * @property {Boolean}  maxLengthEnabled    - Indicate whether max length limit is enabled
 * @property {Number}   maxLength           - The max length of the text field
 * @property {Boolean}  passwordEnabled     - Indicate whether the text field is for entering password
 */
ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{
    _textFieldRender: null,
    _touchWidth: 0,
    _touchHeight: 0,
    _useTouchArea: false,
    _textFieldEventListener: null,
    _textFieldEventSelector: null,
    _attachWithIMEListener: null,
    _detachWithIMEListener: null,
    _insertTextListener: null,
    _deleteBackwardListener: null,
    _attachWithIMESelector: null,
    _detachWithIMESelector: null,
    _insertTextSelector: null,
    _deleteBackwardSelector: null,
    _passwordStyleText: "",
    _textFieldRendererAdaptDirty: true,

    /**
     * allocates and initializes a UITextField.
     * Constructor of ccui.TextField
     * @example
     * // example
     * var uiTextField = new ccui.TextField();
     */
    ctor: function () {
        ccui.Widget.prototype.ctor.call(this);
    },

    init: function(){
        if(ccui.Widget.prototype.init.call(this)){
            this.setTouchEnabled(true);
            return true;
        }
        return false;
    },

    onEnter: function () {
        ccui.Widget.prototype.onEnter.call(this);
        this.setUpdateEnabled(true);
    },

    onExit:function(){
        this.setUpdateEnabled(false);
        ccui.Layout.prototype.onExit.call(this);
    },

    initRenderer: function () {
        this._textFieldRender = ccui.UICCTextField.create("input words here", "Thonburi", 20);
        this.addProtectedChild(this._textFieldRender, ccui.TextField.RENDERER_ZORDER, -1);

    },

    /**
     * Set touch size
     * @param {cc.Size} size
     */
    setTouchSize: function (size) {
        this._touchWidth = size.width;
        this._touchHeight = size.height;
    },

    setTouchAreaEnabled: function(enable){
        this._useTouchArea = enable;
    },

    adaptRenderers: function(){
        if (this._textFieldRendererAdaptDirty)
        {
            this.textfieldRendererScaleChangedWithSize();
            this._textFieldRendererAdaptDirty = false;
        }
    },

    hitTest: function(pt){
        if (this._useTouchArea)
        {
            var nsp = this.convertToNodeSpace(pt);
            var bb = cc.rect(
                -this._touchWidth * this._anchorPoint.x,
                -this._touchHeight * this._anchorPoint.y,
                this._touchWidth, this._touchHeight
            );
            if (
                nsp.x >= bb.origin.x &&
                nsp.x <= bb.origin.x + bb.size.width &&
                nsp.y >= bb.origin.y &&
                nsp.y <= bb.origin.y + bb.size.height
            )
            {
                return true;
            }
        }
        else
        {
            return ccui.Widget.prototype.hitTest.call(this, pt);
        }

        return false;
    },

    /**
     * Get touch size.
     * @returns {cc.Size}
     */
    getTouchSize: function () {
        return cc.size(this._touchWidth, this._touchHeight);
    },

    /**
     *  Changes the string value of textField.
     * @deprecated
     * @param {String} text
     */
    setText: function (text) {
        cc.log("Please use the setString");
        this.setString(text);
    },

    /**
     *  Changes the string value of textField.
     * @param {String} text
     */
    setString: function (text) {
        if (!text) {
            return;
        }
        text = String(text);
        if (this.isMaxLengthEnabled()) {
            text = text.substr(0, this.getMaxLength());
        }
        if (this.isPasswordEnabled()) {
            this._textFieldRender.setPasswordText(text);
            this._textFieldRender.setString("");
            this._textFieldRender.insertText(text, text.length);
        }
        else {
            this._textFieldRender.setString(text);
        }
        this._textFieldRendererAdaptDirty = true;
        this._updateContentSizeWithTextureSize(this._textFieldRender.getContentSize());
    },

    /**
     * @param {String} value
     */
    setPlaceHolder: function (value) {
        this._textFieldRender.setPlaceHolder(value);
        this._textFieldRendererAdaptDirty = true;
        this._updateContentSizeWithTextureSize(this._textFieldRender.getContentSize());
    },

    /**
     * @returns {String}
     */
    getPlaceHolder: function () {
        return this._textFieldRender.getPlaceHolder();
    },

    _setFont: function (font) {
        this._textFieldRender._setFont(font);
        this._textFieldRendererAdaptDirty = true;
    },

    _getFont: function () {
        return this._textFieldRender._getFont();
    },

    /**
     * Set font size for text field content
     * @param {cc.Size} size
     */
    setFontSize: function (size) {
        this._textFieldRender.setFontSize(size);
        this._textFieldRendererAdaptDirty = true;
        this._updateContentSizeWithTextureSize(this._textFieldRender.getContentSize());
    },

    /**
     * Get font size for text field content
     * @param {cc.Size} size
     */
    getFontSize: function () {
        return this._textFieldRender.getSystemFontSize();
    },

    /**
     * Set font name for text field content
     * @param {String} name
     */
    setFontName: function (name) {
        this._textFieldRender.setFontName(name);
        this._textFieldRendererAdaptDirty = true;
        this._updateContentSizeWithTextureSize(this._textFieldRender.getContentSize());

    },

    /**
     * Get font name for text field content
     * @param {cc.Size} size
     */
    getFontName: function () {
        return this._textFieldRender.getSystemFontName();
    },

    /**
     * detach with IME
     */
    didNotSelectSelf: function () {
        this._textFieldRender.detachWithIME();
    },

    /**
     * get textField string value
     * @deprecated
     * @returns {String}
     */
    getStringValue: function () {
        cc.log("Please use the getString");
        return this.getString();
    },

    /**
     * get textField string value
     * @returns {String}
     */
    getString: function () {
        return this._textFieldRender.getString();
    },

    getStringLength: function(){
        return this._textFieldRender.getStringLength();
    },

    /**
     * touch began
     * @param {cc.Point} touchPoint
     */
    onTouchBegan: function (touchPoint, unusedEvent) {
        var self = this;
        var pass = ccui.Widget.prototype.onTouchBegan.call(self, touchPoint, unusedEvent);
        if (self._hitted)
        {
            setTimeout(function(){
                self._textFieldRender.attachWithIME();
            }, 0);
        }
        return pass;
    },

    /**
     * @param {Boolean} enable
     */
    setMaxLengthEnabled: function (enable) {
        this._textFieldRender.setMaxLengthEnabled(enable);
    },

    /**
     * @returns {Boolean}
     */
    isMaxLengthEnabled: function () {
        return this._textFieldRender.isMaxLengthEnabled();
    },

    /**
     * @param {number} length
     */
    setMaxLength: function (length) {
        this._textFieldRender.setMaxLength(length);

        this.setString(this.getString());
    },

    /**
     * @returns {number} length
     */
    getMaxLength: function () {
        return this._textFieldRender.getMaxLength();
    },

    /**
     * @param {Boolean} enable
     */
    setPasswordEnabled: function (enable) {
        this._textFieldRender.setPasswordEnabled(enable);
    },

    /**
     * @returns {Boolean}
     */
    isPasswordEnabled: function () {
        return this._textFieldRender.isPasswordEnabled();
    },

    /**
     * @param {String} enable
     */
    setPasswordStyleText: function (styleText) {
        this._textFieldRender.setPasswordStyleText(styleText);
        this._passwordStyleText = styleText;

        this.setString(this.getString());
    },

    /**
     * @returns {String}
     */
    getPasswordStyleText: function () {
        return this._passwordStyleText;
    },

    update: function (dt) {
        if (this.getAttachWithIME()) {
            this.attachWithIMEEvent();
            this.setAttachWithIME(false);
        }
        if (this.getDetachWithIME()) {
            this.detachWithIMEEvent();
            this.setDetachWithIME(false);
        }
        if (this.getInsertText()) {
            this.insertTextEvent();
            this.setInsertText(false);

            this._textFieldRendererAdaptDirty = true;
            this._updateContentSizeWithTextureSize(this._textFieldRender.getContentSize());
        }
        if (this.getDeleteBackward()) {
            this.deleteBackwardEvent();
            this.setDeleteBackward(false);

            this._textFieldRendererAdaptDirty = true;
            this._updateContentSizeWithTextureSize(this._textFieldRender.getContentSize());
        }
    },

    /**
     * get whether attach with IME.
     * @returns {Boolean}
     */
    getAttachWithIME: function () {
        return this._textFieldRender.getAttachWithIME();
    },

    /**
     * set attach with IME.
     * @param {Boolean} attach
     */
    setAttachWithIME: function (attach) {
        this._textFieldRender.setAttachWithIME(attach);
    },

    /**
     * get whether eetach with IME.
     * @returns {Boolean}
     */
    getDetachWithIME: function () {
        return this._textFieldRender.getDetachWithIME();
    },

    /**
     * set detach with IME.
     * @param {Boolean} detach
     */
    setDetachWithIME: function (detach) {
        this._textFieldRender.setDetachWithIME(detach);
    },

    /**
     * get insertText
     * @returns {String}
     */
    getInsertText: function () {
        return this._textFieldRender.getInsertText();
    },

    /**
     * set insertText
     * @param {String} insertText
     */
    setInsertText: function (insertText) {
        this._textFieldRender.setInsertText(insertText);
    },

    /**
     * @returns {Boolean}
     */
    getDeleteBackward: function () {
        return this._textFieldRender.getDeleteBackward();
    },

    /**
     * @param {Boolean} deleteBackward
     */
    setDeleteBackward: function (deleteBackward) {
        this._textFieldRender.setDeleteBackward(deleteBackward);
    },

    attachWithIMEEvent: function () {
        if (this._textFieldEventListener && this._textFieldEventSelector) {
            this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_ATTACH_WITH_ME);
        }
        if (this._eventCallback) {
            this._eventCallback(this, 0);
        }
    },

    detachWithIMEEvent: function () {
        if (this._textFieldEventListener && this._textFieldEventSelector) {
            this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_DETACH_WITH_ME);
        }
        if (this._eventCallback) {
            this._eventCallback(this, 1);
        }
    },

    insertTextEvent: function () {
        if (this._textFieldEventListener && this._textFieldEventSelector) {
            this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_INSERT_TEXT);
        }
        if (this._eventCallback) {
            this._eventCallback(this, 2);
        }
    },

    deleteBackwardEvent: function () {
        if (this._textFieldEventListener && this._textFieldEventSelector) {
            this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_DELETE_BACKWARD);
        }
        if (this._eventCallback) {
            this._eventCallback(this, 3);
        }
    },

    /**
     * add event listener
     * @param {Function} selector
     * @param {Object} target
     */
    addEventListenerTextField: function (selector, target) {
        this._textFieldEventSelector = selector;
        this._textFieldEventListener = target;
    },

    /**
     * override "setAnchorPoint" of widget.
     * @param {cc.Point|Number} point The anchor point of UILabelBMFont or The anchor point.x of UILabelBMFont.
     * @param {Number} [y] The anchor point.y of UILabelBMFont.
     */
    setAnchorPoint: function (point, y) {
        if (y === undefined) {
            ccui.Widget.prototype.setAnchorPoint.call(this, point);
            this._textFieldRender.setAnchorPoint(point);
        } else {
            ccui.Widget.prototype.setAnchorPoint.call(this, point, y);
            this._textFieldRender.setAnchorPoint(point, y);
        }
    },
    _setAnchorX: function (value) {
        ccui.Widget.prototype._setAnchorX.call(this, value);
        this._textFieldRender._setAnchorX(value);
    },
    _setAnchorY: function (value) {
        ccui.Widget.prototype._setAnchorY.call(this, value);
        this._textFieldRender._setAnchorY(value);
    },

    onSizeChanged: function () {
        ccui.Widget.prototype.onSizeChanged.call(this);
        this._textFieldRendererAdaptDirty = true;
    },

    textfieldRendererScaleChangedWithSize: function () {
        if (this._ignoreSize) {
            this._textFieldRender.setScale(1.0);
            var rendererSize = this.getContentSize();
            this._size.width = rendererSize.width;
            this._size.height = rendererSize.height;
        }
        else {
            var textureSize = this.getContentSize();
            if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
                this._textFieldRender.setScale(1.0);
                return;
            }
            var scaleX = this._size.width / textureSize.width;
            var scaleY = this._size.height / textureSize.height;
            this._textFieldRender.setScaleX(scaleX);
            this._textFieldRender.setScaleY(scaleY);
        }
        this._textFieldRender.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
    },

    /**
     * override "getContentSize" method of widget.
     * @returns {cc.Size}
     */
    getContentSize: function () {
        return this._textFieldRender.getContentSize();
    },
    _getWidth: function () {
        return this._textFieldRender._getWidth();
    },
    _getHeight: function () {
        return this._textFieldRender._getHeight();
    },

    /**
     * override "getContentSize" method of widget.
     * @returns {cc.Node}
     */
    getVirtualRenderer: function () {
        return this._textFieldRender;
    },

    updateTextureColor: function () {
        this.updateColorToRenderer(this._textFieldRender);
    },

    updateTextureOpacity: function () {
        this.updateOpacityToRenderer(this._textFieldRender);
    },

    /**
     * Returns the "class name" of widget.
     * @returns {string}
     */
    getDescription: function () {
        return "TextField";
    },

    attachWithIME: function () {
        this._textFieldRender.attachWithIME();
    },

    createCloneInstance: function () {
        return ccui.TextField.create();
    },

    copySpecialProperties: function (textField) {
        this.setString(textField._textFieldRender.getString());
        this.setPlaceHolder(textField.getString());
        this.setFontSize(textField._textFieldRender.getFontSize());
        this.setFontName(textField._textFieldRender.getFontName());
        this.setMaxLengthEnabled(textField.isMaxLengthEnabled());
        this.setMaxLength(textField.getMaxLength());
        this.setPasswordEnabled(textField.isPasswordEnabled());
        this.setPasswordStyleText(textField._passwordStyleText);
        this.setAttachWithIME(textField.getAttachWithIME());
        this.setDetachWithIME(textField.getDetachWithIME());
        this.setInsertText(textField.getInsertText());
        this.setDeleteBackward(textField.getDeleteBackward());
    }
});

ccui.TextField.create = function(placeholder, fontName, fontSize){
    var widget = new ccui.TextField();
    if (widget && widget.init())
    {
        if(placeholder && fontName && fontSize){
            widget.setPlaceHolder(placeholder);
            widget.setFontName(fontName);
            widget.setFontSize(fontSize);

        }
        return widget;
    }
    return null;

};

var _p = ccui.TextField.prototype;

// Extended properties
/** @expose */
_p.string;
cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
/** @expose */
_p.placeHolder;
cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder);
/** @expose */
_p.font;
cc.defineGetterSetter(_p, "font", _p._getFont, _p._setFont);
/** @expose */
_p.fontSize;
cc.defineGetterSetter(_p, "fontSize", _p.getFontSize, _p.setFontSize);
/** @expose */
_p.fontName;
cc.defineGetterSetter(_p, "fontName", _p.getFontName, _p.setFontName);
/** @expose */
_p.maxLengthEnabled;
cc.defineGetterSetter(_p, "maxLengthEnabled", _p.isMaxLengthEnabled, _p.setMaxLengthEnabled);
/** @expose */
_p.maxLength;
cc.defineGetterSetter(_p, "maxLength", _p.getMaxLength, _p.setMaxLength);
/** @expose */
_p.passwordEnabled;
cc.defineGetterSetter(_p, "passwordEnabled", _p.isPasswordEnabled, _p.setPasswordEnabled);

_p = null;

/**
 * allocates and initializes a UITextField.
 * @constructs
 * @return {ccui.TextField}
 * @example
 * // example
 * var uiTextField = ccui.TextField.create();
 */
ccui.TextField.create = function () {
    return new ccui.TextField();
};

// Constants
//TextField event
ccui.TextField.EVENT_ATTACH_WITH_ME = 0;
ccui.TextField.EVENT_DETACH_WITH_ME = 1;
ccui.TextField.EVENT_INSERT_TEXT = 2;
ccui.TextField.EVENT_DELETE_BACKWARD = 3;

ccui.TextField.RENDERER_ZORDER = -1;


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/seedContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:background="?themeColor"
        android:paddingBottom="16dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="16dp">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:text="TicTacToe"
            android:textColor="@color/material_white"
            android:textSize="32sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tvGameState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tvTitle"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:textColor="@color/material_white"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvMySeed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tvGameState"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:textColor="@color/material_white"
            android:textSize="18sp" />

    </RelativeLayout>

    <ProgressBar
        android:id="@+id/horizontal_indeterminate_progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/seedContainer"
        android:background="?themeColor"
        android:contentDescription="@null"
        android:indeterminate="true"
        android:scaleType="fitCenter" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvGameGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnSurrender"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/horizontal_indeterminate_progress_bar" />

    <Button
        android:id="@+id/btnSurrender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?attr/statusSelector"
        android:text="@string/tictactoe_game_btn_surrender_text"
        android:textColor="@color/material_white"
        android:textSize="20sp" />
</RelativeLayout>


text:
import json
import os
import socket

import datetime
from pymongo import MongoClient
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from center.Helper.DBHelper_Redis import RedisDBHelper
from Helper_Logger import LogHelper
from cloudplat import settings

redisConnect = RedisDBHelper()

jobstores = {
    'redis': RedisJobStore(
        jobs_key="Bamai:crontab",
        host=settings.REDIS_HOST,
        port=settings.REDIS_PORT,
        password=settings.REDIS_PASSWORD),
    'default': MemoryJobStore()
}

executors = {
    'default': ThreadPoolExecutor(10),
    'processpool': ProcessPoolExecutor(1)
}

job_defaults = {
    'coalesce': False,
    'max_instances': 3
}

# scheduler.add_job(_todo, 'date', run_date='2016-02-14 15:01:05')
# scheduler.add_job(_todo, 'interval', hour=2)
# scheduler.add_job(_todo, 'cron', hour=0, minute=0)

scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)

try:
    scheduler.start()
except SystemExit:
    pass


text:
import t

class n11(t.Test):

    class TestResource(t.Resource):

        create = False
        status = True
        location = '/foo'

        def allowed_methods(self, req, rsp):
            return ["POST"]

        def allow_missing_post(self, req, rsp):
            return True

        def content_types_accepted(self, req, rsp):
            return [('application/octet-stream', self.from_octets)]

        def created_location(self, req, rsp):
            return self.location

        def post_is_create(self, req, rsp):
            return self.create

        def process_post(self, req, rsp):
            if not self.create:
                rsp.body = "processed"
            return self.status

        def resource_exists(self, req, rsp):
            return False

        def from_octets(self, req, rsp):
            rsp.body = "created"

        def to_html(self, req, rsp):
            return "Yay"

    def test_post_is_create_no_redirect(self):
        self.TestResource.create = True
        self.TestResource.location = None
        self.req.method = 'POST'
        self.go()
        t.eq(self.rsp.status, '200 OK')
        t.eq(self.rsp.body, 'created')

    def test_post_is_create_redirect(self):
        self.TestResource.create = True
        self.TestResource.location = '/foo'
        self.req.method = 'POST'
        self.go()
        t.eq(self.rsp.status, '303 See Other')
        t.eq(self.rsp.location, '/foo')
        t.eq(self.rsp.body, 'created')

    def test_post_is_process(self):
        self.TestResource.create = False
        self.req.method = 'POST'
        self.go()
        t.eq(self.rsp.status, '200 OK')
        t.eq(self.rsp.location, None)
        t.eq(self.rsp.body, 'processed')

    def test_post_is_process_error(self):
        self.TestResource.create = False
        self.TestResource.status = False
        self.req.method = 'POST'
        self.go()
        self.TestResource.status = True
        t.eq(self.rsp.status, '500 Internal Server Error')
        t.eq(self.rsp.location, None)
        t.eq(self.rsp.body, '')


text:
using System.Collections.Generic;
using System.Linq;

using Autofac;

using Eventualize.Interfaces;
using Eventualize.Interfaces.Domain;
using Eventualize.Interfaces.Domain.MetaModel;
using Eventualize.Interfaces.Infrastructure;
using Eventualize.Interfaces.Materialization;
using Eventualize.Interfaces.Materialization.Progress;
using Eventualize.Interfaces.Persistence;
using Eventualize.Interfaces.Snapshots;

namespace Eventualize.Autofac.Infrastructure
{
    public class AutofacComponentContext : IEventualizeContainer
    {
        private IComponentContext componentContext;

        public AutofacComponentContext(IComponentContext componentContext)
        {
            this.componentContext = componentContext;
        }

        public IEventualizeLogger Logger
        {
            get
            {
                return this.componentContext.Resolve<IEventualizeLogger>();
            }
        }

        public IMaterializationProgessStore MaterializationProgessStore
        {
            get
            {
                return this.componentContext.Resolve<IMaterializationProgessStore>();
            }
        }

        public IMaterializationEventPoller MaterializationEventPoller
        {
            get
            {
                return this.componentContext.Resolve<IMaterializationEventPoller>();
            }
        }

        public IAggregateRepository AggregateRepository
        {
            get
            {
                return this.componentContext.Resolve<IAggregateRepository>();
            }
        }

        public IAggregateFactory AggregateFactory
        {
            get
            {
                return this.componentContext.Resolve<IAggregateFactory>();
            }
        }

        public IEventConverter EventConverter
        {
            get
            {
                return this.componentContext.Resolve<IEventConverter>();
            }
        }

        public ISerializer Serializer
        {
            get
            {
                return this.componentContext.Resolve<ISerializer>();
            }
        }

        public IEnumerable<IMaterializationStrategy> MaterializationStrategies
        {
            get
            {
                return this.componentContext.Resolve<IEnumerable<IMaterializationStrategy>>();
            }
        }

        public IEnumerable<IAggregateMaterializationStrategy> AggregateMaterializationStrategies
        {
            get
            {
                return this.componentContext.Resolve<IEnumerable<IAggregateMaterializationStrategy>>();
            }
        }

        public TInterface Resolve<TInterface>()
        {
            return this.componentContext.Resolve<TInterface>();
        }

        public IAggregateEventStore AggregateEventStore
        {
            get
            {
                return this.componentContext.Resolve<IAggregateEventStore>();
            }
        }

        public ISnapShotStore SnapShotStore
        {
            get
            {
                return this.componentContext.Resolve<ISnapShotStore>();
            }
        }

        public ISnapshotConverter SnapshotConverter
        {
            get
            {
                return this.componentContext.Resolve<ISnapshotConverter>();
            }
        }

        public IDomainIdentityProvider DomainIdentityProvider
        {
            get
            {
                return this.componentContext.Resolve<IDomainIdentityProvider>();
            }
        }

        public IDomainMetaModel DomainMetaModel
        {
            get
            {
                return this.componentContext.Resolve<IDomainMetaModel>();
            }
        }
    }
}


text:
This module displays emails on Mirror and listens for new incoming emails. When a new email is received, the mirror is updated to display it.

![Email visualisation](https://github.com/ronny3050/email-mirror/blob/master/.github/preview.png)

## Installing the module

To install the module, just clone this repository to your __modules__ folder: `git clone https://github.com/ronny3050/email-mirror.git email`.
Then run `cd email` and `npm install` which will install the dependencies.

## Using the module

To use this module, add it to the modules array in the `config/config.js` file:
````javascript
modules: [
	{
		module: 'email',
            position: 'bottom_left',
            header: 'Email',
            config:{
                user: 'johndoe@gmail.com',
                password: 'xxx',
                host: 'imap.gmail.com',
                port: 993,
                tls: true,
                authTimeout: 10000,
                numberOfEmails: 5,
                fade: true
        },
	}
]
````

## Configuration options

The following properties can be configured:

			Option
			Description

			user
			Full email address of the user

			password
			Email password

			host
			IMAP hostname

			post
			Port that imap uses

Default value: 993

			tls
			Is TLS being used?

Possible values: true or false

Default value: true

			authTimeout
			Number of milliseconds to wait to be authenticated after a connection has been established

Default value: 10000 (10 seconds)

			numberOfEmails
			Number of emails to display at a time

Default value: 5

			fade
			Fade older emails to black. (Gradient)

Possible values: true or false

Default value: true