text:
<?php

declare(strict_types=1);

namespace phpDocumentor\Reflection\Php;

use phpDocumentor\Reflection\NodeVisitor\ElementNameResolver;
use PhpParser\Lexer\Emulative;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeTraverserInterface;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use Webmozart\Assert\Assert;

/**
 * Factory to create a array of nodes from a provided file.
 *
 * This factory will use PhpParser and NodeTraverser to do the real processing.
 */
class NodesFactory
{
    /**
     * Parser used to parse the code to nodes.
     */
    private Parser $parser;

    /**
     * Containing a number of visitors to do some post processing steps on nodes.
     */
    private NodeTraverserInterface $traverser;

    /**
     * @param Parser $parser used to parse the code
     * @param NodeTraverserInterface $traverser used to do some post processing on the nodes
     */
    final public function __construct(Parser $parser, NodeTraverserInterface $traverser)
    {
        $this->parser = $parser;
        $this->traverser = $traverser;
    }

    /**
     * Creates a new instance of NodeFactory with default Parser ands Traverser.
     *
     * @param int $kind One of ParserFactory::PREFER_PHP7,
     *  ParserFactory::PREFER_PHP5, ParserFactory::ONLY_PHP7 or ParserFactory::ONLY_PHP5
     *
     * @return static
     */
    public static function createInstance(int $kind = ParserFactory::PREFER_PHP7): self
    {
        $lexer = new Emulative([
            'usedAttributes' => [
                'comments',
                'startLine',
                'endLine',
                'startFilePos',
                'endFilePos',
            ],
        ]);
        $parser = (new ParserFactory())->create($kind, $lexer);
        $traverser = new NodeTraverser();
        $traverser->addVisitor(new NameResolver());
        $traverser->addVisitor(new ElementNameResolver());

        return new static($parser, $traverser);
    }

