text:
// FtaGraph.cpp

#include "FtaGraph.h"
#include "FtaTreeCache.h"
#include "FtaImageRequest.h"
#include "FtaClient.h"
#include "FtaCanvas.h"
#include "FtaApp.h"
#include "wx/listimpl.cpp"

WX_DEFINE_LIST( FtaGraphElementList );

FtaGraph::FtaGraph( void )
{
	layoutNeeded = true;
}

/*virtual*/ FtaGraph::~FtaGraph( void )
{
	DeleteGraphElementList();
}

void FtaGraph::DeleteGraphElementList( void )
{
	while( graphElementList.size() > 0 )
	{
		FtaGraphElementList::iterator iter = graphElementList.begin();
		FtaGraphElement* element = *iter;
		delete element;
		graphElementList.erase( iter );
	}
}

/*virtual*/ bool FtaGraph::Layout( void )
{
	bool success = false;
	FtaPersonIdSetList personIdSetList;

	do
	{
		if( !CreateConnectedComponents( personIdSetList ) )
			break;

		FtaPersonIdSetList::iterator iter = personIdSetList.begin();
		while( iter != personIdSetList.end() )
		{
			FtaPersonIdSet* connectedComponent = *iter;
			if( !LayoutConnectedComponent( *connectedComponent ) )
				break;

			iter++;
		}

		if( iter != personIdSetList.end() )
			break;

		if( PackConnectedComponents( personIdSetList ) )
			break;

		success = true;
	}
	while( false );

	DestroyConnectedComponents( personIdSetList );

	return success;
}

/*virtual*/ bool FtaGraph::LayoutConnectedComponent( FtaPersonIdSet& connectedComponent )
{
	// TODO: I'm thinking that the first thing I'll try is to simply place
	//       individuals at the same generation level on the same row and
	//       draw two arrows from every person to their parents.  How I sort
	//       each row will be based on the idea of minimizing how far the arrows
	//       have to go to reach the parents.

	return false;
}

/*virtual*/ bool FtaGraph::PackConnectedComponents( FtaPersonIdSetList& personIdSetList )
{
	// TODO: The simplest thing I can think of is simply to compute a bounding box
	//       for each component, and then array the boxes.

	return false;
}

/*virtual*/ bool FtaGraph::Draw( GLenum renderMode )
{
	if( !LayoutIfNeeded() )
		return false;

	FtaGraphElementList::iterator iter = graphElementList.begin();
	while( iter != graphElementList.end() )
	{
		FtaGraphElement* element = *iter;
		element->Draw( renderMode );
		iter++;
	}

	return false;
}

/*virtual*/ bool FtaGraph::CalcBoundingBox( FtaAxisAlignedBox& aab )
{
	if( !LayoutIfNeeded() )
		return false;

	aab.max.set( c3ga::vectorE3GA::coord_e1_e2_e3, -1.0, -1.0, -1.0 );
	aab.min.set( c3ga::vectorE3GA::coord_e1_e2_e3, 1.0, 1.0, 1.0 );

	FtaGraphElementList::iterator iter = graphElementList.begin();
	while( iter != graphElementList.end() )
	{
		FtaGraphElement* element = *iter;

		FtaAxisAlignedBox elementAab;
		if( !element->CalcBoundingBox( elementAab ) )
			return false;

		if( !aab.IsValid() )
			aab = elementAab;
		else
			aab.Combine( aab, elementAab );

		iter++;
	}

	return true;
}

bool FtaGraph::LayoutIfNeeded( void )
{
	if( layoutNeeded )
	{
		DeleteGraphElementList();

		if( !Layout() )
			return false;

		layoutNeeded = false;
	}

	return true;
}

void FtaGraph::AddPerson( const wxString& personId )
{
	personIdSet.insert( personId );

	layoutNeeded = true;
}

void FtaGraph::RemovePerson( const wxString& personId )
{
	personIdSet.erase( personId );

	layoutNeeded = true;
}

bool FtaGraph::CreateConnectedComponents( FtaPersonIdSetList& personIdSetList )
{
	FtaPersonIdSet remainingPersons;

	FtaPersonIdSet::iterator iter = personIdSet.begin();
	while( iter != personIdSet.end() )
	{
		wxString personId = *iter;
		remainingPersons.insert( personId );
		iter++;
	}

	while( remainingPersons.size() > 0 )
	{
		iter = remainingPersons.begin();
		wxString personId = *iter;
		FtaPersonIdSet* connectedComponent = new FtaPersonIdSet;
		personIdSetList.push_back( connectedComponent );
		if( !GenerateConnectedComponent( personId, remainingPersons, *connectedComponent ) )
		{
			DestroyConnectedComponents( personIdSetList );
			return false;
		}
	}

	return true;
}

bool FtaGraph::GenerateConnectedComponent( const wxString& personId, FtaPersonIdSet& remainingPersons, FtaPersonIdSet& connectedComponent )
{
	// Do we want to graph this person?
	if( !PersonInGraphSet( personId ) )
		return true;

	// Have we already visited this person?
	if( connectedComponent.find( personId ) != connectedComponent.end() )
		return true;

	connectedComponent.insert( personId );
	remainingPersons.erase( personId );

	const FtaPerson* person = wxGetApp().GetTreeCache()->Lookup( personId, FtaTreeCache::POPULATE_ON_CACHE_MISS );
	if( !person )
		return false;

	wxString motherId = person->GetMotherId();
	if( !GenerateConnectedComponent( motherId, remainingPersons, connectedComponent ) )
		return false;

	wxString fatherId = person->GetFatherId();
	if( !GenerateConnectedComponent( fatherId, remainingPersons, connectedComponent ) )
		return false;

	const FtaPersonIdSet& childrenIdSet = person->GetChildrenIdSet();
	for( FtaPersonIdSet::const_iterator iter = childrenIdSet.begin(); iter != childrenIdSet.end(); iter++ )
	{
		wxString childId = *iter;
		if( !GenerateConnectedComponent( childId, remainingPersons, connectedComponent ) )
			return false;
	}

	const FtaPersonIdSet& spousesIdSet = person->GetSpousesIdSet();
	for( FtaPersonIdSet::const_iterator iter = spousesIdSet.begin(); iter != spousesIdSet.end(); iter++ )
	{
		wxString spouseId = *iter;
		if( !GenerateConnectedComponent( spouseId, remainingPersons, connectedComponent ) )
			return false;
	}

	return true;
}

bool FtaGraph::DestroyConnectedComponents( FtaPersonIdSetList& personIdSetList )
{
	while( personIdSetList.size() > 0 )
	{
		FtaPersonIdSetList::iterator iter = personIdSetList.begin();
		FtaPersonIdSet* connectedComponent = *iter;
		delete connectedComponent;
		personIdSetList.erase( iter );
	}

	return true;
}

bool FtaGraph::PersonInGraphSet( const wxString& personId )
{
	if( personIdSet.find( personId ) != personIdSet.end() )
		return true;

	return false;
}

/*virtual*/ bool FtaGraph::Bind( void )
{
	return true;
}

/*virtual*/ bool FtaGraph::Unbind( void )
{
	return true;
}

/*virtual*/ bool FtaGraph::Animate( void )
{
	bool animating = false;

	FtaGraphElementList::iterator iter = graphElementList.begin();
	while( iter != graphElementList.end() )
	{
		FtaGraphElement* element = *iter;
		if( element->Animate() )
			animating = true;
		iter++;
	}

	return animating;
}

FtaGraphElement::FtaGraphElement( FtaGraph* graph )
{
	this->graph = graph;
}

/*virtual*/ FtaGraphElement::~FtaGraphElement( void )
{
}

/*virtual*/ bool FtaGraphElement::ProcessResponse( FtaAsyncRequest* request, wxJSONValue* responseValue )
{
	return false;
}

FtaGraphNode::FtaGraphNode( FtaGraph* graph ) : FtaGraphElement( graph )
{
	textureRequestSignature = -1;
	texture = GL_INVALID_VALUE;
}

/*virtual*/ FtaGraphNode::~FtaGraphNode( void )
{
	if( textureRequestSignature >= 0 )
	{
		// Don't let the pending request list hang on to a stale pointer.
		FtaClient* client = wxGetApp().GetClient();
		if( client )
			client->CancelAllAsyncRequests( textureRequestSignature );
	}
}

/*virtual*/ bool FtaGraphNode::Animate( void )
{
	if( textureRequestSignature >= 0 )
	{
		FtaClient* client = wxGetApp().GetClient();
		client->ServiceAllAsyncRequests( false, textureRequestSignature );
		return true;
	}

	return false;
}

