text:
require 'puppet/util/cli_execution'
require 'puppet/util/cli_parser'
require 'puppet/util/path_generator'

Puppet::Type.type(:jboss_batch).provide(:cli) do
  include Puppet::Util::CliExecution
  extend  Puppet::Util::CliExecution

  def self.prefetch(resources)
    cached_results = {}
    parser = CliParser.new

    resources.each { |name, resource|
      # don't try to prefetch if noop
      unless resource[:noop]

        # set up attributes of the 'is' provider resource
        is_resource_attributes = {:name => name, :batch => []}

        # dump the root resrouce and cache it
        if cached_results[resource[:server]].nil?
          cached_results[resource[:server]] = execute_cli get_server(resource), format_command('/', 'read-resource', {:recursive => true}), false
        end

        # determine the current state of each batch element and add it to the current 'is' provider resource attributes
        resource[:batch].each { |batch_element|
          # if batch elment is a resource
          # else if batch element is a command
          # else error
          if batch_element.has_key?('address')
            # get the current value of for the given address
            path     = parser.parse_path(batch_element['address'])
            is_value = PathGenerator.root_dump_position(path, cached_results[resource[:server]]['result'])

            # create hash of current resource status
            is_batch_element = { 'address' => batch_element['address'] }
            if is_value
              is_batch_element['ensure']  = "present"
              is_batch_element['options'] = is_value
            else
              is_batch_element['ensure']  = "absent"
            end

            is_resource_attributes[:batch].push(is_batch_element)
          elsif batch_element.has_key?('command')
            # the current state of a command is that it has not been run
            is_resource_attributes[:batch].push({ 'command' => batch_element['command'], 'ensure' => :absent})
          else
            # this error condition should have already been caught by now but throw it here just in case
            raise "Element of the batch is not recognized as a command or a resource, must specify either 'address' or 'command' respectivly: #{batch_element.inspect}"
          end
        }

        # set the 'is' provider for the given resource
        Puppet.debug "jboss_batch[name=#{name}: is_resource_attributes: #{is_resource_attributes.inspect}"
        resource.provider = new(is_resource_attributes)
      end
    }
  end

  def initialize(value={})
    super(value)
    @new_values = {}
  end

  def batch
    @property_hash[:batch]
  end

  def batch=(value)
    @new_values[:batch] = value
  end

  def flush
    tries = self.resource[:tries]
    try_sleep = self.resource[:try_sleep]

    output = nil
    last_error = nil

    # attempt CLI batch for each try
    tries.times do |try|
      begin
        # Only add debug messages for tries > 1 to reduce log spam.
        debug("Exec try #{try+1}/#{tries}") if tries > 1

        # run the batch
        output = execute_batch(@property_hash[:batch], @new_values[:batch])

        # break the try loop if batch was a success
        break if (resource[:expected_output].to_a - output.to_a).empty?

        # sleep before next attempt
        if try_sleep > 0 and tries > 1
          debug("Sleeping for #{try_sleep} seconds between tries")
          sleep try_sleep
        end
      rescue => e
        last_error = e
      end
    end

    if (!output)
      self.fail("Error executing CLI batch `#{resource[:title]}`: #{last_error}")
    end

    # determine if the execution was a success
    success = (resource[:expected_output].to_a - output.to_a).empty?

    # log output if required
    if (resource[:logoutput] == :true || (!success && resource[:logoutput] == :on_failure))
      self.send(@resource[:loglevel], output.inspect)
    end

    # fail if CLI batch failed
    if !success
      self.fail("Error executing CLI batch `#{resource[:title]}`: #{output['failure-description']}")
    end
  end

  # execute a batch based on the current and desired state
  #
  # current_batch_elements - the current state of the batch
  # new_batch_elements     - the desired state of the batch
  def execute_batch current_batch_elements, new_batch_elements

    # NOTE: really this should never happen, but let's be safe
    raise Puppet::Error, "jboss_batch - cli - execute_batch: new_batch_elements must have same number of elements as current_batch_elements" unless new_batch_elements.length == current_batch_elements.length

    # format all of the batches individual commands
    formated_commands = []
    current_batch_elements.zip(new_batch_elements).each do |current_batch_element, new_batch_element|

      # protect against the current and new batches getting out of order
      # NOTE: really this should never happen, but let's be safe
      unless (new_batch_element['address'] == current_batch_element['address'] &&
             new_batch_element['command'] == current_batch_element['command'])

        raise Puppet::Error, "jboss_batch - cli - execute_batch: Current Batch order out of sync with New batch order"
      end

      # if batch elment is a resource
      # else if batch element is a command
      # else error
      if new_batch_element.has_key?('address')

        # if the resource currently exists
        # else if the resource does not currently exist
        if current_batch_element['ensure'].to_sym == :present

          # if ensure the options on the existing resource are set correctly
          # else if ensure the resource does not exist
          if new_batch_element.has_key?('options') && ((new_batch_element['ensure'] || :present).to_sym == :present)

            current_resource_options = current_batch_element['options']
            new_resource_options = new_batch_element['options']

            # determine attributes that need to be undefined
            undefines = new_resource_options.select{ |key, value| value == 'undefined' && current_resource_options[key]}.collect{ |key, value| key}

            # determine attributes who's values have changed
            changes = new_resource_options.to_a - current_resource_options.to_a

            # create formated commands
            formated_attribute_commands = changes.collect { |attribute, value|
              format_command new_batch_element['address'], 'write-attribute', {'name' => attribute, 'value' => value}
            }
            formated_attribute_commands += undefines.collect { |attribute|
              format_command new_batch_element['address'], 'undefine-attribute', {'name' => attribute}
            }

            formated_commands.push(formated_attribute_commands)
          elsif new_batch_element['ensure'].to_sym == :absent
            # remove the resource
            formated_command = format_command(new_batch_element['address'], 'remove')
            formated_commands.push(formated_command)
          end
        else
          # if ensure the resource exists
          # else ensure the resource does not exist
          if ((new_batch_element['ensure'] || :present).to_sym == :present)
            # add the resource with all specified options
            formated_command = format_command(new_batch_element['address'], 'add', new_batch_element['options'])
            formated_commands.push(formated_command)
          end
        end
      elsif new_batch_element.has_key?('command')
        # if command has option
        # else command has no options
        if new_batch_element.has_key?('options')
          parser = CliParser.new
          parsed_command = parser.parse_command new_batch_element['command']
          formated_command = format_command PathGenerator.format_path(parsed_command[0]), parsed_command[1], new_batch_element['options']
          formated_commands.push(formated_command)
        else
          formated_commands.push(new_batch_element['command'])
        end
      else
        # this error condition should have already been caught by now but throw it here just in case
        raise "Element of the batch is not recognized as a command or a resource, must specify either 'address' or 'command' respectivly: #{new_batch_element.inspect}"
      end
    end

    # execute all the commands as a batch
    formated_commands.reject! { |formated_command| formated_command.empty? }

    # execute all of the formated commands
    execute_cli get_server(resource), formated_commands, false, true
  end

  # executes a single command
  def execute_command command, arguments = nil
    # don't try to execute a command if noop
    unless resource[:noop]
      if arguments
        parser = CliParser.new
        parsed_command = parser.parse_command command
        command = format_command PathGenerator.format_path(parsed_command[0]), parsed_command[1], arguments
      end
      execute_cli get_server(resource), command, false
    end
  end
end


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ru.igarin.base.provider"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

</manifest>

redpajama_set_name: RedPajamaGithub


text:
package com.taoswork.tallycheck.datadomain.tallybiz.work;

import com.taoswork.tallycheck.general.extension.utils.IFriendlyEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Gao Yuan on 2015/4/16.
 */
public enum WorkTicketStatus  implements IFriendlyEnum<String> {
    New("new", "new"),
    Working("working","working"),
    Closed("closed","closed"),
    Finished("finished","finished");

    private final String type;
    private final String friendlyType;

    private static final Map<String, WorkTicketStatus> typeToEnum = new HashMap<String, WorkTicketStatus>();

    static {
        for (WorkTicketStatus _enum : values()) {
            typeToEnum.put(_enum.type, _enum);
        }
    }

    WorkTicketStatus(String type, String friendlyType) {
        this.type = type;
        this.friendlyType = friendlyType;
    }

    public static WorkTicketStatus fromType(String character) {
        return typeToEnum.get(character);
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getFriendlyType() {
        return friendlyType;
    }
}


text:
<?php

namespace Nodrew\Bundle\DfpBundle\Model;

/**
 * @package     NodrewDfpBundle
 * @author      Drew Butler <hi@dbtlr.com>
 * @copyright   (c) 2012 Drew Butler
 * @license     http://www.opensource.org/licenses/mit-license.php
 */
class AdUnit extends TargetContainer
{
    protected $path;
    protected $sizes;
    protected $divId;
    protected $targets = array();

    /**
     * @param string $path
     * @param array|null $sizes
     * @param array $targets
     */
    public function __construct($path, $sizes=null, array $targets = array())
    {
        $this->setPath($path);
        $this->setSizes($sizes);
        $this->setTargets($targets);

        $this->buildDivId();
    }

    /**
     * Build the divId.
     */
    public function buildDivId()
    {
        $this->divId = 'dfp-'.spl_object_hash($this);
    }