    /**
     * Will convert the provided code to nodes.
     *
     * @param string $code code to process.
     *
     * @return Node[]
     */
    public function create(string $code): array
    {
        $nodes = $this->parser->parse($code);
        Assert::isArray($nodes);

        return $this->traverser->traverse($nodes);
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var test = require('tape');
var BufferRegistry = require('../../src/webgl-renderers/BufferRegistry');
var TestingContext = require('./helpers/ContextWebGL');
var Buffer = require('../../src/webgl-renderers/Buffer');

test('BufferRegistry', function(t) {

    var registry;
    var geometry = {
        spec: {
            id: 0,
            dynamic: false,
            type: 4,
            bufferNames: [
                'pos', 'texCoord', 'normals', 'indices'
            ],
            bufferValues: [
                [-1, 1, 0, 0, -1, 0, 1,  1, 0],
                [0.0, 0.0, 0.5, 1.0, 1.0, 0.0],
                [0, 0, 1, 0, 0, 1, 0, 0, 1],
                [0, 1, 2]
            ],
            bufferSpacings: [
                3, 2, 3, 1
            ],
            invalidations: [
                0, 1, 2, 3
            ]
        }
    };

    t.test('constructor', function(t) {
        var testingContext = new TestingContext();

        registry = new BufferRegistry(testingContext);

        t.end();
    });

    t.test('allocate', function(t) {
        var bufferData = geometry.spec.bufferValues[0];
        registry.allocate(geometry.spec.id, 'pos', geometry.spec.bufferValues[0], 3);

        var entry = registry.registry[geometry.spec.id];
        t.ok(entry, 'Should create an object in registry accessed by geometry id');

        t.ok(Array.isArray(entry.keys), 'Should have an array for buffer keys');
        t.ok(Array.isArray(entry.values), 'Should have an array for buffer values');
        t.ok(Array.isArray(entry.spacing), 'Should have an array for buffer spacings');
        t.ok(Array.isArray(entry.offset), 'Should have an array for buffer offsets');
        t.ok(Array.isArray(entry.length), 'Should have an array for buffer lengths');

        t.ok(registry._staticBuffers[0], 'Should have an a static buffer entry');
        t.equals(bufferData.length, registry._staticBuffers[0].offset, 'Should set correct offset');
        t.ok(registry._staticBuffers[0].buffer instanceof Buffer, 'Should have reference to a created buffer instance');
        t.ok(!registry._staticBuffers.isIndex, 'isIndex should be set to false for non-indices buffers');

        t.equals(registry._staticBuffers.length, 1, 'Buffers should be shared for static geometries');

        registry.allocate(geometry.spec.id, 'texCoord', geometry.spec.bufferValues[1], 2);

        t.equals(
            registry._staticBuffers[0].offset,
            geometry.spec.bufferValues[0].length +
            geometry.spec.bufferValues[1].length,
            'Offset should be both bufferValue lengths added together'
        );

        registry.allocate(geometry.spec.id, 'indices', geometry.spec.bufferValues[0], 1);

        t.equals(registry._staticBuffers.length, 2, 'Indices should always get their own buffers');

        // Dynamic buffers

        geometry.spec.id++;

        registry.allocate(geometry.spec.id, 'pos', geometry.spec.bufferValues[0], 3, true);
        registry.allocate(geometry.spec.id, 'texCoord', geometry.spec.bufferValues[1], 2, true);
        registry.allocate(geometry.spec.id, 'normals', geometry.spec.bufferValues[2], 3, true);

        t.equals(registry._dynamicBuffers.length, 3, 'Dynamic attributes should always get their own buffers');

        t.end();
    });

    t.end();
});


text:
var SlickSelect = {
	EVENT_CHANGE:"change",
	EVENT_OPEN:"open",
	EVENT_CLOSE:"close",

	CLASS_SLICKSELECT:"slickselect",
	CLASS_DISPLAY_SELECTED:"slickselect-display-selected",
	CLASS_OPTIONS:"slickselect-options",
	CLASS_OPTION:"slickselect-option",
	CLASS_OPTION_SELECTED:"slickselect-option-selected",
	CLASS_OPTION_HIGHLIGHT:"slickselect-option-highlight",
	CLASS_OPEN:"slickselect-open",
	CLASS_HIDDEN:"slickselect-hidden",

	defaultParams:{
		placeholder:null,	//Placeholder text
		scroll:false,		//Enable touch scrolling
		scrollSnapDist:8,	//Distance to snap to option
		clickDist:8,		//Distance to trigger click rather than scroll
		hover:false			//Open on hover
	}
};
(function($){ //Dependencies: jQuery
	$.fn.SlickSelect = function(params){
		var _params = $.extend({}, $.fn.SlickSelect.defaultParams, params);
		var _$select = this;

		var _vars = {
			_slickSelect:null,
			_displaySelected:null,
			_options:null,

			_keyIndex:-1,
			_isDragging:false,
			_beginDragPoint:null,
			_beginDragOptionsPoint:null,

			isOpen:false,
			selectedIndex:-1,
			value:null
		};

		var _methods = {
			initialize:function(initialSelection){
				//Copy classes
				var selectClasses = _$select[0].getAttribute("class");
				selectClasses = (selectClasses) ? selectClasses + " " : "";
				selectClasses += SlickSelect.CLASS_SLICKSELECT;

				//Create SlickSelect
				var slickSelect = document.createElement("div");
				slickSelect.setAttribute("tabindex", 0);
				slickSelect.setAttribute("class", selectClasses);
				_vars._slickSelect = slickSelect;

				var displaySelected = document.createElement("span");
				displaySelected.setAttribute("class", SlickSelect.CLASS_DISPLAY_SELECTED);
				_vars._displaySelected = displaySelected;

				var options = document.createElement("ul");
				options.setAttribute("class", SlickSelect.CLASS_OPTIONS);
				_vars._options = options;

				//Parse select options and create SlickSelect options
				var selectOptions = _$select[0].querySelectorAll("option");
				var selectOptionsLen = selectOptions.length;
				for (var i = 0; i < selectOptionsLen; i++){
					var selectOption = selectOptions[i];

					var slickSelectOption = document.createElement("li");
					slickSelectOption.setAttribute("class", SlickSelect.CLASS_OPTION);
					slickSelectOption.innerHTML = selectOption.innerHTML;

					//Copy attributes
					var selectAttributes = selectOption.attributes;
					var selectAttributesLen = selectAttributes.length;
					for (var j = 0; j < selectAttributesLen; j++){
                        var attrib = selectAttributes[j];
                        if (attrib.specified){
							if (attrib.name == "value"){
								slickSelectOption.setAttribute("data-value", selectOption.getAttribute("value"));
							} else if (attrib.name != "class" && !/^(data\-)?ng\-/.test(attrib.name)){
								slickSelectOption.setAttribute(attrib.name, attrib.value);
							}
                        }
                    }
					options.appendChild(slickSelectOption);
				}
				slickSelect.appendChild(displaySelected);
				slickSelect.appendChild(options);

				_$select[0].parentNode.insertBefore(slickSelect, _$select[0]);
				_$select.addClass(SlickSelect.CLASS_HIDDEN);

				if (initialSelection){
					_methods.selectOption(initialSelection);
				} else {
					var selected = _$select[0].querySelectorAll("option[selected]");
					if (selected.length){
						_methods.selectOption(selected[0].getAttribute("value"));
					} else {
						_methods.selectOption(-1);
					}
				}

				var $slickSelect = $(slickSelect);
				var $doc = $(document);
				$doc.on("keydown", _methods._handler_keydown);
				$slickSelect.on("focusout", _methods._handler_focusout);
				$slickSelect.on("click", _methods._handler_click);
				if (_params.hover){
					$slickSelect.on("mouseenter", _methods._handler_mouseenter);
					$slickSelect.on("mouseleave", _methods._handler_mouseleave);
				}
				if (_params.scroll){
					$slickSelect.on("touchstart mousedown", _methods._handler_beginDrag);
				}
			},

			destroy:function(){
				_methods.close();
				_methods._handler_endDrag();

				var slickSelect = _vars._slickSelect;
				if (slickSelect){
					var $slickSelect = $(slickSelect);
					$slickSelect.off("focusout", _methods._handler_focusout);
					$slickSelect.off("click", _methods._handler_click);
					$slickSelect.off("mouseenter", _methods._handler_mouseenter);
					$slickSelect.off("mouseleave", _methods._handler_mouseleave);
					$slickSelect.off("touchstart mousedown", _methods._handler_beginDrag);

					var $doc = $(document);
					$doc.off("keydown", _methods._handler_keydown);
					$doc.off("touchmove mousemove", _methods._handler_moveDrag);
					$doc.off("touchend mouseup", _methods._handler_endDrag);

					if (slickSelect.parentNode){
						slickSelect.parentNode.removeChild(slickSelect);
					}
					_vars._displaySelected = null;
					_vars._options = null;
					_vars._slickSelect = null;
				}

				_vars._beginDragPoint = null;
				_vars._beginDragOptionsPoint = null;
				_vars.selectedIndex = -1;
				_vars.value = null;

				_$select.removeClass(SlickSelect.CLASS_HIDDEN);
			},

			open:function(){
				if (_vars.isOpen){
					return;
				}
				_vars.isOpen = true;

				$(_vars._slickSelect).addClass(SlickSelect.CLASS_OPEN);
				_$select.trigger(SlickSelect.EVENT_OPEN);
			},

			close:function(){
				if (!_vars.isOpen){
					return;
				}
				_vars.isOpen = false;

				var $slickSelect = $(_vars._slickSelect);

				var $slickSelectOptions = $("." + SlickSelect.CLASS_OPTION, $slickSelect);
				$slickSelectOptions.removeClass(SlickSelect.CLASS_OPTION_HIGHLIGHT);
				_vars._keyIndex = -1; //Reset

				$slickSelect.removeClass(SlickSelect.CLASS_OPEN);
				_$select.trigger(SlickSelect.EVENT_CLOSE);
			},

			//'option' parameter can be an index, value, or $element
			selectOption:function(option){
				var $slickSelectOptions = $("." + SlickSelect.CLASS_OPTION, $(_vars._slickSelect));
				$slickSelectOptions.removeClass(SlickSelect.CLASS_OPTION_SELECTED);

				var $option = null;
				if (!isNaN(option)){ //Number: Index
					if (option == -1){ //Placeholder
						var placeholder = _$select.attr("data-placeholder") || _params.placeholder;
						if (placeholder){
							_vars._displaySelected.innerHTML = placeholder;
							_vars.selectedIndex = -1;
							_vars.value = null;
							_$select[0].selectedIndex = _vars.selectedIndex;
							return;
						} else {
							option = 0;
						}
					}
					if (option != -1){
						$option = $slickSelectOptions.eq(option);
					}
				} else if (!option.jquery){ //String: value $
					$option = $slickSelectOptions.filter("[data-value='" + option + "']");
				} else {
					$option = option;
				}
				var selectedIndex = _vars.selectedIndex;
				if ($option.length){
					selectedIndex = $option.index();
				} else if (selectedIndex < 0 || selectedIndex > $slickSelectOptions.length - 1){
					selectedIndex = 0;
				}

				var $optionSelected = $slickSelectOptions.eq(selectedIndex);
				$optionSelected.addClass(SlickSelect.CLASS_OPTION_SELECTED);
				if (_params.scroll){
					_vars._options.style.top = (-$optionSelected.position().top - 1) + "px";
				}
				if (_vars.selectedIndex != selectedIndex){
					_vars._displaySelected.innerHTML = $optionSelected[0].innerHTML;
					_vars.selectedIndex = selectedIndex;
					_vars.value = $option.attr("data-value");
					_$select[0].selectedIndex = _vars.selectedIndex;
					_$select.trigger(SlickSelect.EVENT_CHANGE);
				}

				_methods.close();
			},

			update:function(){
				var value = _vars.value;
				_methods.destroy();
				_methods.initialize(value);
			},

			_handler_click:function(evt){
				evt.preventDefault();

				var isClick = !_params.scroll;
				if (!isClick){
					var touchPoint = _methods._getTouchPoint(evt);
					var dist = Math.abs(touchPoint[1] - _vars._beginDragPoint[1]);
					if (dist < _params.clickDist){
						isClick = true;
					}
				}
				if (isClick){
					var $target = $(evt.target);
					if ($target.hasClass(SlickSelect.CLASS_OPTION)){
						_methods.selectOption($target);
					} else {
						if (!_vars.isOpen){
							_methods.open();
						} else {
							_methods.close();
						}
					}
				}

				return false;
			},

			_handler_mouseenter:function(evt){
				if (!_vars.isOpen){
					_methods.open();
				}
			},

			_handler_mouseleave:function(evt){
				if (_vars.isOpen){
					_methods.close();
				}
			},

			_handler_keydown:function(evt){
				var $slickSelect = $(_vars._slickSelect);
				if (!$slickSelect.is(":focus")){
					return;
				}
				var $slickSelectOptions = $("." + SlickSelect.CLASS_OPTION, $slickSelect);
				var slickSelectOptionsLen = $slickSelectOptions.length;
				var updateHighlighted = false;
				var keyCode = evt.keyCode;
				switch (true){
					case (keyCode == 38): //Up
						_vars._keyIndex--;
						if (_vars._keyIndex < 0){
							_vars._keyIndex = slickSelectOptionsLen - 1;
						}
						updateHighlighted = true;
						if (!_vars.isOpen){
							_methods.open();
						}
						break;
					case (keyCode == 40): //Down
						_vars._keyIndex++;
						if (_vars._keyIndex > slickSelectOptionsLen - 1){
							_vars._keyIndex = 0;
						}
						updateHighlighted = true;
						if (!_vars.isOpen){
							_methods.open();
						}
						break;
					case (keyCode == 13): //Enter
					case (keyCode == 32): //Space
						if (!_vars.isOpen){
							_methods.open();
						} else {
							if (_vars._keyIndex != -1){
								_methods.selectOption(_vars._keyIndex);
							} else {
								_methods.close();
							}
						}
						break;
					case (keyCode >= 48 && keyCode <= 57): //0-9
					case (keyCode >= 65 && keyCode <= 90): //A-Z
					case (keyCode >= 97 && keyCode <= 122): //a-z
						var keyIndex = _vars._keyIndex;
						var $tempList = $slickSelectOptions.slice(_vars._keyIndex + 1, slickSelectOptionsLen);
						$tempList = $.merge($tempList, $slickSelectOptions.slice(0, _vars._keyIndex + 1)); //Concat lastHalf with firstHalf
						var tempListLen = $tempList.length;
						for (var i = 0; i < tempListLen; i++){
							var $slickSelectOption = $($tempList[i]);
							if ($slickSelectOption.text().substr(0, 1).toLowerCase() == String.fromCharCode(keyCode).toLowerCase()){
								_vars._keyIndex = (i + _vars._keyIndex + 1) % tempListLen;
								updateHighlighted = true;
								if (!_vars.isOpen){
									_methods.open();
								}
								break;
							}
						}
						break;
					default:
						return;
				}

				evt.preventDefault();
				if (updateHighlighted){
					$slickSelectOptions.removeClass(SlickSelect.CLASS_OPTION_HIGHLIGHT);
					var $optionHighlighted = $slickSelectOptions.eq(_vars._keyIndex);
					$optionHighlighted.addClass(SlickSelect.CLASS_OPTION_HIGHLIGHT);

					//Scrolling
					var $options = $(_vars._options);
					var scrollHeight = $options[0].scrollHeight;
					var height = $options.height();
					if (scrollHeight > height){
						var scrollTop = $options.scrollTop();
						var selectedTop = $optionHighlighted.position().top + scrollTop;
						var selectedHeight = $optionHighlighted.outerHeight();
						//Needs to scroll
						if (selectedTop + selectedHeight > scrollTop + height){
							$options.scrollTop(selectedTop - height + selectedHeight);
						} else if (selectedTop < scrollTop){
							$options.scrollTop(selectedTop);
						}
					}
				}
				return false;
			},

			_handler_focusout:function(evt){
				evt.preventDefault();
				if (_vars.isOpen){
					_methods.close();
				}
				return false;
			},

			_handler_beginDrag:function(evt){
				if (_vars._isDragging){
					return;
				}
				_vars._beginDragPoint = _methods._getTouchPoint(evt);

				//Bind events
				var $doc = $(document);
				if (_params.scroll){
					$doc.off("touchmove mousemove", _methods._handler_moveDrag);
					$doc.on("touchmove mousemove", _methods._handler_moveDrag);
					$doc.off("touchend mouseup", _methods._handler_endDrag);
					$doc.on("touchend mouseup", _methods._handler_endDrag);
				}

				var $options = $(_vars._options);
				if ($options.is(":visible")){
					_vars._isDragging = true;
					var optionsPosition = $options.position();
					_vars._beginDragOptionsPoint = [optionsPosition.left, optionsPosition.top];
				}
			},

			_handler_moveDrag:function(evt){
				evt.preventDefault();
				if (!_vars._isDragging){
					return;
				}
				var $slickSelect = $(_vars._slickSelect);
				var $options = $(_vars._options);

				var touchPoint = _methods._getTouchPoint(evt);
				var newTop = _vars._beginDragOptionsPoint[1] + (touchPoint[1] - _vars._beginDragPoint[1]);
				var minTop = $slickSelect.outerHeight() - $options.outerHeight() - 1;
				var maxTop = -1;
				newTop = Math.max(Math.min(newTop, maxTop), minTop);

				var slickSelectHalfHeight = $slickSelect.outerHeight() * 0.5;

				var $slickSelectOptions = $("." + SlickSelect.CLASS_OPTION, $slickSelect);
				var slickSelectOptionsLen = $slickSelectOptions.length;
				for (var i = 0; i < slickSelectOptionsLen; i++){
					var $option = $($slickSelectOptions[i]);
					var optionTop = $option.position().top;
					var optionMiddle = optionTop + $option.outerHeight() * 0.5;
					var dist = Math.abs(newTop + optionMiddle - slickSelectHalfHeight);
					if (dist <= slickSelectHalfHeight){
						$slickSelectOptions.removeClass(SlickSelect.CLASS_OPTION_SELECTED);
						$slickSelectOptions.eq(i).addClass(SlickSelect.CLASS_OPTION_SELECTED);
						if (dist < _params.scrollSnapDist){
							newTop = -optionTop + maxTop;
						}
					}
				}

				$options.css("top", newTop + "px");
			},

			_handler_endDrag:function(evt){
				if (!_vars._isDragging){
					return;
				}
				_vars._isDragging = false;

				//Unbind events
				var $doc = $(document);
				if (_params.scroll){
					$doc.off("touchmove mousemove", _methods._handler_moveDrag);
					$doc.off("touchend mouseup", _methods._handler_endDrag);
				}

				var $optionSelected = $("." + SlickSelect.CLASS_OPTION_SELECTED, $(_vars._slickSelect));
				if ($optionSelected.length){
					_methods.selectOption($optionSelected);
				}
			},

			_getTouchPoint:function(evt){
				var pointData = evt;
				if (evt.originalEvent){
					if (evt.originalEvent.touches || evt.originalEvent.changedTouches){
						pointData = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0];
					}
				}
				return [
					pointData.clientX,
					pointData.clientY
				];
			}
		};

		_$select.SlickSelect = { //Expose public methods
			isOpen:function(){return _vars.isOpen;}, //Getter
			selectedIndex:function(){return _vars.selectedIndex;}, //Getter
			value:function(){return _vars.value;}, //Getter

			initialize:_methods.initialize,
			destroy:_methods.destroy,
			open:_methods.open,
			close:_methods.close,
			selectOption:_methods.selectOption,
			update:_methods.update
		};
		_$select.SlickSelect.initialize();
		return _$select; //jQuery chaining
	}

	$.fn.SlickSelect.defaultParams = SlickSelect.defaultParams;
}(jQuery)); //$


text:
var hprose = require('hprose');
function log(data) {
    console.log(hprose.BytesIO.toString(data));
    return data;
}
module.exports = {
    inputFilter: log,
    outputFilter: log
};


text:
package model

import "github.com/davidlu1997/fast-shortener/config"
import "time"

// Link is a link
type Link struct {
	// URL is the original unshortened URL
	URL string `json:"url"`

	// Key is the shortened key
	Key string `json:"key"`

	// Duration is the persistence time
	Duration *time.Duration `json:"-"`

	// Seconds is the persistence time in seconds
	Seconds int64 `json:"seconds"`
}

// PreSave calculates the duration given seconds
// called before the link is saved
func (l *Link) PreSave() {
	if l.Duration == nil {
		l.Duration = new(time.Duration)
		*l.Duration = time.Duration(l.Seconds) * time.Second
	}
}

// IsValid checks if a link is valid
func (l *Link) IsValid(config *config.Configuration) bool {
	if config == nil {
		return true
	}

	if l.Duration == nil {
		return false
	}

	if *l.Duration > config.Links.MaxDuration || *l.Duration < config.Links.MinDuration {
		return false
	}

	length := len(l.Key)
	if length > config.Links.MaxLength || length < config.Links.MinLength {
		return false
	}

	return true
}


text:
package org.broadleafcommerce.openadmin.server.service.persistence;

import org.springframework.stereotype.Service;

/**
 * @author Jeff Fischer
 */
@Service("blPersistenceThreadManager")
public class PersistenceThreadManager {