/*virtual*/ void FtaGraphNode::Draw( GLenum renderMode )
{
	FtaTreeCache* cache = wxGetApp().GetTreeCache();

	FtaPerson* person = cache->Lookup( personId, FtaTreeCache::FAIL_ON_CACHE_MISS );
	if( !person )
		return;

	wxString portraitUrl = person->GetPortraitUrl();
	if( !( portraitUrl.IsEmpty() || portraitUrl == "No Content" ) && texture == GL_INVALID_VALUE )
	{
		if( textureRequestSignature == -1 )
		{
			textureRequestSignature = FtaClient::NewSignature();
			FtaClient* client = wxGetApp().GetClient();
			bool added = client->AddAsyncRequest( new FtaImageRequest( portraitUrl, this, textureRequestSignature ) );
			wxASSERT( added );
		}
	}

	// TODO: Since the nodes have a 3D appearance, start using lighting?
	// TODO: Draw textured quad here.

	glColor3f( 0.9f, 0.9f, 0.9f );
	aab.Draw( false );

	FtaFontSystem* fontSystem = graph->canvas->GetFontSystem();

	fontSystem->SetLineHeight( aab.GetHeight() / 10.f );
	fontSystem->SetWordWrap( true );
	fontSystem->SetJustification( FtaFontSystem::JUSTIFY_CENTER );
	fontSystem->SetFont( "ChanticleerRomanNF.ttf" );
	fontSystem->SetLineWidth( aab.GetWidth() );
	fontSystem->SetBaseLineDelta( -fontSystem->GetLineHeight() * 1.5f );

	glPushAttrib( GL_LIGHTING_BIT | GL_ENABLE_BIT );
	glDisable( GL_LIGHTING );
	glDisable( GL_DEPTH_TEST );
	glPushMatrix();

	GLfloat x = aab.min.m_e1;
	GLfloat y = aab.min.m_e2;
	GLfloat z = aab.max.m_e3;

	GLfloat length;
	fontSystem->CalcTextLength( person->GetName(), length );
	while( length > fontSystem->GetLineWidth() )
	{
		y -= fontSystem->GetBaseLineDelta();
		length -= fontSystem->GetLineWidth();
	}

	glTranslatef( x, y, z );
	glColor3f( 0.f, 0.f, 0.f );

	fontSystem->DrawText( person->GetName(), true );

	glPopMatrix();
	glPopAttrib();
}

/*virtual*/ bool FtaGraphNode::ProcessResponse( FtaAsyncRequest* request, wxJSONValue* responseValue )
{
	if( !request->IsKindOf( &FtaImageRequest::ms_classInfo ) )
		return false;

	FtaImageRequest* imageRequest = ( FtaImageRequest* )request;
	texture = graph->canvas->GenerateTexture( *imageRequest->GetImage() );

	textureRequestSignature = -2;
	return true;
}

FtaGraphEdge::FtaGraphEdge( FtaGraph* graph ) : FtaGraphElement( graph )
{
	tailNode = nullptr;
	headNode = nullptr;
}

/*virtual*/ FtaGraphEdge::~FtaGraphEdge( void )
{
}

/*virtual*/ void FtaGraphEdge::Draw( GLenum renderMode )
{
	// TODO: We could do CGA-based edge-routing here using a divde-and-conqur algorithm.
	//       A derivative of this class, however, may use dot-generated edge-spline data, which would be better.
}

/*virtual*/ bool FtaGraphEdge::CalcBoundingBox( FtaAxisAlignedBox& aab ) const
{
	return false;
}

// FtaGraph.cpp


text:
package loginstuff;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
/*
 * This class handles the JPanel buttons as if it was a Button Group.
 * So its radio buttons, but for JPanels!
 * @author Olivia Lam
 * */
import java.util.ArrayList;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class LoadDeckScreen extends JPanel{

	private JLabel fileName;

	private JPanel loadPanel;
	private JPanel revertPanel;

	private JButton confirm;
	private JPanel buttons;
	private boolean real;
	private JTextField deckFileName;

	private DeckList deck;

	public LoadDeckScreen()
	{

		setLayout(new GridLayout(2,1));

		loadPanel = new JPanel();
		loadPanel.setLayout(new GridLayout(2,1));

		buttons = new JPanel();
		buttons.setLayout(new BorderLayout());
		confirm = new JButton("Confirm");
		confirm.addActionListener(new confirmListener());
		buttons.add(confirm, BorderLayout.WEST);
		deckFileName = new JTextField();

		loadPanel.add(deckFileName);
		loadPanel.add(buttons);

		revertPanel = new JPanel();
		revertPanel.setLayout(new BorderLayout());
		JLabel hasDeckLabel = new JLabel("Deck loaded!");
		JButton revertButton = new JButton("Revert");
		revertButton.addActionListener(new revertListener());
		revertPanel.add(hasDeckLabel, BorderLayout.WEST);
		revertPanel.add(revertButton, BorderLayout.EAST);
		revertPanel.setVisible(false);

		real = false;

		add(loadPanel);
		add(revertPanel);

		setVisible(true);
	}

	public DeckList getDeckList()
	{
		return this.deck;
	}

	public boolean hasDeckList()
	{
		return (this.deck != null);
	}

	private class confirmListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			try
			{
				deck = loadDeck(deckFileName.getText());
				revertPanel.setVisible(true);
				loadPanel.setVisible(false);

			} catch(FileNotFoundException e)
			{
				JOptionPane.showMessageDialog(null, "The given DeckList was not found!");
			}
		}
	}

	private class revertListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			deck = null;
			revertPanel.setVisible(false);
			loadPanel.setVisible(true);

		}
	}

	public DeckList loadDeck(String filename) throws FileNotFoundException
	{
		return DeckList.deserialize(filename);
	}

	private class exit implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			System.exit(0);

		}

	}

	public void setReal(boolean real)
	{
		this.real = real;
	}

	public boolean isReal()
	{
		return this.real;
	}

	public void setVisibility(boolean show)
	{
		setVisible(show);
	}

}

redpajama_set_name: RedPajamaGithub


text:
var P = require('bluebird')
var cachedSessions = {}

exports.setConfig = function(host,port,secure){
  return
}

/**
 * User Login
 * @param {string} username
 * @param {string} password
 */
exports.login = function(username,password){
  return new P(function(resolve,reject){
    var sess = {
      token: getToken(),
        ip: '127.0.0.1',
        data: {}
    }
    resolve(sess)
  })
}

/**
 * User Logout
 * @param {string} token
 */
exports.logout = function(token){
  return new P(function(resolve,reject){
    if(cachedSessions[token]) cachedSessions[token]= null
    resolve(true)
  })
}

exports.isSessionValid = function(token){
  return !!cachedSessions[token]
}

var getToken = exports.getToken = function(){
  var token =  "AuthSession="+Date.now()
  cachedSessions[token] = true
  return token
}


text:
<?php

namespace Azuki;

class NotFoundException extends Exception
{
}


text:
InfoMany - Positive check for build

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("InfoMany", "testInfoManyPositiveForBuild");
--EXPECT--
OK


text:
// Polynomial evaluation using second order Horners rule
#ifndef BOOST_MATH_TOOLS_POLY_EVAL_4_HPP
#define BOOST_MATH_TOOLS_POLY_EVAL_4_HPP

namespace boost{ namespace math{ namespace tools{ namespace detail{

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<0>*)
{
   return static_cast<V>(0);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<1>*)
{
   return static_cast<V>(a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<2>*)
{
   return static_cast<V>(a[1] * x + a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<3>*)
{
   return static_cast<V>((a[2] * x + a[1]) * x + a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<4>*)
{
   return static_cast<V>(((a[3] * x + a[2]) * x + a[1]) * x + a[0]);
}

}}}} // namespaces

#endif // include guard


text:
namespace _03.A_Miner_Task
{
    using System;
    using System.Collections.Generic;

    public class MinerTask
    {
        //// You are given a sequence of strings, each on a new line. Every odd line on the console
        //// is representing a resource (e.g.Gold, Silver, Copper, and so on), and every even – quantity.
        //// Your task is to collect the resources and print them each on a new line.

        //// Print the resources and their quantities in format:
        //// {resource} –> {quantity}
        //// The quantities inputs will be in the range[1 … 2 000 000 000]