    /**
     * Output the DFP code for this ad unit
     *
     * @param Nodrew\Bundle\DfpBundle\Model\Settings $settings
     * @return string
     */
    public function output(Settings $settings)
    {
        $class  = $settings->getDivClass();
        $style  = $this->getStyles();

        return <<< RETURN

<div id="{$this->divId}" class="{$class}" style="$style">
<script type="text/javascript">
googletag.cmd.push(function() { googletag.display('{$this->divId}'); });
</script>
</div>
RETURN;
    }

    protected function getStyles()
    {
        if ($this->getSizes() == null) {
            return 'width: 0; height: 0; position: absolute; bottom: 0;';
        }

        $width  = $this->getLargestWidth();
        $height = $this->getLargestHeight();

        return "width:{$width}px; height:{$height}px;";
    }

    /**
     * Get the largest width in the sizes.
     *
     * @return int
     */
    public function getLargestWidth()
    {
        if ($this->sizes === null) {
            return 0;
        }

        $largest = 0;
        foreach ($this->sizes as $size) {
            if ($size[0] > $largest) {
                $largest = $size[0];
            }
        }

        return $largest;
    }

    /**
     * Get the largest height in the sizes.
     *
     * @return int
     */
    public function getLargestHeight()
    {
        if ($this->sizes === null) {
            return 0;
        }

        $largest = 0;
        foreach ($this->sizes as $size) {
            if ($size[1] > $largest) {
                $largest = $size[1];
            }
        }

        return $largest;
    }

    /**
     * Fix the given sizes, if possible, so that they will match the internal array needs.
     *
     * @throws Nodrew\Bundle\DfpBundle\Model\AdSizeException
     * @param array|null$sizes
     * @return array|null
     */
    protected function fixSizes($sizes)
    {
        if ($sizes === null) {
            return;
        }

        if (count($sizes) == 0) {
            throw new AdSizeException('The size cannot be an empty array. It should be given as an array with a width and height. ie: array(800,600).');
        }

        if ($this->checkSize($sizes)) {
            return array($sizes);
        }

        foreach ($sizes as $size) {
            if (!$this->checkSize($size)) {
                throw new AdSizeException(sprintf('Cannot take the size: %s as a parameter. A size should be an array giving a width and a height. ie: array(800,600).', printf($size, true)));
            }
        }

        return $sizes;
    }

    /**
     * Check that the given size has is an array with two numeric elements.
     */
    protected function checkSize($size)
    {
        if (is_array($size) && count($size) == 2 && isset($size[0]) && is_numeric($size[0]) && isset($size[1]) && is_numeric($size[1])) {
            return true;
        }

        return false;
    }

    /**
     * Get the path.
     *
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

    /**
     * Get the path.
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Get the sizes.
     *
     * @throws Nodrew\Bundle\DfpBundle\Model\AdSizeException
     * @param array $sizes
     */
    public function setSizes($sizes)
    {
        $this->sizes = $this->fixSizes($sizes);
    }

    /**
     * Get the sizes.
     *
     * @return array
     */
    public function getSizes()
    {
        return $this->sizes;
    }

    /**
     * Get the divId.
     *
     * @param string $divId
     */
    public function setDivId($divId)
    {
        $this->divId = $divId;
    }

    /**
     * Get the divId.
     *
     * @return string
     */
    public function getDivId()
    {
        return $this->divId;
    }
}


text:
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');
const expectedFiles = require('./utils/expected-files');

describe('JHipster generator common', () => {
    before(done => {
        helpers
            .run(require.resolve('../generators/common'))
            .inTmpDir(dir => {
                fse.copySync(path.join(__dirname, '../test/templates/default'), dir);
            })
            .withOptions({
                fromCli: true,
                skipInstall: true,
                skipChecks: true,
            })
            .on('end', done);
    });

    it('creates common files', () => {
        assert.file(expectedFiles.common);
    });
});


text:
package scalan.compilation.lms.common

import java.util.HashMap

import scala.lms.common._
import scala.reflect.SourceContext
import scalan.compilation.lms.cxx.sharedptr.CxxShptrGenHashMapOps

trait HashMapOpsExt extends HashMapOps with IterableOps {
  def hashmap_keys_array[K:Manifest,V:Manifest](m: Rep[HashMap[K,V]])(implicit pos: SourceContext): Rep[Array[K]] = {
    iterable_toarray( hashmap_keys(m) )
  }
}

trait HashMapOpsExpExt extends HashMapOpsExp {
  case class HashMapKeysArray[K:Manifest,V:Manifest](m: Exp[HashMap[K,V]]) extends HashMapDef[K,V,Array[K]]

  def hashmap_keys_array[K:Manifest,V:Manifest](m: Rep[HashMap[K,V]])(implicit pos: SourceContext): Rep[Array[K]] = {
    HashMapKeysArray(m)
  }

  override def mirrorDef[A:Manifest](e: Def[A], f: Transformer)(implicit pos: SourceContext): Def[A] = {
    (e match {
      case HashMapKeysArray(m) =>
        HashMapKeysArray(f(m))
      case _ =>
        super.mirrorDef(e,f)
    }).asInstanceOf[Def[A]]
  }

  override def mirror[A:Manifest](e: Def[A], f: Transformer)(implicit pos: SourceContext): Exp[A] =
    (e match {
      case Reflect(HashMapKeysArray(m), u, es) => reflectMirrored(Reflect(HashMapKeysArray(f(m)), mapOver(f,u), f(es)))(mtype(manifest[A]), pos)
      case _ =>
        super.mirror(e,f)
    }).asInstanceOf[Exp[A]]

}

trait CxxShptrGenHashMapOpsExt extends CxxShptrGenHashMapOps {
  val IR: HashMapOpsExpExt

  import IR._

  override def emitNode(sym: Sym[Any], rhs: Def[Any]) = rhs match {
    case HashMapKeysArray(m) =>
      emitValDef(sym, src"std::make_shared<${remap(sym.tp)}>($m->size())")
      val value_type = src"${remap(m.tp)}::value_type"
      val key_type = src"${remap(m.tp)}::key_type"
      gen"""auto ${sym}_tran = [=]($value_type& p) -> $key_type { return p.first; };
         |std::transform($m->begin(), $m->end(), $sym->begin(), ${sym}_tran);"""
    case _ => super.emitNode(sym, rhs)
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Example: Custom Shape</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
    <link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

Example: Custom Shape

This example shows how to use the Graphics to create a custom shape. Currently, the Graphics module has four shapes:

rect

circle

ellipse

path

You can also create your own custom shapes. If you need to have reusable shapes, you can do this by extending the Shape class. Once you have created a custom class, you can instantiate it by passing
a reference of your class in the type attribute of your config to the addShape method. In this example, we will create shape called RoundedRect.

HTML

<div id="mygraphiccontainer"></div>

CSS

#mygraphiccontainer {
    position: relative;
    width: 400px;
    height: 300px;
}

JavaScript

Create a custom class. When creating shapes, add a method called _draw. This is where you will put your drawing logic for the custom shape. You will also need to mix in any attributes that you need.

var RoundedRect = function()
{
    RoundedRect.superclass.constructor.apply(this, arguments);
}
RoundedRect.NAME = "roundedRect";
Y.extend(RoundedRect, Y.Shape, {
    _draw: function()
    {
        var w = this.get("width"),
            h = this.get("height"),
            ew = this.get("ellipseWidth"),
            eh = this.get("ellipseHeight");
        this.clear();
        this.moveTo(0, eh);
        this.lineTo(0, h - eh);
        this.quadraticCurveTo(0, h, ew, h);
        this.lineTo(w - ew, h);
        this.quadraticCurveTo(w, h, w, h - eh);
        this.lineTo(w, eh);
        this.quadraticCurveTo(w, 0, w - ew, 0);
        this.lineTo(ew, 0);
        this.quadraticCurveTo(0, 0, 0, eh);
        this.end();
    }
}, {
    ATTRS: Y.mix({
        ellipseWidth: {
            value: 4
        },

        ellipseHeight: {
            value: 4
        }
    }, Y.Shape.ATTRS)
});
Y.RoundedRect = RoundedRect;

Create a Graphic instance and render it to an HTMLElement

var mygraphic = new Y.Graphic({render: "#mygraphiccontainer"}),

Using the addShape method, add an instance of the custom class to the Graphic instance.

myroundrect = mygraphic.addShape({
    type: Y.RoundedRect,
    width: 300,
    height: 200,
    x: 50,
    y: 50,
    ellipseWidth: 12,
    ellipseHeight: 12,
    fill: {
        type: "linear",
        stops: [
            {color: "#9aa9bb", offset: 0},
            {color: "#eeefff", offset: 0.4},
            {color: "#00000f", offset: 0.8},
            {color: "#9aa9bb", offset: 1}
        ],
        rotation: 45
    },
    stroke: {
        weight: 2,
        color: "#000"
    }
});

Complete Example Source

<div id="mygraphiccontainer"></div>
<script>
YUI({filter:"raw"}).use('graphics', function (Y)
{
    var RoundedRect = function()
    {
        RoundedRect.superclass.constructor.apply(this, arguments);
    }
    RoundedRect.NAME = "roundedRect";
    Y.extend(RoundedRect, Y.Shape, {
        _draw: function()
        {
            var w = this.get("width"),
                h = this.get("height"),
                ew = this.get("ellipseWidth"),
                eh = this.get("ellipseHeight");
            this.clear();
            this.moveTo(0, eh);
            this.lineTo(0, h - eh);
            this.quadraticCurveTo(0, h, ew, h);
            this.lineTo(w - ew, h);
            this.quadraticCurveTo(w, h, w, h - eh);
            this.lineTo(w, eh);
            this.quadraticCurveTo(w, 0, w - ew, 0);
            this.lineTo(ew, 0);
            this.quadraticCurveTo(0, 0, 0, eh);
            this.end();
        }
    }, {
        ATTRS: Y.mix({
            ellipseWidth: {
                value: 4
            },

            ellipseHeight: {
                value: 4
            }
        }, Y.Shape.ATTRS)
    });
    Y.RoundedRect = RoundedRect;

    var mygraphic = new Y.Graphic({render: "#mygraphiccontainer"}),
        myroundrect = mygraphic.addShape({
            type: Y.RoundedRect,
            width: 300,
            height: 200,
            x: 50,
            y: 50,
            ellipseWidth: 12,
            ellipseHeight: 12,
            fill: {
                type: "linear",
                stops: [
                    {color: "#9aa9bb", offset: 0},
                    {color: "#eeefff", offset: 0.4},
                    {color: "#00000f", offset: 0.8},
                    {color: "#9aa9bb", offset: 1}
                ],
                rotation: 45
            },
            stroke: {
                weight: 2,
                color: "#000"
            }
        });
    });
</script>

Examples