    public <T, G extends Throwable> T operation(TargetModeType targetModeType, Persistable<T, G> persistable) throws G {
        try {
            PersistenceManagerFactory.startPersistenceManager(targetModeType);
            return persistable.execute();
        } finally {
            PersistenceManagerFactory.endPersistenceManager();
        }
    }
}


text:
// ---------------------------------------------------------------------------------------------------
// <copyright file="WebEndPoints.cs" company="Elephant Insurance Services, LLC">
//     Copyright (c) 2015 All Right Reserved
// </copyright>
// <author>Gurpreet Singh</author>
// <date>2015-06-08</date>
// <summary>
//     The WebEndPoints class
// </summary>
// ---------------------------------------------------------------------------------------------------

namespace Elephant.Hank.WindowsApplication.Resources.Constants
{
    /// <summary>
    /// The WebEndPoints class
    /// </summary>
    public static class WebEndPoints
    {
        /// <summary>
        /// The report by web site identifier
        /// </summary>
        public static string ReportByWebSiteId = "#/Website/{0}/Report";

        /// <summary>
        /// The report by web site and report identifier
        /// </summary>
        public static string ReportByWebSiteAndReportId = "#/Website/{0}/Report-Detail/{1}";
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scrutiny.Models
{
	public class ContextModels
	{
		public class Index
		{
            public string Scrutiny_Api_BaseUrl { get; set; }
            public IEnumerable<string> Stylesheets { get; set; }
            public IEnumerable<string> Scripts { get; set; }
        }
    }
}


text:
layout: post
title: SpecFlow, page objects and FluentAutomation
date: 2012-05-16T12:44:00.001Z
author: Marcus Hammarberg
tags:
  - .NET
  - Life of a consultant
  - Agile
  - SpecFlow
modified_time: 2013-01-30T14:40:57.546Z
thumbnail: >-
  http://lh6.ggpht.com/-pWpMISDNgTI/T7OhNxh3t9I/AAAAAAAABPg/9HvHRV6w8IM/s72-c/wlEmoticon-confusedsmile%25255B2%25255D.png?imgmax=800
blogger_id: tag:blogger.com,1999:blog-36533086.post-1609908988336242581
blogger_orig_url: http://www.marcusoft.net/2012/05/specflow-page-objects-and.html
---

I've been putting together a sample for my client on how to automate
against a web page. The purpose is to show how the tools are used and
give a starting ground for training and elaboration. When I was done I
realized that this could be useful for many – so here is my story on how
I set this up, problems I've ran into and solutions to them and
the code.
Please join me on the journey!

### Why test against the UI now again?

The first thing to notice that testing against the UI is not the best
thing you can do. There's an excellent article on that by Gojko Adzic here. But sometime
you don't have much choice, the application may not be in shape for
writing tests against a level under the UI, or you don't have access in
(or knowledge about) the code base.
In these cases UI testing can be thought of as black box testing, you
don't need to know the internals of the application, and can be
useful.
The pros of testing against the UI are (IMHO):

- You're testing the complete application stack, end-to-end
- It's building a confidence and trust with your stakeholders, since
    they can actually see the application being run on the screen.

The cons is (sadly):

- The tests take much longer time to run
- The tests becomes brittle since the GUI often is the part of the
    application that changes most
- Since you're testing the whole stack of the application it's harder
    to setup correct test data and and other prerequisite. You cannot,
    easily, fake or mock part of the application infrastructure.

### The application

The application we're testing is mega simple. It's an
MVC 3
application and I've simply scaffolded the complete application with the
following commands, in the Package Manager console:

> Install-Package MvcScaffolding
> Scaffold Controller Team –Repository

The "Team" above is a small class with the properties Name, City and
date Founded. I've ~~stolen~~ borrowed it from here.

This will produce a simple, but useful, little application in which you
can create a soccer team, that you then can list, edit and delete.
CRUD in a nutshell in other words. But it's
sufficient for our needs in this case.

MVCScaffolding will put you database in your SQLServer express instance
if you don't tell it otherwise, see this post for more information. I don't want that
since I want to be able to move the database together with the source.
So I updated the Web.Config with this:

All of this is made in a web application called Web found in
the source code.

## Installations and setup for the tests

I then created a class library called Specs (hey, love that
BDD stuff you know) and in that created the
following folders:

- Features – where my
    SpecFlow
    features will go
- Steps – where my step definitions will end up
- Automation – for all the infrastructure to get the automation to
    work. In this folder I created a sub folder:
  - PageWrappers – this folder will contain the wrappers for the
        different pages

After that initial set up I was ready to start pulling
NuGet packages in:

> Install-Package SpecFlow

> Install-Package
> NUnit

There 2 is to set up SpecFlow to use it's default NUnit testing library.
In order to be able to manipulate the database I went with
Simple.Data against the generated SQL Compact
database:

> Install-Package Simple.Data.SqlCompact40

Finally it was time for the automation part to get brought in. I'm using
FluentAutomation since I really like the syntax and
the packaging. It can be thought of as an API on top of
WatIn and
Selenium Web Driver.
This is nice since we can change automation provider later without
changing the automation code. FluentAutomation also have a couple of
tricks up it's sleeve that can be useful (running the same test with
multiple browsers, automatic screenshots on errors etc.).

But maybe the most useful thing is shown when you get it from NuGet.
Simply write one command and everything is slurped down to your
computer:

> Install-Package FluentAutomation.SeleniumWebDriver

Here you can see that I've gone with the SeleniumWebDriver. Mainly
because I've heard great things about it and that I've never tried it
before. Also – with FluentAutomation – I don't care….

## Browsers and automation problems

So far so good. My Specs-project now have all the references I'll be
needing. But I haven't used them yet. So I wrote a stupid simple
FluentAutomationTest:

But sadly that didn't work out as planned…

### Gotcha 1 – Firefox is default

Firefox is the default browser for FluentAutomation. So, as I didn't
have it on the computer I tried to reconfigure the test to use another
browser.

This works but I don't want to say in each and every test which browser
to use. But there is a Setup-method…

### Gotcha 2 – Setup is not for everything

Every test class that will use the FluentAutomation should inherit from
FluentTest. This gives you, amongst other things, a Setup-method to
override. But if you try to set up which browser to use that will cause
… a
StackOverflowException
(I've never had one of those before, honestly). So this code is **not
good**:

If you want to set up FluentAutomation up to use a specific browser for
all your tests in the fixture you should probably do something like
this:

So now the test is using InternetExplorer. But …

### Gotcha 3 – InternetExplorer and Enable protect mode

When that test started to run I got the next exception, with a very
helpful message telling me that I needed to enable the protect mode for
all the zones in Internet Explorers Security settings (or something like
that).

Go to InternetExplorer –\> options –\> Security and select each zone.
Make sure that the checkbox for Enabling ProtectMode (whatever that this
) is checked.

Re-running the test and everything was dandy! Success. Surely Chrome
must be much simpler …

### Gotcha 4 – Download and copy the ChromeDriver

I flipped the I.Use() statement to use BrowserType.Chrome and crossed my
fingers. No! Another helpful exception though. It told me to get and
download the ChromeDriver from
<http://code.google.com/p/chromedriver/downloads/list>. And also to copy
it to the bin-directory.

The first part is pretty easy. Just grab the right version for your OS
and save into the solution folder somewhere (I put mine in the root of
the solution).

The second part required some thinking. So before each test run I want
to copy the chromedriver.exe to the bin-directory of the Specs-project.
To achieve this I'm using the Build-events found under
Properties-\>Build Events of the Specs-project. I added the following
little DOS (my God!) command under the Post-build event command line:

> xcopy $(SolutionDir)chromedriver.exe $(TargetDir) /D

After that the test worked fine with Chrome. And it was fast fast
fast.
Now just back to Firefox. I downloaded it and change the
I.Use()-statement to use BrowserType.FireFox (which is default). And …

### Gotcha 5 – Firefox not working

This has to do with the SeleniumDriver not supporting the latest
versions of Firefox, see this post:

> It seems the Selenium WebDriver does not support the latest version of
> Firefox which is at the time of writing: 8.0.1. A workaround is to
> downgrade to Firefox v7.0.1.

I did that… And it worked!

Everything is up and running!

## Page objects and wrappers

One of the problems with UI tests is that they are brittle. The UI is
changing and finding controls on the page can be tricky sometimes. In
order to handle that problem a bit and buffer the problem you can create
a Wrapper around the page. I have described this common pattern here. For a real
indepth look on this pattern in action check this excellent screen cast by
Matt Wynnne

### PageWrapperBase

So I started to create a little base class for the Page wrappers. This
will hold the Browser-object form FluentAutomation to give each
PageWrapper easy access to the automation. Some generic methods can go
in here also. Here is my first stab:

A few things to notice here:

- Each page wrapper that inherits this base class will need to supply
    the relative path to the page
- The base path will be stored in App.Config for the Specs-project
    which will give us possibilities to change that easy as we move
    through the environments
- I'm using a static instance for the Browser so that I don't need to
    open a close for each test

Here is a page using that base class:

As you can see the class only need to supply the relative path to the
page it's wrapping.

#### DBWrapper

I've created a small class with static methods that I use to perform
database tasks. It's based on Simple.Data (LOVE) and in this case goes
against the SQL CE database I'm using in the web application.

### SpecFlow events

SpecFlow gives you a number of events and hooks that you can use to perform task
that you want to run before and after tests.
In this case I'm:

- Cleaning out the testdata I've used and change after each scenario
- Closing the browser after each test run. You DO want to do this or
    you'll have 50+ browser instances open pretty quickly.

### Steps

With the page wrappers in place the steps becomes very simple. Almost
trivial, as it's just delegating off to the page wrapper in questions.

So my tip is to not be afraid of a lot of steps, as long as they are
simple. It's much more important to be able to clearly state the intent
of the scenario.

Another tip is that you can stack different Given/When/Then-attributes
on top of each other for readability. Like this:

All of those steps will hit the same step definition HomePage().

## From feature to automation

Let's follow a step from feature file all the way down to the automation
as a final exercise. Note that here have translated the feature content
to English as it's Swedish in my sample:

1. The step "Given I am on
    the homepage" gets run as part of the scenario
2. SpecFlow calls into the step definition marked with the "\[Given(@"I am on the
    homepage")\]". That method is defined on the Steps-class
3. The step definition contains of a single line; "\_teamListingPageWrapper.Visit();"
    1. \_teamListingPageWrapper
        is a private variable in the Steps-class
4. The Visit()-method is definied on the PageWrapperBase class
    that simply use the Browser instance to Open the URL for the page;
    Browser.Open(pageURL);
    1. The pageURL is put together from the prefix found in the
        app.config and the relative URL for the page we're wrapping ("/"
        in this case)
5. If that works out the scenario continues on the next step: "Then a link for Create New team
    should be present on the page"
6. SpecFlow again calls into the right step definition
7. The step definition propagates into the page wrapper, in the method
    AssertCreateNewTeamLinkExists()
8. In the page wrapper we're looking for that link on the page with the
    following line, that will throw and exception if it fails – as we
    want:
    Browser.Expect.Text("Create
    New").In("a#NewLink");
9. Our test passes!

## Conclusion

Of course I haven't written this in the order described in this blog
post but rather explored / driven the need for new methods on the page
wrappers as the features dictated.
I hope that you have got something out of this and that you can start
use SpecFlow with FluentAutomation from this.


text:
<component name="libraryTable">
  <library name="glide-transformations-2.0.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/jp.wasabeef/glide-transformations/2.0.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/jp.wasabeef/glide-transformations/2.0.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://D:/Program Files/Android/gradl/.gradle/caches/modules-2/files-2.1/jp.wasabeef/glide-transformations/2.0.0/b8437c4d2510f8cc5188b5c2bdf0543f45dfd488/glide-transformations-2.0.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
sudo apt-get install -y vim git tmux
git clone http://git-wip-us.apache.org/repos/asf/mesos.git

# Change working directory.
cd mesos

git checkout 0.20.0

# Bootstrap (***Skip this if you are not building from git repo***).
./bootstrap

# Configure and build.
mkdir build
cd build
../configure
make

# Run test suite.
make check

# Install (***Optional***).
make install


text:
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.CommunityToolkit.ObjectModel;
using Xamarin.Forms;

namespace Xamarin.CommunityToolkit.Behaviors
{
	public class AnimationBehavior : EventToCommandBehavior
	{
		public static readonly BindableProperty AnimationTypeProperty =
			BindableProperty.Create(nameof(AnimationType), typeof(AnimationBase), typeof(AnimationBehavior));

		internal static readonly BindablePropertyKey AnimateCommandPropertyKey =
 			BindableProperty.CreateReadOnly(
 				nameof(AnimateCommand),
 				typeof(ICommand),
 				typeof(AnimationBehavior),
 				default,
 				BindingMode.OneWayToSource,
 				defaultValueCreator: CreateAnimateCommand);

		public static readonly BindableProperty AnimateCommandProperty = AnimateCommandPropertyKey.BindableProperty;

		public AnimationBase? AnimationType
		{
			get => (AnimationBase?)GetValue(AnimationTypeProperty);
			set => SetValue(AnimationTypeProperty, value);
		}

		public ICommand AnimateCommand => (ICommand)GetValue(AnimateCommandProperty);

		bool isAnimating;
		TapGestureRecognizer? tapGestureRecognizer;

		protected override void OnAttachedTo(VisualElement bindable)
		{
			base.OnAttachedTo(bindable);

			if (!string.IsNullOrWhiteSpace(EventName) || !(bindable is View view))
				return;

			tapGestureRecognizer = new TapGestureRecognizer();
			tapGestureRecognizer.Tapped += OnTriggerHandled;
			view.GestureRecognizers.Clear();
			view.GestureRecognizers.Add(tapGestureRecognizer);
		}

		protected override void OnDetachingFrom(VisualElement bindable)
		{
			if (tapGestureRecognizer != null)
				tapGestureRecognizer.Tapped -= OnTriggerHandled;

			base.OnDetachingFrom(bindable);
		}

		protected override async void OnTriggerHandled(object? sender = null, object? eventArgs = null)
		{
			await OnAnimate();

			base.OnTriggerHandled(sender, eventArgs);
		}

		static object CreateAnimateCommand(BindableObject bindable)
			=> new AsyncCommand(((AnimationBehavior)bindable).OnAnimate);

		async Task OnAnimate()
		{
			if (isAnimating || View is not View typedView)
				return;

			isAnimating = true;

			if (AnimationType != null)
				await AnimationType.Animate(typedView);

			isAnimating = false;
		}
	}
}


text:
using System;
using System.Xml.Linq;
using Mono.Cecil;

namespace Tracer.Fody.Filters.DefaultFilter
{
    /// <summary>
    /// Specifies that the namespace should be traced for the given class and method visibility level.
    /// </summary>
    internal class AssemblyLevelTraceOnDefinition : AssemblyLevelTraceDefinition
    {
        private readonly TraceTargetVisibility _targetClass;
        private readonly TraceTargetVisibility _targetMethod;

        internal AssemblyLevelTraceOnDefinition(NamespaceScope namespc, TraceTargetVisibility targetClass, TraceTargetVisibility targetMethod) : base(namespc)
        {
            _targetClass = targetClass;
            _targetMethod = targetMethod;
        }

        internal static AssemblyLevelTraceOnDefinition ParseFromConfig(XElement element)
        {
            return new AssemblyLevelTraceOnDefinition(ParseNamespaceScope(element), ParseTraceTargetVisibility(element, "class"), ParseTraceTargetVisibility(element, "method"));
        }

        private static TraceTargetVisibility ParseTraceTargetVisibility(XElement element, string attributeName)
        {
            var attribute = element.Attribute(attributeName);
            if (attribute == null)
            {
                throw new Exception(String.Format("Tracer: TraceOn config element missing attribute '{0}'.", attributeName));
            }

            switch (attribute.Value.ToLower())
            {
                case "public": return TraceTargetVisibility.Public;
                case "internal": return TraceTargetVisibility.InternalOrMoreVisible;
                case "protected": return TraceTargetVisibility.ProtectedOrMoreVisible;
                case "private": return TraceTargetVisibility.All;
                case "none": return TraceTargetVisibility.None;
                default:
                    throw new Exception(String.Format("Tracer: TraceOn config element attribute '{0}' has an invalid value '{1}'.", attributeName, attribute.Value));
            }
        }

        public TraceTargetVisibility TargetClass
        {
            get { return _targetClass; }
        }

        public TraceTargetVisibility TargetMethod
        {
            get { return _targetMethod; }
        }

        internal override bool IsMatching(MethodDefinition methodDefinition)
        {
            if (base.IsMatching(methodDefinition))
            {
                var declaringType = methodDefinition.DeclaringType;
                var typeVisibility = VisibilityHelper.GetTypeVisibilityLevel(declaringType);
                var methodVisibilityLevel = VisibilityHelper.GetMethodVisibilityLevel(methodDefinition);

                //check type visibility
                if ((int)typeVisibility > (int)_targetClass) return false;

                //then method visibility will decide
                return ((int)methodVisibilityLevel <= (int)_targetMethod);
            }
            return false;
        }

        protected bool Equals(AssemblyLevelTraceOnDefinition other)
        {
            return _targetClass == other._targetClass && _targetMethod == other._targetMethod && NamespaceScope == other.NamespaceScope;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((AssemblyLevelTraceOnDefinition) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return ((int) _targetClass*397) ^ (int) _targetMethod;
            }
        }

        public static bool operator ==(AssemblyLevelTraceOnDefinition left, AssemblyLevelTraceOnDefinition right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(AssemblyLevelTraceOnDefinition left, AssemblyLevelTraceOnDefinition right)
        {
            return !Equals(left, right);
        }

        internal override bool ShouldTrace()
        {
            return true;
        }
    }
}


text:
import Ember from 'ember';
import { debouncedObserver } from 'ui/utils/debounce';
import Util from 'ui/utils/util';
import C from 'ui/utils/constants';

export default Ember.Component.extend({
  swarm       : Ember.inject.service(),

  currentStep : 0,
  subStep     : 0,
  subCount    : 0,
  services    : null,

  init() {
    this._super(...arguments);

    this.updateStep();
    this.get('store').findAllUnremoved('service').then((services) => {
      this.set('services', services);
    });
  },

  steps: [
    'waitSwarm.addHost',
    'waitSwarm.activateHost',
    'waitSwarm.createStack',
    'waitSwarm.startServices',
  ],

  updateStep: debouncedObserver('model.hosts.@each.state','model.stacks.@each.{state,externalId}','services.@each.{state,healthState}', function() {
    this.set('subStep', 0);
    this.set('subCount', 0);

    if ( (this.get('model.hosts.length') + this.get('model.machines.length')) === 0 )
    {
      this.set('currentStep', 0);
      return;
    }

    if ( this.get('model.hosts').filterBy('state','active').get('length') === 0 )
    {
      this.set('currentStep', 1);
      return;
    }

    var stack = this.get('swarm').filterSystemStack(this.get('model.stacks'));
    if ( !stack )
    {
      this.set('currentStep', 2);
      return;
    }

    if ( stack.get('state') !== 'active' )
    {
      if ( stack.get('state') === 'inactive' )
      {
        stack.doAction('activate');
        this.set('currentStep', 3);
        return;
      }
    }

    var services = (this.get('services')||[]).filterBy('environmentId', stack.get('id'));
    var num = services.get('length');
    var healthy = Util.filterByValues(services, 'healthState', C.READY_STATES).get('length');
    if ( num === 0 || healthy < num )
    {
      this.setProperties({
        currentStep: 3,
        subStep: healthy,
        subCount: num
      });
      return;
    }

    this.set('currentStep', 4);
  }),

  stepChanged: function(){
    if ( this.get('currentStep') >= this.get('steps.length') )
    {
      this.sendAction('ready');
    }
  }.observes('currentStep','steps.length'),
});


text:
<?php
namespace Crud\Test\TestCase\Action\Bulk;

use Cake\Routing\DispatcherFactory;
use Cake\Routing\Router;
use Crud\TestSuite\IntegrationTestCase;

class DeleteActionTest extends IntegrationTestCase
{

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'plugin.crud.blogs',
        'plugin.crud.users'
    ];

    /**
     * Table class to mock on
     *
     * @var string
     */
    public $tableClass = 'Crud\Test\App\Model\Table\BlogsTable';

    /**
     * Data provider with all HTTP verbs
     *
     * @return array
     */
    public function allHttpMethodProvider()
    {
        return [
            ['post'],
            ['put'],
        ];
    }

    /**
     * Test the normal HTTP flow for all HTTP verbs
     *
     * @dataProvider allHttpMethodProvider
     * @return void
     */
    public function testAllRequestMethods($method)
    {
        $this->_eventManager->on(
            'Dispatcher.beforeDispatch',
            ['priority' => 1000],
            function ($event) {
                $this->_controller->Flash = $this->getMock(
                    'Cake\Controller\Component\Flash',
                    ['set']
                );

                $this->_controller->Flash
                    ->expects($this->once())
                    ->method('set')
                    ->with(
                        'Delete completed successfully',
                        [
                            'element' => 'default',
                            'params' => ['class' => 'message success', 'original' => 'Delete completed successfully'],
                            'key' => 'flash'
                        ]
                    );

                $this->_subscribeToEvents($this->_controller);
            }
        );

        $this->{$method}('/blogs/deleteAll', [
            'id' => [
                1 => 1,
                2 => 2,
            ],
        ]);

        $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']);
        $this->assertTrue($this->_subject->success);
        $this->assertRedirect('/blogs');
    }

    /**
     * Test the flow when the beforeBulk event is stopped
     *
     * @return void
     */
    public function testStopBeforeBulk()
    {
        $this->_eventManager->on(
            'Dispatcher.beforeDispatch',
            ['priority' => 1000],
            function ($event) {
                $this->_controller->Flash = $this->getMock(
                    'Cake\Controller\Component\Flash',
                    ['set']
                );

                $this->_controller->Flash
                    ->expects($this->once())
                    ->method('set')
                    ->with(
                        'Could not complete deletion',
                        [
                            'element' => 'default',
                            'params' => ['class' => 'message error', 'original' => 'Could not complete deletion'],
                            'key' => 'flash'
                        ]
                    );

                $this->_subscribeToEvents($this->_controller);

                $this->_controller->Crud->on('beforeBulk', function ($event) {
                    $event->stopPropagation();
                });
            }
        );

        $this->post('/blogs/deleteAll', [
            'id' => [
                1 => 1,
                2 => 2,
            ],
        ]);

        $this->assertEvents(['beforeBulk', 'setFlash', 'beforeRedirect']);
        $this->assertFalse($this->_subject->success);
        $this->assertRedirect('/blogs');
    }

    /**
     * Test with UUID request data.
     *
     * @return void
     */
    public function testUuidRequestData()
    {
        $this->_eventManager->on(
            'Dispatcher.beforeDispatch',
            ['priority' => 1000],
            function ($event) {
                $this->_controller->Flash = $this->getMock(
                    'Cake\Controller\Component\Flash',
                    ['set']
                );

                $this->_controller->Flash
                    ->expects($this->once())
                    ->method('set')
                    ->with(
                        'Delete completed successfully',
                        [
                            'element' => 'default',
                            'params' => ['class' => 'message success', 'original' => 'Delete completed successfully'],
                            'key' => 'flash'
                        ]
                    );

                $this->_subscribeToEvents($this->_controller);
            }
        );

        $this->post('/users/deleteAll', [
            'id' => [
                '0acad6f2-b47e-4fc1-9086-cbc906dc45fd' => '0acad6f2-b47e-4fc1-9086-cbc906dc45fd',
                '968ad2b3-f41d-4de3-909a-74a3ce85e826' => '968ad2b3-f41d-4de3-909a-74a3ce85e826',
            ],
        ]);

        $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']);
        $this->assertTrue($this->_subject->success);
        $this->assertRedirect('/users');
    }
}


text:
require "rails_helper"

module OkComputer
  describe ElasticsearchCheck do
    let(:host) { "http://localhost:9200" }

    subject { described_class.new(host) }

    it "is a subclass of Check" do
      subject.should be_a Check
    end

    describe "#new(host, request_timeout)" do
      it "requires host" do
        expect { described_class.new }.to raise_error
      end

      it "saves host as a URI and sets url to cluster health API url" do
        expect(subject.host).to eq URI(host)
        expect(subject.url).to eq(URI("#{host}/_cluster/health"))
      end

      it "defaults request_timeout to 5 seconds" do
        expect(subject.request_timeout).to eq(5)
      end

      it "remembers request_timeout" do
        check = described_class.new(host, 10)
        expect(check.request_timeout).to eq(10)
      end
    end

    describe "#check" do
      context "when the connection is successful" do
        before do
          subject.stub(:cluster_health).and_return(cluster_health)
        end

        context "when the cluster is healthy" do
          let(:cluster_health) do
            {
              cluster_name: "elasticsearch",
              status: "yellow",
              number_of_nodes: 1
            }
          end

          it { should be_successful }
          it { should have_message "Connected to elasticseach cluster 'elasticsearch', 1 nodes, status 'yellow'" }
        end

        context "when the cluster is unhealthy" do
          let(:cluster_health) do
            {
              cluster_name: "elasticsearch",
              status: "red",
              number_of_nodes: 1
            }
          end

          it { should_not be_successful }
          it { should have_message "Connected to elasticseach cluster 'elasticsearch', 1 nodes, status 'red'" }
        end
      end

      context "when the connection fails" do
        let(:error_message) { "Error message" }

        before do
          subject.stub(:cluster_health).and_raise(HttpCheck::ConnectionFailed, error_message)
        end

        it { should_not be_successful }
        it { should have_message "Error: '#{error_message}'" }
      end
    end

    describe "#cluster_health" do
      context "when the connection is successful" do
        let(:cluster_health) do
          {
            cluster_name: "elasticsearch",
            status: "green",
            number_of_nodes: 2
          }
        end

        let(:response) { cluster_health.to_json }

        before do
          subject.stub(:perform_request).and_return(response)
        end

        it "returns a symbolized hash of the cluster health API response" do
          expect(subject.cluster_health).to eq(cluster_health)
        end
      end

      context "when the connection fails" do
        before do
          subject.stub(:perform_request).and_raise(HttpCheck::ConnectionFailed)
        end

        it "raises a ConnectionFailed error" do
          expect { subject.cluster_health }.to raise_error(HttpCheck::ConnectionFailed)
        end
      end
    end
  end
end


text:
package local.dam_2015.frag_todo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import local.dam_2015.frag_todo.fragments.InputFragment;
import local.dam_2015.frag_todo.model.todo;

public class FragActivity extends ActionBarActivity implements InputFragment.setItemListener{

    String TODO = "todo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frag);
    }

    @Override
    public void addTodo(todo todo) {
        //Log.d(TODO);
        InputFragment.setItemListener listFragment;

        try{
            listFragment = (InputFragment.setItemListener) getFragmentManager().findFragmentById(R.id.fragment2);
        } catch(ClassCastException ex) {
            throw new ClassCastException(this.toString() + "must implement setItemListener()");
        }
        listFragment.addTodo(todo);
    }
}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>27.5. pkgutil — Package extension utility — Editorial Documentation</title>
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Editorial Documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Editorial Documentation" href="../index.html" />
    <link rel="up" title="27. Importing Modules" href="modules.html" />
    <link rel="next" title="27.6. modulefinder — Find modules used by a script" href="modulefinder.html" />
    <link rel="prev" title="27.4. zipimport — Import modules from Zip archives" href="zipimport.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <meta name = "viewport" content = "width=device-width; initial-scale=1.0; minimum-scale=1.0; maximum-scale=1.0">

Navigation

