text:
<?php

namespace Imbc\TankopediaBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="Imbc\TankopediaBundle\Entity\Repository\ModuleRepository")
 * @ORM\Table(name="top__module")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({"engine" = "Engine", "gun" = "Gun", "radio" = "Radio", "track" = "Track", "turret" = "Turret"})
 */
abstract class Module
{
    const TYPE_ENGINE = 'engine';
    const TYPE_GUN = 'gun';
    const TYPE_RADIO = 'radio';
    const TYPE_TRACK = 'track';
    const TYPE_TURRET = 'turret';
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="name", type="string")
     */
    protected $name;

    /**
     * @ORM\ManyToOne(targetEntity="Imbc\TankopediaBundle\Entity\Tier", inversedBy="modules")
     * @ORM\JoinColumn(name="tier_id", referencedColumnName="id")
     */
    protected $tier;

    /**
     * @ORM\ManyToOne(targetEntity="Imbc\TankopediaBundle\Entity\Nationality", inversedBy="modules")
     * @ORM\JoinColumn(name="nationality_id", referencedColumnName="id")
     */
    private $nationality;

    /**
     * @ORM\Column(name="cost", type="integer")
     */
    protected $cost;

    /**
     * @ORM\Column(name="weight", type="integer")
     */
    protected $weight;

    /**
     * @ORM\ManyToMany(targetEntity="Imbc\TankopediaBundle\Entity\Tank", inversedBy="modules")
     * @ORM\JoinTable(name="top__tank_module")
     * */
    protected $tanks;

    /**
     * @Gedmo\Slug(fields={"name"})
     * @ORM\Column(length=128, unique=true)
     */
    protected $slug;

    /**
     * Constructor
     */
    public function __construct( $name = null, $tier = null, $nationality = null, $cost = null, $weight = null )
    {
        if( $name !== null ) $this->name = $name;
        if( $tier !== null ) $this->tier = $tier;
        if( $nationality !== null ) $this->nationality = $nationality;
        if( $cost !== null ) $this->cost = $cost;
        if( $weight !== null ) $this->weight = $weight;

        $this->tanks = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return \Imbc\TankopediaBundle\Entity\Module
     */
    public function setName( $name )
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set nationality
     *
     * @param \Imbc\TankopediaBundle\Entity\Nationality $nationality
     * @return \Imbc\TankopediaBundle\Entity\Module
     */
    public function setNationality( \Imbc\TankopediaBundle\Entity\Nationality $nationality = null )
    {
        $this->nationality = $nationality;

        return $this;
    }

    /**
     * Get nationality
     *
     * @return \Imbc\TankopediaBundle\Entity\Nationality
     */
    public function getNationality()
    {
        return $this->nationality;
    }

    /**
     * Set tier
     *
     * @param \Imbc\TankopediaBundle\Entity\Nationality $nationality
     * @return \Imbc\TankopediaBundle\Entity\Module
     */
    public function setTier( \Imbc\TankopediaBundle\Entity\Tier $tier )
    {
        $this->tier = $tier;

        return $this;
    }

    /**
     * Get tier
     *
     * @return \Imbc\TankopediaBundle\Entity\Tier
     */
    public function getTier()
    {
        return $this->tier;
    }

    /**
     * Set cost
     *
     * @param integer $cost
     * @return \Imbc\TankopediaBundle\Entity\Module
     */
    public function setCost( $cost )
    {
        $this->cost = $cost;

        return $this;
    }

    /**
     * Get cost
     *
     * @return integer
     */
    public function getCost()
    {
        return $this->cost;
    }

    /**
     * Set weight
     *
     * @param integer $weight
     * @return \Imbc\TankopediaBundle\Entity\Module
     */
    public function setWeight( $weight )
    {
        $this->weight = $weight;

        return $this;
    }

    /**
     * Get weight
     *
     * @return integer
     */
    public function getWeight()
    {
        return $this->weight;
    }

    /**
     * Add tanks
     *
     * @param \Imbc\TankopediaBundle\Entity\Tank $tank
     * @return \Imbc\TankopediaBundle\Entity\Module
     */
    public function addTank( \Imbc\TankopediaBundle\Entity\Tank $tank )
    {
        if( !$this->tanks->contains( $tank ) )
        {
            $this->tanks->add( $tank );
        }

        return $this;
    }

    /**
     * Remove tanks
     *
     * @param \Imbc\TankopediaBundle\Entity\Tank $tank
     */
    public function removeTank( \Imbc\TankopediaBundle\Entity\Tank $tank )
    {
        if( $this->tanks->contains( $tank ) )
        {
            $this->tanks->removeElement( $tank );
        }
    }

    /**
     * Get tanks
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTanks()
    {
        return $this->tanks;
    }

    /**
     *  Get type
     */
    abstract public function getType();

    /**
     * Get the Slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * __toString overriding method
     */
    public function __toString()
    {
        return $this->name;
    }
}