        public static void Main()
        {
            var resources = new Dictionary<string, decimal>();

            var inputLine = Console.ReadLine();

            while (inputLine != "stop")
            {
                var resource = inputLine;
                var quantity = decimal.Parse(Console.ReadLine());
                //// The "quantity" variable is to keep the different values in case if some of the
                //// resources repeat more than once. Take a look at the description bellow!

                if (!resources.ContainsKey(resource))
                {
                    resources[resource] = 0;
                }

                //// The following code sums the different values
                //// of the equal resources, which repeat more than once.
                resources[resource] += quantity;

                inputLine = Console.ReadLine();
            }

            foreach (var resource in resources)
            {
                Console.WriteLine($"{resource.Key} -> {resource.Value}");
            }
        }
    }
}


text:
"""
Ansible module for determining information about the docker host.

While there are several ansible modules that make use of the docker
api to expose container and image facts in a remote host, they
are unable to return specific information about the host machine
itself. This module exposes the same information obtained through
executing the `docker info` command on a docker host, in json format.
"""

from ansible.module_utils.docker_common import AnsibleDockerClient

def main():
    """Entrypoint for running an Ansible module."""
    client = AnsibleDockerClient()

    client.module.exit_json(
        info=client.info(),
    )

if __name__ == '__main__':
    main()


text:
package org.robotframework.formslibrary.keyword;

import java.awt.Component;
import java.util.List;

import org.robotframework.formslibrary.FormsLibraryException;
import org.robotframework.formslibrary.chooser.ByComponentTypeChooser;
import org.robotframework.formslibrary.context.FormsContext;
import org.robotframework.formslibrary.operator.AlertOperator;
import org.robotframework.formslibrary.operator.ContextOperator;
import org.robotframework.formslibrary.util.ComponentType;
import org.robotframework.formslibrary.util.Logger;
import org.robotframework.formslibrary.util.TextUtil;
import org.robotframework.javalib.annotation.ArgumentNames;
import org.robotframework.javalib.annotation.RobotKeyword;
import org.robotframework.javalib.annotation.RobotKeywords;

@RobotKeywords
public class AlertKeywords {

    @RobotKeyword("Verify that a specific alert message is shown in a warning or error dialog.")
    @ArgumentNames({ "message" })
    public void verifyAlertMessage(String message) {
        String alertMessage = getAlertMessage();
        if (!TextUtil.matches(alertMessage, message)) {
            throw new FormsLibraryException("Alert message '" + alertMessage + "' was not expected.");
        } else {
            Logger.info("Found alert '" + alertMessage + "'.");
        }
    }

    @RobotKeyword("Get the message on an alert dialog. Example:\n\n | ${alertMessage}= | Get Alert Message |\n")
    public String getAlertMessage() {
        return new AlertOperator().getAlertMessage();
    }

    @RobotKeyword("Verify no alert dialog is shown.")
    public void verifyNoAlertIsShown() {

        List<Component> panes = new ContextOperator(FormsContext.getRootContext())
                .findComponents(new ByComponentTypeChooser(-1, ComponentType.ALERT_PANE));
        if (panes.isEmpty()) {
            Logger.info("No alert dialog found.");
        } else {
            String alertMessage = new AlertOperator(panes.get(0)).getAlertMessage();
            throw new FormsLibraryException("Alert message '" + alertMessage + "' was not expected.");
        }
    }
}


text:
define(['mout/lang/isInteger'], function(isInteger){

    describe('lang/isInteger', function(){

        it('should return false if value isn\'t an integer', function(){
            expect( isInteger(false) ).toBe( false );
            expect( isInteger(true) ).toBe( false );
            expect( isInteger('foo') ).toBe( false );
            expect( isInteger('123') ).toBe( false );
            expect( isInteger('123.45') ).toBe( false );
            expect( isInteger(123.45) ).toBe( false );
            expect( isInteger(-0.45) ).toBe( false );
            expect( isInteger(new Number(-0.45)) ).toBe( false );
            expect( isInteger(new Date()) ).toBe( false );
            expect( isInteger(/foo/) ).toBe( false );
            expect( isInteger({}) ).toBe( false );
            expect( isInteger({valueOf:function(){return 123;}}) ).toBe( false );
            expect( isInteger(Infinity) ).toBe( false );
            expect( isInteger(-Infinity) ).toBe( false );
        });

        it('should return true if value is an integer', function () {
            expect( isInteger(0) ).toBe( true );
            expect( isInteger(1) ).toBe( true );
            expect( isInteger(123) ).toBe( true );
            expect( isInteger(-123) ).toBe( true );
            expect( isInteger(new Number(-123)) ).toBe( true );
        });

        it('should work even with large numbers', function () {
            expect( isInteger(Math.pow(2,45) + 0.05) ).toEqual( false );
            expect( isInteger(Math.pow(2,45) - 0.05) ).toEqual( false );
            expect( isInteger(Math.pow(2,45)) ).toEqual( true );
            expect( isInteger(-Math.pow(2,45)) ).toEqual( true );
        });

    });

});


text:
import concatMap from './uncurried/concatMap'
import curry from './curry'

/**
 * Maps a function, that returns a list, over a list and concatenates the
 * results.
 *
 * @function
 * @param {Function} f The function to apply to each value in the list. It must
 * also return a list.
 * @param {Array|String} as The list.
 * @returns {Array|String} A list that contains the elements in the list of
 * `as`, mapped with the function `f`, and concatenated together.
 * @example
 *
 * import { concatMap } from 'fkit'
 * concatMap(a => [a, 0], [1, 2, 3]) // [1, 0, 2, 0, 3, 0]
 * concatMap(a => [a, '-'], 'foo') // 'f-o-o-'
 */
export default curry(concatMap)


text:
package com.atum.tunetube.util;

import android.support.v4.provider.DocumentFile;

import com.atum.tunetube.sql.DatabaseConnection;
import com.atum.tunetube.youtube.YoutubeLink;

import java.io.File;

/**
 * Created by atum-martin on 13/08/2017.
 * This class is used for recreating the applications cache once its been deleted.
 */

public class IndexDiskFiles {

    private final DatabaseConnection db;

    public IndexDiskFiles(DatabaseConnection db){
        this.db = db;
    }