          index

          modules |

          next |

          previous |

Editorial Documentation »

The Python Standard Library »

27. Importing Modules »

27.5. <tt class="xref py py-mod docutils literal">pkgutil</tt> — Package extension utility¶

New in version 2.3.

Source code: Lib/pkgutil.py

This module provides utilities for the import system, in particular package
support.

<tt class="descclassname">pkgutil.</tt><tt class="descname">extend_path</tt><big>(</big>path, name<big>)</big>¶

Extend the search path for the modules which comprise a package.  Intended
use is to place the following code in a package’s <tt class="file docutils literal">__init__.py</tt>:

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

This will add to the package’s <tt class="docutils literal">__path__</tt> all subdirectories of directories
on <tt class="docutils literal">sys.path</tt> named after the package.  This is useful if one wants to
distribute different parts of a single logical package as multiple
directories.

It also looks for <tt class="file docutils literal">*.pkg</tt> files beginning where <tt class="docutils literal">*</tt> matches the
name argument.  This feature is similar to <tt class="file docutils literal">*.pth</tt> files (see the
<tt class="xref py py-mod docutils literal">site</tt> module for more information), except that it doesn’t special-case
lines starting with <tt class="docutils literal">import</tt>.  A <tt class="file docutils literal">*.pkg</tt> file is trusted at face
value: apart from checking for duplicates, all entries found in a
<tt class="file docutils literal">*.pkg</tt> file are added to the path, regardless of whether they exist
on the filesystem.  (This is a feature.)

If the input path is not a list (as is the case for frozen packages) it is
returned unchanged.  The input path is not modified; an extended copy is
returned.  Items are only appended to the copy at the end.

It is assumed that <tt class="xref py py-data docutils literal">sys.path</tt> is a sequence.  Items of <tt class="xref py py-data docutils literal">sys.path</tt>
that are not (Unicode or 8-bit) strings referring to existing directories are
ignored.  Unicode items on <tt class="xref py py-data docutils literal">sys.path</tt> that cause errors when used as
filenames may cause this function to raise an exception (in line with
<tt class="xref py py-func docutils literal">os.path.isdir()</tt> behavior).

class <tt class="descclassname">pkgutil.</tt><tt class="descname">ImpImporter</tt><big>(</big>dirname=None<big>)</big>¶

PEP 302 Importer that wraps Python’s “classic” import algorithm.

If dirname is a string, a PEP 302 importer is created that searches that
directory.  If dirname is <tt class="xref docutils literal">None</tt>, a PEP 302 importer is created that
searches the current <tt class="xref py py-data docutils literal">sys.path</tt>, plus any modules that are frozen or
built-in.

Note that <tt class="xref py py-class docutils literal">ImpImporter</tt> does not currently support being used by
placement on <tt class="xref py py-data docutils literal">sys.meta_path</tt>.

class <tt class="descclassname">pkgutil.</tt><tt class="descname">ImpLoader</tt><big>(</big>fullname, file, filename, etc<big>)</big>¶

PEP 302 Loader that wraps Python’s “classic” import algorithm.

<tt class="descclassname">pkgutil.</tt><tt class="descname">find_loader</tt><big>(</big>fullname<big>)</big>¶

Find a PEP 302 “loader” object for fullname.

If fullname contains dots, path must be the containing package’s
<tt class="docutils literal">__path__</tt>.  Returns <tt class="xref docutils literal">None</tt> if the module cannot be found or imported.
This function uses <tt class="xref py py-func docutils literal">iter_importers()</tt>, and is thus subject to the same
limitations regarding platform-specific special import locations such as the
Windows registry.

<tt class="descclassname">pkgutil.</tt><tt class="descname">get_importer</tt><big>(</big>path_item<big>)</big>¶

Retrieve a PEP 302 importer for the given path_item.

The returned importer is cached in <tt class="xref py py-data docutils literal">sys.path_importer_cache</tt> if it was
newly created by a path hook.

If there is no importer, a wrapper around the basic import machinery is
returned.  This wrapper is never inserted into the importer cache (<tt class="xref docutils literal">None</tt>
is inserted instead).

The cache (or part of it) can be cleared manually if a rescan of
<tt class="xref py py-data docutils literal">sys.path_hooks</tt> is necessary.

<tt class="descclassname">pkgutil.</tt><tt class="descname">get_loader</tt><big>(</big>module_or_name<big>)</big>¶

Get a PEP 302 “loader” object for module_or_name.

If the module or package is accessible via the normal import mechanism, a
wrapper around the relevant part of that machinery is returned.  Returns
<tt class="xref docutils literal">None</tt> if the module cannot be found or imported.  If the named module is
not already imported, its containing package (if any) is imported, in order
to establish the package <tt class="docutils literal">__path__</tt>.

This function uses <tt class="xref py py-func docutils literal">iter_importers()</tt>, and is thus subject to the same
limitations regarding platform-specific special import locations such as the
Windows registry.

<tt class="descclassname">pkgutil.</tt><tt class="descname">iter_importers</tt><big>(</big>fullname=''<big>)</big>¶

Yield PEP 302 importers for the given module name.

If fullname contains a ‘.’, the importers will be for the package containing
fullname, otherwise they will be importers for <tt class="xref py py-data docutils literal">sys.meta_path</tt>,
<tt class="xref py py-data docutils literal">sys.path</tt>, and Python’s “classic” import machinery, in that order.  If
the named module is in a package, that package is imported as a side effect
of invoking this function.

Non-PEP 302 mechanisms (e.g. the Windows registry) used by the standard
import machinery to find files in alternative locations are partially
supported, but are searched after <tt class="xref py py-data docutils literal">sys.path</tt>.  Normally, these
locations are searched before <tt class="xref py py-data docutils literal">sys.path</tt>, preventing <tt class="xref py py-data docutils literal">sys.path</tt>
entries from shadowing them.

For this to cause a visible difference in behaviour, there must be a module
or package name that is accessible via both <tt class="xref py py-data docutils literal">sys.path</tt> and one of the
non-PEP 302 file system mechanisms.  In this case, the emulation will find
the former version, while the builtin import mechanism will find the latter.

Items of the following types can be affected by this discrepancy:
<tt class="docutils literal">imp.C_EXTENSION</tt>, <tt class="docutils literal">imp.PY_SOURCE</tt>, <tt class="docutils literal">imp.PY_COMPILED</tt>,
<tt class="docutils literal">imp.PKG_DIRECTORY</tt>.

<tt class="descclassname">pkgutil.</tt><tt class="descname">iter_modules</tt><big>(</big>path=None, prefix=''<big>)</big>¶

Yields <tt class="docutils literal">(module_loader, name, ispkg)</tt> for all submodules on path, or, if
path is <tt class="xref docutils literal">None</tt>, all top-level modules on <tt class="docutils literal">sys.path</tt>.

path should be either <tt class="xref docutils literal">None</tt> or a list of paths to look for modules in.

prefix is a string to output on the front of every module name on output.

<tt class="descclassname">pkgutil.</tt><tt class="descname">walk_packages</tt><big>(</big>path=None, prefix='', onerror=None<big>)</big>¶

Yields <tt class="docutils literal">(module_loader, name, ispkg)</tt> for all modules recursively on
path, or, if path is <tt class="xref docutils literal">None</tt>, all accessible modules.

path should be either <tt class="xref docutils literal">None</tt> or a list of paths to look for modules in.

prefix is a string to output on the front of every module name on output.

Note that this function must import all packages (not all modules!) on
the given path, in order to access the <tt class="docutils literal">__path__</tt> attribute to find
submodules.

onerror is a function which gets called with one argument (the name of the
package which was being imported) if any exception occurs while trying to
import a package.  If no onerror function is supplied, <tt class="xref py py-exc docutils literal">ImportError</tt>s
are caught and ignored, while all other exceptions are propagated,
terminating the search.

Examples:

# list all modules python can access
walk_packages()

# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__ + '.')

<tt class="descclassname">pkgutil.</tt><tt class="descname">get_data</tt><big>(</big>package, resource<big>)</big>¶

Get a resource from a package.

This is a wrapper for the PEP 302 loader <tt class="xref py py-func docutils literal">get_data()</tt> API.  The
package argument should be the name of a package, in standard module format
(<tt class="docutils literal">foo.bar</tt>).  The resource argument should be in the form of a relative
filename, using <tt class="docutils literal">/</tt> as the path separator.  The parent directory name
<tt class="docutils literal">..</tt> is not allowed, and nor is a rooted name (starting with a <tt class="docutils literal">/</tt>).

The function returns a binary string that is the contents of the specified
resource.

For packages located in the filesystem, which have already been imported,
this is the rough equivalent of:

d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()

If the package cannot be located or loaded, or it uses a PEP 302 loader
which does not support <tt class="xref py py-func docutils literal">get_data()</tt>, then <tt class="xref docutils literal">None</tt> is returned.

New in version 2.6.

