text:
<?php
/**
 * User: balint
 * Date: 2016. 02. 29.
 * Time: 10:21
 */

namespace Evista\Perform\ValueObject;

use Evista\Perform\Exception\FormFieldException;
use Evista\Perform\Exception\CantMoveToDestination;
use Evista\Perform\Exception\NoFileUploadedException;

class UploadedFile
{
    private $userFileName = false;
    private $safeName = false;
    private $type = false;
    private $tmpName = false;
    private $error = false;
    private $size = false;
    private $realType = false;
    private $userExtension = false;
    private $uploadDir = '';

    public function __construct($name, $index, array $_files, $uploadDir)
    {
        if (! $_files[$name]['name'][$index]) {
            throw new NoFileUploadedException('Emtpy file');
        }

        $this->uploadDir = $uploadDir;
        $this->userFileName = $_files[$name]['name'][$index];
        $this->safeName = md5($this->userFileName + microtime(true));
        $this->type = $_files[$name]['type'][$index];
        $this->tmpName = $_files[$name]['tmp_name'][$index];
        $this->error = $_files[$name]['error'][$index];
        $this->size = $_files[$name]['size'][$index];
        $this->findRealType()->getPathInfo();
        $this->userExtension = $this->pathInfo['extension'];
    }

    public static function create($fieldName, $_files, $uploadDir)
    {

        if (count($_files) < 1) {
            throw new NoFileUploadedException('Emtpy file');
        }

        // if the file field has a name with [] the file(s) will be
        // collected to an array, eg.  ['name' => [0 => 'IMG_29042016_134422.png'] }
        // but if not, the keys value is a flat array, so it needs to be normalized
        if (strpos($fieldName, '[]') != strlen($fieldName) - 2) {
            $_files = array_map(
                function ($file) {
                    return array_map(
                        function ($value) {
                            return [$value];
                        },
                        $file
                    );
                },
                $_files
            );
        }

        // $fieldName includes a '[]' when the upload is multiple
        $fieldName = str_replace(['[', ']'], '', $fieldName);

        if (! array_key_exists($fieldName, $_files)) {
            throw FormFieldException::noSuchFieldName($fieldName);
        }

        $requestedFileField = $_files[$fieldName];
        // Count the uploaded files via one of it's child
        if (! array_key_exists('name', $requestedFileField)) {
            throw new NoNameParam('No name param found in file details');
        }
        $uploadedCount = count($requestedFileField['name']);

        for ($index = 0; $index <= $uploadedCount - 1; $index++) {
            yield new self($fieldName, $index, $_files, $uploadDir);
        }
    }

    /**
     * Move file to destination
     *
     * @param  [type] $destination [description]
     * @return $this [type]              [description]
     * @throws CantMoveToDestination
     */
    public function moveToDestination($destination = false)
    {
        if (! $destination) {
            $destination = $this->uploadDir;
        }

        $fileName = $this->getSafeName();
        if (strpos($this->getRealType(), $this->getUserExtension) == 0) {
            $fileName = $this->getSafeName() . '.' . $this->getUserExtension();
        }

        try {
            rename($this->tmpName, $destination . '/' . $fileName);
        } catch (\Exception $exception) {
            throw new CantMoveToDestination("Error Processing Request", 1);
        }

        return $this;
    }

    /**
     * adds real file type
     *
     * @return [type] [description]
     */
    public function findRealType()
    {
        $finfo = new \finfo();
        // Move file to the upload folder for checking
        $fileName = md5(microtime());
        $destination = $this->uploadDir;
        move_uploaded_file($this->tmpName, $destination.'/'.$fileName);
        $this->realType = $finfo->file($destination.'/'.$fileName, FILEINFO_MIME_TYPE);
        $this->tmpName = $destination.'/'.$fileName;

        return $this;
    }

    /**
     * adds pathinfo result to a local variable
     *
     * @return [type] [description]
     */
    public function getPathInfo()
    {
        $this->pathInfo = pathinfo($this->userFileName);

        return $this;
    }

    /**
     * Get the value of User: balint
     *
     * @return mixed
     */
    public function getUserFileName()
    {
        return $this->userFileName;
    }

    /**
     * Set the value of User: balint
     *
     * @param mixed name
     *
     * @return self
     */
    public function setUserFileName($name)
    {
        $this->userFileName = $name;

        return $this;
    }

    /**
     * Get the value of Type
     *
     * @return mixed
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set the value of Type
     *
     * @param mixed type
     *
     * @return self
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get the value of Tmp Name
     *
     * @return mixed
     */
    public function getTmpName()
    {
        return $this->tmpName;
    }

    /**
     * Set the value of Tmp Name
     *
     * @param mixed tmpName
     *
     * @return self
     */
    public function setTmpName($tmpName)
    {
        $this->tmpName = $tmpName;

        return $this;
    }

    /**
     * Get the value of Error
     *
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * Set the value of Error
     *
     * @param mixed error
     *
     * @return self
     */
    public function setError($error)
    {
        $this->error = $error;

        return $this;
    }

    /**
     * Get the value of Size
     *
     * @return mixed
     */
    public function getSize()
    {
        return $this->size;
    }

    /**
     * Set the value of Size
     *
     * @param mixed size
     *
     * @return self
     */
    public function setSize($size)
    {
        $this->size = $size;

        return $this;
    }

    /**
     * Get the value of User Extension
     *
     * @return mixed
     */
    public function getUserExtension()
    {
        return $this->userExtension;
    }

    /**
     * Set the value of User Extension
     *
     * @param mixed userExtension
     *
     * @return self
     */
    public function setUserExtension($userExtension)
    {
        $this->userExtension = $userExtension;

        return $this;
    }

    /**
     * @return bool|string
     */
    public function getSafeName()
    {
        return $this->safeName;
    }

    /**
     * @param bool|string $safeName
     * @return UploadedFile
     */
    public function setSafeName($safeName)
    {
        $this->safeName = $safeName;

        return $this;
    }

    /**
     * @return boolean
     */
    public function getRealType()
    {
        return $this->realType;
    }

    /**
     * @param boolean $realType
     * @return UploadedFile
     */
    public function setRealType($realType)
    {
        $this->realType = $realType;

        return $this;
    }

    /**
     * Get the value of Upload Dir
     *
     * @return mixed
     */
    public function getUploadDir()
    {
        return $this->uploadDir;
    }

    /**
     * Set the value of Upload Dir
     *
     * @param mixed uploadDir
     *
     * @return self
     */
    public function setUploadDir($uploadDir)
    {
        $this->uploadDir = $uploadDir;

        return $this;
    }
}


text:
<?php

namespace Flarum\Events;

use Flarum\Core\Model;

/**
 * The `ModelDates` event is called to retrieve a list of fields for a model
 * that should be converted into date objects.
 */
class ModelDates
{
    /**
     * @var Model
     */
    public $model;

    /**
     * @var array
     */
    public $dates;

    /**
     * @param Model $model
     * @param array $dates
     */
    public function __construct(Model $model, array &$dates)
    {
        $this->model = $model;
        $this->dates = &$dates;
    }
}

redpajama_set_name: RedPajamaGithub


text:
r"""speed.py tests"""

from corelib.units.speed import kmh

def test_speed():
    r"""Test expected values"""
    expected_value = 1.852
    atol = 1e-10
    assert expected_value - atol <= kmh(knots=1.) <= expected_value + atol


text:
package java

import (
	"archive/tar"
	"bytes"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"github.com/golang/protobuf/proto"
	cutil "github.com/hyperledger/fabric/core/container/util"
	"github.com/hyperledger/fabric/core/util"
	pb "github.com/hyperledger/fabric/protos"
)

//hashFilesInDir computes h=hash(h,file bytes) for each file in a directory
//Directory entries are traversed recursively. In the end a single
//hash value is returned for the entire directory structure
func hashFilesInDir(cutoff string, dir string, hash []byte, tw *tar.Writer) ([]byte, error) {
	//ReadDir returns sorted list of files in dir
	fis, err := ioutil.ReadDir(dir)
	if err != nil {
		return hash, fmt.Errorf("ReadDir failed %s\n", err)
	}
	for _, fi := range fis {
		name := fmt.Sprintf("%s/%s", dir, fi.Name())
		if fi.IsDir() {
			var err error
			hash, err = hashFilesInDir(cutoff, name, hash, tw)
			if err != nil {
				return hash, err
			}
			continue
		}
		buf, err := ioutil.ReadFile(name)
		if err != nil {
			fmt.Printf("Error reading %s\n", err)
			return hash, err
		}

		newSlice := make([]byte, len(hash)+len(buf))
		copy(newSlice[len(buf):], hash[:])
		//hash = md5.Sum(newSlice)
		hash = util.ComputeCryptoHash(newSlice)

		if tw != nil {
			is := bytes.NewReader(buf)
			if err = cutil.WriteStreamToPackage(is, name, name[len(cutoff):], tw); err != nil {
				return hash, fmt.Errorf("Error adding file to tar %s", err)
			}
		}
	}
	return hash, nil
}

func isCodeExist(tmppath string) error {
	file, err := os.Open(tmppath)
	if err != nil {
		return fmt.Errorf("Download failer %s", err)
	}
	fi, err := file.Stat()
	if err != nil {
		return fmt.Errorf("could not stat file %s", err)
	}
	if !fi.IsDir() {
		return fmt.Errorf("file %s is not dir\n", file.Name())
	}
	return nil
}

func getCodeFromHTTP(path string) (codegopath string, err error) {
	//TODO
	return "", nil
}

//generateHashcode gets hashcode of the code under path. If path is a HTTP(s) url
//it downloads the code first to compute the hash.
//NOTE: for dev mode, user builds and runs chaincode manually. The name provided
//by the user is equivalent to the path. This method will treat the name
//as codebytes and compute the hash from it. ie, user cannot run the chaincode
//with the same (name, ctor, args)
func generateHashcode(spec *pb.ChaincodeSpec, tw *tar.Writer) (string, error) {
	if spec == nil {
		return "", fmt.Errorf("Cannot generate hashcode from nil spec")
	}

	chaincodeID := spec.ChaincodeID
	if chaincodeID == nil || chaincodeID.Path == "" {
		return "", fmt.Errorf("Cannot generate hashcode from empty chaincode path")
	}

	ctor := spec.CtorMsg
	if ctor == nil || len(ctor.Args) == 0 {
		return "", fmt.Errorf("Cannot generate hashcode from empty ctor")
	}

	codepath := chaincodeID.Path

	var ishttp bool
	defer func() {
		if ishttp {
			os.RemoveAll(codepath)
		}
	}()

	var err error
	if strings.HasPrefix(codepath, "http://") {
		ishttp = true
		codepath = codepath[7:]
		codepath, err = getCodeFromHTTP(codepath)
	} else if strings.HasPrefix(codepath, "https://") {
		ishttp = true
		codepath = codepath[8:]
		codepath, err = getCodeFromHTTP(codepath)
	} else if !strings.HasPrefix(codepath, "/") {
		wd := ""
		wd, err = os.Getwd()
		codepath = wd + "/" + codepath
	}

	if err != nil {
		return "", fmt.Errorf("Error getting code %s", err)
	}

	if err = isCodeExist(codepath); err != nil {
		return "", fmt.Errorf("code does not exist %s", err)
	}

	root := codepath
	if strings.LastIndex(root, "/") == len(root)-1 {
		root = root[:len(root)-1]
	}
	root = root[:strings.LastIndex(root, "/")+1]
	ctorbytes, err := proto.Marshal(ctor)
	if err != nil {
		return "", fmt.Errorf("Error marshalling constructor: %s", err)
	}
	hash := util.GenerateHashFromSignature(codepath, ctorbytes)

	hash, err = hashFilesInDir(root, codepath, hash, tw)
	if err != nil {
		return "", fmt.Errorf("Could not get hashcode for %s - %s\n", codepath, err)
	}

	return hex.EncodeToString(hash[:]), nil
}