                                            Basic Graphics Implementation

                                            Basic Path

                                            Create Gradient Fills

                                            Basic drag with graphic object

                                            Using Transforms

                                            Custom Shape

                                            Transparent Glass with Shadow

                                            Complex Drawing: Violin

Examples That Use This Component

                                            Animating Along a Curved Path


text:
<?php

namespace Blog\Entity;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\ORM\Mapping\PrePersist;

/**
 * Comment entity
 *
 * @Entity
 * @HasLifecycleCallbacks
 */
class Comment
{
	/**
	* @var int
	*
	* @Id
	* @Column(type="integer")
    * @GeneratedValue
	*/
	protected $id;

	/**
	* @var text
	*
	* @Column(type="text")
	*/
	protected $body;

	/**
	* @var \DateTime
	*
	* @Column(type="datetime")
	*/
	protected $publicationDate;

	/**
	* @var Post
	*
	* @ManyToOne(targetEntity="Post", inversedBy="comments")
	*/
	protected $post;

    /**
    * @var commentAuthor
    *
    * @ManyToOne(targetEntity="CommentAuthor", inversedBy="comments")
    */
    protected $commentAuthor;

    /**
     * Set id
     *
     * @param integer $id
     * @return Comment
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

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

    /**
     * Set body
     *
     * @param string $body
     * @return Comment
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

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

    /**
     * Set publicationDate
     *
     * @param \DateTime $publicationDate
     * @return Comment
     */
    public function setPublicationDate($publicationDate)
    {
        $this->publicationDate = $publicationDate;

        return $this;
    }

    /**
     * Get publicationDate
     *
     * @return \DateTime
     */
    public function getPublicationDate()
    {
        return $this->publicationDate;
    }

    /**
     * Set post
     *
     * @param \Blog\Entity\Post $post
     * @return Comment
     */
    public function setPost(\Blog\Entity\Post $post = null)
    {
        $this->post = $post;

        return $this;
    }

    /**
     * Get post
     *
     * @return \Blog\Entity\Post
     */
    public function getPost()
    {
        return $this->post;
    }

    /**
    * Set commentAuthor
    *
    * @param string $commentAuthor
    * @return Comment
    */
    public function setAuthor($commentAuthor)
    {
        $this->commentAuthor = $commentAuthor;

        return $this;
    }

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

    /**
    * Sets publication date to now at persist time
    *
    * @PrePersist
    */
    public function setPublicationDateOnPrePersist()
    {
        if (!$this->publicationDate)
        {
            $this->publicationDate = new \DateTime();
        }
    }

    /**
     * Set commentAuthor
     *
     * @param \Blog\Entity\CommentAuthor $commentAuthor
     * @return Comment
     */
    public function setCommentAuthor(\Blog\Entity\CommentAuthor $commentAuthor = null)
    {
        $this->commentAuthor = $commentAuthor;

        return $this;
    }

    /**
     * Get commentAuthor
     *
     * @return \Blog\Entity\CommentAuthor
     */
    public function getCommentAuthor()
    {
        return $this->commentAuthor;
    }
}


text:
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

def directional_lighting(light, normals, light_intensity=0.5, light_color=(1,1,1),
                         light_direction=(0,1,0)):
    # normals: [nb, :, 3]

    device = light.device

    if isinstance(light_color, tuple) or isinstance(light_color, list):
        light_color = torch.tensor(light_color, dtype=torch.float32, device=device)
    elif isinstance(light_color, np.ndarray):
        light_color = torch.from_numpy(light_color).float().to(device)
    if isinstance(light_direction, tuple) or isinstance(light_direction, list):
        light_direction = torch.tensor(light_direction, dtype=torch.float32, device=device)
    elif isinstance(light_direction, np.ndarray):
        light_direction = torch.from_numpy(light_direction).float().to(device)
    if light_color.ndimension() == 1:
        light_color = light_color[None, :]
    if light_direction.ndimension() == 1:
        light_direction = light_direction[None, :] #[nb, 3]

    cosine = F.relu(torch.sum(normals * light_direction, dim=2)) #[]
    light += light_intensity * (light_color[:, None, :] * cosine[:, :, None])
    return light #[nb, :, 3]


text:
package com.nwire.mailchimp;

public class MailChimpServiceException extends RuntimeException {

	private static final long	serialVersionUID	= 1L;
	private final int			code;

	public MailChimpServiceException(final String message, final int code) {
		super((message == null) || (message.length() == 0) ? null : message);
		this.code = code;
	}

	public enum ErrorType {
		Unknown(Integer.MIN_VALUE),
		ServerError_MethodUnknown(-32601),
		ServerError_InvalidParameters(-32602),
		Unknown_Exception(-99),
		Zend_Uri_Exception(-92),
		PDOException(-91),
		Avesta_Db_Exception(-91),
		XML_RPC2_Exception(-90),
		XML_RPC2_FaultException(-90),
		Too_Many_Connections(-50),
		Parse_Exception(0),
		User_Unknown(100),
		User_Disabled(101),
		User_DoesNotExist(102),
		User_NotApproved(103),
		Invalid_ApiKey(104),
		User_UnderMaintenance(105),
		User_InvalidAction(120),
		User_MissingEmail(121),
		User_CannotSendCampaign(122),
		User_MissingModuleOutbox(123),
		User_ModuleAlreadyPurchased(124),
		User_ModuleNotPurchased(125),
		User_NotEnoughCredit(126),
		MC_InvalidPayment(127),
		List_DoesNotExist(200),
		List_InvalidInterestFieldType(210),
		List_InvalidOption(211),
		List_InvalidUnsubMember(212),
		List_InvalidBounceMember(213),
		List_AlreadySubscribed(214),
		List_NotSubscribed(215),
		List_InvalidImport(220),
		MC_PastedList_Duplicate(221),
		MC_PastedList_InvalidImport(222),
		Email_AlreadySubscribed(230),
		Email_AlreadyUnsubscribed(231),
		Email_NotExists(232),
		Email_NotSubscribed(233),
		List_MergeFieldRequired(250),
		List_CannotRemoveEmailMerge(251),
		List_Merge_InvalidMergeID(252),
		List_TooManyMergeFields(253),
		List_InvalidMergeField(254),
		List_InvalidInterestGroup(270),
		List_TooManyInterestGroups(271),
		Campaign_DoesNotExist(300),
		Campaign_StatsNotAvailable(301),
		Campaign_InvalidAbsplit(310),
		Campaign_InvalidContent(311),
		Campaign_InvalidOption(312),
		Campaign_InvalidStatus(313),
		Campaign_NotSaved(314),
		Campaign_InvalidSegment(315),
		Invalid_EcommOrder(330),
		Absplit_UnknownError(350),
		Absplit_UnknownSplitTest(351),
		Absplit_UnknownTestType(352),
		Absplit_UnknownWaitUnit(353),
		Absplit_UnknownWinnerType(354),
		Absplit_WinnerNotSelected(355),
		Invalid_Analytics(500),
		Invalid_DateTime(501),
		Invalid_Email(502),
		Invalid_SendType(503),
		Invalid_Template(504),
		Invalid_TrackingOptions(505),
		Invalid_Options(506),
		Invalid_Folder(507),
		Module_Unknown(550),
		MonthlyPlan_Unknown(551),
		Order_TypeUnknown(552),
		Invalid_PagingLimit(553),
		Invalid_PagingStart(554);

		private ErrorType(final int code) {
			this.code = code;
		}

		int	code;

	}

	public ErrorType getErrorType() {
		ErrorType result = ErrorType.Unknown;
		final String message = getMessage();
		if (message != null) {
			for (final ErrorType errorType : ErrorType.values()) {
				if (errorType.code == code) {
					result = errorType;
					break;
				}
			}
		}
		return result;
	}
}


text:
MVN="mvn"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

set -e
export LANG=en
cd "$DIR"
"$MVN" -DskipTests=true com.googlecode.gettext-commons:gettext-maven-plugin:gettext


text:
using Newtonsoft.Json;
using JsonSerializer = ServiceStack.Text.JsonSerializer;

namespace JWT.Tests
{
    public class ServiceStackJsonSerializer : IJsonSerializer
    {
        public string Serialize(object obj)
        {
            return JsonSerializer.SerializeToString(obj);
        }