    © Copyright 1990-2017, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Jan 16, 2017.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
How would you tell someone about Creative Commons?

  Here are some toolkits to help start the conversation.

Basics of CC

What is Creative Commons and what are the CC licenses? Get basic info to share the importance of CC with others.

View toolkit »

Education

Why does CC matter in education? See how CC helps expand access and improve the quality of education around the world.

View toolkit »

Government

Why does CC matter in government? See how CC helps improve transparency, efficiency, and innovation.

View toolkit »

Creative Industries

Why does CC matter in creative industries? See how CC enhances creative collaboration.

View toolkit »

Science

Why does CC matter in science? See how CC licenses go beyond access and help us advance our understanding of the world.

View toolkit »

Culture

Why does CC matter in the GLAM sector? See how CC helps us preserve and share the world's cultural heritage.

View toolkit »


text:
package ua.com.fielden.platform.entity.validation.test_entities.definers;

import ua.com.fielden.platform.entity.meta.IAfterChangeEventHandler;
import ua.com.fielden.platform.entity.meta.MetaProperty;

public class MakeProp1NotRequired implements IAfterChangeEventHandler<Integer> {

    @Override
    public void handle(final MetaProperty<Integer> property, final Integer entityPropertyValue) {
         property.getEntity().getProperty("prop1").setRequired(false);
    }

}


text:
/*
 * sample netlink module
 */
#define KMSG_COMPONENT "sampleNetlink"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <net/genetlink.h>

#include <net/ip.h>
#include <net/tcp.h>
#include <net/netfilter/nf_conntrack.h>
#include "sample_nl.h"

#define MODULE_NAME "SampleNetlink"

#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,36)
#define NLA_PUT_U32 nla_put_u32
#define NLA_PUT_STRING nla_put_string
#endif

static struct timer_list sample_timer;
struct sample_nla _sn = {
	.info = {.x = 1, .y = 2},
	.data = {'h','e','l','l','o','\0'},
	};

struct genl_family family = {
	.id	= GENL_ID_GENERATE,
	.name	 = SAMPLE_NL_FAMILY_NAME,
	.version = 1,
	.maxattr = SAMPLE_NL_CMD_MAX,
};

struct genl_multicast_group grp[] = {
	{.name	= SAMPLE_NL_GRP_NAME},
};

/* Policy used for attributes in nested attribute SAMPLE_ECHO_ATTR */
static const struct nla_policy sample_echo_policy[SAMPLE_ECHO_ATTR_MAX + 1] = {
	[SAMPLE_ECHO_ATTR_INFO] = {.type = NLA_NESTED},
	[SAMPLE_ECHO_ATTR_DATA] = {.type = NLA_NUL_STRING, .len = 2048},
};

static const struct nla_policy sample_info_policy[SAMPLE_INFO_ATTR_MAX + 1] = {
	[SAMPLE_INFO_ATTR_X] = {.type = NLA_U32},
	[SAMPLE_INFO_ATTR_Y] = {.type = NLA_U32},
};

static int sample_parse_info(struct sample_info *si, struct nlattr *nla){
	struct nlattr *attrs[SAMPLE_INFO_ATTR_MAX + 1];

	if(nla == NULL ||
			nla_parse_nested(attrs, SAMPLE_INFO_ATTR_MAX, nla, sample_info_policy))
		return -EINVAL;

	if(!attrs[SAMPLE_INFO_ATTR_X] || !attrs[SAMPLE_INFO_ATTR_Y])
		return -EINVAL;

	memset(si, 0, sizeof(*si));
	si->x = nla_get_u32(attrs[SAMPLE_INFO_ATTR_X]);
	si->y = nla_get_u32(attrs[SAMPLE_INFO_ATTR_Y]);
	return 0;
}

static int sample_parse_echo(struct sample_nla *sn, struct nlattr *nla){
	struct nlattr *attrs[SAMPLE_ECHO_ATTR_MAX + 1];

	if(nla == NULL ||
			nla_parse_nested(attrs, SAMPLE_ECHO_ATTR_MAX, nla, sample_echo_policy))
		return -EINVAL;

	if(!attrs[SAMPLE_ECHO_ATTR_DATA] || !attrs[SAMPLE_ECHO_ATTR_INFO])
		return -EINVAL;

	memset(sn, 0, sizeof(*sn));

	strcpy(sn->data, nla_data(attrs[SAMPLE_ECHO_ATTR_DATA]));
	return sample_parse_info(&sn->info, attrs[SAMPLE_ECHO_ATTR_INFO]);
}

static int sample_nl_fill_echo(struct sk_buff *skb, struct sample_nla *sn){
	struct nlattr *nl_info;

	nl_info = nla_nest_start(skb, SAMPLE_ECHO_ATTR_INFO);
	if(!nl_info)
		return -EMSGSIZE;
	NLA_PUT_U32(skb, SAMPLE_INFO_ATTR_X, sn->info.x);
	NLA_PUT_U32(skb, SAMPLE_INFO_ATTR_Y, sn->info.y);
	nla_nest_end(skb, nl_info);
	NLA_PUT_STRING(skb, SAMPLE_ECHO_ATTR_DATA, sn->data);
	return 0;

#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,36)
nla_put_failure:
	nla_nest_cancel(skb, nl_info);
	return -EMSGSIZE;
#endif
}

int sample_echo(struct sk_buff *skb, struct genl_info *info)
{
	int ret = 0, cmd, reply_cmd;
	struct sk_buff *msg;
	struct sample_nla sn;
	void *reply;

	cmd = info->genlhdr->cmd;
	if( cmd == SAMPLE_NL_CMD_ECHO){
		reply_cmd = SAMPLE_NL_CMD_ECHO;
	}else{
		return -EINVAL;
	}

	ret = sample_parse_echo(&sn, info->attrs[SAMPLE_CMD_ATTR_ECHO]);

	if (ret)
		goto out;

	printk("%s(%d) kernel recv echo: x[%u], y[%u], data[%s]\n", __func__, __LINE__, sn.info.x, sn.info.y, sn.data);

	//reply
	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
	if(!msg){
		ret = -ENOMEM;
		goto out;
	}

	reply = genlmsg_put_reply(msg, info, &family, 0, reply_cmd);
	if (reply == NULL){
		ret = -EMSGSIZE;
		goto out;
	}

	if(sample_nl_fill_echo(msg, &sn)){
		ret = -EMSGSIZE;
		goto out;
	}

	genlmsg_end(msg, reply);
	ret = genlmsg_reply(msg, info);

out:
	return ret;
}

int sample_echo_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
	void *hdr;

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36)
	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
			&family, 0, SAMPLE_NL_CMD_ECHO);