text:
require 'fog/core/collection'
require 'fog/openstack/models/network/lb_pool'

module Fog
  module Network
    class OpenStack
      class LbPools < Fog::Collection

        attribute :filters

        model Fog::Network::OpenStack::LbPool

        def initialize(attributes)
          self.filters ||= {}
          super
        end

        def all(filters = filters)
          self.filters = filters
          load(service.list_lb_pools(filters).body['pools'])
        end

        def get(pool_id)
          if pool = service.get_lb_pool(pool_id).body['pool']
            new(pool)
          end
        rescue Fog::Network::OpenStack::NotFound
          nil
        end

      end
    end
  end
end


text:
package parser

import (
	"errors"
	"log"
	"net/url"
	"strings"

	"golang.org/x/net/html"
)

type HTMLParser struct {
	Content string
}

func (parser *HTMLParser) GetFaviconURL() (string, error) {
	tokenizer := html.NewTokenizer(strings.NewReader(parser.Content))

	var tokenType html.TokenType
	var hasAttributes bool

	var attributeKey []byte
	var attributeValue []byte
	var hasMoreAttributes bool

	hasFavicon := false

	for {
		tokenType = tokenizer.Next()

		if tokenType == html.ErrorToken {
			log.Println("An error occurred while parsing HTML:", tokenizer.Err())
			break
		}

		if tokenType == html.StartTagToken || tokenType == html.SelfClosingTagToken {
			_, hasAttributes = tokenizer.TagName()

			if hasAttributes {
				for {
					attributeKey, attributeValue, hasMoreAttributes = tokenizer.TagAttr()

					if string(attributeKey) == "ref" || string(attributeKey) == "rel" {
						if strings.Contains(string(attributeValue), "shortcut") || strings.Contains(string(attributeValue), "icon") {
							hasFavicon = true
						}
					}

					if string(attributeKey) == "href" && hasFavicon {
						// This only returns the raw value. Need to account for non-normalized URLs
						return string(attributeValue), nil
					}

					if !hasMoreAttributes {
						break
					}
				}
			}
		}
	}

	return "", errors.New("URL not found")
}

func NewHTMLParser(content string) *HTMLParser {
	return &HTMLParser{
		Content: content,
	}
}