        public T Deserialize<T>(string json)
        {
            return JsonSerializer.DeserializeFromString<T>(json);
        }
    }

    public class NewtonJsonSerializer : IJsonSerializer
    {
        public string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public T Deserialize<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}


text:
module Hamato
	module ControllerHelpers
		def set_glossary(string, glossary, *args, &block)
			return if glossary.nil? or string.nil?

			if show_glossary?
				use_glossary(glossary)
				string.glossarize!(*args.dup, &block)
			end
		end

		def show_glossary?
			session[:glossary] = params[:glossary] || session[:glossary]
			return (!session[:glossary].nil? and session[:glossary] == '1')
		end
	private

		def use_glossary(glossary)
			Hamato::Glossarize.glossary = glossary
    end
  end
end


text:
:: Batch file used to copy resources to the executable location after a visual studio build
set solutionDir=%1
set targetDir=%2

:: Windows resources
xcopy /Y /E "%solutionDir%WinResources" "%targetDir%"

:: Game data
xcopy /Y /E "%solutionDir%Data" "%targetDir%"


text:
void SGraphPinCustomAsset::Construct(const FArguments& InArgs, UEdGraphPin* InPin)
{
	SGraphPin::Construct(SGraphPin::FArguments(), InPin);
}

TSharedRef<SWidget> SGraphPinCustomAsset::GetDefaultValueWidget()
{
	return SNew(SColorPicker)
		.OnColorCommitted(this, &SGraphPinCustomAsset::ColorPicked);

}

void SGraphPinCustomAsset::ColorPicked(FLinearColor SelectedColor)
{
	UMyCustomAsset* NewValue = NewObject<UMyCustomAsset>();
	NewValue->ColorName = SelectedColor.ToFColor(false).ToHex();
	GraphPinObj->GetSchema()->TrySetDefaultObject(*GraphPinObj, NewValue);
}


text:
subroutine fc3d_clawpack46_set_block(blockno)
    implicit none

    integer :: blockno, blockno_com
    common /comblock/ blockno_com

    blockno_com = blockno
    end subroutine fc3d_clawpack46_set_block

integer function fc3d_clawpack46_get_block()
    implicit none

    integer :: blockno_com
    common /comblock/ blockno_com

    fc3d_clawpack46_get_block = blockno_com
    return
end function fc3d_clawpack46_get_block

subroutine fc3d_clawpack46_unset_block()
    implicit none

    integer :: blockno_com
    common /comblock/ blockno_com

    blockno_com = -1
end subroutine fc3d_clawpack46_unset_block


text:
package com.lady.viktoria.lightdrip.RealmActions;

import android.content.Context;
import android.util.Log;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lady.viktoria.lightdrip.RealmConfig.PrimaryKeyFactory;
import com.lady.viktoria.lightdrip.RealmModels.CalibrationData;
import com.lady.viktoria.lightdrip.RealmModels.GlucoseData;
import com.lady.viktoria.lightdrip.RealmModels.SensorData;
import com.lady.viktoria.lightdrip.RealmSerialize.CalibrationDataSerializer;

import java.util.Date;

import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmResults;
import io.realm.Sort;

import static io.realm.Realm.getDefaultInstance;

public class CalibrationRecord {
    private final static String TAG = CalibrationRecord.class.getSimpleName();

    private static final double LOW_SLOPE_1 = 0.95;
    private static final double LOW_SLOPE_2 = 0.85;
    private static final double HIGH_SLOPE_1 = 1.3;
    private static final double HIGH_SLOPE_2 = 1.4;
    private static final double DEFAULT_LOW_SLOPE_LOW = 1.08;
    private static final double DEFAULT_LOW_SLOPE_HIGH = 1.15;
    private static final int DEFAULT_SLOPE = 1;
    private static final double DEFAULT_HIGH_SLOPE_HIGH = 1.3;
    private static final double DEFAUL_HIGH_SLOPE_LOW = 1.2;
    private static final double MMOLL_TO_MGDL = 18.0182;
    private static final double MGDL_TO_MMOLL = 1 / MMOLL_TO_MGDL;
    Context context;
    private Realm mRealm;
    private Gson gson;

    public CalibrationRecord() {
        Realm.init(context);
        mRealm = getDefaultInstance();
    }

    public void initialCalibration(double bg1, double bg2) {
        SensorRecord sensorRecord = new SensorRecord();
        long currentsensor_id = sensorRecord.currentSensorID();
        double bgReading1 = 0, bgReading2 = 0, ageAdjustedRawData1 = 0, ageAdjustedRawData2 = 0, timestamp1 = 0, timestamp2 = 0;
        GlucoseData obj1 = null, obj2 = null;
        long started_at = 0;
        try {
            RealmResults<GlucoseData> results = mRealm.where(GlucoseData.class).findAll().sort("id", Sort.ASCENDING);
            int resultsize = results.size();
            bgReading1 = results.get(resultsize - 2).getRawData();
            bgReading2 = results.get(resultsize - 1).getRawData();
            ageAdjustedRawData1 = results.get(resultsize - 2).getageAdjustedRawValue();
            ageAdjustedRawData2 = results.get(resultsize - 1).getageAdjustedRawValue();
            timestamp1 = results.get(resultsize - 2).getTimestamp();
            timestamp2 = results.get(resultsize - 1).getTimestamp();
            obj1 = results.get(resultsize - 2);
            obj2 = results.get(resultsize - 1);

            RealmResults<SensorData> results_timestamp = mRealm.where(SensorData.class).findAll();
            long lastID = results_timestamp.last().getid();
            SensorData mSensorData = mRealm.where(SensorData.class)
                    .equalTo("id", lastID)
                    .findFirst();
            started_at = mSensorData.getstarted_at();

        } catch (Exception e) {
            Log.v(TAG, "initialCalibration " + e.getMessage());
        }
        double highBgReading;
        double lowBgReading;
        double highAgeAdjusted;
        double lowAgeAdjusted;
        double highTimestamp;
        double lowTimestamp;
        GlucoseData highRealmObj;
        GlucoseData lowRealmObj;
        double higher_bg = Math.max(bg1, bg2);
        double lower_bg = Math.min(bg1, bg2);

        if (bgReading1 > bgReading2) {
            highBgReading = bgReading1;
            highAgeAdjusted = ageAdjustedRawData1;
            highTimestamp = timestamp1;
            highRealmObj = obj1;
            lowBgReading = bgReading2;
            lowAgeAdjusted = ageAdjustedRawData2;
            lowTimestamp = timestamp2;
            lowRealmObj = obj2;

        } else {
            highBgReading = bgReading2;
            highAgeAdjusted = ageAdjustedRawData2;
            highTimestamp = timestamp2;
            highRealmObj = obj2;
            lowBgReading = bgReading1;
            lowAgeAdjusted = ageAdjustedRawData1;
            lowTimestamp = timestamp1;
            lowRealmObj = obj2;
        }

        long newprimekeyHighCal = PrimaryKeyFactory.getInstance().nextKey(CalibrationData.class);
        mRealm.beginTransaction();
        CalibrationData mCalibrationDataHighCal = mRealm.createObject(CalibrationData.class, newprimekeyHighCal);
        mCalibrationDataHighCal.setbg(higher_bg);
        mCalibrationDataHighCal.setslope(1);
        mCalibrationDataHighCal.setintercept(higher_bg);
        mCalibrationDataHighCal.setsensor_id(currentsensor_id);
        mCalibrationDataHighCal.setestimate_raw_at_time_of_calibration(highAgeAdjusted);
        mCalibrationDataHighCal.setadjusted_raw_value(highAgeAdjusted);
        mCalibrationDataHighCal.setraw_value(highBgReading);
        mCalibrationDataHighCal.setraw_timestamp((long) highTimestamp);
        highRealmObj.setCalculatedValue(higher_bg);
        highRealmObj.setCalibrationFlag(true);
        //highRealmObj.setcalibration_type(higherCalibration);
        mCalibrationDataHighCal.settimestamp(new Date().getTime());
        mCalibrationDataHighCal.setslope_confidence(0.5);
        mCalibrationDataHighCal.setdistance_from_estimate(0);
        mCalibrationDataHighCal.setcheck_in(false);
        mCalibrationDataHighCal.setsensor_confidence(((-0.0018 * higher_bg * higher_bg) + (0.6657 * higher_bg) + 36.7505) / 100);
        mCalibrationDataHighCal.setsensor_age_at_time_of_estimation((double) (mCalibrationDataHighCal.gettimestamp() - started_at));
        //calculate_w_l_s();
        mRealm.commitTransaction();
        mRealm.close();

        long newprimekeyLowCal = PrimaryKeyFactory.getInstance().nextKey(CalibrationData.class);
        mRealm.beginTransaction();
        CalibrationData mCalibrationDataLowCal = mRealm.createObject(CalibrationData.class, newprimekeyLowCal);
        mCalibrationDataLowCal.setbg(lower_bg);
        mCalibrationDataLowCal.setslope(1);
        mCalibrationDataLowCal.setintercept(lower_bg);
        mCalibrationDataLowCal.setsensor_id(currentsensor_id);
        mCalibrationDataLowCal.setestimate_raw_at_time_of_calibration(lowAgeAdjusted);
        mCalibrationDataLowCal.setadjusted_raw_value(lowAgeAdjusted);
        mCalibrationDataLowCal.setraw_value(lowBgReading);
        mCalibrationDataLowCal.setraw_timestamp((long) lowTimestamp);
        lowRealmObj.setCalculatedValue(lower_bg);
        lowRealmObj.setCalibrationFlag(true);
        //lowRealmObj.setcalibration_type(lowerCalibration);
        mCalibrationDataLowCal.settimestamp(new Date().getTime());
        mCalibrationDataLowCal.setslope_confidence(0.5);
        mCalibrationDataLowCal.setdistance_from_estimate(0);
        mCalibrationDataLowCal.setcheck_in(false);
        mCalibrationDataLowCal.setsensor_confidence(((-0.0018 * lower_bg * lower_bg) + (0.6657 * lower_bg) + 36.7505) / 100);
        mCalibrationDataLowCal.setsensor_age_at_time_of_estimation(Double.valueOf(mCalibrationDataLowCal.gettimestamp() - started_at));
        //calculate_w_l_s();
        mRealm.commitTransaction();
        mRealm.close();

        serializeToJson();
        RealmResults<CalibrationData> results = mRealm.where(CalibrationData.class).findAll().sort("id", Sort.ASCENDING);
        int resultsize = results.size();
        CalibrationData result1 = results.get(resultsize - 2);
        CalibrationData result2 = results.get(resultsize - 1);

        String json1 = gson.toJson(mRealm.copyFromRealm(result1));
        String json2 = gson.toJson(mRealm.copyFromRealm(result2));

        Log.v(TAG, "glucoseRecord json1: " + json1);
        Log.v(TAG, "glucoseRecord json2: " + json2);

    }