text:
"""ResNet50+ConvDet model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys

import joblib
from utils import util
from easydict import EasyDict as edict
import numpy as np
import tensorflow as tf
from nn_skeleton import ModelSkeleton

class ResNet50ConvDet(ModelSkeleton):
  def __init__(self, mc, gpu_id=0):
    with tf.device('/gpu:{}'.format(gpu_id)):
      ModelSkeleton.__init__(self, mc)

      self._add_forward_graph()
      self._add_interpretation_graph()
      self._add_loss_graph()
      self._add_train_graph()
      self._add_viz_graph()

  def _add_forward_graph(self):
    """NN architecture."""

    mc = self.mc
    if mc.LOAD_PRETRAINED_MODEL:
      assert tf.gfile.Exists(mc.PRETRAINED_MODEL_PATH), \
          'Cannot find pretrained model at the given path:' \
          '  {}'.format(mc.PRETRAINED_MODEL_PATH)
      self.caffemodel_weight = joblib.load(mc.PRETRAINED_MODEL_PATH)

    conv1 = self._conv_bn_layer(
        self.image_input, 'conv1', 'bn_conv1', 'scale_conv1', filters=64,
        size=7, stride=2, freeze=True, conv_with_bias=True)
    pool1 = self._pooling_layer(
        'pool1', conv1, size=3, stride=2, padding='VALID')

    with tf.variable_scope('conv2_x') as scope:
      with tf.variable_scope('res2a'):
        branch1 = self._conv_bn_layer(
            pool1, 'res2a_branch1', 'bn2a_branch1', 'scale2a_branch1',
            filters=256, size=1, stride=1, freeze=True, relu=False)
        branch2 = self._res_branch(
            pool1, layer_name='2a', in_filters=64, out_filters=256,
            down_sample=False, freeze=True)
        res2a = tf.nn.relu(branch1+branch2, 'relu')
      with tf.variable_scope('res2b'):
        branch2 = self._res_branch(
            res2a, layer_name='2b', in_filters=64, out_filters=256,
            down_sample=False, freeze=True)
        res2b = tf.nn.relu(res2a+branch2, 'relu')
      with tf.variable_scope('res2c'):
        branch2 = self._res_branch(
            res2b, layer_name='2c', in_filters=64, out_filters=256,
            down_sample=False, freeze=True)
        res2c = tf.nn.relu(res2b+branch2, 'relu')

    with tf.variable_scope('conv3_x') as scope:
      with tf.variable_scope('res3a'):
        branch1 = self._conv_bn_layer(
            res2c, 'res3a_branch1', 'bn3a_branch1', 'scale3a_branch1',
            filters=512, size=1, stride=2, freeze=True, relu=False)
        branch2 = self._res_branch(
            res2c, layer_name='3a', in_filters=128, out_filters=512,
            down_sample=True, freeze=True)
        res3a = tf.nn.relu(branch1+branch2, 'relu')
      with tf.variable_scope('res3b'):
        branch2 = self._res_branch(
            res3a, layer_name='3b', in_filters=128, out_filters=512,
            down_sample=False, freeze=True)
        res3b = tf.nn.relu(res3a+branch2, 'relu')
      with tf.variable_scope('res3c'):
        branch2 = self._res_branch(
            res3b, layer_name='3c', in_filters=128, out_filters=512,
            down_sample=False, freeze=True)
        res3c = tf.nn.relu(res3b+branch2, 'relu')
      with tf.variable_scope('res3d'):
        branch2 = self._res_branch(
            res3c, layer_name='3d', in_filters=128, out_filters=512,
            down_sample=False, freeze=True)
        res3d = tf.nn.relu(res3c+branch2, 'relu')

    with tf.variable_scope('conv4_x') as scope:
      with tf.variable_scope('res4a'):
        branch1 = self._conv_bn_layer(
            res3d, 'res4a_branch1', 'bn4a_branch1', 'scale4a_branch1',
            filters=1024, size=1, stride=2, relu=False)
        branch2 = self._res_branch(
            res3d, layer_name='4a', in_filters=256, out_filters=1024,
            down_sample=True)
        res4a = tf.nn.relu(branch1+branch2, 'relu')
      with tf.variable_scope('res4b'):
        branch2 = self._res_branch(
            res4a, layer_name='4b', in_filters=256, out_filters=1024,
            down_sample=False)
        res4b = tf.nn.relu(res4a+branch2, 'relu')
      with tf.variable_scope('res4c'):
        branch2 = self._res_branch(
            res4b, layer_name='4c', in_filters=256, out_filters=1024,
            down_sample=False)
        res4c = tf.nn.relu(res4b+branch2, 'relu')
      with tf.variable_scope('res4d'):
        branch2 = self._res_branch(
            res4c, layer_name='4d', in_filters=256, out_filters=1024,
            down_sample=False)
        res4d = tf.nn.relu(res4c+branch2, 'relu')
      with tf.variable_scope('res4e'):
        branch2 = self._res_branch(
            res4d, layer_name='4e', in_filters=256, out_filters=1024,
            down_sample=False)
        res4e = tf.nn.relu(res4d+branch2, 'relu')
      with tf.variable_scope('res4f'):
        branch2 = self._res_branch(
            res4e, layer_name='4f', in_filters=256, out_filters=1024,
            down_sample=False)
        res4f = tf.nn.relu(res4e+branch2, 'relu')

    dropout4 = tf.nn.dropout(res4f, self.keep_prob, name='drop4')

    num_output = mc.ANCHOR_PER_GRID * (mc.CLASSES + 1 + 4)
    self.preds = self._conv_layer(
        'conv5', dropout4, filters=num_output, size=3, stride=1,
        padding='SAME', xavier=False, relu=False, stddev=0.0001)

  def _res_branch(
      self, inputs, layer_name, in_filters, out_filters, down_sample=False,
      freeze=False):
    """Residual branch constructor.

      Args:
        inputs: input tensor
        layer_name: layer name
        in_filters: number of filters in XX_branch2a and XX_branch2b layers.
        out_filters: number of filters in XX_branch2clayers.
        donw_sample: if true, down sample the input feature map
        freeze: if true, do not change parameters in this layer
      Returns:
        A residual branch output operation.
    """
    with tf.variable_scope('res'+layer_name+'_branch2'):
      stride = 2 if down_sample else 1
      output = self._conv_bn_layer(
          inputs,
          conv_param_name='res'+layer_name+'_branch2a',
          bn_param_name='bn'+layer_name+'_branch2a',
          scale_param_name='scale'+layer_name+'_branch2a',
          filters=in_filters, size=1, stride=stride, freeze=freeze)
      output = self._conv_bn_layer(
          output,
          conv_param_name='res'+layer_name+'_branch2b',
          bn_param_name='bn'+layer_name+'_branch2b',
          scale_param_name='scale'+layer_name+'_branch2b',
          filters=in_filters, size=3, stride=1, freeze=freeze)
      output = self._conv_bn_layer(
          output,
          conv_param_name='res'+layer_name+'_branch2c',
          bn_param_name='bn'+layer_name+'_branch2c',
          scale_param_name='scale'+layer_name+'_branch2c',
          filters=out_filters, size=1, stride=1, freeze=freeze, relu=False)
      return output

redpajama_set_name: RedPajamaGithub


text:
#ifdef OLD_HEADER_FILENAME
#include <iostream.h>
#else
#include <iostream>
#endif
#include <string>

#include "H5Include.h"
#include "H5Exception.h"
#include "H5IdComponent.h"
#include "H5PropList.h"
#include "H5Object.h"
#include "H5AbstractDs.h"
#include "H5FaccProp.h"
#include "H5FcreatProp.h"
#include "H5DcreatProp.h"
#include "H5DxferProp.h"
#include "H5DataSpace.h"
#include "H5DataSet.h"
#include "H5CommonFG.h"
#include "H5Attribute.h"
#include "H5Group.h"
#include "H5File.h"
#include "H5Alltypes.h"

#ifndef H5_NO_NAMESPACE
namespace H5 {
#ifndef H5_NO_STD
    using std::cerr;
    using std::endl;
#endif  // H5_NO_STD
#endif

//--------------------------------------------------------------------------
// Function:	Group default constructor
///\brief	Default constructor: creates a stub Group.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
Group::Group() : H5Object(), id(H5I_INVALID_HID) {}

//--------------------------------------------------------------------------
// Function:	Group copy constructor
///\brief	Copy constructor: makes a copy of the original Group object.
///\param	original - IN: Original group to copy
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
Group::Group(const Group& original) : H5Object(original)
{
    id = original.getId();
    incRefCount(); // increment number of references to this id
}

//--------------------------------------------------------------------------
// Function:	Group::getLocId
///\brief	Returns the id of this group.
///\return	Id of this group
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
hid_t Group::getLocId() const
{
   return( getId() );
}

//--------------------------------------------------------------------------
// Function:	Group overloaded constructor
///\brief	Creates a Group object using the id of an existing group.
///\param	existing_id - IN: Id of an existing group
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
Group::Group(const hid_t existing_id) : H5Object()
{
    id = existing_id;
}

//--------------------------------------------------------------------------
// Function:	Group overload constructor - dereference
///\brief	Given a reference, ref, to an hdf5 group, creates a Group object
///\param	loc - IN: Specifying location referenced object is in
///\param	ref - IN: Reference pointer
///\param	ref_type - IN: Reference type - default to H5R_OBJECT
///\exception	H5::ReferenceException
///\par Description
///		\c obj can be DataSet, Group, or named DataType, that
///		is a datatype that has been named by DataType::commit.
// Programmer	Binh-Minh Ribler - Oct, 2006
//--------------------------------------------------------------------------
Group::Group(const H5Location& loc, const void* ref, H5R_type_t ref_type) : H5Object(), id(H5I_INVALID_HID)
{
    id = H5Location::p_dereference(loc.getId(), ref, ref_type, "constructor - by dereference");
}

//--------------------------------------------------------------------------
// Function:	Group overload constructor - dereference
///\brief	Given a reference, ref, to an hdf5 group, creates a Group object
///\param	attr - IN: Specifying location where the referenced object is in
///\param	ref - IN: Reference pointer
///\param	ref_type - IN: Reference type - default to H5R_OBJECT
///\exception	H5::ReferenceException
// Programmer	Binh-Minh Ribler - Oct, 2006
//--------------------------------------------------------------------------
Group::Group(const Attribute& attr, const void* ref, H5R_type_t ref_type) : H5Object(), id(H5I_INVALID_HID)
{
    id = H5Location::p_dereference(attr.getId(), ref, ref_type, "constructor - by dereference");
}

//--------------------------------------------------------------------------
// Function:    Group::getId
///\brief	Get the id of this group
///\return	Group identifier
// Modification:
//      May 2008 - BMR
//		Class hierarchy is revised to address bugzilla 1068.  Class
//		AbstractDS and Attribute are moved out of H5Object.  In
//		addition, member IdComponent::id is moved into subclasses, and
//		IdComponent::getId now becomes pure virtual function.
// Programmer   Binh-Minh Ribler - May, 2008
//--------------------------------------------------------------------------
hid_t Group::getId() const
{
   return(id);
}

#ifndef DOXYGEN_SHOULD_SKIP_THIS
//--------------------------------------------------------------------------
// Function:    Group::p_setId
///\brief       Sets the identifier of this object to a new value.
///
///\exception   H5::IdComponentException when the attempt to close the HDF5
///		object fails
// Description:
//		The underlaying reference counting in the C library ensures
//		that the current valid id of this object is properly closed.
//		Then the object's id is reset to the new id.
// Programmer   Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void Group::p_setId(const hid_t new_id)
{
    // handling references to this old id
    try {
        close();
    }
    catch (Exception close_error) {
        throw GroupIException("Group::p_setId", close_error.getDetailMsg());
    }
   // reset object's id to the given id
   id = new_id;
}
#endif // DOXYGEN_SHOULD_SKIP_THIS

//--------------------------------------------------------------------------
// Function:	Group::close
///\brief	Closes this group.
///
///\exception	H5::GroupIException
// Programmer	Binh-Minh Ribler - Mar 9, 2005
//--------------------------------------------------------------------------
void Group::close()
{
    if (p_valid_id(id))
    {
	herr_t ret_value = H5Gclose( id );
	if( ret_value < 0 )
	{
	    throw GroupIException("Group::close", "H5Gclose failed");
	}
	// reset the id
	id = H5I_INVALID_HID;
    }
}

//--------------------------------------------------------------------------
// Function:	Group::throwException
///\brief	Throws H5::GroupIException.
///\param	func_name - Name of the function where failure occurs
///\param	msg       - Message describing the failure
///\exception	H5::GroupIException
// Description
//		This function is used in CommonFG implementation so that
//		proper exception can be thrown for file or group.  The
//		argument func_name is a member of CommonFG and "Group::"
//		will be inserted to indicate the function called is an
//		implementation of Group.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void Group::throwException(const H5std_string& func_name, const H5std_string& msg) const
{
   H5std_string full_name = func_name;
   full_name.insert(0, "Group::");
   throw GroupIException(full_name, msg);
}

//--------------------------------------------------------------------------
// Function:	Group destructor
///\brief	Properly terminates access to this group.
// Programmer	Binh-Minh Ribler - 2000
// Modification
//		- Replaced resetIdComponent() with decRefCount() to use C
//		library ID reference counting mechanism - BMR, Feb 20, 2005
//		- Replaced decRefCount with close() to let the C library
//		handle the reference counting - BMR, Jun 1, 2006
//--------------------------------------------------------------------------
Group::~Group()
{
    try {
	close();
    }
    catch (Exception close_error) {
	cerr << "Group::~Group - " << close_error.getDetailMsg() << endl;
    }
}

#ifndef H5_NO_NAMESPACE
} // end namespace
#endif


text:
package Code.customClasses.DancingFinch;

import edu.cmu.ri.createlab.terk.robot.finch.Finch;
import java.awt.Color;
import java.util.Random;

/**
 * The DancingFinch is a controller for the finch which allows the finch to move to
 * a certain beat. It uses a simple state machine which stores the last motion, and
 * based on whether the finch is moving clockwise or counterclockwise, determines its
 * next motion. The finch also changes to a random color after every motion.
 *
 * The DancingFinch provides methods to check if the finch has been tapped sharply,
 * and a method which reverses the direction of the finch.
 *
 * @author Celestine Lau
 *
 */
public class DancingFinch {

	/** The current state of motion of the finch */
	private int state;
	/** The Finch object to control */
	private Finch finch;
	/** The direction the finch will "dance" in */
	private boolean clockwise;
	/** The distance the finch moves on every step, this is related to how often it
	 * has to move
	 */
	private double distance;
	/** The current color of the finch */
	private int color;

	private static Random rng = new Random();
	/* Constants defining the state of the motion */
	private static final int STOP = 0;
	private static final int STRAIGHT = 1;
	private static final int TURN_LEFT = 2;
	private static final int TURN_RIGHT = 3;
	private static final int BACK = 4;

	// Calibrates to gravity
	private double gravityOffset;

	/** The next direction to move, if the finch is moving clockwise */
	private static final int[] clockwiseTransition = new int[] {
		STRAIGHT, TURN_RIGHT, BACK, STRAIGHT, TURN_RIGHT
	};

	/** The next direction to move, if the finch is moving counterclockwise */
	private static final int[] counterclockwiseTransition = new int[] {
		BACK, TURN_LEFT, STRAIGHT, BACK, TURN_LEFT
	};

	/** The array of random colors that the finch can take on */
	private Color[] nextColor = new Color[] {
		Color.red, Color.green, Color.blue, Color.cyan, Color.magenta, Color.yellow, Color.pink, Color.white
	};

	/**
	 * Creates a new DancingFinch object
	 * @param finch The finch object
	 * @throws NullPointerException if finch is null
	 */
	public DancingFinch (Finch finch){
		this.finch = finch;
		state = STOP;
		clockwise = true;
		distance = 15;
		color = 0;
		gravityOffset = finch.getZAcceleration();
	}

	/**
	 * Causes the dancingFinch to execute its next move
	 *
	 */
	public void nextMove() {
		if (clockwise)
			state = clockwiseTransition[state];
		else
			state = counterclockwiseTransition[state];

		changeColor();
		execute(state);
	}

	/**
	 * Causes the dancingFinch to change to a different random color
	 * within the nextColor array
	 */
	private void changeColor(){
		color += rng.nextInt(nextColor.length - 1) + 1;
		if (color >= nextColor.length) color -= nextColor.length;
		finch.setLED(nextColor[color]);
	}

	/**
	 * Executes the next motion of the finch, based on the state
	 * @param state The motion to execute. This can be one of STRAIGHT, TURN_LEFT,
	 * TURN_RIGHT or BACK
	 */
	private void execute(int state) {
		switch (state) {
		case STRAIGHT:
			finch.setWheelVelocities(200,200);
			break;
		case TURN_LEFT:
			finch.setWheelVelocities(-100, 100);
			break;
		case TURN_RIGHT:
			finch.setWheelVelocities(100, -100);
			break;
		case BACK:
			finch.setWheelVelocities(-200, -200);
		default:
			break;
		}

	}

	/**
	 * Sets the array of random colors that the finch can change to
	 * @param colors The array of colors from which random colors are drawn
	 */
	public void setColors(Color[] colors){
		if (colors == null || colors.length == 0) {
			throw new IllegalArgumentException ("At least one color must be specified.");
		}
		this.nextColor = (Color[]) colors.clone();
		color = 0;
	}

	/**
	 * Sets the direction of the DancingFinch
	 * @param clockwise Set to true to make the finch go clockwise, false to make it go
	 * counterclockwise
	 */
	public void setClockwise(boolean clockwise) {
		this.clockwise = clockwise;
	}

	/**
	 * Sets the time interval (in ms) between every motion. The distance the finch will move
	 * will be determined from this value
	 * @param interval The time between each successive call of nextMove(), in milliseconds
	 */
	public void setInterval(int interval) {
		distance = 0.0075 * interval;
	}

	/**
	 * Reverses the direction of the DancingFinch
	 *
	 */
	public void reverse() {
		clockwise = !clockwise;
	}

	/**
	 * Check the z-accelerometers to determine if the user has tapped the finch
	 * @return true if the Finch has been tapped, false otherwise
	 */
	public boolean isTapped() {
		double value = ((finch.getZAcceleration()-gravityOffset));
		return value < -0.3;
	}
}


text:
<?php

namespace Navigation\Controller\Admin;

use Micro\Application\Controller\Crud;
use Micro\Form\Form;
use Navigation\Model;
use Navigation\Helper;
use Micro\Model\EntityInterface;
use Micro\Http\Response\RedirectResponse;
use Micro\Application\Utils;
use Micro\Http\Response\JsonResponse;

class Index extends Crud
{
    protected $model = Model\Menu::class;

    protected $scope = 'admin';

    /**
     * (non-PHPdoc)
     * @see \Micro\Application\Controller\Crud::postValidate()
     */
    protected function postValidate(Form $form, EntityInterface $item, array $data)
    {
        if (isset($data['alias']) && $data['alias']) {

            $m = new Model\Table\Menu();

            $where = array('alias = ?' => $data['alias']);

            if ($item->getId()) {
                $where['id <> ?'] = $item->getId();
            }

            if ($m->fetchRow($where)) {
                $form->alias->addError('Псевдонимът се използва');
                $form->markAsError();
            }
        }
    }

    public function itemsAction()
    {
        $menuId = $this->request->getParam('menuId');

        $menu = $this->getModel()->find((int) $menuId);

        if ($menu === \null) {
            return new RedirectResponse(route(\null, array('action' => 'index', 'menuId' => \null)));
        }

        if ($this->request->isPost()) {
            if ($this->request->getPost('btnAdd')) {
                return new RedirectResponse(route(\null, array('action' => 'add-item')));
            } else if ($this->request->getPost('btnBack')) {
                return new RedirectResponse(route(\null, array('action' => 'index', 'menuId' => \null)));
            }
        }

        $tree = new Helper\Tree($menu->getAlias());
        $items = $tree->getTree(\null);

        $this->view->assign('menu', $menu);
        $this->view->assign('items', $items);

    }

    public function addItemAction()
    {
        $menuId = $this->request->getParam('menuId');
        $id = $this->request->getParam('id');

        $menu = $this->getModel()->find((int) $menuId);

        if ($menu === null) {
            return new RedirectResponse(route(\null, array('action' => 'index', 'menuId' => \null)));
        }

        $model = new Model\Items();

        if ($id) {
            $item = $model->find((int) $id);
            if ($item === null) {
                return new RedirectResponse(route(\null, array('action' => 'items', 'id' => \null)));
            }
        } else {
            $item = $model->createEntity();
        }

        if ($item instanceof Model\Entity\Item) {

        }

        $form = new Form(package_path('Navigation', 'Resources/forms/admin/index-add-item.php'));

        $tree = new Helper\Tree($menu->getAlias());

        $form->parentId->setMultiOptions($tree->flat($tree->getTree(null), '---', array((int) $id)));

        $form->populate($item->toArray());

        if ($this->request->isPost()) {

            $post = $this->request->getPost();

            if (isset($post['btnBack'])) {
                return new RedirectResponse(route(\null, array('action' => 'items', 'id' => \null)));
            }

            $form->isValid($post);

            if (isset($post['alias']) && $post['alias']) {

                $m = new Model\Table\Items();

                $where = array('alias = ?' => $post['alias']);

                if ($item->getId()) {
                    $where['id <> ?'] = $item->getId();
                }

                if ($m->fetchRow($where)) {
                    $form->alias->addError('Псевдонимът се използва');
                    $form->markAsError();
                }
            }

            if (!$form->hasErrors()) {

                if (isset($post['routeData'])) {
                    $routeData = $post['routeData'];
                } else {
                    $routeData = array();
                }

                foreach ($routeData as $k => $v) {
                    if (empty($v)) {
                        unset($routeData[$k]);
                    }
                }

                $post = Utils::arrayMapRecursive('trim', $post, true);

                $item->setFromArray($post);

                $item->setMenuId($menuId);

                if ($item->getRoute() === \null) {
                    if ($item->getUrl() === \null) {
                        $item->setUrl('#');
                    }
                } else {
                    $item->setUrl(\null);
                }

                if ($item->getRoute()) {
                    if (($navigationHelper = $this->getNavigationHelper($item->getRoute())) !== \null) {
                        if (method_exists($navigationHelper, 'decode')) {
                            $navigationHelper->decode($routeData, $item);
                        }
                    }
                }

                $item->setRouteData(empty($routeData) ? \null : json_encode($routeData));

                if ($item->getOrder() === \null) {
                    if ($item->getParentId()) {
                        $and = ' AND parentId = ' . (int) $item->getParentId();
                    } else {
                        $and = ' AND parentId IS NULL';
                    }
                    $item->setOrder($model->getTable()->getAdapter()->fetchOne('SELECT IFNULL(MAX(`order`), 0) + 1 FROM MenuItems WHERE menuId = ' . (int) $menuId . $and));
                }

                try {

                    $model->save($item);

                    if (isset($post['btnApply'])) {
                        $redirectResponse = new RedirectResponse(route(\null, ['action' => 'add-item', 'id' => $item->getId()]));
                    } else {
                        $redirectResponse = new RedirectResponse(route(\null, ['action' => 'items', 'id' => \null]));
                    }

                    return $redirectResponse->withFlash('Информацията е записана');

                } catch (\Exception $e) {

                    if ($item->getId()) {
                        $redirectResponse = new RedirectResponse(route(\null, ['action' => 'add-item', 'id' => $item->getId()]));
                    } else {
                        $redirectResponse = new RedirectResponse(route(\null, ['action' => 'items', 'id' => \null]));
                    }

                    return $redirectResponse->withFlash((env('development') ? $e->getMessage() : 'Възникна грешка. Опитайте по-късно'), 'danger');
                }
            }
        }

        $this->view->assign('menu', $menu);
        $this->view->assign('item', $item);
        $this->view->assign('form', $form);
    }

    public function ajaxGetRouteDataAction()
    {
        $routeName = $this->request->getPost('route');
        $routeData = $this->request->getPost('routeData');
        $qsaData   = $this->request->getPost('qsaData');

        $routeData = $routeData ? json_decode($routeData, \true) : [];
        $routeData = is_array($routeData) ? $routeData : [];

        $route = $this->container->get('router')->getRoute($routeName);

        $route->compile();

        $navigationData = [];

        if (($navigationHelper = $this->getNavigationHelper($routeName)) !== \null) {
            if (method_exists($navigationHelper, 'resolve')) {
                $navigationData = $navigationHelper->resolve($routeData);
            }
        }

        $this->view->assign('route', $route);
        $this->view->assign('routeData', $routeData);
        $this->view->assign('qsaData', $qsaData);
        $this->view->assign('navigationData', $navigationData);
    }

    protected function getNavigationHelper($routeName)
    {
        $route = $this->container->get('router')->getRoute($routeName);

        $handler = $route->getHandler(\false);

        if (is_string($handler) && strpos($handler, '@') !== \false) {
            list($package, $action) = explode('@', $handler);
            $parts = explode('\\', $package);
            $navigationHelper = \ucfirst(Utils::camelize($parts[0])) . '\\Navigation\\' . \ucfirst(Utils::camelize($routeName));
            if (class_exists($navigationHelper, \true)) {
                $navigationHelper = new $navigationHelper($route);
                return $navigationHelper;
            }
        }

        return null;
    }

    public function deleteItemAction()
    {
        $id = $this->request->getParam('id');

        $model = new Model\Items();

        $entity = $model->find((int) $id);

        if ($entity) {
            $model->delete($entity);
        }

        return new RedirectResponse(route(\null, array('action' => 'items', 'id' => \null)));
    }

    public function ajaxSetOrderAction()
    {
        $data = $this->request->getPost('data', '[]');
        $data = json_decode($data, true);
        $data = is_array($data) ? $data : array();

        try {
            $menuItemsModel = new Model\Table\Items();
            $menuItemsModel->updateTree($data);
        } catch (\Exception $e) {
            return new JsonResponse(['success' => 0]);
        }

        return new JsonResponse(['success' => 1]);
    }
}


text:
<?php
/**
 * Created: 22.04.13 01:00
 * @author Adam Kopeć <adam.kopec@gmail.com>
 */

namespace My\WorkBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity
 */
class User extends BaseUser {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

}


text:
angular.module('metaModifier', [])
.provider('metaModifier', function($compileProvider, $rootScopeProvider, $rootElementProvider) {
  var added = {};

  this.$get = function() {
    var Meta = {};
	var head = angular.element(document.getElementsByTagName('head')[0]);

    // Used to add metadata to the head
    Meta.addMap = function(meta) {
    	head.append(processMap(meta));
    	angular.forEach(meta, function(value, key){
    		added.key = value;
    	});
    };

    // Takes a key and value and makes a meta tag
	var makeMetaTag = function(key, value) {
		return '<meta name="'+key+'" content="'+value+'">';
	};

	// Take mapped data in mappedData and
	var processMap = function(metadataMap) {
		var text = '';
		angular.forEach(metadataMap, function(value, key){
			if (added.key) return; // Don't add same one twice
			text += makeMetaTag(key, value);
		});
		return text;
	};
	return Meta;
  };
});


text:
Titanium.UI.setBackgroundImage("/images/bgImage.png");

var win = Titanium.UI.currentWindow;

var btnBack = Ti.UI.createButton({
    title: L("NavButton_back")
});

win.leftNavButton = btnBack;

btnBack.addEventListener("click", function() {
    win.remove(scrollView);
    win.close();
});

win.addEventListener("android:back", function() {
    win.remove(scrollView);
    win.close();
});

var pWidth = Ti.Platform.displayCaps.platformWidth;

var pHeight = Ti.Platform.displayCaps.platformHeight;

var win1 = Titanium.UI.createWindow({
    url: "/windows/Overlays.js",
    title: L("Overlays_win_title"),
    modal: true,
    backgroundImage: "/images/bgImage.png"
});

win1.padre = win.padre;

var addedServers = [];

Ti.App.Properties.hasProperty("addedServers") && (addedServers = Ti.App.Properties.getList("addedServers"));

if (addedServers.length > 0) {
    var xmlData = Ti.XML;
    xmlData = Titanium.XML.parseString(addedServers[win.serverIndex].describeCoverageArray[win.layerIndex]);
    var btnSend = Titanium.UI.createButton({
        title: L("WcsGetCoverage_button_title"),
        font: {
            fontSize: 18,
            fontFamily: "Helvetica Neue",
            fontWeight: "bold"
        },
        top: 10,
        right: 10,
        width: Math.round(pWidth / 4),
        height: Math.round(pHeight / 12),
        backgroundImage: "/images/button.png"
    });
    var tblGetCoverage = Titanium.UI.createTableView({
        width: pWidth - 20,
        height: pHeight - btnSend.height - 120,
        top: btnSend.top + btnSend.height + 10,
        left: 10,
        backgroundColor: "#B0C4DE",
        borderRadius: 12,
        borderColor: "#AFEEEE",
        borderWidth: 2,
        minRowHeight: 90
    });
    var sectionBoundingBox = Ti.UI.createTableViewSection({
        headerTitle: L("WcsGetCoverage_section1_title")
    });
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "boundingBox-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row1_title"),
        font: {
            fontSize: 22,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        width: "auto",
        height: 30
    });
    var descriptionRow = Titanium.UI.createLabel({
        text: xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("srsName"),
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        left: 10,
        top: 35,
        width: "auto",
        height: "auto"
    });
    row.add(titleRow);
    row.add(descriptionRow);
    sectionBoundingBox.add(row);
    var minLat = 0;
    var maxLat = 0;
    var minLon = 0;
    var maxLon = 0;
    var str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("axisLabels");
    var data = [];
    data = str.split(" ");
    if ("lat" === data[0]) {
        str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getElementsByTagName("gml:lowerCorner").item(0).textContent;
        var numbersArray = [];
        numbersArray = str.split(" ");
        minLat = parseFloat(numbersArray[0]).toFixed(6);
        minLon = parseFloat(numbersArray[1]).toFixed(6);
        str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getElementsByTagName("gml:upperCorner").item(0).textContent;
        numbersArray = [];
        numbersArray = str.split(" ");
        maxLat = parseFloat(numbersArray[0]).toFixed(6);
        maxLon = parseFloat(numbersArray[1]).toFixed(6);
    } else {
        str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getElementsByTagName("gml:lowerCorner").item(0).textContent;
        var numbersArray = [];
        numbersArray = str.split(" ");
        minLon = parseFloat(numbersArray[0]).toFixed(6);
        minLat = parseFloat(numbersArray[1]).toFixed(6);
        str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getElementsByTagName("gml:upperCorner").item(0).textContent;
        numbersArray = [];
        numbersArray = str.split(" ");
        maxLon = parseFloat(numbersArray[0]).toFixed(6);
        maxLat = parseFloat(numbersArray[1]).toFixed(6);
    }
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "boundingBox-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row2_title"),
        font: {
            fontSize: 22,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        width: "auto",
        height: 30
    });
    var descriptionRow = Titanium.UI.createLabel({
        text: minLat,
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        left: 10,
        top: 35,
        width: "auto",
        height: "auto"
    });
    row.add(titleRow);
    row.add(descriptionRow);
    sectionBoundingBox.add(row);
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "boundingBox-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row3_title"),
        font: {
            fontSize: 22,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        width: "auto",
        height: 30
    });
    var descriptionRow = Titanium.UI.createLabel({
        text: minLon,
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        left: 10,
        top: 35,
        width: "auto",
        height: "auto"
    });
    row.add(titleRow);
    row.add(descriptionRow);
    sectionBoundingBox.add(row);
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "boundingBox-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row4_title"),
        font: {
            fontSize: 22,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        width: "auto",
        height: 30
    });
    var descriptionRow = Titanium.UI.createLabel({
        text: maxLat,
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        left: 10,
        top: 35,
        width: "auto",
        height: "auto"
    });
    row.add(titleRow);
    row.add(descriptionRow);
    sectionBoundingBox.add(row);
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "boundingBox-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row5_title"),
        font: {
            fontSize: 22,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        width: "auto",
        height: 30
    });
    var descriptionRow = Titanium.UI.createLabel({
        text: maxLon,
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        left: 10,
        top: 35,
        width: "auto",
        height: "auto"
    });
    row.add(titleRow);
    row.add(descriptionRow);
    sectionBoundingBox.add(row);
    var sectionRangeSubsetting = Ti.UI.createTableViewSection({
        headerTitle: L("WcsGetCoverage_section2_title")
    });
    var rangeType = Ti.XML.Element;
    rangeType = xmlData.documentElement.getElementsByTagName("gmlcov:rangeType").item(0);
    if (null != rangeType.getElementsByTagName("swe:field")) for (var i = 0; rangeType.getElementsByTagName("swe:field").length > i; i++) {
        var row = Titanium.UI.createTableViewRow({
            hasChild: false,
            className: "bands-row"
        });
        var titleRow = Titanium.UI.createLabel({
            text: rangeType.getElementsByTagName("swe:field").item(i).getAttribute("name"),
            font: {
                fontSize: 22,
                fontWeight: "bold"
            },
            color: "#000",
            left: 10,
            top: 30,
            width: "auto",
            height: 30
        });
        var iconImage = Titanium.UI.createImageView({
            image: "/images/check.png",
            width: 48,
            height: 48,
            right: 10,
            top: 20,
            visible: true
        });
        row.add(titleRow);
        row.add(iconImage);
        row.addEventListener("click", function(e) {
            e.row.children[1].visible = !e.row.children[1].visible;
        });
        sectionRangeSubsetting.add(row);
    }
    var sectionImageSize = Ti.UI.createTableViewSection({
        headerTitle: L("WcsGetCoverage_section3_title")
    });
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "imageSize-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row6_title"),
        font: {
            fontSize: 24,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        height: 30,
        width: row.width
    });
    var txtWidth = Ti.UI.createTextField({
        keyboardType: Titanium.UI.KEYBOARD_NUMBER_PAD,
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        backgroundColor: "#B0C4DE",
        left: 0,
        top: 35,
        width: row.width,
        height: 55,
        hintText: L("WcsGetCoverage_row6_hintText")
    });
    row.add(titleRow);
    row.add(txtWidth);
    sectionImageSize.add(row);
    var row = Titanium.UI.createTableViewRow({
        hasChild: false,
        className: "imageSize-row"
    });
    var titleRow = Titanium.UI.createLabel({
        text: L("WcsGetCoverage_row7_title"),
        font: {
            fontSize: 24,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 5,
        height: 30,
        width: row.width
    });
    var txtHeight = Ti.UI.createTextField({
        keyboardType: Titanium.UI.KEYBOARD_NUMBER_PAD,
        font: {
            fontSize: 20,
            fontWeight: "normal"
        },
        color: "#fff",
        backgroundColor: "#B0C4DE",
        left: 0,
        top: 35,
        width: row.width,
        height: 55,
        hintText: L("WcsGetCoverage_row7_hintText")
    });
    row.add(titleRow);
    row.add(txtHeight);
    sectionImageSize.add(row);
    tblGetCoverage.data = [ sectionBoundingBox, sectionRangeSubsetting, sectionImageSize ];
    var scrollView = Titanium.UI.createScrollView({
        top: 0,
        contentHeight: "auto",
        showVerticalScrollIndicator: true
    });
    var totalRows = 0;
    for (var i = 0; tblGetCoverage.data.length > i; i++) totalRows += tblGetCoverage.data[i].rowCount;
    tblGetCoverage.height = 90 * totalRows + 90;
    scrollView.add(btnSend);
    scrollView.add(tblGetCoverage);
    win.add(scrollView);
    btnSend.addEventListener("touchstart", function() {
        btnSend.backgroundImage = "/images/button_focused.png";
    });
    btnSend.addEventListener("touchend", function() {
        btnSend.backgroundImage = "/images/button.png";
    });
    btnSend.addEventListener("click", function() {
        if (0 >= txtWidth.value || 0 >= txtHeight.value) alert(L("WcsGetCoverage_ErrorMessage")); else {
            var indicatorStyle;
            indicatorStyle = Ti.UI.ActivityIndicatorStyle.DARK;
            var actInd = Ti.UI.createActivityIndicator({
                color: "black",
                font: {
                    fontFamily: "Helvetica Neue",
                    fontSize: 26,
                    fontWeight: "bold"
                },
                message: "Loading data...",
                style: indicatorStyle,
                height: Ti.UI.SIZE,
                width: Ti.UI.SIZE
            });
            win.add(actInd);
            actInd.show();
            var coverageId = xmlData.documentElement.getElementsByTagName("wcs:CoverageId").item(0).textContent;
            var coverageCrs = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("srsName");
            var colorsBands = [];
            var strBandsRequest = "";
            for (var i = 0; tblGetCoverage.data[1].rowCount > i; i++) if (true == tblGetCoverage.data[1].rows[i].children[1].visible) {
                colorsBands.push(tblGetCoverage.data[1].rows[i].children[0].text);
                strBandsRequest += tblGetCoverage.data[1].rows[i].children[0].text + ",";
            }
            strBandsRequest = strBandsRequest.substr(0, strBandsRequest.length - 1);
            strBandsRequest.length > 0 && (strBandsRequest = "&rangesubset=" + strBandsRequest);
            1 == colorsBands.length && (strBandsRequest += "," + colorsBands[0]);
            var strRequest = "";
            strRequest = addedServers[win.serverIndex].url;
            strRequest += "?service=wcs&version=2.0.0";
            strRequest += "&request=GetCoverage";
            strRequest += "&coverageid=" + coverageId;
            strRequest += "&size=long(" + txtWidth.value + ")";
            strRequest += "&size=lat(" + txtHeight.value + ")";
            strRequest += "&format=image/png";
            strRequest += strBandsRequest;
            strRequest += "&outputcrs=" + coverageCrs;
            var xhr = Titanium.Network.createHTTPClient();
            xhr.onload = function() {
                var strImageData = Ti.Utils.base64encode(this.responseData);
                actInd.setMessage(L("WcsGetCoverage_message"));
                var mapLayers = [];
                void 0 != Ti.App.mapLayers && (mapLayers = Ti.App.mapLayers);
                var newLayer = {
                    layerId: coverageId,
                    serverName: addedServers[win.serverIndex].name,
                    serverUrl: addedServers[win.serverIndex].url,
                    visible: true,
                    opacity: 1,
                    crs: coverageCrs,
                    minLat: minLat,
                    minLon: minLon,
                    maxLat: maxLat,
                    maxLon: maxLon,
                    strImage: strImageData,
                    imgWidth: txtWidth.value,
                    imgHeight: txtHeight.value,
                    bands: colorsBands,
                    serverIndex: win.serverIndex,
                    layerIndex: win.layerIndex
                };
                mapLayers.push(newLayer);
                Ti.App.mapLayers = mapLayers;
                actInd.hide();
                true == Ti.App.isAndroid ? win1.open() : win.padre.openWindow(win1);
            };
            xhr.onerror = function() {
                Ti.API.error("ERROR: " + this.status + " - " + this.statusText);
                alert("ERROR\n\n" + this.status + " - " + this.statusText);
            };
            xhr.open("GET", strRequest);
            xhr.send();
        }
    });
}


text:
import itertools

import numpy
import six

import chainer
from chainer import cuda
from chainer.functions.activation import sigmoid
from chainer.functions.activation import tanh
from chainer.functions.array import concat
from chainer.functions.array import reshape
from chainer.functions.array import split_axis
from chainer.functions.array import stack
from chainer.functions.connection import linear
from chainer.functions.connection import n_step_rnn
from chainer.functions.connection.n_step_rnn import get_random_state
from chainer.functions.noise import dropout
from chainer.utils import argument

if cuda.cudnn_enabled:
    cudnn = cuda.cudnn
    libcudnn = cuda.cudnn.cudnn
    _cudnn_version = libcudnn.getVersion()

class NStepGRU(n_step_rnn.BaseNStepRNN):

    def __init__(self, n_layers, states, **kwargs):
        n_step_rnn.BaseNStepRNN.__init__(
            self, n_layers, states, rnn_dir='uni', rnn_mode='gru', **kwargs)

class NStepBiGRU(n_step_rnn.BaseNStepRNN):

    def __init__(self, n_layers, states, **kwargs):
        n_step_rnn.BaseNStepRNN.__init__(
            self, n_layers, states, rnn_dir='bi', rnn_mode='gru', **kwargs)

def n_step_gru(
        n_layers, dropout_ratio, hx, ws, bs, xs, **kwargs):
    """n_step_gru(n_layers, dropout_ratio, hx, ws, bs, xs)

    Stacked Uni-directional Gated Recurrent Unit function.

    This function calculates stacked Uni-directional GRU with sequences.
    This function gets an initial hidden state :math:`h_0`, an input
    sequence :math:`x`, weight matrices :math:`W`, and bias vectors :math:`b`.
    This function calculates hidden states :math:`h_t` for each time :math:`t`
    from input :math:`x_t`.

    .. math::
       r_t &= \\sigma(W_0 x_t + W_3 h_{t-1} + b_0 + b_3) \\\\
       z_t &= \\sigma(W_1 x_t + W_4 h_{t-1} + b_1 + b_4) \\\\
       h'_t &= \\tanh(W_2 x_t + b_2 + r_t \\cdot (W_5 h_{t-1} + b_5)) \\\\
       h_t &= (1 - z_t) \\cdot h'_t + z_t \\cdot h_{t-1}

    As the function accepts a sequence, it calculates :math:`h_t` for all
    :math:`t` with one call. Six weight matrices and six bias vectors are
    required for each layers. So, when :math:`S` layers exists, you need to
    prepare :math:`6S` weigth matrices and :math:`6S` bias vectors.

    If the number of layers ``n_layers`` is greather than :math:`1`, input
    of ``k``-th layer is hidden state ``h_t`` of ``k-1``-th layer.
    Note that all input variables except first layer may have different shape
    from the first layer.

    .. warning::

       ``train`` and ``use_cudnn`` arguments are not supported anymore since
       v2.
       Instead, use ``chainer.using_config('train', train)`` and
       ``chainer.using_config('use_cudnn', use_cudnn)`` respectively.
       See :func:`chainer.using_config`.

    Args:
        n_layers(int): Number of layers.
        dropout_ratio(float): Dropout ratio.
        hx (chainer.Variable): Variable holding stacked hidden states.
            Its shape is ``(S, B, N)`` where ``S`` is number of layers and is
            equal to ``n_layers``, ``B`` is mini-batch size, and ``N`` is
            dimention of hidden units.
        ws (list of list of chainer.Variable): Weight matrices. ``ws[i]``
            represents weights for i-th layer.
            Each ``ws[i]`` is a list containing six matrices.
            ``ws[i][j]`` is corresponding with ``W_j`` in the equation.
            Only ``ws[0][j]`` where ``0 <= j < 3`` is ``(I, N)`` shape as they
            are multiplied with input variables. All other matrices has
            ``(N, N)`` shape.
        bs (list of list of chainer.Variable): Bias vectors. ``bs[i]``
            represnents biases for i-th layer.
            Each ``bs[i]`` is a list containing six vectors.
            ``bs[i][j]`` is corresponding with ``b_j`` in the equation.
            Shape of each matrix is ``(N,)`` where ``N`` is dimention of
            hidden units.
        xs (list of chainer.Variable): A list of :class:`~chainer.Variable`
            holding input values. Each element ``xs[t]`` holds input value
            for time ``t``. Its shape is ``(B_t, I)``, where ``B_t`` is
            mini-batch size for time ``t``, and ``I`` is size of input units.
            Note that this functions supports variable length sequences.
            When sequneces has different lengths, sort sequences in descending
            order by length, and transpose the sorted sequence.
            :func:`~chainer.functions.transpose_sequence` transpose a list
            of :func:`~chainer.Variable` holding sequence.
            So ``xs`` needs to satisfy
            ``xs[t].shape[0] >= xs[t + 1].shape[0]``.

    Returns:
        tuple: This functions returns a tuple concaining three elements,
            ``hy`` and ``ys``.

            - ``hy`` is an updated hidden states whose shape is same as ``hx``.
            - ``ys`` is a list of :class:`~chainer.Variable` . Each element
              ``ys[t]`` holds hidden states of the last layer corresponding
              to an input ``xs[t]``. Its shape is ``(B_t, N)`` where ``B_t`` is
              mini-batch size for time ``t``, and ``N`` is size of hidden
              units. Note that ``B_t`` is the same value as ``xs[t]``.

    """

    return n_step_gru_base(n_layers, dropout_ratio, hx, ws, bs, xs,
                           use_bi_direction=False, **kwargs)

def n_step_bigru(
        n_layers, dropout_ratio, hx, ws, bs, xs, **kwargs):
    """n_step_bigru(n_layers, dropout_ratio, hx, ws, bs, xs)

    Stacked Bi-directional Gated Recurrent Unit function.

    This function calculates stacked Bi-directional GRU with sequences.
    This function gets an initial hidden state :math:`h_0`, an input
    sequence :math:`x`, weight matrices :math:`W`, and bias vectors :math:`b`.
    This function calculates hidden states :math:`h_t` for each time :math:`t`
    from input :math:`x_t`.

    .. math::
       r^{f}_t &= \\sigma(W^{f}_0 x_t + W^{f}_3 h_{t-1} + b^{f}_0 + b^{f}_3)
       \\\\
       z^{f}_t &= \\sigma(W^{f}_1 x_t + W^{f}_4 h_{t-1} + b^{f}_1 + b^{f}_4)
       \\\\
       h^{f'}_t &= \\tanh(W^{f}_2 x_t + b^{f}_2 + r^{f}_t \\cdot (W^{f}_5
       h_{t-1} + b^{f}_5)) \\\\
       h^{f}_t &= (1 - z^{f}_t) \\cdot h^{f'}_t + z^{f}_t \\cdot h_{t-1}
       \\\\
       r^{b}_t &= \\sigma(W^{b}_0 x_t + W^{b}_3 h_{t-1} + b^{b}_0 + b^{b}_3)
       \\\\
       z^{b}_t &= \\sigma(W^{b}_1 x_t + W^{b}_4 h_{t-1} + b^{b}_1 + b^{b}_4)
       \\\\
       h^{b'}_t &= \\tanh(W^{b}_2 x_t + b^{b}_2 + r^{b}_t \\cdot (W^{b}_5
       h_{t-1} + b^{b}_5)) \\\\
       h^{b}_t &= (1 - z^{b}_t) \\cdot h^{b'}_t + z^{b}_t \\cdot h_{t-1}
       \\\\
       h_t  &= [h^{f}_t; h^{f}_t] \\\\

    where :math:`W^{f}` is weight matrices for forward-GRU, :math:`W^{b}` is
    weight matrices for backward-GRU.

    As the function accepts a sequence, it calculates :math:`h_t` for all
    :math:`t` with one call. Six weight matrices and six bias vectors are
    required for each layers. So, when :math:`S` layers exists, you need to
    prepare :math:`6S` weigth matrices and :math:`6S` bias vectors.

    If the number of layers ``n_layers`` is greather than :math:`1`, input
    of ``k``-th layer is hidden state ``h_t`` of ``k-1``-th layer.
    Note that all input variables except first layer may have different shape
    from the first layer.

    .. warning::

       ``train`` and ``use_cudnn`` arguments are not supported anymore since
       v2.
       Instead, use ``chainer.using_config('train', train)`` and
       ``chainer.using_config('use_cudnn', use_cudnn)`` respectively.
       See :func:`chainer.using_config`.

    Args:
        n_layers(int): Number of layers.
        dropout_ratio(float): Dropout ratio.
        hx (chainer.Variable): Variable holding stacked hidden states.
            Its shape is ``(S, B, N)`` where ``S`` is number of layers and is
            equal to ``n_layers``, ``B`` is mini-batch size, and ``N`` is
            dimention of hidden units.
        ws (list of list of chainer.Variable): Weight matrices. ``ws[i]``
            represents weights for i-th layer.
            Each ``ws[i]`` is a list containing six matrices.
            ``ws[i][j]`` is corresponding with ``W_j`` in the equation.
            Only ``ws[0][j]`` where ``0 <= j < 3`` is ``(I, N)`` shape as they
            are multiplied with input variables. All other matrices has
            ``(N, N)`` shape.
        bs (list of list of chainer.Variable): Bias vectors. ``bs[i]``
            represnents biases for i-th layer.
            Each ``bs[i]`` is a list containing six vectors.
            ``bs[i][j]`` is corresponding with ``b_j`` in the equation.
            Shape of each matrix is ``(N,)`` where ``N`` is dimention of
            hidden units.
        xs (list of chainer.Variable): A list of :class:`~chainer.Variable`
            holding input values. Each element ``xs[t]`` holds input value
            for time ``t``. Its shape is ``(B_t, I)``, where ``B_t`` is
            mini-batch size for time ``t``, and ``I`` is size of input units.
            Note that this functions supports variable length sequences.
            When sequneces has different lengths, sort sequences in descending
            order by length, and transpose the sorted sequence.
            :func:`~chainer.functions.transpose_sequence` transpose a list
            of :func:`~chainer.Variable` holding sequence.
            So ``xs`` needs to satisfy
            ``xs[t].shape[0] >= xs[t + 1].shape[0]``.
        use_bi_direction (bool): If ``True``, this function uses
            Bi-direction GRU.

    Returns:
        tuple: This functions returns a tuple concaining three elements,
            ``hy`` and ``ys``.

            - ``hy`` is an updated hidden states whose shape is same as ``hx``.
            - ``ys`` is a list of :class:`~chainer.Variable` . Each element
              ``ys[t]`` holds hidden states of the last layer corresponding
              to an input ``xs[t]``. Its shape is ``(B_t, N)`` where ``B_t`` is
              mini-batch size for time ``t``, and ``N`` is size of hidden
              units. Note that ``B_t`` is the same value as ``xs[t]``.

    """

    return n_step_gru_base(n_layers, dropout_ratio, hx, ws, bs, xs,
                           use_bi_direction=True, **kwargs)

def n_step_gru_base(n_layers, dropout_ratio, hx, ws, bs, xs,
                    use_bi_direction, **kwargs):
    """n_step_gru_base(n_layers, dropout_ratio, hx, ws, bs, xs, use_bi_direction)

    Base function for Stack GRU/BiGRU functions.

    This function is used at  :func:`chainer.functions.n_step_bigru` and
    :func:`chainer.functions.n_step_gru`.
    This function's behavior depends on argument ``use_bi_direction``.

    .. warning::

       ``train`` and ``use_cudnn`` arguments are not supported anymore since
       v2.
       Instead, use ``chainer.using_config('train', train)`` and
       ``chainer.using_config('use_cudnn', use_cudnn)`` respectively.
       See :func:`chainer.using_config`.

    Args:
        n_layers(int): Number of layers.
        dropout_ratio(float): Dropout ratio.
        hx (chainer.Variable): Variable holding stacked hidden states.
            Its shape is ``(S, B, N)`` where ``S`` is number of layers and is
            equal to ``n_layers``, ``B`` is mini-batch size, and ``N`` is
            dimention of hidden units.
        ws (list of list of chainer.Variable): Weight matrices. ``ws[i]``
            represents weights for i-th layer.
            Each ``ws[i]`` is a list containing six matrices.
            ``ws[i][j]`` is corresponding with ``W_j`` in the equation.
            Only ``ws[0][j]`` where ``0 <= j < 3`` is ``(I, N)`` shape as they
            are multiplied with input variables. All other matrices has
            ``(N, N)`` shape.
        bs (list of list of chainer.Variable): Bias vectors. ``bs[i]``
            represnents biases for i-th layer.
            Each ``bs[i]`` is a list containing six vectors.
            ``bs[i][j]`` is corresponding with ``b_j`` in the equation.
            Shape of each matrix is ``(N,)`` where ``N`` is dimention of
            hidden units.
        xs (list of chainer.Variable): A list of :class:`~chainer.Variable`
            holding input values. Each element ``xs[t]`` holds input value
            for time ``t``. Its shape is ``(B_t, I)``, where ``B_t`` is
            mini-batch size for time ``t``, and ``I`` is size of input units.
            Note that this functions supports variable length sequences.
            When sequneces has different lengths, sort sequences in descending
            order by length, and transpose the sorted sequence.
            :func:`~chainer.functions.transpose_sequence` transpose a list
            of :func:`~chainer.Variable` holding sequence.
            So ``xs`` needs to satisfy
            ``xs[t].shape[0] >= xs[t + 1].shape[0]``.
        activation (str): Activation function name.
            Please select ``tanh`` or ``relu``.
        use_bi_direction (bool): If ``True``, this function uses
            Bi-direction GRU.

    .. seealso::
       :func:`chainer.functions.n_step_rnn`
       :func:`chainer.functions.n_step_birnn`

    """  # NOQA
    argument.check_unexpected_kwargs(
        kwargs, train='train argument is not supported anymore. '
        'Use chainer.using_config',
        use_cudnn='use_cudnn argument is not supported anymore. '
        'Use chainer.using_config')
    argument.assert_kwargs_empty(kwargs)

    xp = cuda.get_array_module(hx, hx.data)

    if xp is not numpy and chainer.should_use_cudnn('>=auto', 5000):
        states = get_random_state().create_dropout_states(dropout_ratio)
        # flatten all input variables
        inputs = tuple(itertools.chain(
            (hx, ),
            itertools.chain.from_iterable(ws),
            itertools.chain.from_iterable(bs),
            xs))
        if use_bi_direction:
            rnn = NStepBiGRU(n_layers, states)
        else:
            rnn = NStepGRU(n_layers, states)

        ret = rnn(*inputs)
        hy, = ret[:1]
        ys = ret[1:]
        return hy, ys

    else:
        direction = 2 if use_bi_direction else 1
        hx = split_axis.split_axis(hx, n_layers * direction, axis=0,
                                   force_tuple=True)
        hx = [reshape.reshape(h, h.shape[1:]) for h in hx]

        xws = [concat.concat([w[0], w[1], w[2]], axis=0) for w in ws]
        hws = [concat.concat([w[3], w[4], w[5]], axis=0) for w in ws]
        xbs = [concat.concat([b[0], b[1], b[2]], axis=0) for b in bs]
        hbs = [concat.concat([b[3], b[4], b[5]], axis=0) for b in bs]

        xs_next = xs
        hy = []
        for layer in six.moves.range(n_layers):

            def _one_directional_loop(di):
                # di=0, forward GRU
                # di=1, backward GRU
                xs_list = xs_next if di == 0 else reversed(xs_next)
                layer_idx = direction * layer + di
                h = hx[layer_idx]
                h_list = []
                for x in xs_list:
                    batch = x.shape[0]
                    if h.shape[0] > batch:
                        h, h_rest = split_axis.split_axis(h, [batch], axis=0)
                    else:
                        h_rest = None

                    if layer > 0:
                        x = dropout.dropout(x, ratio=dropout_ratio)

                    gru_x = linear.linear(x, xws[layer_idx], xbs[layer_idx])
                    gru_h = linear.linear(h, hws[layer_idx], hbs[layer_idx])

                    W_r_x, W_z_x, W_x = split_axis.split_axis(gru_x, 3, axis=1)
                    U_r_h, U_z_h, U_x = split_axis.split_axis(gru_h, 3, axis=1)

                    r = sigmoid.sigmoid(W_r_x + U_r_h)
                    z = sigmoid.sigmoid(W_z_x + U_z_h)
                    h_bar = tanh.tanh(W_x + r * U_x)
                    h_bar = (1 - z) * h_bar + z * h
                    if h_rest is not None:
                        h = concat.concat([h_bar, h_rest], axis=0)
                    else:
                        h = h_bar
                    h_list.append(h_bar)
                return h, h_list

            # Forward GRU
            h, h_forward = _one_directional_loop(di=0)
            hy.append(h)

            if use_bi_direction:
                # Backward GRU
                h, h_backward = _one_directional_loop(di=1)
                h_backward.reverse()
                # Concat
                xs_next = [concat.concat([hfi, hbi], axis=1) for (hfi, hbi) in
                           six.moves.zip(h_forward, h_backward)]
                hy.append(h)
            else:
                # Uni-directional GRU
                xs_next = h_forward

        ys = xs_next
        hy = stack.stack(hy)
        return hy, tuple(ys)


text:
namespace iroha {
namespace opt {
namespace sched {

BBWirePlan::BBWirePlan(BBDataPath *dp) : dp_(dp) {
}

BBWirePlan::~BBWirePlan() {
}

void BBWirePlan::Save() {
  auto &nodes = dp_->GetNodes();
  for (auto p : nodes) {
    PathNode *pn = p.second;
    st_indexes_[pn] = pn->GetFinalStIndex();
  }
}

void BBWirePlan::Restore() {
  for (auto p : st_indexes_) {
    PathNode *pn = p.first;
    int index = p.second;
    pn->SetFinalStIndex(index);
  }
}

BBDataPath *BBWirePlan::GetBBDataPath() {
  return dp_;
}

map<PathNode *, int> &BBWirePlan::GetStIndexes() {
  return st_indexes_;
}

}  // namespace sched
}  // namespace opt
}  // namespace iroha


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity repository-class="RequestKeeperBundle\Repository\RequestRepository" name="RequestKeeperBundle\Entity\Request">

    <indexes>
      <index columns="route" />
      <index columns="method" />
      <index columns="ip" />
      <index columns="created" />
    </indexes>

    <id name="id" type="integer" column="id">
      <generator strategy="AUTO"/>
    </id>

    <field name="route" type="string" column="route" length="255"/>
    <field name="method" type="string" column="method" length="20"/>
    <field name="ip" type="string" column="ip" length="50"/>
    <field name="created" type="datetime" column="created"/>

    <one-to-one field="requestData" target-entity="RequestKeeperBundle\Entity\RequestData">
      <cascade>
        <cascade-persist/>
      </cascade>
      <join-column name="id" referenced-column-name="id"  />
    </one-to-one>

  </entity>
</doctrine-mapping>


text:
AUI.add('aui-media-gallery-plugin', function(A) {
/**
 * The ImageGallery Media Plugin
 *
 * @module 'aui-media-gallery-plugin
 */

var Lang = A.Lang,
	Do = A.Do,

	NAME = 'mediaGalleryPlugin';

var MediaGalleryPlugin = function(config) {
	var instance = this;

    MediaGalleryPlugin.superclass.constructor.apply(instance, arguments);
};

MediaGalleryPlugin.NAME = NAME;
MediaGalleryPlugin.NS = 'media';

A.extend(MediaGalleryPlugin, A.MediaViewerPlugin, {
	initializer: function(config) {
		var instance = this;

		var handles = instance._handles;

		handles['show'].detach();

		handles['_changeRequest'] = instance.beforeHostMethod('_changeRequest', instance._changeRequest);

		handles['_changeRequest'] = instance.beforeHostMethod('_changeRequest', instance._loadImage);
	}
});

A.MediaGalleryPlugin = MediaGalleryPlugin;

A.MediaGallery = A.ImageGallery;

}, '@VERSION@' ,{skinnable:false, requires:['aui-media-viewer-plugin','aui-image-viewer-gallery']});


text:
#include "HeatDemoBenchmark.h"
#include "DemoBenchmark.h"
#include "HeatDemoCPU.h"
#include "HeatDemoSingleGPU.h"
#include "HeatDemoMultiGPU.h"
#include "SequentialScheduler.h"
#include "AsyncScheduler.h"
#include "ThreadScheduler.h"
#include "DemoBenchmark.h"
#include "CudaUtilities.h"

const int device = 0;

void heat_demo_benchmark()
{
	cudaSetDevice(device);
	CUDA::check("cudaSetDevice");
	HeatDemoSingleGPU demo;
	string name = "Single-CUDA";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_gpu;
	run(demo, bench);
}

void heat_multi_demo_benchmark()
{
	HeatDemoMultiGPU demo;
	demo.unset_opengl();
	string name = "Multi-CUDA";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_gpu;
	run(demo, bench);
}

void heat_multi_demo_benchmark_seq()
{
	HeatDemoMultiGPU demo;
	demo.unset_opengl();
	demo.set_scheduler(new SequentialScheduler<CudaPartition>());
	string name = "Multi-CUDA-Seq";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_gpu;
	run(demo, bench);
}

void heat_multi_demo_benchmark_async()
{
	HeatDemoMultiGPU demo;
	demo.unset_opengl();
	demo.set_scheduler(new AsyncScheduler<CudaPartition>());
	string name = "Multi-CUDA-Async";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_gpu;
	run(demo, bench);
}

void heat_multi_demo_benchmark_threads()
{
	HeatDemoMultiGPU demo;
	demo.unset_opengl();
	demo.set_scheduler(new ThreadScheduler<CudaPartition>());
	string name = "Multi-CUDA-Threads";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_gpu;
	run(demo, bench);
}

void heat_demo_benchmark_cpu()
{
	HeatDemoCPU demo;
	demo.unset_opengl();
	demo.set_parallel(false);
	string name = "Single-CPU";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_cpu / 5;
	run(demo, bench);
}

void heat_multi_demo_benchmark_cpu()
{
	HeatDemoCPU demo;
	demo.unset_opengl();
	demo.set_parallel(true);
	string name = "Multi-CPU-Async";
	DemoBenchmark bench{ demo, name };
	bench.iterations = benchmark_iterations_cpu;
	run(demo, bench);
}

void heat_multi_single_vs_multi()
{
	bool is_first = true;
	string name_s = "single GPU";
	string name_m = "multi GPU async";

	vector<int> sizes;
	for (int i = 1; i < 30; i++)
	{
		sizes.push_back(i * 1024);
	}

	for (auto& sz : sizes)
	{
		cudaSetDevice(device);
		CUDA::check("cudaSetDevice");

		try
		{
			HeatDemoSingleGPU demo_s;
			stringstream str_s;
			str_s << name_s << ";" << sz;
			DemoBenchmark bench_s{ demo_s, str_s.str(), sz, sz };
			bench_s.iterations = benchmark_iterations_gpu;
			bench_s.print_header = is_first;
			bench_s.save_results = false;
			run(demo_s, bench_s);
		}
		catch (std::exception & e)
		{
		}

		is_first = false;

		try
		{
			HeatDemoMultiGPU demo_m;
			demo_m.unset_opengl();
			demo_m.set_scheduler(new AsyncScheduler<CudaPartition>());
			stringstream str_m;
			str_m << name_m << ";" << sz;
			DemoBenchmark bench_m{ demo_m, str_m.str(), sz, sz };
			bench_m.iterations = benchmark_iterations_gpu;
			bench_m.print_header = is_first;
			bench_m.save_results = false;
			run(demo_m, bench_m);
		}
		catch (std::exception & e)
		{
		}
	}

}

void run_demo(IDemo& demo, vector<int>& sizes)
{
	bool is_first = true;
	for (auto& sz : sizes)
	{
		try
		{
			DemoBenchmark bench{ demo, "???", sz, sz };
			bench.iterations = benchmark_iterations_gpu;
			bench.print_header = is_first;
			bench.save_results = false;
			run(demo, bench);
		}
		catch (std::exception & e)
		{
			cerr << "ERROR " << e.what() << endl;
		}
		is_first = false;
	}
}


text:
package com.github.twitch4j.helix.domain;

import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.twitch4j.eventsub.domain.Reward;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.With;
import lombok.experimental.Accessors;
import lombok.experimental.SuperBuilder;
import lombok.extern.jackson.Jacksonized;
import org.jetbrains.annotations.Nullable;

import java.time.Instant;

@Data
@With
@Builder(toBuilder = true)
@Setter(AccessLevel.PRIVATE)
@NoArgsConstructor
@AllArgsConstructor
@Jacksonized
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CustomReward {

    /**
     * ID of the channel the reward is for.
     */
    private String broadcasterId;

    /**
     * Login of the channel the reward is for.
     */
    private String broadcasterLogin;

    /**
     * Display name of the channel the reward is for.
     */
    private String broadcasterName;

    /**
     * ID of the reward.
     */
    private String id;

    /**
     * The title of the reward.
     */
    private String title;

    /**
     * The prompt for the viewer when they are redeeming the reward.
     */
    private String prompt;

    /**
     * The cost of the reward.
     */
    private Integer cost;

    /**
     * Set of custom images of 1x, 2x and 4x sizes for the reward.
     * Can be null if no images have been uploaded.
     */
    @Nullable
    private Reward.Image image;

    /**
     * Set of default images of 1x, 2x and 4x sizes for the reward
     */
    private Reward.Image defaultImage;

    /**
     * Whether the reward currently enabled; if false the reward won't show up to viewers.
     * Default: true.
     */
    @Accessors(fluent = true)
    @JsonProperty("is_enabled")
    private Boolean isEnabled;

    /**
     * Custom background color for the reward.
     * <p>
     * Format: Hex with {@literal #} prefix, ideally in ALL CAPS.
     */
    private String backgroundColor;

    /**
     * Does the user need to enter information when redeeming the reward.
     * Default: false.
     */
    @Accessors(fluent = true)
    @JsonProperty("is_user_input_required")
    private Boolean isUserInputRequired;

    /**
     * Whether a maximum per stream is enabled and what the maximum is.
     */
    private MaxPerStreamSetting maxPerStreamSetting;

    /**
     * Whether a maximum per user per stream is enabled and what the maximum is.
     */
    private MaxPerUserPerStreamSetting maxPerUserPerStreamSetting;

    /**
     * Whether a cooldown is enabled and what the cooldown is.
     */
    private GlobalCooldownSetting globalCooldownSetting;

    /**
     * Whether the reward is currently paused; if true viewers can't redeem.
     */
    @Accessors(fluent = true)
    @JsonProperty("is_paused")
    private Boolean isPaused;

    /**
     * Whether the reward is currently in stock; if false viewers can't redeem.
     */
    @Accessors(fluent = true)
    @JsonProperty("is_in_stock")
    private Boolean isInStock;

    /**
     * Whether redemptions should be set to FULFILLED status immediately when redeemed and skip the request queue instead of the normal UNFULFILLED status.
     */
    private Boolean shouldRedemptionsSkipRequestQueue;

    /**
     * The number of redemptions redeemed during the current live stream.
     * Counts against the max_per_stream_setting limit.
     * Null if the broadcasters stream isn't live or max_per_stream_setting isn't enabled.
     */
    @Nullable
    private Integer redemptionsRedeemedCurrentStream;

    /**
     * Timestamp of the cooldown expiration.
     * Null if the reward isn't on cooldown.
     */
    @Nullable
    private Instant cooldownExpiresAt;

    @Data
    @Setter(AccessLevel.PRIVATE)
    @NoArgsConstructor
    @AllArgsConstructor(access = AccessLevel.PRIVATE)
    @SuperBuilder(toBuilder = true)
    @Jacksonized
    @EqualsAndHashCode(callSuper = false)
    public static class MaxPerStreamSetting extends Setting {

        @Getter(onMethod_ = { @JsonIgnore })
        @Accessors(fluent = true)
        @JsonAlias("is_enabled")
        @JsonProperty("is_max_per_stream_enabled")
        private Boolean isEnabled;

        private Integer maxPerStream;

    }

    @Data
    @Setter(AccessLevel.PRIVATE)
    @NoArgsConstructor
    @AllArgsConstructor(access = AccessLevel.PRIVATE)
    @SuperBuilder(toBuilder = true)
    @Jacksonized
    @EqualsAndHashCode(callSuper = false)
    public static class MaxPerUserPerStreamSetting extends Setting {

        @Getter(onMethod_ = { @JsonIgnore })
        @Accessors(fluent = true)
        @JsonAlias("is_enabled")
        @JsonProperty("is_max_per_user_per_stream_enabled")
        private Boolean isEnabled;

        private Integer maxPerUserPerStream;

    }

    @Data
    @Setter(AccessLevel.PRIVATE)
    @NoArgsConstructor
    @AllArgsConstructor(access = AccessLevel.PRIVATE)
    @SuperBuilder(toBuilder = true)
    @Jacksonized
    @EqualsAndHashCode(callSuper = false)
    public static class GlobalCooldownSetting extends Setting {

        @Getter(onMethod_ = { @JsonIgnore })
        @Accessors(fluent = true)
        @JsonAlias("is_enabled")
        @JsonProperty("is_global_cooldown_enabled")
        private Boolean isEnabled;

        private Integer globalCooldownSeconds;

    }

    @NoArgsConstructor
    @SuperBuilder(toBuilder = true)
    public static abstract class Setting {
        abstract Boolean isEnabled();
    }

}


text:
package com.amazonaws.services.greengrass.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum LoggerComponent {

    GreengrassSystem("GreengrassSystem"),
    Lambda("Lambda");

    private String value;

    private LoggerComponent(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return LoggerComponent corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static LoggerComponent fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (LoggerComponent enumEntry : LoggerComponent.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
<?php
/* @var Concrete\Attribute\Address\Controller $controller */
/* @var Concrete\Core\Form\Service\Form $form */
/* @var array $scopeItems */
/* @var Concrete\Core\Attribute\View $view */

$app = Concrete\Core\Support\Facade\Application::getFacadeApplication();
$co = $app->make('helper/lists/countries');
$countries = $co->getCountries();
foreach (array_keys($countries) as $countryID) {
    if (empty($countryID) || empty($countries[$countryID])) {
        unset($countries[$countryID]);
    }
}
if (isset($_POST['akHasCustomCountries'])) {
    $akHasCustomCountries = $_POST['akHasCustomCountries'];
} elseif (!isset($akHasCustomCountries)) {
    $akHasCustomCountries = 0;
}
if (!isset($akDefaultCountry)) {
    $akDefaultCountry = '';
}
if ($akHasCustomCountries) {
    if (isset($_POST['akCustomCountries'])) {
        $akCustomCountries = $_POST['akCustomCountries'];
    }
    if (empty($akCustomCountries) || !is_array($akCustomCountries)) {
        $akCustomCountries = array();
    }
} else {
    $akCustomCountries = array_keys($countries);
}
?>
<fieldset class="ccm-attribute ccm-attribute-address">
    <legend><?=t('Address Options')?></legend>

        <?= $form->label('', t('Available Countries')) ?>

            <?= $form->radio('akHasCustomCountries', 0, $akHasCustomCountries) ?>
            <?= t('All Available Countries') ?>

            <?= $form->radio('akHasCustomCountries', 1, $akHasCustomCountries) ?>
            <?= t('Selected Countries') ?>

        <?= $form->selectMultiple('akCustomCountries', $countries, $akCustomCountries, ['size' => 7]) ?>

        <?= $form->label('akDefaultCountry', t('Default Country')) ?>
        <?= $form->select('akDefaultCountry', array_merge(['' => t('Choose Country')], $countries), $akDefaultCountry) ?>

        <?= $form->label('', t('Geolocation')) ?>

            <?= $form->checkbox('akGeolocateCountry', 1, isset($akGeolocateCountry) ? $akGeolocateCountry : false) ?>
            <?= t('Suggest the Country from the user IP address') ?>

</fieldset>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-project</artifactId>
    <version>9.2.5.v20141112</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>jetty-nosql</artifactId>
  <name>Jetty :: NoSQL Session Managers</name>
  <url>http://www.eclipse.org/jetty</url>
  <properties>
    <bundle-symbolic-name>${project.groupId}.nosql</bundle-symbolic-name>
  </properties>
  <build>
    <defaultGoal>install</defaultGoal>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptorRefs>
                <descriptorRef>config</descriptorRef>
              </descriptorRefs>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <configuration>
          <instructions>
            <Import-Package>javax.servlet.*;version="[2.6.0,3.2)",org.eclipse.jetty.server.session.jmx;version="9.1";resolution:=optional,,org.eclipse.jetty.*;version="9.1",*</Import-Package>
          </instructions>
        </configuration>
        <extensions>true</extensions>
        <executions>
          <execution>
            <goals>
              <goal>manifest</goal>
            </goals>
           </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <id>artifact-jar</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <archive>
            <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-server</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty.toolchain</groupId>
      <artifactId>jetty-test-helper</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-jmx</artifactId>
      <version>${project.version}</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>2.6.1</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty.tests</groupId>
      <artifactId>test-sessions-common</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
using PingYourPackage.API.Model.Dtos;
using PingYourPackage.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PingYourPackage.API.Model {

    internal static class ShipmentExtensions {

        internal static ShipmentDto ToShipmentDto(this Shipment shipment) {

            return new ShipmentDto {
                Key = shipment.Key,
                AffiliateKey = shipment.AffiliateKey,
                Price = shipment.Price,
                ReceiverName = shipment.ReceiverName,
                ReceiverSurname = shipment.ReceiverSurname,
                ReceiverAddress = shipment.ReceiverAddress,
                ReceiverZipCode = shipment.ReceiverZipCode,
                ReceiverCity = shipment.ReceiverCity,
                ReceiverCountry = shipment.ReceiverCountry,
                ReceiverTelephone = shipment.ReceiverTelephone,
                ReceiverEmail = shipment.ReceiverEmail,
                CreatedOn = shipment.CreatedOn,
                ShipmentType = shipment.ShipmentType.ToShipmentTypeDto(),
                ShipmentStates = shipment.ShipmentStates.Select(ss => ss.ToShipmentStateDto())
            };
        }
    }
}


text:
package com.padepokan79.controller;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.json.JSONArray;

import com.padepokan79.model.Convertor;
import com.padepokan79.model.MdJabatanTbl;
import com.padepokan79.util.DatabaseConnection;

public class MdJabatanTblController extends DatabaseConnection implements MdJabatanTbl{
public MdJabatanTblController(){

	}
	public JSONArray queryMenghapusJabatan(String query, String inputKode){
		try
		{

			PreparedStatement st = (PreparedStatement) conn.prepareStatement(query);
			st.setString(1, inputKode);

			st.executeUpdate();

//			ResultSet rs = (ResultSet) st.executeQuery();
//			return Convertor.convertToJSON(rs);

		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	public JSONArray queryMenambahkanJabatan(String query, String inputKode, String inputGapok, String j, int a, int b, int c, String i){
		try
		{

			PreparedStatement st = (PreparedStatement) conn.prepareStatement(query);
			st.setString(1, inputKode);
			st.setString(2, inputGapok);
			st.setString(3, j);
			st.setInt(4, a);
			st.setInt(5, b);
			st.setInt(6, c);
			st.setString(7, i);

			st.executeUpdate();

//			ResultSet rs = (ResultSet) st.executeQuery();
//			return Convertor.convertToJSON(rs);

		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public JSONArray queryMengeditJabatan(String query, String a, String i){
		try
		{

			PreparedStatement st = (PreparedStatement) conn.prepareStatement(query);

			st.setString(1, i);
			st.setString(2, a);

			st.executeUpdate();

		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	public JSONArray mencariJabatan (String query, String kode) throws SQLException {
		PreparedStatement st = null;
		try
		{
			st = (PreparedStatement) conn.prepareStatement(query);

			st.setString(1, kode);

			ResultSet rs = (ResultSet) st.executeQuery();
			JSONArray result=Convertor.convertToJSON(rs);
			//rs=null;

			if(st!=null) {
				st.close();
			}

		return result;
		}catch(Exception e){

		}
		return null;
	}

	public JSONArray queryMenampilkanTabelJabatan(String query) throws SQLException{
PreparedStatement st = null;

		try
		{
			st=(PreparedStatement) conn.prepareStatement(query);
			// execute the query, and get a java resultset
			//for insert, update, delete
			//st.executeUpdate();
			ResultSet rs = (ResultSet) st.executeQuery();
			JSONArray result=Convertor.convertToJSON(rs);
			//rs=null;

			if(st!=null) {
				st.close();
			}

		return result;
		}catch(Exception e){

		}
		return null;
	}
	public JSONArray getMenambahJabatan(String inputKode, String input, String i, int a, int b, int c, String j){
		try
		{
			String query = menambahData;
			return queryMenambahkanJabatan(query, inputKode, input, i, a, b, c, j);
		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
//	public JSONArray getMencariBUlan(int inputKode){
//		try
//		{
//			String query = mencariBulan;
//			return mencariBulan(query, inputKode);
//		}catch (Exception e) {
//			// TODO: handle exception
//		}
//		return null;
//	}
	public JSONArray getMenampilkanTabelJabatan(){
		try
		{
			String query = menampilkanJabatan;
			return queryMenampilkanTabelJabatan(query);
		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	public JSONArray getMengeditJabatan(String kode, String param){
		try
		{
			String query = mengubahJabatan;
			return queryMengeditJabatan(query, kode, param);
		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	public JSONArray getMenghapusJabatan(String inputKode){
		try
		{
			String query = menghapusData;
			return queryMenghapusJabatan(query, inputKode);
		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public JSONArray getmencariJabatan(String kode){
		try
		{
			String query = mencariData;
			return mencariJabatan(query, kode);
		}catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}


text:
/* Makes the group title take up the full width. */
.vis-labelset .vis-label .vis-inner {
  display: block;
}

/*
  Makes items labels display fully even if time range is too small
  to contain it
*/
.vis-item .vis-item-overflow {
  overflow: visible;
  cursor: pointer;
}

.group-title {
  font-weight: bold;
  padding: 5px;
}

/*
  Limit the group step title width to 50em, otherwise the items may
  be pushed off the right side of the screen and be inaccessible.
*/
.group-title > .title {
  display: inline-block;
  white-space: nowrap;
  max-width: 50em;
  overflow: hidden;
  text-overflow: ellipsis;
}

/*
  TODO(dburger): these status styles could come from default.css but are
  apparently overridden by styles from .vis-item. This could likely be
  fixed by tweaking the style in default.css to get higher specificity.

  In the following the second selector with the "a" tag
  takes care of a specificity problem where jquery's
  .ui-widget-content a {color: #333;} ends up winning for a tags nested in
  a div with one of the following classes as is done on the "Results"
  time list that gets the .ui-widget-content from being inside jquery
  tabs on the timeline page.
*/
.status-EXPIRED, .status-EXPIRED a {
  color: #FFFFFF;
  background-color: #ac39ac;
  border-color: #ACA0B3;
}

.status-EXCEPTION, .status-EXCEPTION a {
  color: #FFFFFF;
  background-color: #c6c;
  border-color: #ACA0B3;
}

.status-INFRA_FAILURE, .status-INFRA_FAILURE a {
  color: #FFFFFF;
  background-color: #c6c;
  border-color: #ACA0B3;
}

.status-WARNING, .status-WARNING a {
  color: #FFFFFF;
  background-color: #fa3;
  border-color: #C29D46;
}

.status-NOT_RUN, .status-NOT_RUN a {
  color: #000;
  background-color: #ccc;
  border-color: #ccc;
}

.status-RUNNING, .status-RUNNING a {
  color: #000;
  background-color: #fd3;
  border-color: #C5C56D;
}

.status-FAILURE, .status-FAILURE a {
  color: #000;
  background-color: #e88;
  border-color: #A77272;
  border-style: solid;
}

.status-CANCELED, .status-CANCELED a {
  color: #000;
  background-color: #8ef;
  border-color: #00d8fc;
  border-style: solid;
}

.status-SUCCESS, .status-SUCCESS a {
  color: #000;
  background-color: #8d4;
  border-color: #4F8530;
}

/*
  Positioned absolutely so that the timeline renders directly over it
  and does not jump when we remove this from the page.
*/
#timeline-rendering {
  position: absolute;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia melanothrix Vain.

### Remarks
null