#else
	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq,
			&family, 0, SAMPLE_NL_CMD_ECHO);
#endif
			//&family, NLM_F_MULTI, SAMPLE_NL_CMD_ECHO);
	if(!hdr)
		return -EMSGSIZE;

	printk("echo: x[%u], y[%u], data[%s]\n", _sn.info.x, _sn.info.y, _sn.data);
	if(sample_nl_fill_echo(skb, &_sn)){
		genlmsg_cancel(skb, hdr);
		goto nla_put_failure;
	}
	return genlmsg_end(skb, hdr);

nla_put_failure:
	genlmsg_cancel(skb, hdr);
	return -EMSGSIZE;
}

struct genl_ops ops[] = {
	{
	.cmd	= SAMPLE_NL_CMD_ECHO,
	.flags	= GENL_ADMIN_PERM, // just root
	.policy	= sample_echo_policy,
	.doit	= sample_echo,
	.dumpit	= sample_echo_dump,
	},
};

static void sample_nl_notify(struct sample_nla *sn)
{
	int ret;
	void	*hdr;
	struct sk_buff	*skb;

	skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
	if(!skb){
		return;
	}

	hdr = genlmsg_put(skb, 0, 0, &family, 0, SAMPLE_NL_CMD_NOTIFY);
	if (!hdr)
		goto fail_fill;

	if(sample_nl_fill_echo(skb, sn)){
		ret = -EMSGSIZE;
		goto fail_fill;
	}

	if (genlmsg_end(skb, hdr) < 0)
		goto fail_fill;

	rcu_read_lock();
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36)
	ret = genlmsg_multicast_allns(&family, skb, 0, 0, GFP_ATOMIC);