    public void singleCalibration(double bg) {
        SensorRecord sensorRecord = new SensorRecord();
        GlucoseRecord glucoseRecord = new GlucoseRecord();
        boolean currentsensor = sensorRecord.isSensorActive();
        long currentsensor_id = sensorRecord.currentSensorID();
        if (currentsensor && glucoseRecord.lastGluscoseEntry() != null) {
            long newprimekeyLowCal = PrimaryKeyFactory.getInstance().nextKey(CalibrationData.class);
            mRealm.beginTransaction();
            CalibrationData mCalibrationData = mRealm.createObject(CalibrationData.class, newprimekeyLowCal);
            mCalibrationData.setbg(bg);
            mCalibrationData.setcheck_in(false);
            mCalibrationData.settimestamp(new Date().getTime());
            //mCalibrationDataLowCal.setestimate_raw_at_time_of_calibration();
            //mCalibrationDataLowCal.setadjusted_raw_value();
            mCalibrationData.setsensor_id(currentsensor_id);

            //mCalibrationDataLowCal.setraw_value();
            //mCalibrationDataLowCal.setraw_timestamp();
            mRealm.commitTransaction();
            mRealm.close();

        } else {
            Log.d("CALIBRATION", "No sensor, cant save!");
        }
        //return lastCalibration();
    }

    public CalibrationData lastCalibration() {
        return mRealm.where(CalibrationData.class)
                .findAllSorted("id", Sort.DESCENDING)
                .where()
                .findFirst();
    }

    private void serializeToJson() {
        gson = new GsonBuilder()
                .setExclusionStrategies(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes f) {
                        return f.getDeclaringClass().equals(RealmObject.class);
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return false;
                    }
                })
                .registerTypeAdapter(CalibrationData.class, new CalibrationDataSerializer())
                .create();
    }

    /*
    private static void calculate_w_l_s() {
        SensorRecord sensorRecord = new SensorRecord();
        if (sensorRecord.isSensorActive()) {
            double l = 0;
            double m = 0;
            double n = 0;
            double p = 0;
            double q = 0;
            double w;
            List<Calibration> calibrations = allForSensorInLastFourDays(); //5 days was a bit much, dropped this to 4
            if (calibrations.size() <= 1) {
                Calibration calibration = Calibration.last();
                calibration.slope = 1;
                calibration.intercept = calibration.bg - (calibration.raw_value * calibration.slope);
                //calibration.save();
                //CalibrationRequest.createOffset(calibration.bg, 25);
            } else {
                for (Calibration calibration : calibrations) {
                    w = calibration.calculateWeight();
                    l += (w);
                    m += (w * calibration.estimate_raw_at_time_of_calibration);
                    n += (w * calibration.estimate_raw_at_time_of_calibration * calibration.estimate_raw_at_time_of_calibration);
                    p += (w * calibration.bg);
                    q += (w * calibration.estimate_raw_at_time_of_calibration * calibration.bg);
                }

                Calibration last_calibration = Calibration.last();
                w = (last_calibration.calculateWeight() * (calibrations.size() * 0.14));
                l += (w);
                m += (w * last_calibration.estimate_raw_at_time_of_calibration);
                n += (w * last_calibration.estimate_raw_at_time_of_calibration * last_calibration.estimate_raw_at_time_of_calibration);
                p += (w * last_calibration.bg);
                q += (w * last_calibration.estimate_raw_at_time_of_calibration * last_calibration.bg);

                double d = (l * n) - (m * m);
                Calibration calibration = Calibration.last();
                calibration.intercept = ((n * p) - (m * q)) / d;
                calibration.slope = ((l * q) - (m * p)) / d;
                if ((calibrations.size() == 2 && calibration.slope < LOW_SLOPE_1) || (calibration.slope < LOW_SLOPE_2)) { // I have not seen a case where a value below 7.5 proved to be accurate but we should keep an eye on this
                    calibration.slope = calibration.slopeOOBHandler(0);
                    if (calibrations.size() > 2) {
                        calibration.possible_bad = true;
                    }
                    calibration.intercept = calibration.bg - (calibration.estimate_raw_at_time_of_calibration * calibration.slope);
                    //  CalibrationRequest.createOffset(calibration.bg, 25);
                }
                if ((calibrations.size() == 2 && calibration.slope > HIGH_SLOPE_1) || (calibration.slope > HIGH_SLOPE_2)) {
                    calibration.slope = calibration.slopeOOBHandler(1);
                    if (calibrations.size() > 2) {
                        calibration.possible_bad = true;
                    }
                    calibration.intercept = calibration.bg - (calibration.estimate_raw_at_time_of_calibration * calibration.slope);
                    //CalibrationRequest.createOffset(calibration.bg, 25);
                }
                Log.d(TAG, "Calculated Calibration Slope: " + calibration.slope);
                Log.d(TAG, "Calculated Calibration intercept: " + calibration.intercept);
                //calibration.save();
            }
        } else {
            Log.d(TAG, "NO Current active sensor found!!");
        }
    }

    private double slopeOOBHandler(int status) {
        // If the last slope was reasonable and reasonably close, use that, otherwise use a slope that may be a little steep, but its best to play it safe when uncertain
        List<Calibration> calibrations = Calibration.latest(3);
        Calibration thisCalibration = calibrations.get(0);
        if (status == 0) {
            if (calibrations.size() == 3) {
                if ((Math.abs(thisCalibration.bg - thisCalibration.estimate_bg_at_time_of_calibration) < 30) && (calibrations.get(1).possible_bad != null && calibrations.get(1).possible_bad == true)) {
                    return calibrations.get(1).slope;
                } else {
                    return Math.max(((-0.048) * (thisCalibration.sensor_age_at_time_of_estimation / (60000 * 60 * 24))) + 1.1, DEFAULT_LOW_SLOPE_LOW);
                }
            } else if (calibrations.size() == 2) {
                return Math.max(((-0.048) * (thisCalibration.sensor_age_at_time_of_estimation / (60000 * 60 * 24))) + 1.1, DEFAULT_LOW_SLOPE_HIGH);
            }
            return DEFAULT_SLOPE;
        } else {
            if (calibrations.size() == 3) {
                if ((Math.abs(thisCalibration.bg - thisCalibration.estimate_bg_at_time_of_calibration) < 30) && (calibrations.get(1).possible_bad != null && calibrations.get(1).possible_bad == true)) {
                    return calibrations.get(1).slope;
                } else {
                    return DEFAULT_HIGH_SLOPE_HIGH;
                }
            } else if (calibrations.size() == 2) {
                return DEFAUL_HIGH_SLOPE_LOW;
            }
        }
        return DEFAULT_SLOPE;
    }
    */
}


text:
package com.github.avarabyeu.jashing.core;

import com.github.avarabyeu.jashing.core.eventsource.annotation.NoCache;
import com.google.common.collect.Maps;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.Gson;
import freemarker.cache.ClassTemplateLoader;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.server.handlers.sse.ServerSentEventConnection;
import io.undertow.server.handlers.sse.ServerSentEventHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.InstanceFactory;
import io.undertow.servlet.api.InstanceHandle;
import io.undertow.servlet.util.ImmediateInstanceHandle;
import io.undertow.util.AttachmentKey;
import io.undertow.util.Headers;
import io.undertow.util.StatusCodes;
import ro.isdc.wro.http.ConfigurableWroFilter;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;

import static com.github.avarabyeu.jashing.utils.StringUtils.substringBefore;

/**
 * HTTP Server Controller. Bootstraps server and specifies all needed mappings and request handlers
 *
 * @author avarabyeu
 */
class JashingServer extends AbstractIdleService {