func (parser *HTMLParser) NormalizeURL(baseURL, partialURL string) (string, error) {
	result := ""

	parsedBase, err := url.Parse(baseURL)
	if err != nil {
		return result, err
	}

	parsedURL, err := url.Parse(partialURL)
	if err != nil {
		return result, err
	}

	resolvedURL := parsedBase.ResolveReference(parsedURL)
	result = resolvedURL.String()

	return result, nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2018 NY <nyssance@icloud.com>
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resources>

    <string name="details">Oplysninger</string>
    <string name="sd_card">SD-kort</string>
    <string name="themes">TEMA</string>
    <string name="google_play_store">Google Play Butik</string>
    <string name="play_store">Play Butik</string>
    <string name="store">Store</string>
    <string name="applications">Apps</string>
    <string name="install">Installer</string>
    <string name="uninstall">Afinstaller</string>
    <string name="documents">Dokumenter</string>
    <string name="music">Musik</string>
    <string name="pictures">Billeder</string>
    <string name="favorites">Foretrukne</string>
    <string name="open">Åbn</string>
    <string name="open_with">Åbn med</string>
    <string name="delete">Slet</string>
    <string name="share">Del</string>
    <string name="rename">Omdøb</string>
    <string name="create_folder">Opret mappe</string>
    <string name="create_shortcut">installere genveje</string>
    <string name="view">Vis</string>
    <string name="thumbnails">Miniaturebilleder</string>
    <string name="list">Listevisning</string>
    <string name="filmstrip">Filmstrip-visning</string>
    <string name="grid">Gittervisning</string>
    <string name="refresh">Opdater</string>
    <string name="sort">Sorter efter</string>
    <string name="name">Efter navn</string>
    <string name="last_modified">Efter ændringsdato</string>
    <string name="type">Type</string>
    <string name="size">Efter størrelse</string>
    <string name="history">Historik</string>
    <string name="back">Gå tilbage</string>
    <string name="forward">Gå fremad</string>
    <string name="up">Gå op</string>
    <string name="home">Hjem</string>
    <string name="settings">Indstillinger</string>
    <string name="help">Hjælp</string>
    <string name="move">Flyt</string>
    <string name="new_folder">Ny mappe</string>

</resources>


text:
namespace WinUX.Xaml.VisualStateTriggers.DeviceTrigger
{
    using Windows.Foundation.Metadata;
    using Windows.Graphics.Display;
    using Windows.UI.Xaml;

    using WinUX.Device.Profile;

    /// <summary>
    /// Defines the properties for the <see cref="DeviceTrigger"/>.
    /// </summary>
    public sealed partial class DeviceTrigger
    {
        /// <summary>
        /// Defines the dependency property for <see cref="DeviceType"/>.
        /// </summary>
        public static readonly DependencyProperty DeviceTypeProperty = DependencyProperty.Register(
            nameof(DeviceType),
            typeof(DeviceType),
            typeof(DeviceTrigger),
            new PropertyMetadata(DeviceType.Unknown, OnDeviceTypeChanged));

        /// <summary>
        /// Defines the dependency property for <see cref="SupportsContinuum"/>.
        /// </summary>
        public static readonly DependencyProperty SupportsContinuumProperty =
            DependencyProperty.Register(
                nameof(SupportsContinuum),
                typeof(bool),
                typeof(DeviceTrigger),
                new PropertyMetadata(false));

        /// <summary>
        /// Gets or sets the expected device type.
        /// </summary>
        public DeviceType DeviceType
        {
            get
            {
                return (DeviceType)this.GetValue(DeviceTypeProperty);
            }
            set
            {
                this.SetValue(DeviceTypeProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to support continuum for Mobile.
        /// </summary>
        public bool SupportsContinuum
        {
            get
            {
                return (bool)this.GetValue(SupportsContinuumProperty);
            }
            set
            {
                this.SetValue(SupportsContinuumProperty, value);
            }
        }

        private static double ScreenDiagonal
        {
            get
            {
                var di = DisplayInformation.GetForCurrentView();

                return ApiInformation.IsPropertyPresent(
                           typeof(DisplayInformation).ToString(),
                           nameof(di.DiagonalSizeInInches)) && di.DiagonalSizeInInches != null
                           ? di.DiagonalSizeInInches.Value
                           : 7;
            }
        }
    }
}


text:
function randomShortInt(){
	return this.r.genrand_int32()
}

function randomSignedShortInt(){
	var sign=this.rint(2)? '':'-'
	return sign+this.r.genrand_int32()
}

function randomLongInt(){
	return this.r.genrand_int31()+this.r.genrand_int32()
}

function randomSignedLongInt(){
	var sign=this.rint(2)? '':'-'
	return sign+this.r.genrand_int32()+this.r.genrand_int32()
}

function randomShortFloat(){
	return this.r.genrand_res53()
}

function randomSignedShortFloat(){
	var sign=this.rint(2)? '':'-'
	return sign+this.r.genrand_res53()
}

function randomLongFloat(){
	return ''+this.r.genrand_res53()+this.r.genrand_int32()
}

function randomSignedLongFloat(){
	var sign=this.rint(2)? '':'-'
	return sign+this.r.genrand_res53()+this.r.genrand_int32()
}

function randomInterestingNumber(){
	var interestingNumbers=[
		"-2147483648", /* Overflow signed 32-bit when decremented */
		"-100000000",    /* Large negative number (100M)            */
  		"-32769",        /* Overflow signed 16-bit                  */
   		"32768",        /* Overflow signed 16-bit                  */
   		"65535",        /* Overflow unsig 16-bit when incremented  */
   		"65536",        /* Overflow unsig 16 bit                   */
   		"100000000",    /* Large positive number (100M)            */
   		"2147483647",    /* Overflow signed 32-bit when incremented */
		"-32768",        /* Overflow signed 16-bit when decremented */
		"-129",          /* Overflow signed 8-bit                   */
		"128",          /* Overflow signed 8-bit                   */
		"255",          /* Overflow unsig 8-bit when incremented   */
		"256",          /* Overflow unsig 8-bit                    */
		"512",          /* One-off with common buffer size         */
		"1000",         /* One-off with common buffer size         */
		"1024",         /* One-off with common buffer size         */
		"4096",         /* One-off with common buffer size         */
		"32767",         /* Overflow signed 16-bit when incremented */
		"-128",          /* Overflow signed 8-bit when decremented  */
		"-1",            /*                                         */
		"0",            /*                                         */
		"1",            /*                                         */
		"16",           /* One-off with common buffer size         */
		"32",           /* One-off with common buffer size         */
		"64",           /* One-off with common buffer size         */
		"100",          /* One-off with common buffer size         */
		"127"           /* Overflow signed 8-bit when incremented  */

	]
	var endings=[
		'000000000000000000000000000000000000000000000000000001',
		'999999999999999999999999999999999999999999999999999999',
	]
	var interestingValue=this.ra(interestingNumbers)
	if(!this.rint(3))
		interestingValue+=1
	else if(this.rint(2))
		interestingValue=interestingValue+'.'+this.ra(endings)
	if(!this.rint(3))
		return '-'+interestingValue
	else
		return interestingValue
}

var numberGenerators=[
	{generator:randomShortInt,weight:4},
	{generator:randomSignedShortInt,weight:2},
	{generator:randomLongInt,weight:3},
	{generator:randomSignedLongInt,weight:1},
	{generator:randomShortFloat,weight:2},
	{generator:randomLongFloat,weight:2},
	{generator:randomSignedShortFloat,weight:1},
	{generator:randomSignedLongFloat,weight:1},
	{generator:randomInterestingNumber,weight:5}
]

function calcGeneratorWeights(generators){
	var weightedGeneratorsList=new Array()
	generators.forEach(function(generator){
		var weight=generator.weight
		while(weight--){
			weightedGeneratorsList.push(generator.generator)
		}
	})
	return weightedGeneratorsList
}

var numberGeneratorList=calcGeneratorWeights(numberGenerators)

module.exports={
	randomNumber:function(){
		return (this.ra(numberGeneratorList)).call(this)
	}
}


text:
import { observable, autorun } from 'mobx';
import cupStore from './CupState.js'

// import ButtonSelect from './ButtonSelect.js'

class CupItem extends Phaser.Group{
	constructor(index) {
		super(game, game.world, 'cup'+index)
		this.index = index
		this.w = game.cache.getImage('cup').width
		this.h = game.cache.getImage('cup').height

		this.repsonsive = {leftRight: 10, padding: 20, scale: 1}

		this.getScale()

		this.scale.set(this.repsonsive.scale)

		this.createCup()
		// this.createButton()

		this.inputEnabled = true;

		autorun( () => {
			this.prevData = this.id
			this.id = cupStore.idList[index]
			if(this.prevData !== undefined) {
				const direction = this.id - this.prevData
				if(direction!==0) {
					this.shift(direction)
				}
			}

			if(cupStore.status === cupStore.STATUS_SELECT) {
				this.cup.input.useHandCursor = true;
				this.cup.events.onInputDown.add(this.onSelect, this)
			}else {
				this.cup.events.onInputDown.remove(this.onSelect, this)
				this.cup.input.useHandCursor = false;
			}

		} )

		this.createFood()
		this.craeteText()

		this.cup.bringToTop()

		if(!this.prevData) {
			const pos = this.setPos(this.id)
			this.x = pos.x
			this.y = pos.y
		}
	}

	getScale() {
		let spaceAvailable = game.width - (this.repsonsive.leftRight * 2)
		let spaceUsed = (game.cache.getImage('cup').width + this.repsonsive.padding) * 3
		let spaceLeftOver
		if(spaceAvailable > spaceUsed) {
			this.repsonsive.leftRight = 0
			this.repsonsive.padding = 0
			spaceAvailable = game.width - (this.repsonsive.leftRight * 2)
			spaceUsed = (game.cache.getImage('cup').width + this.repsonsive.padding) * 3
			spaceLeftOver = spaceAvailable - spaceUsed
			this.repsonsive.scale = 1
			this.repsonsive.leftRight = spaceLeftOver * .25
			this.repsonsive.padding = spaceLeftOver * .25
		}else{
			spaceAvailable = game.width - (this.repsonsive.leftRight * 2)
			spaceUsed = (game.cache.getImage('cup').width + this.repsonsive.padding) * 3
			this.repsonsive.scale = spaceAvailable / spaceUsed
		}
	}

	shift(direction) {
		let paths = []
		let destination
		let cupWidth = this.width
		let yHeight = (30*this.scale.x) * direction

		destination = this.setPos(this.id)
		const dist = destination.x - this.x

		paths = [
			{x:this.x, y:this.y},
			{x:this.x+(dist/2), y:this.y+yHeight},
			{...destination},
		]

		const time = cupStore.getDifficulty().speed
		const me = this
		const scaleSize = yHeight > 0 ? this.scale.x*1.1 : this.scale.x*.9
		TweenMax.to(this, time, {bezier:{curviness: 2.5, type:"thru", values:paths}, ease:Sine.easeInOut, onUpdate:function(){
			me.parent.sort('y', Phaser.Group.SORT_ASCENDING);
		}})

		TweenMax.to(this.scale, time/2, {x:scaleSize, y:scaleSize, yoyo:true, repeat:1, ease:Sine.easeInOut})

	}

	onSelect() {

		if(cupStore.status === cupStore.STATUS_SELECT) {
			this.showHide()
			cupStore.addTartar(this.foodData)
			cupStore.statusUpdate(cupStore.STATUS_SHUFFLE)
		}
	}

	getEdge() {

	}

	showHide() {
		const tl = new TimelineMax()
		tl.to(this.cup, .3, {y:-160})
		tl.to(this.cup, .3, {y:0}, "+=.7")
		return tl
	}

	setPos(id) {
		const paddingRight = this.repsonsive.padding
		let x = this.repsonsive.leftRight
		x += ((this.w*this.scale.x) + paddingRight) * id

		return {x:x, y:game.height-(this.height*1.4)}
	}

	craeteText() {
		const text = game.add.text(this.w/2, this.h/2, this.index, {fill:'white', font:'88px Arial'})
		text.anchor.set(.5)
		text.alpha = 0
		this.add(text)
	}

	createCup() {
		this.cup = game.add.image(0, 0, 'cup')
		this.cup.inputEnabled = true
		// this.cup.alpha = .3

		this.add(this.cup)
	}

	createButton() {
		this.buttonSelect = new ButtonSelect(this.onSelect.bind(this))
		this.buttonSelect.alignTo(this.cup, Phaser.BOTTOM_CENTER, 0, 10)
		this.add(this.buttonSelect)
	}

	createFood() {
		this.foodData = cupStore.foodList[this.index]
		const food = game.add.image(0, 0, this.foodData.id)
		food.anchor.set(.5)
		food.x = this.w/2
		food.y = this.h - (food.height*.65)
		this.add(food)
	}

	// tween(id) {
	// 	const pos = this.setPos(id)
	// 	TweenMax.to(this, .85, pos)
	// }

	// render() {
	// 	console.log(Math.random());
	// }

	// create(x, y, data) {
	// 	console.log(this);
	// }

}

export default CupItem


text:
<component name="libraryTable">
  <library name="Maven: org.springframework.boot:spring-boot-starter-json:2.0.0.M2">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/springframework/boot/spring-boot-starter-json/2.0.0.M2/spring-boot-starter-json-2.0.0.M2.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/springframework/boot/spring-boot-starter-json/2.0.0.M2/spring-boot-starter-json-2.0.0.M2-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/springframework/boot/spring-boot-starter-json/2.0.0.M2/spring-boot-starter-json-2.0.0.M2-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?php
namespace Agl\Core\Db;

/**
 * Interface - Db
 *
 * @category Agl_Core
 * @package Agl_Core_Db
 * @version 0.1.0
 */

interface DbInterface
{
    /**
     * Supported database engine : MySQL.
     */
    const MYSQL = 'mysql';

    /**
     * Load filters keys.
     */
    const FILTER_CONDITIONS = 'conditions';
    const FILTER_LIMIT      = 'limit';
    const FILTER_ORDER      = 'order';

    /**
     * Order RANDOM keyword.
     */
    const ORDER_RAND = 'RAND';

    public function setConnection($pHost, $pName, $pUser = NULL, $pPassword = NULL);
    public function getConnection();
    public function incrementCounter();
    public function countQueries();
    public function connect($pHost, $pDb, $pUser = NULL, $pPass = NULL);
    public function listCollections(array $pWithFields = array());
}


text:
from oslo_log import log as logging
from sqlalchemy import Boolean, Column, DateTime, ForeignKey
from sqlalchemy import Integer, MetaData, String, Table

from cinder.i18n import _LE

LOG = logging.getLogger(__name__)

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    sm_backend_config = Table('sm_backend_config', meta, autoload=True)
    sm_flavors = Table('sm_flavors', meta, autoload=True)
    sm_volume = Table('sm_volume', meta, autoload=True)

    tables = [sm_volume, sm_backend_config, sm_flavors]

    for table in tables:
        try:
            table.drop()
        except Exception:
            LOG.exception(_LE('Exception while dropping table %s.'),
                          repr(table))
            raise

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    Table('volumes', meta, autoload=True)

    sm_backend_config = Table(
        'sm_backend_config', meta,
        Column('created_at', DateTime),
        Column('updated_at', DateTime),
        Column('deleted_at', DateTime),
        Column('deleted', Boolean),
        Column('id', Integer, primary_key=True, nullable=False),
        Column('flavor_id', Integer, ForeignKey('sm_flavors.id'),
               nullable=False),
        Column('sr_uuid', String(length=255)),
        Column('sr_type', String(length=255)),
        Column('config_params', String(length=2047)),
        mysql_engine='InnoDB',
        mysql_charset='utf8'
    )

    sm_flavors = Table(
        'sm_flavors', meta,
        Column('created_at', DateTime),
        Column('updated_at', DateTime),
        Column('deleted_at', DateTime),
        Column('deleted', Boolean),
        Column('id', Integer, primary_key=True, nullable=False),
        Column('label', String(length=255)),
        Column('description', String(length=255)),
        mysql_engine='InnoDB',
        mysql_charset='utf8'
    )

    sm_volume = Table(
        'sm_volume', meta,
        Column('created_at', DateTime),
        Column('updated_at', DateTime),
        Column('deleted_at', DateTime),
        Column('deleted', Boolean),
        Column('id', String(length=36),
               ForeignKey('volumes.id'),
               primary_key=True,
               nullable=False),
        Column('backend_id', Integer, ForeignKey('sm_backend_config.id'),
               nullable=False),
        Column('vdi_uuid', String(length=255)),
        mysql_engine='InnoDB',
        mysql_charset='utf8'
    )

    tables = [sm_flavors, sm_backend_config, sm_volume]

    for table in tables:
        try:
            table.create()
        except Exception:
            LOG.exception(_LE('Exception while creating table %s.'),
                          repr(table))
            raise


text: Simple game for school project


text:
public class EqualsAndHashCodeNewStyle {
	int b;
	double c;
	int f;
	int d;
	int f() {
		return 0;
	}
	int g;
	long i() {
		return 0;
	}
	int j;
	@Override
	@SuppressWarnings("all")
	public boolean equals(final Object o) {
		if (o == this) return true;
		if (!(o instanceof EqualsAndHashCodeNewStyle)) return false;
		final EqualsAndHashCodeNewStyle other = (EqualsAndHashCodeNewStyle) o;
		if (!other.canEqual((Object) this)) return false;
		if (this.b != other.b) return false;
		if (Double.compare(this.c, other.c) != 0) return false;
		if (this.d != other.d) return false;
		if (this.f() != other.f()) return false;
		if (this.i() != other.i()) return false;
		return true;
	}
	@SuppressWarnings("all")
	protected boolean canEqual(final Object other) {
		return other instanceof EqualsAndHashCodeNewStyle;
	}
	@Override
	@SuppressWarnings("all")
	public int hashCode() {
		final int PRIME = 59;
		int result = 1;
		result = result * PRIME + this.b;
		final long $c = Double.doubleToLongBits(this.c);
		result = result * PRIME + (int) ($c >>> 32 ^ $c);
		result = result * PRIME + this.d;
		result = result * PRIME + this.f();
		final long $$i = this.i();
		result = result * PRIME + (int) ($$i >>> 32 ^ $$i);
		return result;
	}
}


text:
/*global jasmine, module, expect, inject, describe, it, before, beforeEach, after, afterEach */

describe('crud feature', function(){
  beforeEach(module('coopr-ui.feature.crud'));

  describe('CrudCreateCtrl', function() {
    var $scope, myApi;

    beforeEach(inject(function($rootScope, $controller, _myApi_) {
      $scope = $rootScope.$new();
      myApi = _myApi_;
      $controller('CrudCreateCtrl', {$scope: $scope, $state: {
        current: { data: {modelName:'Cluster'} }
      }});
    }));

    it('has a doSubmit method', function() {
      expect($scope.doSubmit).toEqual(jasmine.any(Function));
    });

    it('model is a *modelName* instance', function() {
      expect($scope.model).toEqual(jasmine.any(myApi.Cluster));
    });

  });

});


text:
title: The State of Ghost vs. WordPress
date: 2015-05-20 13:38:00 +0200
excerpt: I do like the concept of Ghost, but I'm not committing to a product where I'm missing important features compared to WordPress.
categories: Blogging
tags: [Ghost, WordPress]
permalink: /ghost-vs-wordpress
redirect_from:
  - /ghost-vs-wordpress/
layout: post
---
After two years in, [Ghost is taking a look back](https://blog.ghost.org/year-2/). They are profitable and show how they spent their money. It's a long but very good read.

What I consider epic is the [publicly available revenue data](https://ghost.org/about/#metrics) of hosted Ghost, which is called [Ghost(Pro)](https://ghost.org/pricing/), and the rest of the non-profit company that the Ghost Foundation is.

I do like the concept of Ghost, but I'm not committing to an "unfinished" product, where I'm missing important features compared to WordPress. Comparing WordPress to Ghost is a little bit unfair, because WordPress exists so much longer and has a huge plugin repository. So I tested some versions over time but never made the jump from WordPress to Ghost.

## Evolvement of Ghost

I go to the public [Ghost roadmap](https://trello.com/b/EceUgtCL/ghost-roadmap) every once in a while to see what they're up to. There were a couple of things missing, which I consider essential for running a blog. Most of those have been added in 2015.

- __Navigation menu for pages__. Before you had to edit the theme directly to add pages to a menu. This feature is rudimentary.
- __Prev/Next post links__, to link posts in single post view.
- __Generate sitemap.xml__, for search engines to easier find all your content.
- __Open Graph Tags by default__, for displaying the articles title, excerpt and image automatically on Facebook or Twitter when being shared.
- __Mobile uploads in editor__. Without this I couldn't post images to articles when being on my iPhone or iPad. The [WordPress app on iOS](https://itunes.apple.com/us/app/wordpress/id335703880?mt=8) or [Android](https://play.google.com/store/apps/details?id=org.wordpress.android) is still much better, though.
- __Tag management__, for editing or deleting tags. This feature is rudimentary.
- __Better RSS feed__, to include the featured image.

Now it seems Ghost would be ready to replace WordPress for me. Almost.

## Features I'm still missing

The current version (0.6.3) is still missing a couple of features:

- __[Post filter menu](https://trello.com/c/7GUDsl3J/48-post-filter-menu)__, to easily find my drafts (I have dozens) or to only show my published posts.
- __Search__, to be able to search the post content only. Google site search is very inconvenient if you search for a phrase which is also in your menu or footer, because you'll get _all_ of your pages as a result.
- __(Semi-)Automatic updates__. I like my blog keeping updated automatically. If this is not possible I like to get an email if an update is available and press a button in the admin area to manually update.

Interestingly, everything I want I do get from WordPress today.

## Ghost's Promise of Speed

Ghost promised to be faster than WordPress, which can be quite heavy on servers. Compared to stock WordPress, Ghost's performance is 3–4 times better. Using plenty of plugins, WordPress is getting even slower.

But caching can speed up WordPress tremendously. On my setup (nginx, Batcache, memcache, Zend PHP opcache) caching improves WordPress performance 50 times. So my cached WordPress blog is 15 times faster than Ghost, which doesn't support caching out of the box.

## Bottom line Ghost vs. WordPress

Ghost is much slower than cached WordPress. And I'm still missing a couple of features. So I'm staying with WordPress for now and keep on waiting.


text:
package org.bedework.util.calendar.diff;

import org.bedework.util.calendar.XcalUtil.TzGetter;
import org.bedework.util.xml.tagdefs.XcalTags;

import org.apache.log4j.Logger;
import org.oasis_open.docs.ws_calendar.ns.soap.ComponentSelectionType;
import org.oasis_open.docs.ws_calendar.ns.soap.ObjectFactory;

import ietf.params.xml.ns.icalendar_2.CreatedPropType;
import ietf.params.xml.ns.icalendar_2.DtstampPropType;
import ietf.params.xml.ns.icalendar_2.IcalendarType;
import ietf.params.xml.ns.icalendar_2.LastModifiedPropType;
import ietf.params.xml.ns.icalendar_2.ProdidPropType;
import ietf.params.xml.ns.icalendar_2.VcalendarType;
import ietf.params.xml.ns.icalendar_2.VersionPropType;
import ietf.params.xml.ns.icalendar_2.XBedeworkUidParamType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** This class compares 2 components. These components may contain other
 * sub-components, for example alarms. What is produced is a set of updates
 * to generate one from the other.
 *
 *
For this to work, and for updates to be applicable, we need well defined
 * rules determining how we match components. For example, an event is matched
 * if the UID and RECURRENCE-ID matches.
 *
 *
This is a little more difficult for some components which don't have a uid,
 * alarms for example.
 *
 * @author Mike Douglass
 */
public class XmlIcalCompare {
  protected transient Logger log;

  /** */
  public static final List<Object> defaultSkipList;

  static {
    defaultSkipList = new ArrayList<Object>();

    /* Calendar properties */
    defaultSkipList.add(new ProdidPropType());
    defaultSkipList.add(new VersionPropType());

    /* Entity properties */
    defaultSkipList.add(new CreatedPropType());
    defaultSkipList.add(new DtstampPropType());
    defaultSkipList.add(new LastModifiedPropType());

    /* Parameters */
    defaultSkipList.add(new XBedeworkUidParamType());
  }

  /** Stuff to which all the generated objects need access.
   */
  static class Globals {
    Map<String, Object> skipMap;
    ObjectFactory of;
    ValueMatcher matcher;
    TzGetter tzs;

    Globals(final Map<String, Object> skipMap,
            final ObjectFactory of,
            final ValueMatcher matcher,
            final TzGetter tzs) {
      this.skipMap = skipMap;
      this.of = of;
      this.matcher = matcher;
      this.tzs = tzs;
    }
  }

  private Globals globals;

  /** The skippedEntities allow the diff process to ignore components,
   * properties and/or parameters that should not take part in the comparison.
   *
   *
Populate the list with empty icalendar objects.
   *
   * @param skippedEntities Objects of the class that should be skipped
   * @param tzs
   */
  public XmlIcalCompare(final List<? extends Object> skippedEntities,
                        final TzGetter tzs) {
    globals = new Globals(new HashMap<String, Object>(),
                          new ObjectFactory(),
                          new ValueMatcher(),
                          tzs);

    for (Object o: skippedEntities) {
      globals.skipMap.put(o.getClass().getCanonicalName(), o);
    }
  }

  /** Compare the parameters. Return null for equal or a select element.
   *
   * @param newval
   * @param oldval
   * @return SelectElementType if val1 and val2 differ else null.
   */
  public ComponentSelectionType diff(final IcalendarType newval,
                                     final IcalendarType oldval) {
    VcalendarType nv = newval.getVcalendar().get(0);
    VcalendarType ov = oldval.getVcalendar().get(0);

    CompWrapper ncw = new CompWrapper(globals,
                                      XcalTags.vcalendar,
                                      nv);
    CompWrapper ocw = new CompWrapper(globals,
                                      XcalTags.vcalendar,
                                      ov);

    return ncw.diff(ocw);
  }

  private Logger getLogger() {
    if (log == null) {
      log = Logger.getLogger(this.getClass());
    }

    return log;
  }

  @SuppressWarnings("unused")
  private void trace(final String msg) {
    getLogger().debug(msg);
  }
}


text:
package nl.armatiek.xmlindex.saxon.functions.xmlindex;

import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.TransformerException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ErrorListener implements javax.xml.transform.ErrorListener {

  private static final Logger logger = LoggerFactory.getLogger(ErrorListener.class);

  private String reference;

  private List<TransformerException> errors;

  public ErrorListener(String reference) {
    this.reference = reference;
  }

  @Override
  public void warning(TransformerException exception) throws TransformerException {
    logger.warn("Warning processing " + reference, exception);
  }

  @Override
  public void error(TransformerException exception) throws TransformerException {
    logger.warn("Error processing " + reference, exception);
    addException(exception);
  }

  @Override
  public void fatalError(TransformerException exception) throws TransformerException {
    logger.warn("Fatal error processing " + reference, exception);
    addException(exception);
  }

  public TransformerException getFirstError() {
    if (errors.isEmpty())
      return null;
    return errors.get(0);
  }

  private void addException(TransformerException exception) {
    if (errors == null)
      errors = new ArrayList<TransformerException>();
    errors.add(exception);
  }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;

namespace Microsoft.CodeAnalysis.EditAndContinue
{
    internal sealed class EncDebuggingSessionInfo
    {
        public readonly List<EncEditSessionInfo> EditSessions = new List<EncEditSessionInfo>();
        public int EmptyEditSessions { get; private set; }

        internal void EndEditSession(EncEditSessionInfo encEditSessionInfo)
        {
            if (encEditSessionInfo.IsEmpty())
            {
                EmptyEditSessions++;
            }
            else
            {
                EditSessions.Add(encEditSessionInfo);
            }
        }
    }
}


text:
package io.github.tcdl.msb.config.activemq;

import com.typesafe.config.Config;
import io.github.tcdl.msb.api.SubscriptionType;
import io.github.tcdl.msb.config.ConfigurationUtil;

import java.util.Optional;

public class ActiveMQBrokerConfig {

    private String url;
    private final Optional<String> username;
    private final Optional<String> password;
    private final SubscriptionType defaultSubscriptionType;
    private final Optional<String> groupId;
    private final boolean durable;
    private final int prefetchCount;
    private final int connectionIdleTimeout;

    private ActiveMQBrokerConfig(String url, Optional<String> username, Optional<String> password,
                                 SubscriptionType defaultSubscriptionType, Optional<String> groupId,
                                 boolean durable, int prefetchCount, int connectionIdleTimeout) {
        this.url = url;
        this.username = username;
        this.password = password;
        this.defaultSubscriptionType = defaultSubscriptionType;
        this.groupId = groupId;
        this.durable = durable;
        this.prefetchCount = prefetchCount;
        this.connectionIdleTimeout = connectionIdleTimeout;
    }

    public final static class ActiveMQBrokerConfigBuilder {

        private String url;
        private Optional<String> username;
        private Optional<String> password;
        private SubscriptionType defaultSubscriptionType;
        private Optional<String> groupId;
        private boolean durable;
        private int prefetchCount;
        private int connectionIdleTimeout;

        public ActiveMQBrokerConfigBuilder withConfig(Config config) {
            this.url = ConfigurationUtil.getString(config, "url");
            this.username = ConfigurationUtil.getOptionalString(config, "username");
            this.password = ConfigurationUtil.getOptionalString(config, "password");
            this.defaultSubscriptionType = SubscriptionType.valueOf(ConfigurationUtil.getString(config, "defaultSubscriptionType").toUpperCase());
            this.groupId = ConfigurationUtil.getOptionalString(config, "groupId");
            this.durable = ConfigurationUtil.getBoolean(config, "durable");
            this.prefetchCount = ConfigurationUtil.getInt(config, "prefetchCount");
            this.connectionIdleTimeout = ConfigurationUtil.getInt(config, "connectionIdleTimeout");
            return this;
        }

        public ActiveMQBrokerConfig build() {
            return new ActiveMQBrokerConfig(url, username, password, defaultSubscriptionType, groupId, durable, prefetchCount, connectionIdleTimeout);
        }
    }

    public String getUrl() {
        return url;
    }

    public Optional<String> getUsername() {
        return username;
    }

    public Optional<String> getPassword() {
        return password;
    }

    public SubscriptionType getDefaultSubscriptionType() {
        return defaultSubscriptionType;
    }

    public Optional<String> getGroupId() {
        return groupId;
    }

    public boolean isDurable() {
        return durable;
    }

    public int getPrefetchCount() {
        return prefetchCount;
    }

    public int getConnectionIdleTimeout() {
        return connectionIdleTimeout;
    }

    @Override
    public String toString() {
        return String.format("ActiveMQBrokerConfig [url=%s, username=%s, password=xxx, defaultSubscriptionType=%s, groupId=%s, durable=%s, prefetchCount=%s, connectionIdleTimeout=%s",
                url, username, defaultSubscriptionType, groupId, durable, prefetchCount, connectionIdleTimeout);
    }
}


text:
package org.jboss.weld.tests.producer.field;

import javax.inject.Inject;
import java.util.Collection;
import java.util.List;

public class Target {

    @Inject
    private Collection<String> strings;

    @Inject
    private Collection<Integer> integers;

    @Inject
    private List<String> stringList;

    public Collection<String> getStrings() {
        return strings;
    }

    public Collection<Integer> getIntegers() {
        return integers;
    }

    public List<String> getStringList() {
        return stringList;
    }

}


text:
var extractor = require('../extractor/put');
var fixtures = require('./fixtures/_index');

module.exports.extractor = {};

module.exports.extractor.invalidPut = function(test, common) {
  test('constructor: invalidCallback', function(t) {
    var proxy = extractor();
    t.equal(typeof proxy, 'function', 'function returned');
    t.throws(proxy, /(undefined|cb) is not a function$/, 'exception thrown');
    t.end();
  });
}

module.exports.extractor.respEmitsError = function(test, common) {
  test('resp: emitsError', function(t) {
    var proxy = extractor( function( err, resp ){
      t.equal(typeof err, 'string', 'error emitted');
      t.equal(err, 'an upstream error', err);
      t.end();
    });
    t.equal(typeof proxy, 'function', 'function returned');
    proxy( 'an upstream error' ); // upstream error
  });
}

module.exports.extractor.respFail = function(test, common) {
  test('resp: respFail', function(t) {
    var proxy = extractor( function( err, resp ){
      t.equal(err, undefined, 'no error emitted');
      t.equal(resp, false, 'put operation failed');
      t.end();
    });
    t.equal(typeof proxy, 'function', 'function returned');
    proxy(); // no hits
  });
  test('resp: respFail', function(t) {
    var proxy = extractor( function( err, resp ){
      t.equal(err, undefined, 'no error emitted');
      t.equal(resp, false, 'put operation failed');
      t.end();
    });
    t.equal(typeof proxy, 'function', 'function returned');
    proxy( undefined, { created: false } ); // fail
  });
}

module.exports.extractor.respSuccess = function(test, common) {
  test('resp: respSuccess', function(t) {
    var proxy = extractor( function( err, resp ){
      t.equal(err, undefined, 'no error emitted');
      t.equal(typeof resp, 'object', 'put operation success');
      t.equal(resp._id, '1', 'field returned');
      t.equal(resp._index, 'delme', 'field returned');
      t.equal(resp._type, 'tweet', 'field returned');
      t.end();
    });
    t.equal(typeof proxy, 'function', 'function returned');
    proxy( null, fixtures.put );
  });
}

module.exports.extractor.genericFailure = function(test, common) {
  test('resp: genericFailure', function(t) {
    var proxy = extractor( function( err, resp ){
      t.equal(err, fixtures.genericfail.error, 'error emitted');
      t.equal(resp, undefined, 'no results returned');
      t.end();
    });
    t.equal(typeof proxy, 'function', 'function returned');
    proxy( null, fixtures.genericfail );
  });
}

module.exports.all = function (tape, common) {

  function test(name, testFunction) {
    return tape('put extractor: ' + name, testFunction)
  }

  for( var testCase in module.exports.extractor ){
    module.exports.extractor[testCase](test, common);
  }
}


text:
package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class InTheAir extends StdRoom
{
	@Override public String ID(){return "InTheAir";}
	public InTheAir()
	{
		super();
		basePhyStats.setWeight(1);
		name="the sky";
		recoverPhyStats();
	}
	@Override public int domainType(){return Room.DOMAIN_OUTDOORS_AIR;}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!super.okMessage(myHost,msg))
			return false;
		return isOkAirAffect(this,msg);
	}

	public static void airAffects(Room room, CMMsg msg)
	{
		if(CMLib.flags().isSleeping(room))
			return;
		boolean foundReversed=false;
		boolean foundNormal=false;
		final Vector<Physical> needToFall=new Vector<Physical>();
		final Vector<Physical> mightNeedAdjusting=new Vector<Physical>();
		for(int i=0;i<room.numInhabitants();i++)
		{
			final MOB mob=room.fetchInhabitant(i);
			if((mob!=null)
			&&((mob.getStartRoom()==null)||(mob.getStartRoom()!=room)))
			{
				final Ability A=mob.fetchEffect("Falling");
				if(A!=null)
				{
					if(A.proficiency()>=100)
					{
						foundReversed=true;
						mightNeedAdjusting.addElement(mob);
					}
					foundNormal=foundNormal||(A.proficiency()<=0);
				}
				else
					needToFall.addElement(mob);
			}
		}
		for(int i=0;i<room.numItems();i++)
		{
			final Item item=room.getItem(i);
			if(item!=null)
			{
				final Ability A=item.fetchEffect("Falling");
				if(A!=null)
				{
					if(A.proficiency()>=100)
					{
						foundReversed=true;
						mightNeedAdjusting.addElement(item);
					}
					foundNormal=foundNormal||(A.proficiency()<=0);
				}
				else
				if(item.container()==null)
					needToFall.addElement(item);
			}
		}
		final int avg=((foundReversed)&&(!foundNormal))?100:0;
		for(final Physical P : mightNeedAdjusting)
		{
			final Ability A=P.fetchEffect("Falling");
			if(A!=null)
				A.setProficiency(avg);
		}
		final TrackingLibrary tracker = CMLib.tracking();
		for(final Physical P : needToFall)
			tracker.makeFall(P,room,avg);
	}

	@Override
	public void executeMsg(final Environmental myHost, final CMMsg msg)
	{
		super.executeMsg(myHost,msg);
		InTheAir.airAffects(this,msg);
	}

	public static boolean isOkAirAffect(Room room, CMMsg msg)
	{
		if(CMLib.flags().isSleeping(room))
			return true;
		if((msg.sourceMinor()==CMMsg.TYP_SIT)
		&&(!(msg.target() instanceof Exit))
		&&(!msg.sourceMajor(CMMsg.MASK_ALWAYS)))
		{
			msg.source().tell(CMLib.lang().L("You can't sit here."));
			return false;
		}
		if((msg.sourceMinor()==CMMsg.TYP_SLEEP)&&(!msg.sourceMajor(CMMsg.MASK_ALWAYS)))
		{
			msg.source().tell(CMLib.lang().L("You can't sleep here."));
			return false;
		}

		if((msg.targetMinor()==CMMsg.TYP_ENTER)
		&&(msg.amITarget(room)))
		{
			final MOB mob=msg.source();
			if((!CMLib.flags().isInFlight(mob))&&(!CMLib.flags().isFalling(mob)))
			{
				mob.tell(CMLib.lang().L("You can't fly."));
				return false;
			}
			if(CMLib.dice().rollPercentage()>50)
			switch(room.getArea().getClimateObj().weatherType(room))
			{
			case Climate.WEATHER_BLIZZARD:
				room.show(mob,null,CMMsg.MSG_OK_VISUAL,CMLib.lang().L("The swirling blizzard inhibits <S-YOUPOSS> progress."));
				return false;
			case Climate.WEATHER_HAIL:
				room.show(mob,null,CMMsg.MSG_OK_VISUAL,CMLib.lang().L("The hail storm inhibits <S-YOUPOSS> progress."));
				return false;
			case Climate.WEATHER_RAIN:
				room.show(mob,null,CMMsg.MSG_OK_VISUAL,CMLib.lang().L("The rain storm inhibits <S-YOUPOSS> progress."));
				return false;
			case Climate.WEATHER_SLEET:
				room.show(mob,null,CMMsg.MSG_OK_VISUAL,CMLib.lang().L("The biting sleet inhibits <S-YOUPOSS> progress."));
				return false;
			case Climate.WEATHER_THUNDERSTORM:
				room.show(mob,null,CMMsg.MSG_OK_VISUAL,CMLib.lang().L("The thunderstorm inhibits <S-YOUPOSS> progress."));
				return false;
			case Climate.WEATHER_WINDY:
				room.show(mob,null,CMMsg.MSG_OK_VISUAL,CMLib.lang().L("The hard winds inhibit <S-YOUPOSS> progress."));
				return false;
			}
		}
		InTheAir.airAffects(room,msg);
		return true;
	}
}


text:
package org.apache.flink.runtime.rest.handler.job;

import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.executiongraph.AccessExecutionGraph;
import org.apache.flink.runtime.executiongraph.AccessExecutionJobVertex;
import org.apache.flink.runtime.executiongraph.AccessExecutionVertex;
import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.rest.NotFoundException;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.handler.RestHandlerException;
import org.apache.flink.runtime.rest.handler.legacy.ExecutionGraphCache;
import org.apache.flink.runtime.rest.handler.legacy.metrics.MetricFetcher;
import org.apache.flink.runtime.rest.handler.util.MutableIOMetrics;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.JobIDPathParameter;
import org.apache.flink.runtime.rest.messages.JobVertexIdPathParameter;
import org.apache.flink.runtime.rest.messages.JobVertexMessageParameters;
import org.apache.flink.runtime.rest.messages.JobVertexTaskManagersInfo;
import org.apache.flink.runtime.rest.messages.MessageHeaders;
import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.runtime.rest.messages.job.metrics.IOMetricsInfo;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.history.ArchivedJson;
import org.apache.flink.runtime.webmonitor.history.JsonArchivist;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;
import org.apache.flink.util.Preconditions;

import javax.annotation.Nullable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * A request handler that provides the details of a job vertex, including id, name, and the
 * runtime and metrics of all its subtasks aggregated by TaskManager.
 */
public class JobVertexTaskManagersHandler extends AbstractExecutionGraphHandler<JobVertexTaskManagersInfo, JobVertexMessageParameters> implements JsonArchivist {
	private MetricFetcher<?> metricFetcher;

	public JobVertexTaskManagersHandler(
			CompletableFuture<String> localRestAddress,
			GatewayRetriever<? extends RestfulGateway> leaderRetriever,
			Time timeout,
			Map<String, String> responseHeaders,
			MessageHeaders<EmptyRequestBody, JobVertexTaskManagersInfo, JobVertexMessageParameters> messageHeaders,
			ExecutionGraphCache executionGraphCache,
			Executor executor,
			MetricFetcher<?> metricFetcher) {
		super(localRestAddress, leaderRetriever, timeout, responseHeaders, messageHeaders, executionGraphCache, executor);
		this.metricFetcher = Preconditions.checkNotNull(metricFetcher);
	}

	@Override
	protected JobVertexTaskManagersInfo handleRequest(
			HandlerRequest<EmptyRequestBody, JobVertexMessageParameters> request,
			AccessExecutionGraph executionGraph) throws RestHandlerException {
		JobID jobID = request.getPathParameter(JobIDPathParameter.class);
		JobVertexID jobVertexID = request.getPathParameter(JobVertexIdPathParameter.class);
		AccessExecutionJobVertex jobVertex = executionGraph.getJobVertex(jobVertexID);

		if (jobVertex == null) {
			throw new NotFoundException(String.format("JobVertex %s not found", jobVertexID));
		}

		return createJobVertexTaskManagersInfo(jobVertex, jobID, metricFetcher);
	}

	@Override
	public Collection<ArchivedJson> archiveJsonWithPath(AccessExecutionGraph graph) throws IOException {
		Collection<? extends AccessExecutionJobVertex> vertices = graph.getAllVertices().values();
		List<ArchivedJson> archive = new ArrayList<>(vertices.size());
		for (AccessExecutionJobVertex task : vertices) {
			ResponseBody json = createJobVertexTaskManagersInfo(task, graph.getJobID(), null);
			String path = getMessageHeaders().getTargetRestEndpointURL()
				.replace(':' + JobIDPathParameter.KEY, graph.getJobID().toString())
				.replace(':' + JobVertexIdPathParameter.KEY, task.getJobVertexId().toString());
			archive.add(new ArchivedJson(path, json));
		}
		return archive;
	}

	private static JobVertexTaskManagersInfo createJobVertexTaskManagersInfo(AccessExecutionJobVertex jobVertex, JobID jobID, @Nullable MetricFetcher<?> metricFetcher) {
		// Build a map that groups tasks by TaskManager
		Map<String, List<AccessExecutionVertex>> taskManagerVertices = new HashMap<>();
		for (AccessExecutionVertex vertex : jobVertex.getTaskVertices()) {
			TaskManagerLocation location = vertex.getCurrentAssignedResourceLocation();
			String taskManager = location == null ? "(unassigned)" : location.getHostname() + ':' + location.dataPort();
			List<AccessExecutionVertex> vertices = taskManagerVertices.computeIfAbsent(
				taskManager,
				ignored -> new ArrayList<>(4));
			vertices.add(vertex);
		}

		final long now = System.currentTimeMillis();

		List<JobVertexTaskManagersInfo.TaskManagersInfo> taskManagersInfoList = new ArrayList<>(4);
		for (Map.Entry<String, List<AccessExecutionVertex>> entry : taskManagerVertices.entrySet()) {
			String host = entry.getKey();
			List<AccessExecutionVertex> taskVertices = entry.getValue();

			int[] tasksPerState = new int[ExecutionState.values().length];

			long startTime = Long.MAX_VALUE;
			long endTime = 0;
			boolean allFinished = true;

			MutableIOMetrics counts = new MutableIOMetrics();

			for (AccessExecutionVertex vertex : taskVertices) {
				final ExecutionState state = vertex.getExecutionState();
				tasksPerState[state.ordinal()]++;

				// take the earliest start time
				long started = vertex.getStateTimestamp(ExecutionState.DEPLOYING);
				if (started > 0) {
					startTime = Math.min(startTime, started);
				}

				allFinished &= state.isTerminal();
				endTime = Math.max(endTime, vertex.getStateTimestamp(state));

				counts.addIOMetrics(
					vertex.getCurrentExecutionAttempt(),
					metricFetcher,
					jobID.toString(),
					jobVertex.getJobVertexId().toString());
			}

			long duration;
			if (startTime < Long.MAX_VALUE) {
				if (allFinished) {
					duration = endTime - startTime;
				}
				else {
					endTime = -1L;
					duration = now - startTime;
				}
			}
			else {
				startTime = -1L;
				endTime = -1L;
				duration = -1L;
			}

			ExecutionState jobVertexState = ExecutionJobVertex.getAggregateJobVertexState(
				tasksPerState,
				taskVertices.size());

			final IOMetricsInfo jobVertexMetrics = new IOMetricsInfo(
				counts.getNumBytesInLocal() + counts.getNumBytesInRemote(),
				counts.isNumBytesInLocalComplete() && counts.isNumBytesInRemoteComplete(),
				counts.getNumBytesOut(),
				counts.isNumBytesOutComplete(),
				counts.getNumRecordsIn(),
				counts.isNumRecordsInComplete(),
				counts.getNumRecordsOut(),
				counts.isNumRecordsOutComplete());

			Map<ExecutionState, Integer> statusCounts = new HashMap<>(ExecutionState.values().length);
			for (ExecutionState state : ExecutionState.values()) {
				statusCounts.put(state, tasksPerState[state.ordinal()]);
			}
			taskManagersInfoList.add(new JobVertexTaskManagersInfo.TaskManagersInfo(
				host,
				jobVertexState,
				startTime,
				endTime,
				duration,
				jobVertexMetrics,
				statusCounts));
		}

		return new JobVertexTaskManagersInfo(jobVertex.getJobVertexId(), jobVertex.getName(), now, taskManagersInfoList);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- INSPIRE data theme keywords (gmd:descriptiveKeywords) -->
<g:element xmlns:g="http://www.esri.com/geoportal/gxe"
           xmlns:h="http://www.esri.com/geoportal/gxe/html"
           h:class=""
           g:targetName="gmd:descriptiveKeywords" g:minOccurs="1" g:maxOccurs="1"
           g:extends="$base/xtn/ui/UI_Element.xml">
  <g:header g:rendered="false"/>
  <g:body>
	  <g:element g:targetName="gmd:MD_Keywords" g:minOccurs="0" g:maxOccurs="1"
	    h:tag="div" g:jsClass="gxe.control.Element">

	    <!-- keyword selection
	    <g:element g:targetName="gmd:keyword" g:minOccurs="1" g:maxOccurs="unbounded"
	      g:label="$i18n.catalog.mdParam.inspire.keyword.dataTheme.label"
	      g:extends="$base/schema/gco/basicTypes/CharacterString_PropertyType.xml">
	      <g:body>
	        <g:element g:isIsoWMVL="true">
	          <g:body>
	            <g:input g:extends="$base/core/ui/InputSelectMany.xml">
	              <g:options g:i18nBase="catalog.mdParam.inspire.keyword.dataTheme">
		              <g:option g:value="Addresses" g:alias="Addresses" g:label="$i18nBase.addresses"/>
		              <g:option g:value="Administrative units" g:alias="Administrative_units" g:label="$i18nBase.administrativeUnits"/>
		              <g:option g:value="Agricultural and aquaculture facilities" g:alias="Agricultural_and_aquaculture_facilities" g:label="$i18nBase.agriculturalAndAquacultureFacilities"/>
		              <g:option g:value="Area management/restriction/regulation zones and reporting units" g:alias="Area_management_restriction_regulation_zones_and_reporting_units" g:label="$i18nBase.areaManagementRestrictionRegulationZonesAndReportingUnits"/>
		              <g:option g:value="Atmospheric conditions" g:alias="Atmospheric_conditions" g:label="$i18nBase.atmosphericConditions"/>
		              <g:option g:value="Bio-geographical regions" g:alias="Bio-geographical_regions" g:label="$i18nBase.bioGeographicalRegions"/>
		              <g:option g:value="Buildings" g:alias="Buildings" g:label="$i18nBase.buildings"/>
		              <g:option g:value="Cadastral parcels" g:alias="Cadastral_parcels" g:label="$i18nBase.cadastralParcels"/>
	                <g:option g:value="Coordinate reference systems" g:alias="Coordinate_reference_systems" g:label="$i18nBase.coordinateReferenceSystems"/>
			            <g:option g:value="Elevation" g:alias="Elevation" g:label="$i18nBase.elevation"/>
			            <g:option g:value="Energy resources" g:alias="Energy_resources" g:label="$i18nBase.energyResources"/>
			            <g:option g:value="Environmental monitoring facilities" g:alias="Environmental_monitoring_facilities" g:label="$i18nBase.environmentalMonitoringFacilities"/>
			            <g:option g:value="Geographical grid systems" g:alias="Geographical_grid_systems" g:label="$i18nBase.geographicalGridSystems"/>
			            <g:option g:value="Geographical names" g:alias="Geographical_names" g:label="$i18nBase.geographicalNames"/>
			            <g:option g:value="Geology" g:alias="Geology" g:label="$i18nBase.geology"/>
			            <g:option g:value="Habitats and biotopes" g:alias="Habitats_and_biotopes" g:label="$i18nBase.habitatsAndBiotopes"/>
			            <g:option g:value="Human health and safety" g:alias="Human_health_and_safety" g:label="$i18nBase.humanHealthAndSafety"/>
			            <g:option g:value="Hydrography" g:alias="Hydrography" g:label="$i18nBase.hydrography"/>
			            <g:option g:value="Land cover" g:alias="Land_cover" g:label="$i18nBase.landCover"/>
			            <g:option g:value="Land use" g:alias="Land_use" g:label="$i18nBase.landUser"/>
			            <g:option g:value="Meteorological geographical features" g:alias="Meteorological_geographical_features" g:label="$i18nBase.meteorologicalGeographicalFeatures"/>
			            <g:option g:value="Mineral resources" g:alias="Mineral_resources" g:label="$i18nBase.mineralResources"/>
			            <g:option g:value="Natural risk zones" g:alias="Natural_risk_zones" g:label="$i18nBase.naturalRiskZones"/>
			            <g:option g:value="Oceanographic geographical features" g:alias="Oceanographic_geographical_features" g:label="$i18nBase.oceanographicGeographicalFeatures"/>
			            <g:option g:value="Orthoimagery" g:alias="Orthoimagery" g:label="$i18nBase.orthoimagery"/>
			            <g:option g:value="Population distribution — demography" g:alias="Population_distribution_-_demography" g:label="$i18nBase.populationDistributionDemography"/>
			            <g:option g:value="Production and industrial facilities" g:alias="Production_and_industrial_facilities" g:label="$i18nBase.productionAndIndustrialFacilities"/>
			            <g:option g:value="Protected sites" g:alias="Protected_sites" g:label="$i18nBase.protectedSites"/>
			            <g:option g:value="Sea regions" g:alias="Sea_regions" g:label="$i18nBase.seaRegions"/>
			            <g:option g:value="Soil" g:alias="Soil" g:label="$i18nBase.soil"/>
			            <g:option g:value="Species distribution" g:alias="Species_distribution" g:label="$i18nBase.speciesDistribution"/>
			            <g:option g:value="Statistical units" g:alias="Statistical_units" g:label="$i18nBase.statisticalUnits"/>
			            <g:option g:value="Transport networks" g:alias="Transport_networks" g:label="$i18nBase.transportNetworks"/>
			            <g:option g:value="Utility and governmental services" g:alias="Utility_and_Government_services" g:label="$i18nBase.utilityAndGovernmentService"/>
		            </g:options>
		          </g:input>
		        </g:body>
		      </g:element>
		    </g:body>
	    </g:element>
	    -->

	    <g:element g:targetName="gmd:keyword" g:minOccurs="1" g:maxOccurs="unbounded"
        g:label="$i18n.catalog.mdParam.inspire.keyword.dataTheme.label"
        g:extends="$base/schema/gco/basicTypes/CharacterString_PropertyType.xml">
        <g:body>
          <g:element g:isIsoWMVL="true">
            <g:body>
              <g:input g:extends="$base/core/ui/InputDelimitedTextArea.xml"
                 g:jsClass="gxe.control.InputGemetTheme"
                 h:cols="60" h:rows="8"/>
            </g:body>
          </g:element>
        </g:body>
      </g:element>

	    <!-- GEMET - INSPIRE themes, version 1.0 -->
	    <g:element g:targetName="gmd:thesaurusName"
	      h:tag="div" h:class="gxeDisplayNone" g:jsClass="gxe.control.Element">
	      <g:element g:targetName="gmd:CI_Citation" h:tag="div" g:jsClass="gxe.control.Element">
	        <g:element g:targetName="gmd:title" h:tag="div" g:jsClass="gxe.control.Element">
	          <g:element g:targetName="gco:CharacterString" h:tag="div" g:jsClass="gxe.control.Element"
	            g:fixedValue="GEMET - INSPIRE themes, version 1.0">
	            <g:input g:extends="$base/core/ui/InputText.xml"/>
	          </g:element>
	        </g:element>
	        <g:element g:targetName="gmd:date" h:tag="div" g:jsClass="gxe.control.Element">
	          <g:element g:targetName="gmd:CI_Date" h:tag="div" g:jsClass="gxe.control.Element">
	            <g:element g:targetName="gmd:date" h:tag="div" g:jsClass="gxe.control.Element">
	             <g:element g:targetName="gco:Date" h:tag="div" g:jsClass="gxe.control.Element"
	               g:fixedValue="2008-06-01">
	               <g:input g:extends="$base/core/ui/InputText.xml"/>
	             </g:element>
	           </g:element>
	            <g:element g:targetName="gmd:dateType" h:tag="div" g:jsClass="gxe.control.Element">
	             <g:element g:targetName="gmd:CI_DateTypeCode" h:tag="div" g:jsClass="gxe.control.Element"
	               g:fixedValue="publication">
	               <g:input g:extends="$base/core/ui/InputText.xml"/>
	               <g:attribute g:targetNS="" g:targetName="codeList" h:tag="div" g:jsClass="gxe.control.Attribute"
	                 g:fixedValue="http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/Codelist/ML_gmxCodelists.xml#CI_DateTypeCode">
	                 <g:input g:extends="$base/core/ui/InputText.xml"/>
	               </g:attribute>
	               <g:attribute g:targetNS="" g:targetName="codeListValue" h:tag="div" g:jsClass="gxe.control.Attribute"
	                 g:fixedValue="publication">
	                 <g:input g:extends="$base/core/ui/InputText.xml"/>
	               </g:attribute>
	             </g:element>
	           </g:element>
	          </g:element>
	        </g:element>
	      </g:element>
	    </g:element>

	  </g:element>
	</g:body>
</g:element>


text:
using System.Collections.Generic;

using commercetools.CustomFields;

using Newtonsoft.Json;

namespace commercetools.Common
{
    /// <summary>
    /// The representation to be sent to the server when creating a new asset.
    /// </summary>
    /// <see href="http://dev.commercetools.com/http-api-types.html#assetdraft"/>
    public class AssetDraft
    {
        #region Properties

        [JsonProperty(PropertyName = "sources")]
        public List<ArraySource> Sources { get; set; }

        [JsonProperty(PropertyName = "name")]
        public LocalizedString Name { get; set; }

        [JsonProperty(PropertyName = "description")]
        public LocalizedString Description { get; set; }

        [JsonProperty(PropertyName = "tags")]
        public string Tags { get; set; }

        [JsonProperty(PropertyName = "custom")]
        public CustomFieldsDraft Custom { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        public AssetDraft(List<ArraySource> sources)
        {
            this.Sources = sources;
        }

        #endregion
    }
}


text:
from tempest.api.network import base
from tempest import clients
from tempest.common.utils.data_utils import rand_name
from tempest.test import attr

class QuotasTest(base.BaseNetworkTest):
    _interface = 'json'

    """
    Tests the following operations in the Neutron API using the REST client for
    Neutron:

        list quotas for tenants who have non-default quota values
        show quotas for a specified tenant
        update quotas for a specified tenant
        reset quotas to default values for a specified tenant

    v2.0 of the API is assumed. It is also assumed that the following
    option is defined in the [service_available] section of etc/tempest.conf:

        neutron as True

    Finally, it is assumed that the per-tenant quota extension API is
    configured in /etc/neutron/neutron.conf as follows:

        quota_driver = neutron.db.quota_db.DbQuotaDriver
    """

    @classmethod
    def setUpClass(cls):
        super(QuotasTest, cls).setUpClass()
        admin_manager = clients.AdminManager()
        cls.admin_client = admin_manager.network_client
        cls.identity_admin_client = admin_manager.identity_client

    @attr(type='gate')
    def test_quotas(self):
        # Add a tenant to conduct the test
        test_tenant = rand_name('test_tenant_')
        test_description = rand_name('desc_')
        _, tenant = self.identity_admin_client.create_tenant(
            name=test_tenant,
            description=test_description)
        tenant_id = tenant['id']
        self.addCleanup(self.identity_admin_client.delete_tenant, tenant_id)
        # Change quotas for tenant
        new_quotas = {'network': 0, 'security_group': 0}
        resp, quota_set = self.admin_client.update_quotas(tenant_id,
                                                          **new_quotas)
        self.assertEqual('200', resp['status'])
        self.addCleanup(self.admin_client.reset_quotas, tenant_id)
        self.assertEqual(0, quota_set['network'])
        self.assertEqual(0, quota_set['security_group'])
        # Confirm our tenant is listed among tenants with non default quotas
        resp, non_default_quotas = self.admin_client.list_quotas()
        self.assertEqual('200', resp['status'])
        found = False
        for qs in non_default_quotas:
            if qs['tenant_id'] == tenant_id:
                found = True
        self.assertTrue(found)
        # Confirm from APi quotas were changed as requested for tenant
        resp, quota_set = self.admin_client.show_quotas(tenant_id)
        self.assertEqual('200', resp['status'])
        self.assertEqual(0, quota_set['network'])
        self.assertEqual(0, quota_set['security_group'])
        # Reset quotas to default and confirm
        resp, body = self.admin_client.reset_quotas(tenant_id)
        self.assertEqual('204', resp['status'])
        resp, non_default_quotas = self.admin_client.list_quotas()
        self.assertEqual('200', resp['status'])
        for q in non_default_quotas:
            self.assertNotEqual(tenant_id, q['tenant_id'])


text:
jQuery.fn.definePlugin('Accordion', function($){

	return {
		init: function(){
			this.markup();
			this.showFirst();
			this.bindEvents();
			this.applyCSS();
		},
		markup:function(){
			if(!this.$el.hasClass('accordion')){
				this.$el.addClass('accordion');
			}
            if(this.options.border){
                this.$el.find('.' + this.options.triggerClass).addClass(this.options.borderClass);
                this.$el.find('.' + this.options.triggerClass).find('li:nth-last-child(1)').addClass('last-child');
            }

		},
		getDefaults: function(){
			return {
				triggerClass : "acc-pane",
				triggerCSS : {},
                borderClass: 'border',
				contentClass : "acc-content",
				contentCSS : {},
				animationTime : 150,
				activeClass : 'acc-active',
				ease : 'linear',
				openByDeafult:'acc-open',
				value : 0,
				toggleOpen: true,
                border: true
			};
		},
		showFirst: function () {
			var opt = this.options;
			this.$el.find('.' + opt.contentClass).hide();
			var $panels = this.$el.find('.' + opt.triggerClass);
			var $toOpen;
			if(typeof this.options.value === 'string'){
				$toOpen = $panels.filter(this.options.value);
			} else {
				$toOpen = $panels.eq(this.options.value || 0);
			}

			var $openByDefault = this.$el.find('.'+opt.triggerClass+'.' + opt.openByDeafult)
			$toOpen = $toOpen.add($openByDefault);

			$toOpen.addClass(opt.activeClass + ' ' + opt.openByDeafult)
				.find('.'+opt.contentClass)
				.css('display','block');
		},
		getValue: function () {
			var triggers = this.$el.find('.' + this.options.triggerClass);
			for(var i = 0; i < triggers.length; i++){
				if(triggers.eq(i).hasClass(this.options.activeClass)){
					return i;
				}
			}
			return -1;
		},
		setValue: function ($el) {
			var opt = this.options;
			if(typeof $el === 'number'){
				$el = this.$el.find('.' + opt.triggerClass).eq($el);
			}
			if ($el.find('.' + opt.contentClass).is(':hidden')) {
				this.openElementContent($el);
			} else if (opt.toggleOpen){
				this.closeElementContent($el);
			}
		},
		closeElementContent: function ($el) {
			var opt = this.options;
			this.$el.find('.' + opt.triggerClass)
				.removeClass(opt.openByDeafult)
				.removeClass(opt.activeClass)
				.find('.' + opt.contentClass)
				.slideUp(opt.animationTime, opt.ease, function(){
                    $(document.body).trigger('uilib-update-scroll-bars');
                });
        },
		openElementContent: function ($el) {
			var opt = this.options;
			this.closeElementContent($el);

			var $active = $el.toggleClass(opt.activeClass).find('.'+opt.contentClass);
			$active.slideDown(opt.animationTime, opt.ease, function(){
				$active.css('overflow', 'visible');
				$(document.body).trigger('uilib-update-scroll-bars');
			});
		},
        applyCSS: function () {
			this.$el.find('.' + this.options.contentClass).css(this.options.contentCSS);
			this.$el.find('.' + this.options.triggerClass).css(this.options.triggerCSS);
		},
		bindEvents: function () {
			var that = this;
			this.$el.on('click', '.' + this.options.triggerClass, function (e) {
				if($(e.target).parents('.'+that.options.contentClass).length === 0){
					e.preventDefault();
					that.setValue($(this));
					that.triggerChangeEvent(that.getValue());
				}
			});
		}
	};

});


text:
require 'spec_helper'

module Alchemy
  describe "Picture::Url" do
    include ActionDispatch::TestProcess

    # Helper to dedoce a hashed dragonfly job
    def decode_dragon_fly_job(url)
      job = url.split('/')[2]
      Dragonfly::Serializer.json_b64_decode(job)
    end

    let(:image) do
      fixture_file_upload(
        File.expand_path('../../../fixtures/500x500.png', __FILE__),
        'image/png'
      )
    end

    let(:picture) do
      create(:alchemy_picture, image_file: image)
    end

    describe "#url" do
      subject(:url) { picture.url(options) }

      let(:options) { Hash.new }

      it 'includes the name and render format' do
        expect(url).to match /\/#{picture.name}\.#{picture.default_render_format}/
      end

      context "when no image is present" do
        before do
          expect(picture).to receive(:image_file) { nil }
        end

        it 'returns nil' do
          expect(url).to be_nil
        end

        it "logs warning" do
          expect(Alchemy::Logger).to receive(:warn)
          url
        end
      end

      context "when a size is passed in" do
        let(:options) do
          {size: '120x160'}
        end

        it 'resizes the image without upsampling it' do
          job = decode_dragon_fly_job(url)
          expect(job[1]).to include("120x160>")
        end

        context "but upsample set to true" do
          let(:options) do
            {
              size: '1600x1200',
              upsample: true
            }
          end

          it "resizes the image with upsampling it" do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to include("1600x1200")
          end
        end

        context "and crop is set to true" do
          let(:options) do
            {
              size: '160x120',
              crop: true
            }
          end

          it "crops from center and resizes the picture" do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to include("160x120#")
          end

          context "and crop_from and crop_size is passed in" do
            let(:options) do
              {
                crop_size: '123x44',
                crop_from: '0x0',
                size: '160x120',
                crop: true
              }
            end

            it "crops and resizes the picture" do
              job = decode_dragon_fly_job(url)
              expect(job[1]).to include("-crop 123x44+0+0 -resize 160x120>")
            end
          end
        end

        context "and crop is set to false" do
          let(:options) do
            {
              size: '160x120',
              crop: false
            }
          end

          it "does not crop the picture" do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to_not include("160x120#")
          end

          context "and crop_from and crop_size is passed in" do
            let(:options) do
              {
                crop_size: '123x44',
                crop_from: '0x0',
                size: '160x120',
                crop: false
              }
            end

            it "does not crop the picture" do
              job = decode_dragon_fly_job(url)
              expect(job[1]).to_not include("-crop 123x44+0+0")
            end
          end
        end

        context "with no height given" do
          let(:options) do
            {size: '40'}
          end

          it "resizes the image inferring the height" do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to include("40>")
          end
        end

        context "with no width given" do
          let(:options) do
            {size: 'x30'}
          end

          it "resizes the image inferring the width" do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to include("x30>")
          end
        end
      end

      context "when no size is passed in" do
        it 'does not resize the image' do
          # only the fetch step should be present
          expect(decode_dragon_fly_job(url).size).to eq(1)
        end
      end

      context "when a different format is requested" do
        let(:options) do
          {format: 'gif'}
        end

        it 'converts the format' do
          job = decode_dragon_fly_job(url)
          expect(job[1]).to include("encode", "gif")
        end

        context "but image has not a convertible format (svg)" do
          let(:image) do
            fixture_file_upload(
              File.expand_path('../../../fixtures/icon.svg', __FILE__),
              'image/svg+xml'
            )
          end

          it 'does not convert the picture format' do
            # only the fetch step should be present
            expect(decode_dragon_fly_job(url).size).to eq(1)
          end
        end

        context 'for an animated gif' do
          let(:options) do
            {format: 'png'}
          end

          let(:image) do
            fixture_file_upload(
              File.expand_path('../../../fixtures/animated.gif', __FILE__),
              'image/gif'
            )
          end

          it 'flattens the image.' do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to include("-flatten")
          end
        end
      end

      context "requesting a not allowed format" do
        let(:options) do
          {format: 'zip'}
        end

        it "returns nil" do
          expect(url).to be_nil
        end

        it "logs warning" do
          expect(Alchemy::Logger).to receive(:warn)
          url
        end
      end

      context "when jpg format is requested" do
        let(:options) do
          {format: 'jpg'}
        end

        it 'sets the default quality' do
          job = decode_dragon_fly_job(url)
          expect(job[1]).to include("-quality 85")
        end

        context "and quality is passed" do
          let(:options) do
            {format: 'jpg', quality: '30'}
          end

          it 'sets the quality' do
            job = decode_dragon_fly_job(url)
            expect(job[1]).to include("-quality 30")
          end
        end
      end
    end
  end
end


text:
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace Alachisoft.NCache.Runtime.Exceptions
{
    /// <summary>
    /// Thrown when an exception occurs during a clustered operation.
    /// </summary>
    /// <example>The following example demonstrates how to use this exception in your code.
    /// <code>
    ///
    /// try
    /// {
    ///	    ...
    /// }
    /// catch(GeneralFailureException ex)
    /// {
    ///     ...
    /// }
    ///
    /// </code>
    /// </example>
    [Serializable]
    public class GeneralFailureException : CacheException
    {
        /// <summary>
        /// default constructor.
        /// </summary>
        public GeneralFailureException()
        {
        }

        /// <summary>
        /// overloaded constructor, takes the reason as parameter.
        /// </summary>
        public GeneralFailureException(string reason)
            : base(reason)
        {
        }

        /// <summary>
        /// overloaded constructor.
        /// </summary>
        /// <param name="reason">reason for exception</param>
        /// <param name="inner">nested exception</param>
        public GeneralFailureException(string reason, Exception inner)
            : base(reason, inner)
        {
        }

        #region /                 --- ISerializable ---           /

        /// <summary>
        /// overloaded constructor, manual serialization.
        /// </summary>
        protected GeneralFailureException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// manual serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
        }

        #endregion
    }
}


text:
package com.malleamus.speckle;

import java.util.Hashtable;
import java.util.Map;

public abstract class UI {

	private Map<String, View> viewRegistry = new Hashtable<String, View>();

	public abstract View getDefaultView();

	public void registerView(String tag, View view) {
		viewRegistry.put(tag, view);
	}

	public void withdrawView(String tag) {
		viewRegistry.remove(tag);
	}

	public boolean hasView(String tag) {
		return viewRegistry.containsKey(tag);
	}

	public View getView(String tag) {
		return viewRegistry.get(tag);
	}
}


text:
package com.sxt.models.dto;

import java.math.BigDecimal;

/**
 *
 * @author
 * @date:2016年5月11日 下午6:01:11
 *
 */
public class InvestProductDto {

	private String productId;
	private Integer rewardId;
	private BigDecimal investMoney;
	private String payPass;
	private Integer uid;

	public String getProductId() {
		return productId;
	}
	public void setProductId(String productId) {
		this.productId = productId;
	}
	public Integer getRewardId() {
		return rewardId;
	}
	public void setRewardId(Integer rewardId) {
		this.rewardId = rewardId;
	}
	public BigDecimal getInvestMoney() {
		return investMoney;
	}
	public void setInvestMoney(BigDecimal investMoney) {
		this.investMoney = investMoney;
	}
	public String getPayPass() {
		return payPass;
	}
	public void setPayPass(String payPass) {
		this.payPass = payPass;
	}
	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}

}


text:
package org.mrgeo.services.version;

//import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.context.SecurityContext;
//import org.springframework.security.core.context.SecurityContextHolder;

import java.io.IOException;
import java.util.Properties;

/**
 * @author Steve Ingram
 *         Date: 11/18/13
 */
public class VersionService {

    private final Properties props = new Properties();

    private static final Logger log = LoggerFactory.getLogger(VersionService.class);

    public VersionService() {
        try
        {
            props.load( getClass().getClassLoader().getResourceAsStream("version.properties") );
        }
        catch (IOException e)
        {
            log.error("Version error: " + e.getMessage(), e);
        }
    }

    public String getVersionJson() {
        StringBuilder sb = new StringBuilder();

        sb.append("{");
        sb.append(" \"name\": \"").append(props.getProperty("name")).append("\",");
        sb.append(" \"version\": \"").append(props.getProperty("version")).append("\",");
        sb.append(" \"revision\": \"").append(props.getProperty("revision")).append("\",");
        sb.append(" \"build\": \"").append(props.getProperty("build")).append("\",");
        sb.append(" \"buildTime\": \"").append(props.getProperty("buildTime")).append("\",");
        String packaging = props.getProperty("packaging");
        if ( packaging != null ) {
            packaging = packaging.replaceAll("\"", "");
        } else {
            packaging = "No packaging information";
        }
        sb.append(" \"packaging\": \"").append(packaging).append("\"");
        // The following is sample code showing how to obtain authorizations for
        // the logged in user (if authentication is enabled). It is strictly here
        // as an example for testing. It was never meant to actually be returned
        // with version information in a production system.
//        SecurityContext secCtx = SecurityContextHolder.getContext();
//        if (secCtx != null)
//        {
//          Authentication a = secCtx.getAuthentication();
//          if (a != null)
//          {
//            java.util.Collection<? extends GrantedAuthority> auths = a.getAuthorities();
//            String[] roles = new String[auths.size()];
//            int i = 0;
//            for (GrantedAuthority auth : auths)
//            {
//              roles[i] = auth.getAuthority();
//              i++;
//            }
//            sb.append(" \"roles\": \"").append(StringUtils.join(roles, ",")).append("\"");
//          }
//        }
        sb.append(" }");
        return sb.toString();
    }
}