#else
	ret = genlmsg_multicast_allns(skb, 0, grp[0].id, GFP_KERNEL);
#endif
	rcu_read_unlock();

	if (ret && ret != -ESRCH) {
		printk("%s: Error notifying group (%d)\n",
			__func__, ret);
		nlmsg_free(skb);
	}
	return;

fail_fill:
	printk("%s: Failed to fill nl_attr.\n", 	__func__);
	nlmsg_free(skb);
	return;
}

static void sample_timer_callback(unsigned long data)
{
	sample_nl_notify(&_sn);
	mod_timer(&sample_timer, jiffies + msecs_to_jiffies(2000));
	return;
}

static int __init sample_nl_init(void)
{
	int ret = 0;

#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,36)
	/* register the new family and all opertations but the first one */
	ret = genl_register_family_with_ops_groups(&family, ops, grp);
	if (ret) {
		printk(KERN_CRIT "%s: Could not register netlink family (%d)\n",
				__func__, ret);
		return ret;
	}
#else
	/* register the new family and all opertations but the first one */
	ret = genl_register_family(&family);
	if (ret) {
		printk(KERN_CRIT "%s: Could not register netlink family (%d)\n",
				__func__, ret);
		return ret;
	}
	ret = genl_register_ops(&family, &ops[0]);
	if (ret) {
		printk(KERN_CRIT "%s: Could not register netlink ops, ret:%d\n",
				__func__, ret);
		genl_unregister_family(&family);
		return ret;
	}

	ret = genl_register_mc_group(&family, &grp[0]);
	if (ret) {
		printk(KERN_CRIT "Module %s: group error (%d)\n",
				MODULE_NAME, ret);
		genl_unregister_ops(&family, &ops[0]);
		genl_unregister_family(&family);
		return ret;
	}
#endif
	setup_timer(&sample_timer, sample_timer_callback, 0);
	mod_timer(&sample_timer, jiffies + msecs_to_jiffies(2000));

	printk("Module %s initialized\n", MODULE_NAME);

	return 0;
}

static void __exit sample_nl_exit(void)
{
	int ret;
	ret = del_timer_sync(&sample_timer);
	if (ret)
		printk("Timer is still in use...\n");
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,36)
	genl_unregister_family(&family);
#else
	genl_unregister_mc_group(&family, &grp[0]);
	genl_unregister_ops(&family, &ops[0]);
	genl_unregister_family(&family);
#endif
	printk("Module %s exit\n", MODULE_NAME);
}