    public static final AttachmentKey<RateLimiter> RATE_LIMITER_KEY = AttachmentKey.create(RateLimiter.class);

    private final Integer port;

    private final EventBus eventBus;
    private final Gson gson;
    private final Optional<Long> timeout;

    private ServerSentEventHandler sseHandler;
    private Undertow server;

    public JashingServer(Integer port, EventBus eventBus, Gson gson, Optional<Long> timeout) {
        this.port = port;
        this.eventBus = eventBus;
        this.gson = gson;
        this.timeout = timeout;
    }

    @Override
    protected void startUp() throws Exception {
        freemarker.template.Configuration configuration = new freemarker.template.Configuration(
                freemarker.template.Configuration.VERSION_2_3_23);
        configuration.setTemplateLoader(new ClassTemplateLoader(Jashing.class, "/"));

        ConcurrentMap<String, JashingEvent> eventCache = Maps.newConcurrentMap();

        sseHandler = Handlers
                .serverSentEvents((connection, lastEventId) -> {
                    timeout.ifPresent(timeout -> {
                        connection.putAttachment(RATE_LIMITER_KEY, RateLimiter.create(timeout));
                        eventCache.values().forEach(serverSentEvent -> sendEvent(connection, serverSentEvent));
                    });
                });

        eventBus.register(new Consumer<JashingEvent>() {
            @Subscribe
            @Override
            public void accept(JashingEvent serverSentEvent) {
                if (!serverSentEvent.getClass().isAnnotationPresent(NoCache.class)) {
                    eventCache.put(serverSentEvent.getId(), serverSentEvent);
                }
                sseHandler.getConnections().parallelStream().forEach(c -> sendEvent(c, serverSentEvent));
            }
        });

        ResourceHandler widgetsHandler = Handlers.resource(
                new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(),
                        "statics"));

        RoutingHandler routingHandler = Handlers.routing()
                .get("/views/{widget}", exchange -> {

                    exchange.setStatusCode(StatusCodes.FOUND);
                    String widgetName = exchange.getQueryParameters().get("widget").getFirst();
                    exchange.getResponseHeaders().put(Headers.LOCATION,
                            "/assets/widgets/" + substringBefore(widgetName, ".html") + "/" + widgetName);
                    exchange.endExchange();

                })
                .get("/{dashboard}", exchange -> {
                    StringWriter out = new StringWriter();
                    configuration.getTemplate(
                            "/views/dashboards/" + exchange.getQueryParameters()
                                    .get("dashboard").poll()
                                    + ".ftl.html").process(Collections.EMPTY_MAP, out);

                    exchange.getResponseSender().send(out.toString());
                })
                .get("/events", sseHandler)
                .get("/", Handlers.redirect("/sample"));

        HttpHandler rootHandler = Handlers.path(routingHandler)
                .addPrefixPath("/assets", widgetsHandler)
                .addPrefixPath("/compiled", getAggregationHandler());

        server = Undertow.builder().addHttpListener(port, "0.0.0.0")
                .setHandler(rootHandler).build();

        server.start();
    }

    private void sendEvent(ServerSentEventConnection c, JashingEvent serverSentEvent) {
        //wait if there is rate limiter
        Optional.ofNullable(c.getAttachment(RATE_LIMITER_KEY)).ifPresent(RateLimiter::acquire);
        c.send(gson.toJson(serverSentEvent));
    }

    /**
     * Uses Wro4j Filter to pre-process resources
     * Required for coffee scripts compilation and saas processing
     * Wro4j uses Servlet API so we make fake Servlet Deployment here to emulate servlet-based environment
     *
     * @return Static resources handler
     */
    private HttpHandler getAggregationHandler() throws ServletException {
        DeploymentInfo deploymentInfo = Servlets
                .deployment()
                .setClassLoader(JashingServer.class.getClassLoader())
                .setContextPath("/")
                .setDeploymentName("jashing")
                .addFilterUrlMapping("wro4j", "/*", DispatcherType.REQUEST)
                .addFilter(Servlets.filter("wro4j", ConfigurableWroFilter.class,
                        new InstanceFactory<ConfigurableWroFilter>() {
                            @Override
                            public InstanceHandle<ConfigurableWroFilter> createInstance()
                                    throws InstantiationException {
                                ConfigurableWroFilter filter = new ConfigurableWroFilter();
                                filter.setWroManagerFactory(new WroManagerFactory());
                                return new ImmediateInstanceHandle<>(filter);
                            }
                        }));
        DeploymentManager deployment = Servlets.defaultContainer().addDeployment(deploymentInfo);
        deployment.deploy();
        return deployment.start();
    }