    public void indexDirectory(DocumentFile provider){
        if(provider == null || !provider.exists() || !provider.isDirectory() || provider.listFiles() == null)
            return;
        for(DocumentFile file : provider.listFiles()){

            if(!file.getName().endsWith(".m3u")){
                continue;
            }
            String title = file.getName().replaceAll("_", " ");
            title = title.substring(0, title.length()-4);
            YoutubeLink link = new YoutubeLink(title.replaceAll("'", ""), title);
            db.updatePlaytime(link);
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Beih. Sydowia 4: 32 (1961)

#### Original name
Cyphella australis Speg., 1881

### Remarks
null


text:
			Transaction
			<button class="btn btn-primary btn-xs" onClick="Main.buttonTrigger.actionToggleShortcut()">
				  |  Shortcuts
			</button>

			<button type="button" class="btn btn-success btn-lg tooltip-info" data-placement="bottom" onClick="transaction.openFormAdd();" title="Show form input data">
				   Add new
			</button>

			<?php echo $page_section_info_shortcuts;?>

		<?php echo $page_section_form_add;?>

	<fieldset>
		<legend>Record data
			<button class="btn btn-default btn-sm tooltip-info" id="btn-refresh" data-placement="right" onClick="category.reloadListData(this);" title="Refresh">
				<img src="<?php echo images_url();?>/ajax-load-4-1.png" />
			</button>
		</legend>
	</fieldset>

		<?php echo $page_section_list_data;?>

		<?php echo $page_section_form_edit;?>


text:
@class ABAddressBook, NSMutableDictionary, NSObject<OS_dispatch_queue>;

@interface IDESourceControlPersonManager : NSObject
{
    ABAddressBook *_addressBook;
    NSMutableDictionary *_peopleByRepository;
    NSMutableDictionary *_savedABPeoplePairingsByRepository;
    NSObject<OS_dispatch_queue> *_addressBookDispatchQueue;
}

+ (id)logAspect;
+ (id)sharedSourceControlPeopleRepository;
- (void).cxx_destruct;
- (void)_saveAuthorsABPairingDictionary:(id)arg1 forSourceControlTree:(id)arg2;
- (id)_autoSetupAddressBookSupportWithEmails:(id)arg1;
- (void)_findABPersonForSourceTree:(id)arg1 person:(id)arg2 withCompletionBlock:(CDUnknownBlockType)arg3;
- (id)_loadAuthorABPairingForSourceTree:(id)arg1;
- (id)_authorsFromCustomDataSpecifier:(id)arg1 dataStore:(id)arg2;
- (id)_findABPersonFromKnownAuthors:(id)arg1 author:(id)arg2;
- (id)_addressBook;
- (id)_savedNameForSourceTree:(id)arg1;
- (void)clearPersonPairing:(id)arg1 forSourceControlTree:(id)arg2;
- (void)savePersonPairing:(id)arg1 forSourceControlTree:(id)arg2;
- (id)_scPeopleForTree:(id)arg1;
- (id)personMatchingSourceControlTree:(id)arg1 forUserName:(id)arg2 email:(id)arg3 createIfNeeded:(BOOL)arg4;
- (id)vips;
- (id)me;
- (id)init;

@end


text:
Deface::Override.new(
  :name          => "replace_search_results",
  :virtual_path  => "spree/products/index",
  :replace => "[data-hook='search_results']",
  :partial => 'tshop/products/search_results',
)


text:
<?php
function testFinallyStatementHasExpectedEndLine()
{
    try {
        throw Exception();
    } finally {
        echo "FOO";
    }
}


text:
<?php
namespace MyOrm;

class Model extends \Orm\Model
{
	protected static $_write_connection;
	protected static $_write_connection_default;
	protected static $_connection;
	protected static $_connection_default;

	protected static $image_prefix;
	protected static $basic_list_cache = array();
	protected static $basic_props = array();

	/**
	 * Fetch the database connection name to use
	 *
	 * @param	bool	if true return the writeable connection (if set)
	 * @return  null|string
	 */
	public static function connection($writeable = false)
	{
		// if in tracsaction, conection force to be writable.
		if (\DB::in_transaction()) $writeable = true;

		if ($writeable)
		{
			if (empty(static::$_write_connection))
			{
				static::$_write_connection = static::get_write_connection_default();
			}

			return static::$_write_connection;
		}

		if (empty(static::$_connection))
		{
			static::$_connection = static::get_read_connection_default();
		}

		return static::$_connection;
	}

	protected static function get_write_connection_default()
	{
		if (static::$_write_connection_default) return static::$_write_connection_default;

		if (!$db_configs = \Config::get('db')) \FuelException('Db setting error.');

		if (!empty($db_configs['active'])) return $db_configs['active'];

		return static::search_write_connection_default();
	}

	protected static function search_write_connection_default()
	{
		$connection_set_first = '';
		foreach ($db_configs as $db => $config)
		{
			if (!static::check_is_db_config($config)) continue;

			// set first set db to master db.
			static::$_write_connection_default = $db;
			break;
		}
		if (empty(static::$_write_connection_default)) \FuelException('Db setting error.');

		return static::$_write_connection_default;
	}

	public static function get_read_connection_default()
	{
		if (static::$_connection_default) return static::$_connection_default;
		static::$_connection_default = static::get_read_connection_random();

		return static::$_connection_default;
	}

	protected static function get_read_connection_random()
	{
		$connection_rates = array();
		$db_configs = \Config::get('db');
		foreach ($db_configs as $db => $config)
		{
			if (!static::check_is_db_config($config)) continue;

			$connection_rates[$db] = 1;
			if (isset($config['connection_rate'])) $connection_rates[$db] = $config['connection_rate'];
		}

		return \Util_Array::rand_weighted($connection_rates);
	}

	protected static function check_is_db_config($config)
	{
		if (empty($config)) return false;
		if (!is_array($config)) return false;
		if (empty($config['type'])) return false;
		if (!in_array($config['type'], array('pdo', 'mysql', 'mysqli'))) return false;

		return true;
	}

	public static function clear_cache()
	{
		static::$_cached_objects[get_called_class()] = [];
	}

	public static function get_table_name()
	{
		return static::$_table_name;
	}

	public function get_image()
	{
		if (!static::$image_prefix) return null;
		if (empty($this->file_name)) return static::$image_prefix;

		return $this->file_name;
	}

	public function update_public_flag($public_flag)
	{
		$this->public_flag = $public_flag;
		return $this->save();
	}

	public function get_image_prefix()
	{
		return static::$image_prefix;
	}

	public static function check_authority($id, $target_member_id = 0, $related_tables = array(), $member_id_prop = 'member_id', $parent_table_with_member_id = null)
	{
		$id = (int)$id;
		if (!$id) throw new \HttpNotFoundException;

		$params = array('rows_limit' => 1);
		if ($related_tables && !is_array($related_tables)) $related_tables = (array)$related_tables;
		if ($related_tables) $params['related'] = $related_tables;
		if (!$obj = self::find($id, $params)) throw new \HttpNotFoundException;
		if ($target_member_id)
		{
			if ($parent_table_with_member_id)
			{
				if (!$related_tables || !in_array($parent_table_with_member_id, $related_tables))
				{
					throw new \InvalidArgumentException('Parameter parent_table_with_member_id is invalid.');
				}
				if ($obj->{$parent_table_with_member_id}->{$member_id_prop} != $target_member_id) throw new \HttpForbiddenException;
			}
			else
			{
				if ($obj->{$member_id_prop} != $target_member_id) throw new \HttpForbiddenException;
			}
		}

		return $obj;
	}

	public static function get_one4pk($pk_value, $relateds = array(), $pk_name = 'id')
	{
		$query = self::query()->where($pk_name, $pk_value);
		if ($relateds) $query->related($relateds);

		return $query->get_one();
	}

	public static function get_one4unique_key($unique_key_value, $relateds = array(), $unique_key = 'id')
	{
		$query = self::query()->where($unique_key, $unique_key_value);
		if ($relateds) $query->related($relateds);

		return $query->get_one();
	}

	public static function get_one4id($id, $relateds = array())
	{
		return self::get_one4unique_key(intval($id), $relateds);
	}

	public static function check_authority4unique_key($unique_key_prop, $value, $target_member_id = 0, $relateds = array(), $member_id_prop = 'member_id')
	{
		if (!$value) throw new \HttpNotFoundException;
		if (!$obj = self::get_one4unique_key($value, $relateds, $unique_key_prop)) throw new \HttpNotFoundException;
		if ($target_member_id && $obj->{$member_id_prop} != $target_member_id) throw new \HttpForbiddenException;

		return $obj;
	}

	public static function get_one4conditions(array $conditions)
	{
		return self::query()
			->where($conditions)
			->get_one();
	}

	public static function get_list($where_conds = array(), $limit = 0, $is_latest = false, $is_desc = false, $since_id = 0, $max_id = 0, $relateds = array(), $is_return_array = false, $is_return_all_count = false, $select_props = array(), $sort_prop = 'id')
	{
		$is_reverse = false;
		if ($limit && $is_latest && !$is_desc)
		{
			$is_desc = true;
			$is_reverse = true;
		}

		if ($where_conds && !is_array($where_conds)) $where_conds = (array)$where_conds;
		$query = static::get_list_query($where_conds ? array('where' => $where_conds) : array());
		$all_records_count = $is_return_all_count ? $query->count() : false;

		$params = array();
		if ($since_id)
		{
			$params[] = array($sort_prop, '>', $since_id);
		}
		if ($max_id)
		{
			$params[] = array($sort_prop, '<=', $max_id);
		}
		if ($params) $query->where($params);

		if ($select_props)
		{
			if (!is_array($select_props)) $select_props = (array)$select_props;
			foreach ($select_props as $select_prop) $query->select($select_prop);
		}

		if ($relateds) $query->related($relateds);

		if ($limit)
		{
			$rows_limit = $limit + 1;
			$query->rows_limit($rows_limit);
		}
		$query->order_by($sort_prop, ($is_desc) ? 'desc' : 'asc');
		$list = $query->get();

		$next_id = 0;
		if ($limit && count($list) > $limit)
		{
			$next_obj = array_pop($list);
			$next_id = $next_obj->id;
		}
		if ($is_reverse) $list = array_reverse($list);

		if ($is_return_array)
		{
			$list_array = array();
			foreach ($list as $key => $obj) $list_array[] = $obj->to_array();
		}

		return array($is_return_array ? $list_array : $list, $next_id, $all_records_count);
	}

	public static function get_all($relateds = array(), $params = array(), $order_by = null, $limit = 0, $offset = 0, $selects = array(), $with_all_count = false, $as_array = false)
	{
		$all_count = 0;
		if (!is_array($relateds)) $relateds = (array)$relateds;

		if (empty($order_by)) $order_by = array('id' => 'asc');
		$query = self::query()->order_by($order_by);
		if ($selects) $query->select($selects);
		if ($relateds) $query->related($relateds);
		if ($params) $query = static::set_where($query, $params);
		if ($with_all_count) $all_count = $query->count();
		if ($limit) $query->rows_limit($limit);
		if ($offset) $query->rows_offset($offset);
		$list = $query->get();
		if ($as_array)
		{
			$list_array = array();
			foreach ($list as $key => $obj) $list_array[] = $obj->to_array();
		}

		if ($with_all_count) return array($as_array ? $list_array : $list, $all_count);

		return $as_array ? $list_array : $list;
	}

	public static function get4slug($slug)
	{
		return self::query()->where('slug', $slug)->get_one();
	}

	public static function change_registered_status4unique_key(array $params)
	{
		if ($obj = self::get_one4conditions($params))
		{
			$obj->delete();
		}
		else
		{
			$obj = self::forge($params);
			$obj->save();
		}

		return $obj->id;
	}

	public static function get_cols($col, $params = array(), $order_by = array())
	{
		$query = self::query()->select($col);
		if ($params) $query = static::set_where($query, $params);
		if ($order_by) $query->order_by($order_by);

		return \Util_Orm::conv_col2array($query->get(), $col);
	}

	public static function get_assoc($key_col, $value_col, $params = array(), $order_by = array(), $limit = 0)
	{
		$query = self::query()->select($key_col, $value_col);
		if ($params) $query = static::set_where($query, $params);
		if ($order_by) $query->order_by($order_by);
		if ($limit) $query->rows_limit($limit);

		return \Util_Orm::conv_cols2assoc($query->get(), $key_col, $value_col);
	}

	public static function get_pager_list($params = array(), $page = 1, $is_return_array = false, \Orm\Query $query = null)
	{
		if ($is_return_array && isset($params['related'])) unset($params['related']);
		if (!$query) $query = self::get_list_query($params);
		$count = $query->count();

		// limit, offset
		$page = (int)$page;
		if ($page < 1) $page = 1;

		$limit  = 0;
		$offset = 0;
		if (!empty($params['limit']))
		{
			$limit  = $params['limit'];
			$offset = $limit * ($page - 1);

			$query = $query->rows_limit($limit);
			$query = $query->rows_offset($offset);
		}
		$next_page = ($limit && $count > $offset + $limit) ? $page + 1 : 0;

		$list = $query->get();
		if ($is_return_array)
		{
			foreach ($list as $key => $obj)
			{
				$list[$key] = $obj->to_array();
			}
		}

		return array('list' => $list, 'page' => $page, 'next_page' => $next_page);
	}

	public static function get_list_count($params = array(), \Orm\Query $query = null)
	{
		if (!$query) $query = self::get_list_query($params);

		return $query->count();
	}

	public static function get_list_query($params = array())
	{
		$query = self::query();

		// select
		if (!empty($params['select']))
		{
			$selects = is_array($params['select']) ? $params['select'] : (array)$params['select'];
			if (!is_array($params['select'])) $selects = (array)$params['select'];
			foreach ($selects as $select)
			{
				$query->select($select);
			}
		}

		// related
		if (!empty($params['related']))
		{
			$query->related($params['related']);
		}

		// where
		if (!empty($params['where']))
		{
			$query = self::set_where($query, $params['where']);
		}
		// order by
		if (!empty($params['order_by']))
		{
			foreach ($params['order_by'] as $key => $value)
			{
				if (is_numeric($key) && !in_array($value, array('asc', 'desc')))
				{
					$key   = $value;
					$value = 'asc';
				}
				$query->order_by($key, $value);
			}
		}

		return $query;
	}

	public static function get_list_and_count($params = array())
	{
		$query = self::get_list_query($params);
		$count = $query->count();

		if (!empty($params['limit']))
		{
			$query->rows_limit($params['limit']);
		}
		if (!empty($params['offset']))
		{
			$query->rows_offset($params['offset']);
		}
		$list = $query->get();

		return array($list, $count);
	}

	public static function get_count($conditions = array())
	{
		$query = self::query();
		if ($conditions) $query = $query->where($conditions);

		return $query->count();
	}

	public static function get4ids($ids, $limit = 0, $sort = array('id' => 'asc'), $relateds = array())
	{
		if (!is_array($ids)) $ids = (array)$ids;
		if (!$ids = \Util_Array::cast_values($ids, 'int', true)) throw new \InvalidArgumentException('First parameter is invalid.');

		$query = self::query()->where('id', 'in', $ids);
		if ($relateds) $query->related($relateds);
		if ($sort)
		{
			foreach ($sort as $column => $order)
			{
				$query->order_by($column, $order);
			}
		}
		if ($limit) $query->rows_limit($limit);

		return $query->get();
	}

	public static function get_next_sort_order($sort_order_col_name = 'sort_order')
	{
		$max = (int)self::query()->max($sort_order_col_name);

		return \Site_Util::get_next_sort_order_num($max);
	}

	public static function get_col_array($column, $params = array())
	{
		$params['select'] = $column;
		$query = self::get_list_query($params);

		return \Util_Orm::conv_col2array($query->get(), $column);
	}

	public static function get_last($conditions = array(), $sort_col = 'id')
	{
		$query = self::query();
		if ($conditions) $query->where($conditions);
		$query->order_by($sort_col, 'desc')->rows_limit(1);

		return $query->get_one();
	}

	private static function add_where(\Orm\Query $query, $wheres, $key = null)
	{
		$method = 'where';
		if ($key)
		{
			if ($key === 'or')
			{
				$method = 'or_where';
			}
			elseif ($key === 'and')
			{
				$method = 'and_where';
			}
		}
		if (count($wheres) == 2)
		{
			$query = $query->$method($wheres[0], $wheres[1]);
		}
		elseif (count($wheres) === 3)
		{
			$query = $query->$method($wheres[0], $wheres[1], $wheres[2]);
		}

		return $query;
	}

	public static function get_one_basic4id($id, $props = array())
	{
		if (!empty(static::$basic_list_cache[$id])) return static::$basic_list_cache[$id];

		if (!is_array($props)) $props = (array)$props;
		if (!$props) $props = static::$basic_props;
		if (!$props) throw new \FuelException('basic_props not set.');

		static::$basic_list_cache[$id] = array();
		if ($obj = static::get_one4id($id))
		{
			static::$basic_list_cache[$id] = array();
			foreach ($props as $prop)
			{
				static::$basic_list_cache[$id][$prop] = $prop == 'file' ? $obj->get_image() : $obj->{$prop};
			}
		}

		return static::$basic_list_cache[$id];
	}

	public static function get_basic4ids($ids, $basic_props = array(), $is_clear_cache = false)
	{
		if ($is_clear_cache) static::clear_cache();

		$objs = array();
		foreach ($ids as $id)
		{
			$objs[$id] = static::get_one_basic4id($id, $basic_props);
		}

		return $objs;
	}

	public static function get_property($column_name, $delete_validation_rules = array())
	{
		$property = self::property($column_name);
		if ($delete_validation_rules && !empty($property['validation']))
		{
			$property['validation'] = \Util_Array::delete_in_array($property['validation'], $delete_validation_rules);
		}

		return $property;
	}

	public static function get_property_value($column_name, $key, $default = null)
	{
		$property = static::get_property($column_name);

		return \Arr::get($property, $key, $default);
	}

	public function set_values(array $values, $ignore_props_additional = array())
	{
		if (!$values) return;

		$ignore_props = array_unique(static::get_ignore_props2edit() + $ignore_props_additional);
		foreach ($values as $key => $value)
		{
			if (!isset(static::$_properties[$key])) continue;
			if (in_array($key, $ignore_props)) continue;

			$this->{$key} = $value;
		}
	}

	protected static function get_ignore_props2edit()
	{
		$ignore_props = array();
		foreach (static::$_properties as $prop => $attrs)
		{
			if (!is_array($attrs))
			{
				$ignore_props[] = $attrs;
				continue;
			}

			if (isset($attrs['form']['type']) && $attrs['form']['type'] !== false)
			{
				continue;
			}

			$ignore_props[] = $prop;
		}

		return $ignore_props;
	}

	protected static function set_where(\Orm\Query $query, $params = array())
	{
		if (!$params) return $query;

		if (!is_array($params)) $params = (array)$params;
		if (!\Arr::is_multi($params))
		{
			return static::set_where4not_multi($query, $params);
		}

		if (count($params) == 3
			&& !is_array($params[0]) && !is_array($params[1])
			&& in_array(strtolower($params[1]), array('in', 'not in', '<', '>', '<=', '>=', 'like', 'collate utf8_unicode_ci like')))
		{
			return static::set_where4not_multi($query, $params);
		}

		$method = 'where';
		foreach ($params as $key => $param)
		{
			if ($key === 'and' || $key === 'or')
			{
				$method_open  = $key.'_where_open';
				$method_close = $key.'_where_close';
				$query->$method_open();
				foreach ($where as $key_child => $where_child)
				{
					$query = self::add_where($query, $where_child, $key_child);
				}
				$query = $query->$method_close();
			}
			else
			{
				$query = static::set_where4not_multi($query, $param);
			}
		}

		return $query;
	}

	protected static function set_where4not_multi(\Orm\Query $query, $params = array())
	{
		if (!$params) return $query;

		if (\Arr::is_assoc($params))
		{
			$query->where($params);

			return $query;
		}

		if (count($params) == 2)
		{
			$query->where($params[0], $params[1]);
		}
		elseif (count($params) == 3)
		{
			$query->where($params[0], $params[1], $params[2]);
		}
		else
		{
			throw new \InvalidArgumentException('Second parameter is invalid.');
		}

		return $query;
	}

	public static function get_enum_values($prop, $is_value_only = false)
	{
		if (! isset(static::$_properties[$prop]['enum_values']))
		{
			throw new \FuelException(sprintf('Property %s is not set enum values.', $prop));
		}
		$values = static::$_properties[$prop]['enum_values'];

		return $is_value_only ? array_values($values) : $values;
	}

	public static function get_enum_value4key($prop, $key, $is_return_bool = false)
	{
		$values = static::get_enum_values($prop);
		if (is_numeric($key))
		{
			if (in_array($key, array_keys($values))) return $key;

			if ($is_return_bool) return false;
			throw new \InvalidArgumentException('Parameter is invalid.');
		}

		if (! isset($values[$key]))
		{
			if ($is_return_bool) return false;
			throw new \InvalidArgumentException('Parameter is invalid.');
		}

		return $values[$key];
	}

	public static function get_enum_key4value($prop, $value, $is_return_bool = false)
	{
		$values = static::get_enum_values($prop);
		if (!is_numeric($value))
		{
			if (in_array($value, array_keys($values))) return $value;

			if ($is_return_bool) return false;
			throw new \InvalidArgumentException('Parameter is invalid.');
		}

		foreach ($values as $key => $item)
		{
			if ($value == $item) return $key;
		}

		if ($is_return_bool) return false;
		throw new \InvalidArgumentException('Parameter is invalid.');
	}

	public function get_enum_key($prop)
	{
		return static::get_enum_key4value($prop, $this->{$prop});
	}

	public function get_enum_label($prop, $is_return_bool = false)
	{
		$property = static::get_property($prop);
		$label = \Arr::get($property['form']['options'], $this->{$prop});
		if (is_null($label))
		{
			if ($is_return_bool) return false;
			throw new \InvalidArgumentException('First parameter is invalid.');
		}

		return $label;
	}

	public function check_enum_value4key($prop, $key)
	{
		if (is_null($this->{$prop})) return false;

		return $this->{$prop} == static::get_enum_value4key($prop, $key);
	}

	public function check_enum_value4keys($prop, $keys)
	{
		if (! is_array($keys)) $keys = (array)$keys;
		foreach ($keys as $key)
		{
			if (static::check_enum_value4key($prop, $key)) return true;
		}

		return false;
	}
}


text:
touch privatekey.json
echo "{\
  \"private_key_id\": \"$GAE_PRIVATE_KEY_ID\",\
  \"private_key\": \"$GAE_PRIVATE_KEY\",\
  \"client_email\": \"$GAE_CLIENT_EMAIL\",\
  \"client_id\": \"$GAE_CLIENT_ID\",\
  \"type\": \"service_account\"\
}" | tee privatekey.json > /dev/null 2> /dev/null
/usr/bin/gcloud auth activate-service-account --key-file privatekey.json
/usr/bin/gcloud config set project "$GAE_PROJECT_ID"
/usr/bin/gsutil -d ls gs://test-user-data-upload


text:
(function() {
  var Client, Gist, HttpError, Issue, Label, Me, Milestone, Notification, Org, Pr, Repo, Search, Team, User, extend, request, url,
    extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    slice = [].slice;

  request = require('request');

  url = require('url');

  Me = require('./me');

  User = require('./user');

  Repo = require('./repo');

  Org = require('./org');

  Gist = require('./gist');

  Team = require('./team');

  Pr = require('./pr');

  Issue = require('./issue');

  Milestone = require('./milestone');

  Label = require('./label');

  Notification = require('./notification');

  extend = require('deep-extend');

  Search = require('./search');

  HttpError = (function(superClass) {
    extend1(HttpError, superClass);

    function HttpError(message, statusCode, headers, body1) {
      this.message = message;
      this.statusCode = statusCode;
      this.headers = headers;
      this.body = body1;
    }

    return HttpError;

  })(Error);

  Client = (function() {
    function Client(token1, options1) {
      this.token = token1;
      this.options = options1;
      this.limit = bind(this.limit, this);
      this.requestOptions = bind(this.requestOptions, this);
      this.request = this.options && this.options.request || request;
      this.requestDefaults = {
        headers: {
          'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
        }
      };
    }

    Client.prototype.me = function() {
      return new Me(this);
    };

    Client.prototype.user = function(name) {
      return new User(name, this);
    };

    Client.prototype.repo = function(name) {
      return new Repo(name, this);
    };

    Client.prototype.org = function(name) {
      return new Org(name, this);
    };

    Client.prototype.gist = function() {
      return new Gist(this);
    };

    Client.prototype.team = function(id) {
      return new Team(id, this);
    };

    Client.prototype.pr = function(repo, number) {
      return new Pr(repo, number, this);
    };

    Client.prototype.search = function() {
      return new Search(this);
    };

    Client.prototype.issue = function(repo, number) {
      return new Issue(repo, number, this);
    };

    Client.prototype.milestone = function(repo, number) {
      return new Milestone(repo, number, this);
    };

    Client.prototype.label = function(repo, name) {
      return new Label(repo, name, this);
    };

    Client.prototype.notification = function(id) {
      return new Notification(id, this);
    };

    Client.prototype.requestOptions = function(params1, params2) {
      return extend(this.requestDefaults, params1, params2);
    };

    Client.prototype.buildUrl = function(path, pageOrQuery, per_page) {
      var _url, q, query, separator;
      if (path == null) {
        path = '/';
      }
      if (pageOrQuery == null) {
        pageOrQuery = null;
      }
      if (per_page == null) {
        per_page = null;
      }
      if ((pageOrQuery != null) && typeof pageOrQuery === 'object') {
        query = pageOrQuery;
      } else {
        query = {};
        if (pageOrQuery != null) {
          query.page = pageOrQuery;
        }
        if (per_page != null) {
          query.per_page = per_page;
        }
      }
      if (this.token) {
        if (typeof this.token === 'string') {
          query.access_token = this.token;
        } else if (typeof this.token === 'object' && this.token.id) {
          query.client_id = this.token.id;
          query.client_secret = this.token.secret;
        }
      }
      if (query.q) {
        q = query.q;
        delete query.q;
        if (Object.keys(query).length) {
          separator = '&';
        } else {
          separator = '?';
        }
      }
      if (this.options.authUrl) {
        _url = this.options.authUrl;
      } else {
        _url = url.format({
          protocol: this.options && this.options.protocol || "https:",
          auth: this.token && this.token.username && this.token.password ? this.token.username + ":" + this.token.password : '',
          hostname: this.options && this.options.hostname || "api.github.com",
          port: this.options && this.options.port,
          pathname: path,
          query: query
        });
      }
      if (q) {
        _url += separator + "q=" + q;
        query.q = q;
      }
      console.log(_url);
      return _url;
    };

    Client.prototype.errorHandle = function(res, body, callback) {
      var err, ref;
      if (Math.floor(res.statusCode / 100) === 5) {
        return callback(new HttpError('Error ' + res.statusCode, res.statusCode, res.headers));
      }
      if (typeof body === 'string') {
        try {
          body = JSON.parse(body || '{}');
        } catch (_error) {
          err = _error;
          return callback(err);
        }
      }
      if (body.message && ((ref = res.statusCode) === 400 || ref === 401 || ref === 403 || ref === 404 || ref === 410 || ref === 422)) {
        return callback(new HttpError(body.message, res.statusCode, res.headers, body));
      }
      return callback(null, res.statusCode, body, res.headers);
    };

    Client.prototype.get = function() {
      var callback, i, params, path;
      path = arguments[0], params = 3 <= arguments.length ? slice.call(arguments, 1, i = arguments.length - 1) : (i = 1, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET'
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.getNoFollow = function() {
      var callback, i, params, path;
      path = arguments[0], params = 3 <= arguments.length ? slice.call(arguments, 1, i = arguments.length - 1) : (i = 1, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET',
        followRedirect: false
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.getOptions = function() {
      var callback, i, options, params, path;
      path = arguments[0], options = arguments[1], params = 4 <= arguments.length ? slice.call(arguments, 2, i = arguments.length - 1) : (i = 2, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET'
      }, options), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.post = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'POST',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.patch = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'PATCH',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.put = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'PUT',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.del = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'DELETE',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.limit = function(callback) {
      return this.get('/rate_limit', function(err, s, b) {
        if (err) {
          return callback(err);
        }
        if (s !== 200) {
          return callback(new HttpError('Client rate_limit error', s));
        } else {
          return callback(null, b.rate.remaining, b.rate.limit, b);
        }
      });
    };

    return Client;

  })();

  module.exports = function() {
    var credentials, token;
    token = arguments[0], credentials = 2 <= arguments.length ? slice.call(arguments, 1) : [];
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Client, [token].concat(slice.call(credentials)), function(){});
  };

}).call(this);


text:
'use strict';

var TestHelper = require('../../../TestHelper');

var TestContainer = require('mocha-test-container-support');

/* global bootstrapModeler, inject */

var propertiesPanelModule = require('../../../../lib'),
    domQuery = require('min-dom/lib/query'),
    domClasses = require('min-dom/lib/classes'),
    coreModule = require('bpmn-js/lib/core'),
    selectionModule = require('diagram-js/lib/features/selection'),
    modelingModule = require('bpmn-js/lib/features/modeling'),
    propertiesProviderModule = require('../../../../lib/provider/camunda'),
    camundaModdlePackage = require('camunda-bpmn-moddle/resources/camunda'),
    getBusinessObject = require('bpmn-js/lib/util/ModelUtil').getBusinessObject;

var extensionElementsHelper = require('../../../../lib/helper/ExtensionElementsHelper');

describe('listener-fieldInjection - properties', function() {

  var diagramXML = require('./ListenerFieldInjection.bpmn');

  var testModules = [
    coreModule, selectionModule, modelingModule,
    propertiesPanelModule,
    propertiesProviderModule
  ];

  var container;

  beforeEach(function() {
    container = TestContainer.get(this);
  });

  beforeEach(bootstrapModeler(diagramXML, {
    modules: testModules,
    moddleExtensions: { camunda: camundaModdlePackage }
  }));

  beforeEach(inject(function(commandStack, propertiesPanel) {

    var undoButton = document.createElement('button');
    undoButton.textContent = 'UNDO';

    undoButton.addEventListener('click', function() {
      commandStack.undo();
    });

    container.appendChild(undoButton);

    propertiesPanel.attachTo(container);
  }));

  function getExtensionElements(bo, type) {
    return extensionElementsHelper.getExtensionElements(bo, type) || [];
  }

  function getCamundaFields(bo, type, idx) {
    var extensionElements = getExtensionElements(bo, type);
    return extensionElements[idx].fields || [];
  }

  function getInput(container, inputNode) {
    return domQuery('div[data-entry=' + inputNode.dataEntry + '] input[name=' + inputNode.name + ']', container);
  }

  function getTextbox(container, inputNode) {
    return domQuery('div[data-entry=' + inputNode.dataEntry + '] div[name=' + inputNode.name + ']', container);
  }

  function getSelect(container, inputNode) {
    return domQuery('div[data-entry=' + inputNode.dataEntry + '] select[name=' + inputNode.name + ']', container);
  }

  function getAddButton(container, selector) {
    return domQuery('div[data-entry=' + selector + '] button[data-action=createElement]', container);
  }

  function getRemoveButton(container, selector) {
    return domQuery('div[data-entry=' + selector + '] button[data-action=removeElement]', container);
  }

  function selectOption(container, inputNode) {
    var select = getSelect(container, inputNode);

    select.options[0].selected = 'selected';
    TestHelper.triggerEvent(select, 'change');
  }

  var EXECEUTION_LISTENER_TYPE = 'camunda:ExecutionListener',
      TASK_LISTENER_TYPE       = 'camunda:TaskListener';

  var FIELD_NAME_ELEMENT                = { dataEntry: 'listener-field-name', name: 'fieldName' },
      FIELD_TYPE_ELEMENT                = { dataEntry: 'listener-field-type', name: 'fieldType' },
      FIELD_VALUE_ELEMENT               = { dataEntry: 'listener-field-value', name: 'fieldValue' },
      FIELDS_SELECT_ELEMENT             = { dataEntry: 'listener-fields', name: 'selectedExtensionElement' },
      EXECUTION_LISTENER_SELECT_ELEMENT = { dataEntry: 'executionListeners', name: 'selectedExtensionElement' },
      TASK_LISTENER_SELECT_ELEMENT      = { dataEntry: 'taskListeners', name: 'selectedExtensionElement' };

  describe('get', function() {

    describe('#serviceTask', function() {

      var camundaField;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('ServiceTask');
        selection.select(shape);

        var bo = getBusinessObject(shape);
        camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0)[0];

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);
        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

      }));

      it('name', inject(function(propertiesPanel) {

        var field = getInput(propertiesPanel._container, FIELD_NAME_ELEMENT);

        expect(field.value).to.equal(camundaField.get('name'));

      }));

      it('fieldType', inject(function(propertiesPanel) {

        var field = getSelect(propertiesPanel._container, FIELD_TYPE_ELEMENT);

        expect(field.value).to.equal('string');

      }));

      it('fieldValue', inject(function(propertiesPanel) {

        var field = getTextbox(propertiesPanel._container, FIELD_VALUE_ELEMENT);

        expect(field.textContent).to.equal(camundaField.get('string'));

      }));

    });

    describe('#user select executionListener', function() {

      var camundaField;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        var bo = getBusinessObject(shape);
        camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0)[0];

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);
        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

      }));

      it('name', inject(function(propertiesPanel) {

        var field = getInput(propertiesPanel._container, FIELD_NAME_ELEMENT);

        expect(field.value).to.equal(camundaField.get('name'));

      }));

      it('fieldType', inject(function(propertiesPanel) {

        var field = getSelect(propertiesPanel._container, FIELD_TYPE_ELEMENT);

        expect(field.value).to.equal('string');

      }));

      it('fieldValue', inject(function(propertiesPanel) {

        var field = getTextbox(propertiesPanel._container, FIELD_VALUE_ELEMENT);

        expect(field.textContent).to.equal('myStringValue');

      }));

    });