module_init(sample_nl_init);
module_exit(sample_nl_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("yubo");
MODULE_DESCRIPTION("Sample Netlink kernel module for Linux");


text:
var i = 1;

// execute if jsPlum is ready
jsPlumb.ready(function () {

    // set state machine as container
    jsPlumb.setContainer($("#stm"));

    var j = 0;
    /*var inst = jsPlumb.getInstance({
        Endpoint: ["Dot", {radius: 2}],
        HoverPaintStyle: {strokeStyle: "#1e8151", lineWidth: 2 },
        ConnectionOverlays: [
            [ "Arrow", {
                location: 1,
                id: "arrow",
                length: 14,
                foldback: 0.8
            } ]
            //[ "Label", { label: "connecting", id: "label", cssClass: "aLabel" }]
        ],
        Container: "stm"
    });*/

    // triggered before connection is set to prevent drawing a self loop
    inst.bind("beforeDrop", function (con) {
        // source and target ID's are same
        if (con.sourceId === con.targetId) {
            return false;

        } else {
            return true;
        }
    });

    // triggered if a connection was drawn between to units
    inst.bind("connection", function (con) {

        // only use if scenario name is set (don't access at loading scenario)
        if ( $("#lname")[0].innerHTML.length != 0 ) {
            // get current scenario name
            var currentScenario = $("#lname")[0].innerHTML;

            // add connection in JSON structure
            for (var n=0; n<myAuthorSystem.length; n++) {
                if (myAuthorSystem[n].name == currentScenario) {
                    myAuthorSystem[n]["connections"].push({
                        sourceId:con.sourceId,
                        targetId:con.targetId,
                        connId:con.connection.id,
                        connLabel: "PRE",
                        connTitle: "Voraussetzung (PRE)"
                    });
                    // add label to connection
                    con.connection.addOverlay([ "Label", { label: "PRE", id: "label", cssClass: "aLabel" }]);

                    // add title to label
                    var label = con.connection.getOverlay("label");
                    var labelID = $(label)[0].canvas.id;
                    $("#" + labelID)[0].setAttribute("title", "Vorausetzung (PRE)");
                    break;
                }
            }
        }
    });

    var current_labelConnection;
    var current_connection;
    // triggered if connection or label is clicked
    // c = connection element
    // e = event
    inst.bind("click", function (c, e) {

        // if label was clicked show tab information
        if (c.id == "label") {

            // get name of source and target unit
            var sourceUnit = c._jsPlumb.component.source.textContent;
            var targetUnit = c._jsPlumb.component.target.textContent;

            // add names in relations labels
            $("#preLabelRelations").html(sourceUnit + " ist eine");
            $("#postLabelRelations").html("für " + targetUnit);

            // update current label
            current_labelConnection = c.canvas.id;

            // store current connection
            current_connection = c;

            // clear marking from label connections
            $(".aLabel").css("background-color", "");
            $(".aLabel").css("color", "");

            // set label connection mark
            $("#" + c.canvas.id).css("background-color", "#1e8151");
            $("#" + c.canvas.id).css("color", "white");

            // clear unit marking and hide unit properties
            $(".w").css("background", "");
            $(".w").css("color", "");
            $(".tabContents").hide();
            $(".tab-Container").hide();

            // set label connection property visible
            $("#tabUnitLabel").css("display", "block");

            // show right selection of the current label in selection bar
            $("#selectRelations").children("option").each(function() {
                if ( $(this)[0].value.toUpperCase() == c.canvas.innerText ) {
                    $("#selectRelations").select2("data", {id:$(this)[0].value, text:$(this)[0].innerHTML});
                }
            });

            // needed to prevent clicking the container as well
            e.stopPropagation();

        // if connection was clicked, delete it
        }
        /*else {
            // detach all connections
            inst.detach(c);

            // get id and current scenario name
            var connID = c.id;
            var currentScenario = $("#lname")[0].innerHTML;

            // delete connection in JSON structure
            for (var n=0; n<myAuthorSystem.length; n++) {
                if (myAuthorSystem[n].name == currentScenario) {
                    for (var l=0; l<myAuthorSystem[n]["connections"].length; l++) {
                        if (myAuthorSystem[n]["connections"][l].connId == connID) {
                            myAuthorSystem[n]["connections"].splice(l, 1);
                            break;
                        }
                    }
                    break;
                }
            }
        }*/
    });

    // deletes selected connection
    $("#btnDeleteConnection").on("click", function() {

        // get connection object
        var con = $("#" + current_labelConnection)[0]._jsPlumb.component;

        // detach connection
        inst.detach(con);

        // get id and current scenario name
        var connID = con.id;
        var currentScenario = $("#lname")[0].innerHTML;

        // delete connection in JSON structure
        for (var n=0; n<myAuthorSystem.length; n++) {
            if (myAuthorSystem[n].name == currentScenario) {
                for (var l=0; l<myAuthorSystem[n]["connections"].length; l++) {
                    if (myAuthorSystem[n]["connections"][l].connId == connID) {
                        myAuthorSystem[n]["connections"].splice(l, 1);
                        break;
                    }
                }
                break;
            }
        }

        // hide tab after connection was deleted
        $("#tabUnitLabel").hide();
    });

    // triggered if an option for a label connection was selected
    $("#selectRelations").select2().on("select2-selecting", function(e) {
        // set new name on label
        $("#" + current_labelConnection).html(e.val.toUpperCase());
        $("#" + current_labelConnection)[0].setAttribute("title", e.choice.text);

        // unmark label
        $("#" + current_labelConnection).css("background-color", "");
        $("#" + current_labelConnection).css("color", "");

        // hide property in tab
        $("#tabUnitLabel").hide();

        // get connection id and scenario name
        var connID = $("#" + current_labelConnection)[0]._jsPlumb.component.id;
        var currentScenario = $("#lname")[0].innerHTML;

        // put label text in JSON structure
        for (var m=0; m<myAuthorSystem.length; m++) {
            if (myAuthorSystem[m].name == currentScenario) {
                for (var p=0; p<myAuthorSystem[m]["connections"].length; p++) {
                    if (myAuthorSystem[m]["connections"][p].connId == connID) {
                        myAuthorSystem[m]["connections"][p].connLabel = e.val.toUpperCase();
                        myAuthorSystem[m]["connections"][p].connTitle = e.choice.text;
                        break;
                    }
                }
            }
        }
    });

    // delete current unit + connections in tab "Eigenschaften"
    $("#btnDeleteUnit").on("click", function() {

        // get unit name from inout field
        var unitName = $("#inputUnitName")[0].value;

        // find right unit
        $("#stm").children("div.w").children("div.title").each(function() {
            if (this.innerHTML == unitName) {
                // get unit id
                var unitID = $(this).parent()[0].getAttribute("id");

                // delete all connections
                inst.detachAllConnections($("#" + unitID));

                // delete unit
                $(this).parent().remove();
            }
        });
    });

    // delete one or more units + connections in modal window "Lernszenarien löschen"
    $("#btnDeleteUnits2").on("click", function() {

        // get all selected units which should be deleted from multi selection bar
        var list_deleteableUnits = $("#selectMultiDeleteUnits").select2("data");

        for (var i=0; i<list_deleteableUnits.length; i++) {
            // get unit id
            var unitID = list_deleteableUnits[i].id;

            // delete all connections
            inst.detachAllConnections($("#" + unitID));

            // delete unit in state machine
            $("#" + unitID).remove();
        }
    });

    // triggered if add unit (plus icon) or create new unit in navigation bar was clicked
    $('#navadd,#createLearnUnit').click(function(e) {

        /* if loaded sceanrio */
        // get last id number
        var max = 0;
        $("#stm").children("div.w").each(function() {
            var id = parseInt($(this)[0].getAttribute("id").slice(-1));
            if (id > max) {
                max = id;
            }
        });
        // prevent that two unit have the same id
        max = max + 1;

        // build unit DOM
        var newState = $('
').attr('id', 'state' + max).addClass('w');
        var title = $('
').addClass('title').css("padding", "0px 7px");
        var stateName = $('<input>').attr('type', 'text').css("color", "#34495e");
        title.append(stateName);

        // add div for context information icons
        var divContextIcons = $("
").addClass("unit-icons");

        // create connection point
        var ep = $('
').addClass('ep');

        window.jsp = inst;
        var windows = jsPlumb.getSelector("#stm .w");

        // add elements to unit DOM
        newState.append(divContextIcons);
        newState.append(title);
        newState.append(ep);

        // add unit DOM to state machine
        $('#stm').append(newState);

        var nameSet = false;

        // if the unit name was written and enter was clicked
        stateName.keyup(function(e) {
            if (e.keyCode === 13) {

                // set unit name
                $(this).parent().text(this.value);

                // set event listeners
                activateFunctionalities(newState);

                // set the new unit as current unit name
                global_currentInputUnitName = this.value;

                // add learning unit in menu bar
                var nameCurrentScenario = $("#lname")[0].innerText;
                var liCurrentScenario;

                // find correct scenario in menu
                $("span.title").each(function() {
                    if ($(this)[0].innerText == nameCurrentScenario) {
                        liCurrentScenario = $(this);
                    }
                });

                // build DOM for menu bar
                var ulCurrentScenario;
                var liNewUnit = $("
").addClass("last");
                var aNewUnit = $("").attr("href", "#");
                var spanNewUnit = $("");
                liCurrentScenario = liCurrentScenario.parent("a").parent("li");

                // necessary if the running scenario has a unit already
                if (liCurrentScenario.hasClass("has-sub")) {

                    // get unit list
                    ulCurrentScenario = liCurrentScenario.children("ul");

                    // add unit in menu bar
                    spanNewUnit[0].innerText = this.value;
                    aNewUnit.append(spanNewUnit);
                    liNewUnit.append(aNewUnit);
                    ulCurrentScenario.append(liNewUnit);
                }

                // necessary if the running scenario has no units
                if (liCurrentScenario.hasClass("last")) {

                    // create list DOM
                    ulCurrentScenario = $("
").attr("style", "display:none");

                    // editing scenario DOM
                    liCurrentScenario.removeClass("last");
                    liCurrentScenario.addClass("active");
                    liCurrentScenario.addClass("has-sub");

                    // append content name on DOM
                    spanNewUnit[0].innerText = this.value;
                    aNewUnit.append(spanNewUnit);
                    liNewUnit.append(aNewUnit);
                    ulCurrentScenario.append(liNewUnit);
                    liCurrentScenario.append(ulCurrentScenario);

                    // append a holder to toggle the menu bar
                    liCurrentScenario.children("a").append('');

                    // get the functionalities into the menu bar
                    liCurrentScenario.children("a").click(function() {
                        $(this).removeAttr('href');
                        var element = $(this).parent('li');

                        if (element.hasClass('open')) {
                            element.removeClass('open');
                            element.find('li').removeClass('open');
                            element.find('ul').slideUp();
                        }
                        else {
                            element.addClass('open');
                            element.children('ul').slideDown();
                            element.siblings('li').children('ul').slideUp();
                            element.siblings('li').removeClass('open');
                            element.siblings('li').find('li').removeClass('open');
                            element.siblings('li').find('ul').slideUp();
                        }
                    });
                }

                // update JSON structure
                // get new unit in its scenario
                for (var k=0; k<myAuthorSystem.length; k++) {
                    if (myAuthorSystem[k]["name"] == nameCurrentScenario) {
                        myAuthorSystem[k]["units"].push(
                            {   name:this.value,            // displayed name
                                description:"",             // description of the unit
                                sat:"all",                  // how much context information have to be satisfied
                                contextInformations:[],     // list of containing context information
                                metaData:[],                // list of containing meta data
                                //connections:[],           // list of connections with other units
                                posX:0,                     // absolute X position in the displayed container
                                posY:0                      // absolute Y position in the displayed container
                            }
                        );
                    }
                }

                // hide tabs because all units will be unmarked
                $(".tabContents").hide();

                nameSet = true;
            }

            // to set the source and target points, it is necessary to wait until the name was entered
            // --> prevent the wrong placement of the dots
            if (nameSet) {

                // make the unit draggable
                inst.draggable(newState, {
                    //containment: 'parent'
                    containment: '.body'
                });

                // set target point
                inst.makeTarget(newState, {
                    anchor: "Continuous",
                    dropOptions: { hoverClass: "dragHover" },
                    allowLoopback: false
                });

                // set source point
                inst.makeSource(ep, {
                    parent: newState,
                    anchor: "Continuous",
                    connector: [ "StateMachine", { curviness: 20 } ],
                    connectorStyle: { strokeStyle: "#5c96bc", lineWidth: 2, outlineColor: "transparent", outlineWidth: 4 }
                });

                nameSet = false;
            }

        });

        // set focus pn input field
        stateName.focus();

        j++;

        // if in state machine was scrolled, all elements have to be repainted
        $("#stm").on("scroll", function() {
            inst.repaintEverything();
        });

    });

});


text:
package org.scalatra

import org.specs2.mutable.Specification
import org.scalatra.util.{MultiMap, MultiMapHeadView, MapWithIndifferentAccess}
import org.scalatra.util.conversion.TypeConverter
import java.util.Date
import java.text.SimpleDateFormat

class ParamsExtensionSpec extends Specification {

  import ScalatraParamsImplicits._

  case class FakeParams(params: Map[String, String]) extends MultiMapHeadView[String, String] with MapWithIndifferentAccess[String] {
    protected def multiMap = MultiMap(params.map(e => (e._1, List(e._2).toSeq)))
  }

  "Scalatra 'Params pimping'" should {

    "add a getAs[T] method to Scalatra Params that returns Option[T]" in {

      val params: Params = FakeParams(Map("a" -> "1", "b" -> "", "c" -> null))

      params.getAs[Int]("a") must beSome(1)

      params.getAs[Int]("b") must beNone
      params.getAs[Int]("c") must beNone

      params.getAs[Int]("unexistent") must beNone
    }

    "add a getAs[Date] method to Scalatra Params that returns Option[Date]" in {

      val (format, dateAsText) = ("dd/MM/yyyy", "9/11/2001")

      val params: Params = FakeParams(Map("TwinTowers" -> dateAsText))

      val expectedDate = new SimpleDateFormat(format).parse(dateAsText)

      params.getAs[Date]("TwinTowers" -> format) must beSome(expectedDate)

    }

    "return None if a conversion is invalid" in {
      val params: Params = FakeParams(Map("a" -> "hello world"))
      params.getAs[Int]("a") must beNone
    }

    case class Bogus(name: String)

    "implicitly find TypeConverter(s) for a custom type" in {

      implicit val bogusConverter: TypeConverter[String, Bogus] = (s: String) => Some(Bogus(s))

      val params: Params = FakeParams(Map("a" -> "buffybuffy"))

      params.getAs[Bogus]("a") must beSome

      params.getAs[Bogus]("a").get aka "The bogus value" must_== Bogus("buffybuffy")

    }

    "explicitely receive a custom TypeConverter" in {

      val params: Params = FakeParams(Map("a" -> "buffybuffy"))

      params.getAs[Bogus]("a")((s: String) => Some(Bogus(s.toUpperCase))) must beSome(Bogus("BUFFYBUFFY"))

    }
  }

  "Scalatra 'MultiParams' pimping" should {

    "add a getAs[T] method" in {

      val multiParams: MultiMap = Map("CODES" -> List("1", "2").toSeq, "invalids" -> List("a", "b"))

      multiParams.getAs[Int]("CODES") must beSome[Seq[Int]]
      multiParams.getAs[Int]("CODES").get must containAllOf(List(1, 2)).inOrder
    }

    "return None for unexistent parameters" in {
      val multiParams: MultiMap = Map("invalids" -> List("1", "a", "2"))
      multiParams.getAs[Int]("blah") must beNone
    }

    "return Empty list if some conversion is invalid" in {
      val multiParams: MultiMap = Map("invalids" -> List("1", "a", "2"))
      multiParams.getAs[Int]("invalids") must_== Some(List(1, 2))
    }

    "return Empty list if all conversions are invalid" in {
      val multiParams: MultiMap = Map("invalids" -> List("a", "b"))
      multiParams.getAs[Int]("invalids") must_== Some(Nil)
    }

    "add a getAs[Date] method" in {

      val (format, datesAsText) = ("dd/MM/yyyy", List("20/12/2012", "10/02/2001"))

      val multiParams: MultiMap = Map("DATES" -> datesAsText.toSeq)

      val expectedDates = datesAsText.map {
        new SimpleDateFormat(format).parse(_)
      }

      multiParams.getAs[Date]("DATES" -> format) must beSome[Seq[Date]]
      multiParams.getAs[Date]("DATES" -> format).get must containAllOf(expectedDates).inOrder
    }
  }
}


text:
export function getPages (state = 1, action) {
  switch (action.type) {
    case 'FETCH_RECIPES':
      return state;
    case 'FETCH_RECIPES_SUCCESS':
      return action.pages;
    default:
       return state;
  }
}


text:
There is no proposal for a standard generator, but for the sake of completeness,
if an array iterator consumes an array, an array generator would lazily produce
one.
An array generator object would implement `yield` as a method with behavior
analogous to the same keyword within a generator function.
The `yield` method would add a value to the array.

```js
var array = [];
var generator = generate(array);
generator.yield(10);
generator.yield(20);
generator.yield(30);
expect(array).toEqual([10, 20, 30]);
```

Since ECMAScript 5, at Doug Crockford's behest, JavaScript allows keywords to be
used for property names, making this parallel between keywords and methods
possible.
A generator might also implement `return` and `throw` methods, but a meaningful
implementation for an array generator is a stretch of the imagination.
Although an array generator is of dubious utility, it foreshadows the interface
of asynchronous generators, for which meaningful implementations of `return` and
`throw` methods are easier to obtain, and go on to inform a sensible design for
asynchronous generator functions.


text:
package org.openhubframework.openhub.spi.alerts;

import java.util.List;

/**
 * Alerts configuration contract.
 *
 * @author Petr Juza
 * @since 0.4
 */
public interface AlertsConfiguration {

    /**
     * Gets alert info.
     *
     * @param id the alert identifier
     * @return {@link AlertInfo}
     */
    AlertInfo getAlert(String id);

    /**
     * Gets list of all alerts.
     *
     * @param enabledOnly if {@code true} then only enabled alerts are returned
     * @return list of all alerts in order from configuration file
     */
    List<AlertInfo> getAlerts(boolean enabledOnly);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DukesServer.MVP.Model.Service.Entities;

namespace DukesServer
{
    public class PlayerMessageArgs: EventArgs
    {
        public string Message { get; set; }
    }

    public class PlayerSongArgs : EventArgs
    {
        public QueuedSong Song { get; set; }
    }

    public interface IPlayer: IDisposable
    {
        event EventHandler OnPlaying;
        event EventHandler OnPaused;
        event EventHandler OnStopped;
        event EventHandler<PlayerMessageArgs> OnPlayerMessage;
        event EventHandler<PlayerSongArgs> OnPlayNewSong;

        void Play();
        void Resume();
        void Pause();

        PlayerState State { get; }
		QueuedSong CurrentSong { get; set; }
    }
}