    @Override
    protected void shutDown() throws Exception {
        /* close connections */
        sseHandler.getConnections().forEach(ServerSentEventConnection::shutdown);

        /* stop the server */
        server.stop();

    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Console\Command\Generate\EntityConfigCommand.
 */

namespace Drupal\Console\Command\Generate;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\Generate\EntityCommand;
use Drupal\Console\Generator\EntityConfigGenerator;
use Drupal\Console\Style\DrupalStyle;

class EntityConfigCommand extends EntityCommand
{
    protected function configure()
    {
        $this->setEntityType('EntityConfig');
        $this->setCommandName('generate:entity:config');
        parent::configure();

        $this->addOption(
            'bundle-of',
            null,
            InputOption::VALUE_NONE,
            $this->trans('commands.generate.entity.config.options.bundle-of')
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function interact(InputInterface $input, OutputInterface $output)
    {
        parent::interact($input, $output);

        $output = new DrupalStyle($input, $output);

        // --bundle-of option
        $bundle_of = $input->getOption('bundle-of');
        if (!$bundle_of) {
            $bundle_of = $output->confirm(
                $this->trans('commands.generate.entity.config.questions.bundle-of'),
                false
            );
            $input->setOption('bundle-of', $bundle_of);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $module = $input->getOption('module');
        $entity_class = $input->getOption('entity-class');
        $entity_name = $input->getOption('entity-name');
        $label = $input->getOption('label');
        $bundle_of = $input->getOption('bundle-of');

        $this
            ->getGenerator()
            ->generate($module, $entity_name, $entity_class, $label, $bundle_of);
    }

    protected function createGenerator()
    {
        return new EntityConfigGenerator();
    }
}


text:
import feed from '../fixtures/feed';
import page from '../fixtures/page';

function renderIframe (id, html) {
  let iframe = document.getElementById(id)
  iframe.src = "data:text/html;charset=utf-8,"+encodeURIComponent(html);
  // iframe.contentWindow.location.hash = 'development=1';
}

window.polySolvePage(feed, {}, (err, html, details) => {
  if (err) {
    console.warn(err);
    return;
  }
  renderIframe('feed', html);
  console.log(details);
});
window.polySolvePage(page, {}, (err, html, details) => {
  if (err) {
    console.warn(err);
    return;
  }
  renderIframe('page', html);
  console.log(details);
});


text:
package net.jforum.util.preferences;

import net.jforum.util.FileChangeListener;

import org.apache.log4j.Logger;

/**
 * Listener for changed file events.
 * <p>
 * On change of the registered resource file the global settings are re-initialized
 * by calling SystemGlobals.initGlobals.
 * <p>
 * @author Rafael Steil
 * @version $Id$
 */
public class SystemGlobalsListener implements FileChangeListener
{
    private static final Logger LOGGER = Logger.getLogger(SystemGlobalsListener.class);

    /**
     * @see net.jforum.util.FileChangeListener#fileChanged(java.lang.String)
     */
    public void fileChanged(final String filename)
    {
        LOGGER.info("File change detected: "+ filename);

        SystemGlobals.initGlobals(SystemGlobals.getApplicationPath(),
                                  SystemGlobals.getValue(ConfigKeys.DEFAULT_CONFIG));
    }
}


text:
<?php

class UserController extends Zend_Controller_Action
{

    protected $_auth = null;

    public function init()
    {
        $this->_auth = Zend_Auth::getInstance();
    }

    public function indexAction()
    {
        $auth = Zend_Auth::getInstance();
        $id = $auth->getStorage()->read()['id'];
        $userMapper = new Application_Model_UserMapper();
        $user = new Application_Model_User($userMapper->read($id));
        $view = $this->view;
        $view->headTitle("User Profile");

        $view->assign('username',$user->getUsername());
        $view->assign('firstname',$user->getFirstname());
        $view->assign('surname',$user->getSurname());
        $view->assign('email',$user->getEmail());
        $view->assign('gender',$user->getGender());
        $view->assign('lastloggedindate',$user->getLastloggedindate());
        $view->assign('createddate',$user->getCreateddate());
        $view->assign('picture',$user->getPicture());
        }

    public function editAction()
    {
        $this->view->headTitle("Edit User Profile");
        $form = new Application_Form_Register();
        $form->removeElement('username');
        $form->removeElement('submit');
        $form->removeElement('passwordraw');
        $form->removeElement('passwordcheck');

        $password = new Zend_Form_Element_Password('passwordraw');
        $password
                    ->setLabel("Change password")
                    ->addFilter('StringTrim')
                    ->setAttrib('id','register-pwd')
                    ->setAttrib('placeholder','Password')
                    ->setAttrib('tabindex', '11')
                    ->setAttrib('class', 'form-field input-xxlarge')
                    ->setDecorators(array(
                                        'ViewHelper',
                                        array('Errors', array ('class' => 'help-inline')),
                                        array(
                                            'Label',
                                            array('placement' => 'prepend',
                                            )
                                        )
                                    ))
                    ->setOrder(17);
        ;

        $passwordcheck = new Zend_Form_Element_Password('passwordcheck');
        $passwordcheck
                    ->setLabel("Repeat new password")
                    ->addFilter('StringTrim')
                    ->addValidator('Identical', false, array('token' => 'passwordraw'))
                    ->setAttrib('id','register-pwdRpt')
                    ->setAttrib('placeholder','Repeat password')
                    ->setAttrib('tabindex', '12')
                    ->setAttrib('class', 'form-field input-xxlarge')
                    ->setDecorators(array(
                                        'ViewHelper',
                                        array('Errors', array ('class' => 'help-inline')),
                                        array(
                                            'Label',
                                            array('placement' => 'prepend',
                                            )
                                        )
                                    ))
                    ->setOrder(18);
        ;

        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Submit changes')
                ->setOptions(array('class' => 'btn pillBtn'))
                ->setAttrib('id', 'register-btn')
                ->setAttrib('tabindex', '13')
                ->setDecorators(array('ViewHelper',array('Errors', array ('class' => 'help-inline'))))
                ->setOrder(20);
        ;
        $form->addElement($password);
        $form->addElement($passwordcheck);
        $form->addElement($submit);

        $view = $this->view;
        $view->title = 'Edit User Profile';

        $auth = Zend_Auth::getInstance();
        $id = $auth->getStorage()->read()['id'];
        if($id >0)
        {
            $userMapper = new Application_Model_UserMapper();
            $user = new Application_Model_User($userMapper->read($id));

            $users = array();

            $img = $user->getPicture();
            if (!empty($img))
            {
                $url = PUBLIC_PATH . "/images/" . $img;
                $url = join("/",explode("\\",$url));
                $url = explode("htdocs/", $url)[1];
                //Zend_Debug::dump($_SERVER);exit();
                $view->assign('image', "http://" . $_SERVER["HTTP_HOST"] . "/" . $url);
                $view->assign('hasimage', true);
            }
            else
                $view->assign('hasimage', false);

            $users['username'] = $user->getUsername();
            $users['firstname'] = $user->getFirstname();
            $users['surname'] = $user->getSurname();
            $users['gender'] = $user->getGender();
            $users['email'] = $user->getEmail();

            $form->populate($users);
        }
        else {
            return $this->redirect('account/login/');
        }

        $request = $this->getRequest();

        if ($request->isPost() )
        {
            if ($form->isValid( $request->getPost()))
            {
               $values = $form->getValues();
                $form->populate($values);
                $val = $this->getRequest()->getPost();
                if ($form->isValid( $request->getPost() )) {
                    Zend_debug::dump($val);
                    if(isset($val["passwordraw"]))
                    {
                        $user->setPasswordraw($val["passwordraw"]);
                    }
                    $user->setFirstname($val["firstname"]);
                    $user->setSurname($val["surname"]);
                    $user->setEmail($val["email"]);
                    $user->setGender($val["gender"]);
                    $modifiedd = new DateTime('now', new DateTimeZone('UTC'));
                    $modifiedd = $modifiedd->format('Y-m-d H:i:s');
                    $user->setModifieddate( $modifiedd );

                    if($form->picture->isUploaded())
                    {
                        $mime = $form->picture->getMimeType();
                        $exts = explode('/', $mime);
                        $ext = end($exts);
                        $new_img_name = base64_encode(bored_Utility::randomString(20) . microtime());
                        $form->picture->addFilter('Rename',$new_img_name . '.' . $ext, true);
                        $user->setPicture($new_img_name . '.' . $ext);

                        try {
                            if ($form->picture->receive()) {
                                $userMapper = new Application_Model_UserMapper();
                                $uid = $userMapper->save($user);
                                $user->setId($uid);
                                return $this->redirect('user/index');
                            }
                            else
                            {
                                throw new Zend_Exception("Your image wasn't received correctly.");
                            }

                        }
                        catch (Zend_File_Transfer_Exception $e)
                        {
                            throw new Zend_Exception("Your image was not uploaded.");
                        }
                    }
                    else {
                        $userMapper = new Application_Model_UserMapper();
                        $uid = $userMapper->save($user);
                        $user->setId($uid);
                        return $this->redirect('user/index');
                    }
                }
            }
        }
        $view->form = $form;
    }

}


text:
from rqalpha.interface import AbstractMod
from rqalpha.utils.disk_persist_provider import DiskPersistProvider
from rqalpha.const import RUN_TYPE, PERSIST_MODE
from rqalpha.utils.logger import user_system_log, system_log
from rqalpha.utils.i18n import gettext as _

from .direct_data_source import DirectDataSource
from .redis_data_source import RedisDataSource
from .event_source import RealtimeEventSource

class RealtimeTradeMod(AbstractMod):

    def start_up(self, env, mod_config):

        if env.config.base.run_type in (RUN_TYPE.PAPER_TRADING, RUN_TYPE.LIVE_TRADING):
            user_system_log.warn(_("[Warning] When you use this version of RealtimeTradeMod, history_bars can only get data from yesterday."))

            if mod_config.redis_uri:
                env.set_data_source(RedisDataSource(env.config.base.data_bundle_path, mod_config.redis_uri))
                system_log.info(_("RealtimeTradeMod using market from redis"))
            else:
                env.set_data_source(DirectDataSource(env.config.base.data_bundle_path))
                system_log.info(_("RealtimeTradeMod using market from network"))

            env.set_event_source(RealtimeEventSource(mod_config.fps, mod_config))

            # add persist
            persist_provider = DiskPersistProvider(mod_config.persist_path)
            env.set_persist_provider(persist_provider)

            env.config.base.persist = True
            env.config.base.persist_mode = PERSIST_MODE.REAL_TIME

    def tear_down(self, code, exception=None):
        pass


text:
<!doctype html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Map projection types in GEE 5.1.0 — Google Earth Enterprise 5.3.2 documentation</title>
    <link rel="stylesheet" href="../../static/bizstyle.css" type="text/css" />
    <link rel="stylesheet" href="../../static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Add flat imagery to Mercator map databases in GEE 5.1.0" href="addFlatImageryToMercatorMapDBInGEE5.1.0.html" />
    <link rel="prev" title="Manage mosaics with virtual rasters" href="manageMosaicsWithVirtualRasters.html" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.2 documentation »

Fusion Resources and Projects »

Previous topic

Manage mosaics with virtual rasters

Next topic

Add flat imagery to Mercator map databases in GEE 5.1.0

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Map projection types in GEE 5.1.0¶

In addition to using Google Earth Enterprise Fusion to prepare and
publish data in Google Earth EC, you can use it to prepare and
publish map data in Google Maps.

Google Earth Enterprise 5.1.0 supports the following projection
types for map databases:

Mercator map—The Mercator map database includes the Google
Maps layer and optionally uses the Google Base Map from
google.com. It also uses a local copy of the Google Maps API
that requires no communication with google.com.

Flat Projection map—The Flat Projection map database uses
the local copy of the Google Maps API that requires no
communication with google.com.

Preparing map data

When you prepare map data, there are four components:

Resources (vector and imagery)

Map Layers (Flat projection and Mercator maps supported)

Map Projects (map and imagery)

Map Database

Vector and imagery resources

For Flat Projection maps, you can share the same vector and
imagery resources for both Google Earth EC and Google Maps
databases.

For Mercator maps, you can create Mercator-based imagery
projects or your Mercator maps can share the same imagery
resources as a Flat Projection map database by projecting the flat
imagery as Mercator on the Fly. Now that your Mercator map
databases can share the same imagery projects as a Flat Projection
map databases, you can save on both storage space and database
building time by eliminating the need for Mercator-based imagery.

For more information, see Add flat imagery to Mercator map databases in GEE 5.1.0.

Access map tools

With map databases, in addition to vector and imagery projects,
you have the extra step of creating map layers.
Defining a map layer includes adding resources and defining the
display rules and filters for the layer.

You access the map tools from the toolbar of the Asset Manager
dialog:

Open Fusion and click Tools > Asset Manager to open the
Asset Manager dialog.

Select either Mercator Map Tools (2D) or Flat Projection
Map Tools (2D) from the Asset Manager toolbar.

For information about creating map projects and databases, read
the tutorial lesson, Creating a Map Database.

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.2 documentation »

Fusion Resources and Projects »

        © Copyright 2019, Open GEE Contributors.
      Created using Sphinx 1.7.5.


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

namespace Config.Net.Stores
{
   class CommandLineConfigStore : IConfigStore
   {
      private readonly Dictionary<string, string> _nameToValue = new Dictionary<string, string>();
      private static readonly char[] ArgPrefixes = new[] { '-', '/' };
      private static readonly string[] ArgDelimiters = new[] { ":", "=" };

      public bool CanRead => true;

      public bool CanWrite => false;

      public string Name => "Command Line Arguments";

      public CommandLineConfigStore(string[] args,
         Dictionary<int, Option> positionToOption)
      {
         Parse(args ?? Environment.GetCommandLineArgs(), positionToOption);
      }

      public void Dispose()
      {
      }

      public string Read(string key)
      {
         if (key == null) return null;

         string value;
         _nameToValue.TryGetValue(key, out value);
         return value;
      }

      public void Write(string key, string value)
      {
         throw new NotSupportedException();
      }

      private void Parse(string[] args, Dictionary<int, Option> positionToOption)
      {
         _nameToValue.Clear();

         if (args == null) return;

         for(int i = 0; i < args.Length; i++)
         {
            string name;
            string value;

            if(positionToOption != null && positionToOption.TryGetValue(i, out Option option))
            {
               name = option.Name;
               value = args[i];
            }
            else
            {
               var nameValue = args[i].SplitByDelimiter(ArgDelimiters);
               name = nameValue.Item1.TrimStart(ArgPrefixes);
               value = nameValue.Item2;
            }

            if(name != null && value != null)
            {
               _nameToValue[name] = value;
            }
         }
      }
   }
}


text:
namespace Microsoft.Web.Mvc {
    using System.Web;

    public delegate string MvcSubstitutionCallback(HttpContextBase httpContext);
}


text:
var PackageSuggestionsConstants = require('../../constants/package-suggestions');

/**
 * Emits a search action to the hacker news store
 *
 * @param {Application} app
 * @param {Object} payload
 * @param {Function} callback
 */
var searchHotelUrbano = module.exports = function(app, payload, callback) {
    app.emit(PackageSuggestionsConstants.SEARCH_START, payload);

    app.getService('PackageSuggestionsService').search(payload, function(error, response) {
        if (error) {
            app.emit(PackageSuggestionsConstants.SEARCH_ERROR, error);
            return callback && callback(error);
        }

        app.emit(PackageSuggestionsConstants.SEARCH_SUCCESS, response);
        callback && callback(null, response);
    });
};

searchHotelUrbano.identifier = 'searchHotelUrbano';


text:
@implementation GITransition {

    CGFloat viewH;
    UIView *_selfView;
    BOOL isModalVCOnBottom;
    BOOL reversed;
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                   presentingController:(UIViewController *)presenting
                                                                   sourceController:(UIViewController *)source {
    return self;
}

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return self;
}

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext{
    return 1.0;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{

    self.transitionContext = transitionContext;
    isModalVCOnBottom = NO;

    UIViewController *fromtVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIView *containerView = [transitionContext containerView];

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // Swizzling
        Method originalMethod = class_getInstanceMethod([containerView class], @selector(hitTest:withEvent:));
        Method swappedMethod = class_getInstanceMethod([containerView class], @selector(GI_hitTest:withEvent:));
        method_exchangeImplementations(originalMethod, swappedMethod);
    });

    CGRect finalFrameVC = [transitionContext finalFrameForViewController:toVC];
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    viewH = CGRectGetHeight(fromtVC.view.frame);

    // Define wich viewController we will move, and wich just scale
    UIViewController *modalVC = reversed ? fromtVC : toVC;
    UIViewController *nonModalVC = reversed ? toVC : fromtVC;

    CGRect modalFinalFrame = reversed ? CGRectOffset(finalFrameVC, 0, viewH) : finalFrameVC;
    float scaleFactor = 0.0;
    float alphaVal = 0.0;

    if (reversed) {
        scaleFactor = 1.0;
        alphaVal = 1.0;
    }
    else {
        // Set offset from the top for modalView
        modalFinalFrame.origin.y += kModalViewYOffset;
        // If we'll present now modalVC - hide it under the screen
        modalVC.view.frame = CGRectOffset(finalFrameVC, 0, viewH);

        scaleFactor = kNonModalViewMinScale;
        alphaVal = kNonModalViewMinAlpha;

        [containerView addSubview:toVC.view];
    }

    [UIView animateWithDuration:duration delay:0.0
         usingSpringWithDamping:100
          initialSpringVelocity:10
                        options:UIViewAnimationOptionAllowUserInteraction animations:^{

                            nonModalVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, scaleFactor, scaleFactor);
                            nonModalVC.view.alpha = alphaVal;
                            modalVC.view.frame = modalFinalFrame;

                            if (self.closeVCNow) {
                                toVC.view.transform = CGAffineTransformIdentity; // Fix rotation issue http://stackoverflow.com/questions/31969524/ios-custom-transitions-and-rotation/35182783#35182783
                                toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
                                self.closeVCNow = NO;
                            }

                        } completion:^(BOOL finished) {
                            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
                             reversed = !reversed;
    }];

}

#pragma GestureRecognizer delegate

- (void)addGestureRecognizersToView:(UIView *)viewNavBar withSelfView:(UIView *)selfView{
    _selfView = selfView;

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [viewNavBar addGestureRecognizer:pan];

    UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [viewNavBar addGestureRecognizer:tapRec];
}

- (void)tap:(UITapGestureRecognizer *)recognizer {
    if (isModalVCOnBottom) {
        [self moveModalViewUp:YES andDuration:0.4];
    }
}

- (void)pan:(UIPanGestureRecognizer *)recognizer{

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [recognizer setTranslation:CGPointZero inView:_selfView.superview];
    }

    // This don't allow drag modalVC beyond the screen
    // and don't allow drag it up when modalVC placed on the bottom
    if ([recognizer translationInView:_selfView].y < 0.1 || isModalVCOnBottom) {
        return;
    }

    CGFloat percentage = [recognizer translationInView:_selfView].y / CGRectGetHeight(_selfView.bounds);

    float scaleFactor = kNonModalViewMinScale + (1 - kNonModalViewMinScale) * percentage;
    float alphaVal = kNonModalViewMinAlpha + (1 - kNonModalViewMinAlpha) * percentage;

    [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.transform = CGAffineTransformScale(CGAffineTransformIdentity, scaleFactor, scaleFactor);
    [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.alpha = alphaVal;

    CGRect modalVCFrame = [_transitionContext viewForKey:UITransitionContextToViewKey].frame;
    modalVCFrame.origin.y = percentage * CGRectGetHeight(_selfView.frame) + kModalViewYOffset;
    [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view.frame = modalVCFrame;

    if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) {

        CGFloat velocityY = [recognizer velocityInView:recognizer.view.superview].y;
        BOOL cancelUp = (velocityY < 0) || (velocityY == 0 && recognizer.view.frame.origin.y < CGRectGetHeight(_selfView.bounds)/2);

        CGFloat points = cancelUp ? recognizer.view.frame.origin.y : CGRectGetHeight(_selfView.bounds) - recognizer.view.frame.origin.y;
        NSTimeInterval duration = points / velocityY;

        if (duration < 0.2) {
            duration = 0.2;
        }
        else if(duration > 0.4){
            duration = 0.4;
        }

        // Move view
        [self moveModalViewUp:cancelUp andDuration:duration];
    }
}

- (void)moveModalViewUp:(BOOL)cancelUp andDuration:(NSTimeInterval)duration {

    CGRect modalVCFrame = [_transitionContext viewForKey:UITransitionContextToViewKey].frame;
    modalVCFrame.origin.y = cancelUp ? kModalViewYOffset : viewH - kModalViewNavBarHeight;
    CGAffineTransform transformVal = cancelUp ?
                                                CGAffineTransformMakeScale(kNonModalViewMinScale, kNonModalViewMinScale)
                                              :
                                                CGAffineTransformIdentity;
    CGFloat alphaVal = cancelUp ? kNonModalViewMinAlpha : 1.0;

    [UIView animateWithDuration:duration animations:^{
        [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view.frame = modalVCFrame;
        [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.transform = transformVal;
        [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.alpha = alphaVal;
    } completion:^(BOOL finished) {
        isModalVCOnBottom = !cancelUp;
    }];
}

@end


text:
package CobaiaEx;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

public class Aluno {

	private int maticula;
	private String nome;
	private String sobrenome;
	private Date dataNascimento;

	private DateFormat dateFormat = DateFormat.getDateInstance();

	public int getMaticula() {
		return maticula;
	}
	public void setMaticula(int maticula) {
		this.maticula = maticula;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public String getSobrenome() {
		return sobrenome;
	}
	public void setSobrenome(String sobrenome) {
		this.sobrenome = sobrenome;
	}
	public Date getDataNascimento() {
		return dataNascimento;
	}
	public void setDataNascimento(Date dataNascimento) {
		this.dataNascimento = dataNascimento;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + maticula;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Aluno other = (Aluno) obj;
		if (maticula != other.maticula)
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Aluno [maticula=" + maticula + ", nome=" + nome
				+ ", sobrenome=" + sobrenome + ", dataNascimento="
				+ dataNascimento + "]";
	}
	public String toCSV() {
		StringBuilder builder = new StringBuilder();

		//11030226; Ana Flavia;Moraes;07/02/1999

		builder.append(maticula);
		builder.append(";");
		builder.append(nome);
		builder.append(" ");
		builder.append(sobrenome);
		builder.append(";");
		builder.append(dateFormat.format(dataNascimento));

		return builder.toString();

	}
	public void setDataNascimento(String data) {
		try {
			dataNascimento = dateFormat.parse(data);
		} catch (ParseException e) {
			System.err.println("A data " + data +"eh invalida");
		}

	}

}


text:
namespace higanbana
{
}


text:
FactoryGirl.define do
  factory :post do
    title { Faker::Lorem.sentence }
    body  { Faker::Lorem.paragraphs(3).join("\n") }
  end
end