    describe('#user select taskListener', function() {

      var camundaField;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        var bo = getBusinessObject(shape);
        camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0)[0];

        // select listener
        selectOption(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);
        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

      }));

      it('name', inject(function(propertiesPanel) {

        var field = getInput(propertiesPanel._container, FIELD_NAME_ELEMENT);

        expect(field.value).to.equal(camundaField.get('name'));

      }));

      it('fieldType', inject(function(propertiesPanel) {

        var field = getSelect(propertiesPanel._container, FIELD_TYPE_ELEMENT);

        expect(field.value).to.equal('expression');

      }));

      it('fieldValue', inject(function(propertiesPanel) {

        var field = getTextbox(propertiesPanel._container, FIELD_VALUE_ELEMENT);

        expect(field.textContent).to.equal('${myExpression}');

      }));

    });

  });

  describe('set', function() {

    describe('#serviceTask', function() {

      var camundaField;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('ServiceTask');
        selection.select(shape);

        var bo = getBusinessObject(shape);
        camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0)[0];

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);
        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

      }));

      describe('#name', function() {

        var field;

        beforeEach(inject(function(propertiesPanel) {

          field = getInput(propertiesPanel._container, FIELD_NAME_ELEMENT);

          TestHelper.triggerValue(field, 'FOO', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.value).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(field.value).to.equal('FieldServiceTaskOne');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(field.value).to.equal('FOO');

          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(camundaField.get('name')).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(camundaField.get('name')).to.equal('FieldServiceTaskOne');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(camundaField.get('name')).to.equal('FOO');

          }));

        });

      });

      describe('#fieldType', function() {

        var field;

        beforeEach(inject(function(propertiesPanel) {

          field = getSelect(propertiesPanel._container, FIELD_TYPE_ELEMENT);

          // select 'expression'
          field.options[1].selected = 'selected';
          TestHelper.triggerEvent(field, 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.value).to.equal('expression');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(field.value).to.equal('string');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(field.value).to.equal('expression');

          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(camundaField.get('string')).to.be.undefined;
            expect(camundaField.get('expression')).to.be.defined;
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(camundaField.get('string')).to.be.defined;
            expect(camundaField.get('expression')).to.be.undefined;
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(camundaField.get('string')).to.be.undefined;
            expect(camundaField.get('expression')).to.be.defined;
          }));

        });

      });

      describe('#fieldValue', function() {

        var field;

        beforeEach(inject(function(propertiesPanel) {
          field = getTextbox(propertiesPanel._container, FIELD_VALUE_ELEMENT);

          TestHelper.triggerValue(field, 'FOO', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.textContent).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(field.textContent).to.equal('myStringValue');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(field.textContent).to.equal('FOO');

          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(camundaField.get('string')).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(camundaField.get('string')).to.equal('myStringValue');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(camundaField.get('string')).to.equal('FOO');
          }));

        });

      });

    });

    describe('#userTask', function() {

      var camundaField;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        var bo = getBusinessObject(shape);
        camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0)[0];

        // select listener
        selectOption(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);
        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

      }));

      describe('#name', function() {

        var field;

        beforeEach(inject(function(propertiesPanel) {
          field = getInput(propertiesPanel._container, FIELD_NAME_ELEMENT);

          TestHelper.triggerValue(field, 'FOO', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.value).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(field.value).to.equal('FieldUserTask');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(field.value).to.equal('FOO');

          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(camundaField.get('name')).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(camundaField.get('name')).to.equal('FieldUserTask');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(camundaField.get('name')).to.equal('FOO');

          }));

        });

      });

      describe('#fieldType', function() {

        var field;

        beforeEach(inject(function(propertiesPanel) {
          field = getSelect(propertiesPanel._container, FIELD_TYPE_ELEMENT);

          // select 'string'
          field.options[0].selected = 'selected';
          TestHelper.triggerEvent(field, 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.value).to.equal('string');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(field.value).to.equal('expression');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(field.value).to.equal('string');

          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(camundaField.get('expression')).to.be.undefined;
            expect(camundaField.get('string')).to.be.defined;
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(camundaField.get('expression')).to.be.defined;
            expect(camundaField.get('string')).to.be.undefined;
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(camundaField.get('expression')).to.be.undefined;
            expect(camundaField.get('string')).to.be.defined;
          }));

        });

      });

      describe('#fieldValue', function() {

        var field;

        beforeEach(inject(function(propertiesPanel) {
          field = getTextbox(propertiesPanel._container, FIELD_VALUE_ELEMENT);

          TestHelper.triggerValue(field, 'FOO', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.textContent).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(field.textContent).to.equal('${myExpression}');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(field.textContent).to.equal('FOO');

          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(camundaField.get('expression')).to.equal('FOO');
          });

          it('should undo', inject(function(commandStack) {

            commandStack.undo();

            expect(camundaField.get('expression')).to.equal('${myExpression}');
          }));

          it('should redo', inject(function(commandStack) {

            commandStack.undo();
            commandStack.redo();

            expect(camundaField.get('expression')).to.equal('FOO');
          }));

        });

      });

    });

  });

  describe('add camunda:field', function() {

    describe('#userTask', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        bo = getBusinessObject(shape);

        // select listener
        selectOption(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);

        var button = getAddButton(propertiesPanel._container, 'listener-fields');

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {
          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(2);
        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);
        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(2);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {
          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(2);
        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);
        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(2);
        }));

      });

    });

    describe('#serviceTask', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('ServiceTask');
        selection.select(shape);

        bo = getBusinessObject(shape);

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);

        var button = getAddButton(propertiesPanel._container, 'listener-fields');

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {
          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(3);
        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(2);
        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(3);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {
          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(3);
        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(2);
        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(3);
        }));

      });

    });

    describe('#endEvent', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('EndEvent_1');
        selection.select(shape);

        bo = getBusinessObject(shape);

        // add execution listener
        var button = getAddButton(propertiesPanel._container, 'executionListeners');

        TestHelper.triggerEvent(button, 'click');

        // add camunda:field
        button = getAddButton(propertiesPanel._container, 'listener-fields');

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {
          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);
        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);
        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {
          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);
        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(0);
        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);
        }));

      });

    });

  });

  describe('remove camunda:field', function() {

    describe('#serviceTask', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('ServiceTask');
        selection.select(shape);

        bo = getBusinessObject(shape);

        var button = getRemoveButton(propertiesPanel._container, 'listener-fields');

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);

        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {
          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);
        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(2);
        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {
          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);
        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(2);
        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);
        }));

      });

    });

    describe('#userTask', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        bo = getBusinessObject(shape);

        var button = getRemoveButton(propertiesPanel._container, 'listener-fields');

        // select listener
        selectOption(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);

        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {
          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);
        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);
        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, FIELDS_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {
          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(0);
        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);
        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(0);
        }));

      });

    });

  });

  describe('remove camunda:listener', function() {

    describe('#userTask remove executionListener', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        bo = getBusinessObject(shape);

        var button = getRemoveButton(propertiesPanel._container, 'executionListeners');

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {

          var field = getSelect(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);

        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);

        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {

          expect(getExtensionElements(bo, EXECEUTION_LISTENER_TYPE)).to.have.length.of(0);

        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          expect(getExtensionElements(bo, EXECEUTION_LISTENER_TYPE)).to.have.length.of(1);
          var camundaField = getCamundaFields(bo, EXECEUTION_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);

        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          expect(getExtensionElements(bo, EXECEUTION_LISTENER_TYPE)).to.have.length.of(0);

        }));

      });

    });

    describe('#userTask remove taskListener', function() {

      var bo;

      beforeEach(inject(function(propertiesPanel, elementRegistry, selection) {
        var shape = elementRegistry.get('UserTask');
        selection.select(shape);

        bo = getBusinessObject(shape);

        var button = getRemoveButton(propertiesPanel._container, 'taskListeners');

        // select listener
        selectOption(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);

        TestHelper.triggerEvent(button, 'click');

      }));

      describe('in the DOM', function() {

        it('should execute', inject(function(propertiesPanel) {

          var field = getSelect(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);

        }));

        it('should undo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();

          var field = getSelect(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(1);
        }));

        it('should redo', inject(function(commandStack, propertiesPanel) {

          commandStack.undo();
          commandStack.redo();

          var field = getSelect(propertiesPanel._container, TASK_LISTENER_SELECT_ELEMENT);
          expect(field.options).to.have.length.of(0);

        }));

      });

      describe('on the business object', function() {

        it('should execute', function() {

          expect(getExtensionElements(bo, TASK_LISTENER_TYPE)).to.have.length.of(0);

        });

        it('should undo', inject(function(commandStack) {

          commandStack.undo();

          expect(getExtensionElements(bo, TASK_LISTENER_TYPE)).to.have.length.of(1);

          var camundaField = getCamundaFields(bo, TASK_LISTENER_TYPE, 0);
          expect(camundaField).to.have.length.of(1);

        }));

        it('should redo', inject(function(commandStack) {

          commandStack.undo();
          commandStack.redo();

          expect(getExtensionElements(bo, TASK_LISTENER_TYPE)).to.have.length.of(0);

        }));

      });

    });

  });

  describe('validation errors', function() {

    beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

      var item = elementRegistry.get('StartEvent_1');
      selection.select(item);

      // select listener
      selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);

      // select field
      selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

    }));

    it('should be shown if the name field is empty', inject(function(propertiesPanel) {

      var field = getInput(propertiesPanel._container, FIELD_NAME_ELEMENT);

      expect(domClasses(field).has('invalid')).to.be.true;

    }));

    it('should be shown if fieldType selected and no fieldValue is empty', inject(function(propertiesPanel) {

      var fieldType = getSelect(propertiesPanel._container, FIELD_TYPE_ELEMENT);
      var fieldValue = getTextbox(propertiesPanel._container, FIELD_VALUE_ELEMENT);

      expect(fieldType.value).to.equal('string');
      expect(domClasses(fieldValue).has('invalid')).to.be.true;

    }));

  });

  describe('control visibility', function() {

    function expectVisible(visible, getter, inputNode, parentElement) {

      return inject(function(propertiesPanel, selection, elementRegistry) {

        var field = getter(propertiesPanel._container, inputNode);

        if (parentElement) {
          field = field.parentElement;
        }

        // then
        if (visible) {
          expect(field).to.exist;
        } else {
          expect(domClasses(field).has('bpp-hidden')).to.be.true;
        }
      });
    }

    describe('should show', function() {

      beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

        var item = elementRegistry.get('ServiceTask');
        selection.select(item);

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);

        // select field
        selectOption(propertiesPanel._container, FIELDS_SELECT_ELEMENT);

      }));

      it('fieldName', expectVisible(true, getInput, FIELD_NAME_ELEMENT));
      it('fieldType', expectVisible(true, getSelect, FIELD_TYPE_ELEMENT));
      it('fieldValue', expectVisible(true, getTextbox, FIELD_VALUE_ELEMENT));

    });

    describe('should hide', function() {

      beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

        var item = elementRegistry.get('ServiceTask');
        selection.select(item);

        // select listener
        selectOption(propertiesPanel._container, EXECUTION_LISTENER_SELECT_ELEMENT);

      }));

      it('fieldName', expectVisible(false, getInput, FIELD_NAME_ELEMENT, true));
      it('fieldType', expectVisible(false, getSelect, FIELD_TYPE_ELEMENT));
      it('fieldValue', expectVisible(false, getTextbox, FIELD_VALUE_ELEMENT, true));

    });

  });

});