text:
The best way to learn how to use something is through examples. The .NET solution contains a simple sample to get you started.

## Simple Console ([source](./SimpleConsole))

This sample demonstrate the combination of all Recognizers to extract possible values from the user's input.

The important piece is the `Microsoft.Recognizers.Text` NuGet package, which you'll need to add using:

````
Install-Package Microsoft.Recognizers.Text
````

Then, the sample uses the recognize methods of each available Recognizer. We need to do so by passing the Culture code we'll want to detect. E.g.: `en-us`.

So far, the available recognition methods are:

````C#
using Microsoft.Recognizers.Text;
using Microsoft.Recognizers.Text.DateTime;
using Microsoft.Recognizers.Text.Number;
using Microsoft.Recognizers.Text.NumberWithUnit;
using Microsoft.Recognizers.Text.Sequence;

// Use English for the Recognizers culture
var culture = Culture.English;

// Number recognizer will find any number from the input
// E.g "I have two apples" will return "2".
NumberRecognizer.RecognizeNumber(query, culture);

// Ordinal number recognizer will find any ordinal number
// E.g "eleventh" will return "11".
NumberRecognizer.RecognizeOrdinal(query, culture);

// Percentage recognizer will find any number presented as percentage
// E.g "one hundred percents" will return "100%"
NumberRecognizer.RecognizePercentage(query, culture);

// Number Range recognizer will find any cardinal or ordinal number range
// E.g. "between 2 and 5" will return "(2,5)"
NumberRecognizer.RecognizeNumberRange(query, culture);

// Age recognizer will find any age number presented
// E.g "After ninety five years of age, perspectives change" will return "95 Year"
NumberWithUnitRecognizer.RecognizeAge(query, culture);

// Currency recognizer will find any currency presented
// E.g "Interest expense in the 1988 third quarter was $ 75.3 million" will return "75300000 Dollar"
NumberWithUnitRecognizer.RecognizeCurrency(query, culture);

// Dimension recognizer will find any dimension presented
// E.g "The six-mile trip to my airport hotel that had taken 20 minutes earlier in the day took more than three hours." will return "6 Mile"
NumberWithUnitRecognizer.RecognizeDimension(query, culture);

// Temperature recognizer will find any temperature presented
// E.g "Set the temperature to 30 degrees celsius" will return "30 C"
NumberWithUnitRecognizer.RecognizeTemperature(query, culture);

// Datetime recognizer This model will find any Date even if its write in coloquial language
// E.g "I'll go back 8pm today" will return "2017-10-04 20:00:00"
DateTimeRecognizer.RecognizeDateTime(query, culture);

// PhoneNumber recognizer will find any phone number presented
// E.g "My phone number is ( 19 ) 38294427."
SequenceRecognizer.RecognizePhoneNumber(query, culture);

//IP recognizer will find any Ipv4/Ipv6 presented
// E.g "My Ip is 8.8.8.8"
SequenceRecognizer.RecognizeIpAddress(query, culture);

//Boolean recognizer will find yes/no like responses, including emoji -
// E.g "yup, I need that" will return "True"
ChoiceRecognizer.RecognizeBoolean(query, culture);
````

All these methods accept an input string and culture, and returns an **IEnumerable** of [ModelResult](../Microsoft.Recognizers.Text/Models/ModelResult.cs):

Alternatively, you can obtain model instances that can be re-used for recognizing multiple inputs:

````C#
// Number model
var recognizer = new NumberRecognizer("en-us");
var model = recognizer.GetNumberModel();

// Parse input using Number model
var result = model.Parse("I have twenty apples");

// result is:
// [
// 	{
// 		"start": 7,
// 		"end": 12,
// 		"resolution": {
// 			"value": "20"
// 		},
// 		"text": "twenty",
// 		"typeName": "number"
// 	}
// ]
````

## BotBuilder Sample ([source](./BotBuilder))

This sample demonstrate how the Recognizers can be used with a BotBuilder Bot to parse user input. The bot provides a basic experience for ordering roses, it starts by asking the amount of roses and then asks for a delivery date and time.

Then, launch the [BotFramework Emulator](https://github.com/Microsoft/BotFramework-Emulator/releases) and connect it to **http://127.0.0.1:3979/api/messages**.

Once connected, the bot will send a welcome message. You can start the order flow by sending any message to the bot.

In order to validate user input, Custom Prompts Dialogs are used: [`QuantityPrompt`](./BotBuilder/Dialogs/QuantityPrompt.cs) and [`DeliveryPrompt`](./BotBuilder/Dialogs/DeliveryPrompt.cs).

The minimum required code for a Custom Prompt is the `TryParse` method. This is a copy of the [QuantityPrompt](./BotBuilder/Dialogs/QuantityPrompt.cs) `TryParse` method, which validates that the user input is an Integer, between 1 and 100 and not a decimal number:

````C#
protected override bool TryParse(IMessageActivity message, out int result)
{
    result = 0;

    // Get Number for the specified culture
    var results = NumberRecognizer.RecognizeNumber(message.Text, this.culture);
    if (results.Count > 0)
    {
        if (results.First().TypeName == "number" &&
            double.TryParse(results.First().Resolution["value"].ToString(), out double value))
        {
            // Validate number
            if (value < 1)
            {
                this.promptOptions.DefaultRetry = "I need to deliver at least one rose =)";
                return false;
            }
            else if (value > 100)
            {
                this.promptOptions.DefaultRetry = "You cannot order more than 100 roses per day. Sorry!";
                return false;
            }
            else if (value % 1 != 0)
            {
                this.promptOptions.DefaultRetry = "I need to send whole roses, not fractions of them. How many would you like to send?";
                return false;
            }

            // return as Int
            result = Convert.ToInt32(value);
            return true;
        }
    }

    // No parse results
    this.promptOptions.DefaultRetry = "I'm sorry, that doesn't seem to be a valid quantity";
    return false;
}
````

From our existing dialog, we can invoke this prompt as follows:

````C#
[Serializable]
public class RootDialog : IDialog<object>
{
    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(this.MessageReceivedAsync);
    }

    private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> activity)
    {
        // Welcome message
        // ...

        // Prompt for amount of roses
        var prompt = new QuantityPrompt(GetCurrentCultureCode());
        context.Call(prompt, this.OnQuantitySelected);
    }

    private async Task OnQuantitySelected(IDialogContext context, IAwaitable<int> result)
    {
        try
        {
            var quantity = await result;
            var quantityMessage = quantity == 1
                ? "I'll send just one rose."
                : $"I'll send {quantity} roses.";
            await context.PostAsync(quantityMessage);

            // Store amount
            context.ConversationData.SetValue("quantity", quantity);

            // Prompt for delivery date
            // ...

        }
        catch (TooManyAttemptsException)
        {
            await context.PostAsync("Restarting now...");
            context.Wait(this.MessageReceivedAsync);
        }
    }

    // ...
}
````

Asking the user for a specific delivery time may require special parsing, like extracting both date and time from the user input, or even obtain a range of dates and times.

The [`DeliveryPrompt`](./BotBuilder/Dialogs/DeliveryPrompt.cs) does exactly that. It will prompt the user for a possible delivery time, parse the user's input and extract, at least, one of these avaliable return values using the DateTime Recognizer:

 - date
 - daterange
 - datetime
 - datetimerange

(These are the DateTime Recognizer types that contains *date* information)

> NOTE: The DateTime Recognizer uses LUIS datetimeV2 subtypes. For a full list, please visit [LUIS prebuilt entities - Subtypes of datetimeV2](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/pre-builtentities#subtypes-of-datetimev2).

This prompt uses a helper method to call the DateTime Recognizer, to validate the subtype and check the selected delivery moment is at least one hour from now:

````C#
public static Extraction ValidateAndExtract(string input)
{
    // Get DateTime for the specified culture
    var results = DateTimeRecognizer.RecognizeDateTime(input, culture);

    // Check there are valid results
    if (results.Count > 0 && results.First().TypeName.StartsWith("datetimeV2"))
    {
        // The DateTime model can return several resolution types (https://github.com/Microsoft/Recognizers-Text/blob/master/.NET/Microsoft.Recognizers.Text.DateTime/Constants.cs#L7-L15)
        // We only care for those with a date, date and time, or date time period:
        // date, daterange, datetime, datetimerange

        var first = results.First();
        var resolutionValues = (IList<Dictionary<string, string>>)first.Resolution["values"];

        var subType = first.TypeName.Split('.').Last();
        if (subType.Contains("date") && !subType.Contains("range"))
        {
            // a date (or date & time) or multiple
            var moment = resolutionValues.Select(v => DateTime.Parse(v["value"])).FirstOrDefault();
            if (IsFuture(moment))
            {
                // a future moment, valid!
                return new Extraction
                {
                    IsValid = true,
                    Values = new[] { moment }
                };
            }

            // a past moment
            return new Extraction
            {
                IsValid = false,
                Values = new[] { moment },
                ErrorMessage = PastValueErrorMessage.Replace("$moment$", MomentOrRangeToString(moment))
            };
        }
        else if (subType.Contains("date") && subType.Contains("range"))
        {
            // range
            var from = DateTime.Parse(resolutionValues.First()["start"]);
            var to = DateTime.Parse(resolutionValues.First()["end"]);
            if (IsFuture(from) && IsFuture(to))
            {
                // future
                return new Extraction
                {
                    IsValid = true,
                    Values = new[] { from, to }
                };
            }

            var values = new[] { from, to };
            return new Extraction
            {
                IsValid = false,
                Values = values,
                ErrorMessage = PastValueErrorMessage.Replace("$moment$", MomentOrRangeToString(values))
            };
        }
    }

    return new Extraction
    {
        IsValid = false,
        Values = Enumerable.Empty<DateTime>(),
        ErrorMessage = "I'm sorry, that doesn't seem to be a valid delivery date and time"
    };
}

public static bool IsFuture(DateTime date)
{
    // at least one hour
    return date > DateTime.Now.AddHours(1);
}
````

We use the helper function from Custom Prompt form the [`TryParse` method](./BotBuilder/Dialogs/DeliveryPrompt.cs#L33):

````C#
protected override bool TryParse(IMessageActivity message, out IEnumerable<DateTime> result)
{
    var extraction = ValidateAndExtract(message.Text, this.culture);
    if (!extraction.IsValid)
    {
        this.promptOptions.DefaultRetry = extraction.ErrorMessage;
    }

    result = extraction.Values;
    return extraction.IsValid;
}
````

Finally, this is how you call the prompt and obtain the date (or dates) back:

````C#
private async Task OnQuantitySelected(IDialogContext context, IAwaitable<int> result)
{
        // ...

        // Prompt for delivery date
        var prompt = new DeliveryPrompt(GetCurrentCultureCode());
        context.Call(prompt, this.OnDeliverySelected);
}

private async Task OnDeliverySelected(IDialogContext context, IAwaitable<IEnumerable<DateTime>> result)
{
    try
    {
        // "result" contains the date (or array of dates) returned from the prompt
        var momentOrRange = await result;
        var quantity = context.ConversationData.GetValue<int>("quantity");
        var nRoses = quantity == 1 ? "Just one rose" : $"{quantity} roses";
        var text = $"Thank you! I'll deliver {nRoses} {DeliveryPrompt.MomentOrRangeToString(momentOrRange)}.";

        await context.PostAsync(text);

        // TODO: It should continue to a checkout dialog or page
        await context.PostAsync("Have a nice day!");
    }
    catch (TooManyAttemptsException)
    {
        await context.PostAsync("Restarting now...");
    }
    finally
    {
        context.Wait(this.MessageReceivedAsync);
    }
}
````


text:
<resources>

    <!-- Base application theme. -->
    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
        <!-- Customize your theme here. -->
    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/primaryColor</item>
        <item name="colorPrimaryDark">@color/primaryColorDark</item>
        <item name="colorAccent">@color/accentColor</item>
    </style>

</resources>

redpajama_set_name: RedPajamaGithub


text:
package web

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"

	auth "github.com/liut/simpauth"

	"github.com/liut/staffio/pkg/models"
	"github.com/liut/staffio/pkg/settings"
)

var (
	authzr auth.Authorizer
)

func init() {
	authzr = auth.New(auth.WithURI("/login"), auth.WithCookie(
		settings.Current.CookieName,
		settings.Current.CookiePath,
		settings.Current.CookieDomain,
	), auth.WithMaxAge(settings.Current.CookieMaxAge))
}

// consts
const (
	kAuthUser = "user"
)

type User = auth.User

func UserFromStaff(staff *models.Staff) *auth.User {
	return &auth.User{
		UID:  staff.UID,
		Name: staff.GetName(),
	}
}

func AuthUserMiddleware(redirect bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		user, err := authzr.UserFromRequest(c.Request)
		if err != nil {
			log.Printf("user from request ERR %s", err)
			if redirect {
				markReferer(c)
				c.Redirect(302, UrlFor("login"))
				c.Abort()
			} else {
				c.AbortWithStatus(http.StatusUnauthorized)
				// apiError(c, ERROR_INTERNAL, err)
			}
			return
		}
		// log.Printf("got user %q", user.UID)
		c.Set(kAuthUser, user)
		c.Next()
		user.Refresh()
		user.Signin(c.Writer)
	}
}

func (s *server) authGroup(name ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		v, exist := c.Get(kAuthUser)
		if !exist {
			c.AbortWithStatus(http.StatusUnauthorized)
			c.Abort()
			return
		}
		user := v.(*User)
		if !s.InGroupAny(user.UID, name...) {
			c.AbortWithStatus(http.StatusForbidden)
			c.Abort()
			return
		}
	}
}

func UserWithContext(c *gin.Context) (user *User) {
	if v, ok := c.Get(kAuthUser); ok {
		user = v.(*User)
	}
	if user == nil {
		panic("user not found in request")
	}

	return
}

func signinStaffGin(c *gin.Context, staff *models.Staff) {
	user := UserFromStaff(staff)
	user.Refresh()
	log.Printf("login ok %v", user)
	sess := ginSession(c)
	sess.Set(kAuthUser, user)
	authzr.Signin(user, c.Writer)
	SessionSave(sess, c.Writer)
}


text:
package org.jrebirth.af.core.resource;

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

import javafx.scene.paint.Color;

import org.jrebirth.af.api.resource.color.ColorItem;
import org.jrebirth.af.core.resource.color.RGB255Color;
import org.jrebirth.af.core.test.AbstractTest;

import org.junit.Test;

public class TestMemory2 extends AbstractTest {

    @Test
    public void checkFullConf() {
        final int mb = 1024 * 1024;

        // Getting the runtime reference from system
        final Runtime runtime = Runtime.getRuntime();

        System.out.println("Used Memory1:"
                + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        final List<Color> list = new ArrayList<>();
        for (int red = 0; red < 256; red++) {

            for (int green = 0; green < 256; green++) {

                for (int blue = 0; blue < 2; blue++) {

                    final ColorItem ci = Resources.create(new RGB255Color(0, 0, 0));
                    list.add(ci.get());

                }

            }
        }

        // ResourceBuilders.COLOR_BUILDER.get(key);

        System.out.println("Used Memory2:"
                + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        callGC();

        System.out.println("Used Memory3:"
                + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        list.clear();

        System.out.println("Used Memory4:"
                + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        callGC();

        System.out.println("Used Memory5:"
                + (runtime.totalMemory() - runtime.freeMemory()) / mb);
    }

    /**
     * TODO To complete.
     *
     * @throws InterruptedException
     */
    private void callGC() {
        System.gc();
        try {
            Thread.sleep(2000);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
        System.gc();
    }
}


text:
  Manduel est
      une ville située dans le département de Gard en Languedoc-Roussillon. Elle totalisait 5 729 habitants en 2008.

La commune est équipée en ce qui concerne l'enseignement de un collège.
S'agissant les très jeunes, la localité dispose de deux maternelles et deux écoles primaires.
Manduel propose les équipements permettant une vie àgréable.
Lors d'un projet de transaction immobilière à Manduel, il est important regarder la qualité des équipements éducatifs

À coté de Manduel sont positionnées géographiquement les communes de
Rodilhan à 3 km, 2 531 habitants,
Bezouce localisée à 7 km, 2 070 habitants,
Marguerittes à 5 km, 8 692 habitants,
Jonquières-Saint-Vincent à 7 km, 2 933 habitants,
Caissargues localisée à 8 km, 3 886 habitants,
Bouillargues située à 4 km, 5 418 habitants,
 entre autres. De plus, Manduel est située à seulement neuf km de Nîmes.

À Manduel, la valorisation moyenne à la vente d'un appartement s'évalue à 1 096 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 2 067 € du m². À la location la valorisation moyenne se situe à 10,22 € du m² par mois.

La ville propose de multiples  équipements sportifs, elle propose entre autres un terrain de tennis, un centre d'équitation, un terrain de sport et deux salles de combat.

À Manduel le salaire moyen par mois par habitant est situé à environ 2 045 €  net. Ceci est au dessous de la moyenne nationale.

Le parc de logements, à Manduel, était réparti en 2011 en 309 appartements et 2 191 maisons soit
 un marché relativement équilibré.


text:
<?php
if( !defined( 'MEDIAWIKI' ) ) {
	die( -1 );
}

class SkinBooty extends SkinSkinny {

	public static $modules = array();

	public $skinname = 'booty';
	public $stylename = 'booty';
	//default template, this can be changed by skin layouts
	public $template = 'BootyTemplate';
	public $useHeadElement = true;

	public function __construct( $options=array() ){
		if(!empty(Booty::$skinOptions)){
			$options = Skinny::mergeOptionsArrays(Booty::$skinOptions, $options);
		}
		parent::__construct( $options );
	}

	public static function init(){

		$template = array(
			'localBasePath' => $GLOBALS['egBootyBasePath'],
		  'remoteBasePath' => $GLOBALS['egBootyBaseURL']
		 );

		$modules = array(

			//Bootstrap 3 & FontAwesome
			'bootstrap.css' => $template + array(
		    'styles' => array(
		    	'bootstrap-3.0.3/css/bootstrap.css'=>array('media'=>'screen')
		    ),
		    'position'=>'top',
		    'group'=>'bootstrap'
			),

			'bootstrap.js' => $template + array(
			  'scripts'=> array('bootstrap-3.0.3/js/bootstrap.js'),
		    'group'=>'bootstrap'
			),

		  'font-awesome' => $template + array(
		  	'styles' => array(
		    	'font-awesome-4.0.3/css/font-awesome.css'=>array('media'=>'screen')
		    ),
				'position'=>'top',
		    'group'=>'bootstrap'
		  ),

			//Resources for Booty applicable to all layouts
		  'skin.booty.css' => $template + array(
		    'styles'=> array('base/css/layout.css', 'base/css/content.css'),
		    'position' => 'top',
		    'group'=>'booty'
		  ),
		  'skin.booty.js' => $template + array(
		    'scripts'=> array('base/js/init.js'),
		    'position'=> 'bottom',
		    'dependencies'=>array(
		    	'bootstrap.js'
		    ),
		    'group'=>'booty'
		  )
		);

		self::addModules($modules);
	}

	public function initPage( OutputPage $out ) {
		$baseURL = $GLOBALS['egBootyBaseURL'];

		//add the css modules separately to prevent a FOUC
		$out->addModuleStyles( 'bootstrap.css' );
		$out->addModuleStyles( 'skin.booty.css');
		$out->addModuleStyles( 'font-awesome' );

		//since we're using theb mediawiki generated head element, we have to add the viewport meta tag
		//so the layout scaled properly to mobile devices
		$out->addMeta( 'viewport', 'width=device-width');//,initial-width=1,maximum-width=1' );

		/* Until ResourceLoader can correctly parse multiple urls in a single font-family
		webfont files have to be defined in the head to prevent it screwing things up */

		$out->addInlineStyle("@font-face {
		  font-family: 'Glyphicons Halflings';
		  src: url('$baseURL/bootstrap-3.0.3/fonts/glyphicons-halflings-regular.eot');
		  src: url('$baseURL/bootstrap-3.0.3/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('$baseURL/bootstrap-3.0.3/fonts/glyphicons-halflings-regular.woff') format('woff'), url('$baseURL/bootstrap-3.0.3/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('$baseURL/bootstrap-3.0.3/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
		}");
		$out->addInlineStyle("@font-face {
		  font-family: 'FontAwesome';
		  src: url('$baseURL/font-awesome-4.0.3/fonts/fontawesome-webfont.eot?v=4.0.3');
		  src: url('$baseURL/font-awesome-4.0.3/fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'), url('$baseURL/font-awesome-4.0.3/fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'), url('$baseURL/font-awesome-4.0.3/fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'), url('$baseURL/font-awesome-4.0.3/fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');
		  font-weight: normal;
		  font-style: normal;
		}");

		//js items will be appended after page load
		$out->addModules( 'bootstrap.js' );
		$out->addModules( 'skin.booty.js' );

		$out->addHeadItem('meta-viewport', '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">');

		parent::initPage( $out );

	}

}


text:
"""
Zebra-printer-based, MIDI-controlled Photo Booth :D

Created on Fri Apr 07 19:59:58 2017

@author: tennessee

Copyright 2017, Tennessee Carmel-Veilleux.
https://github.com/tcarmelveilleux/zolaroid
"""
from __future__ import print_function
import os
import sys
import cv2
import threading
import numpy as np
import argparse
import tempfile

try:
    from midi_driver import MidiControllerDriver, get_midi_devices_list
    MIDI_SUPPORT = True
except:
    MIDI_SUPPORT = False

DEFAULT_WIDTH = 4.0
DEFAULT_HEIGHT = 6.0
DEFAULT_DPI = 203

FRAME_OFF_X_IN = 0.54
FRAME_OFF_Y_IN = 0.65
FRAME_WIDTH_IN = 2.75
FRAME_HEIGHT_IN = 4.6
FRAME_DPI = DEFAULT_DPI
FRAME_MIN_MARGIN_IN = 0.08

PLAY_AXIS = 41
ALPHA_AXIS = 16
BETA_AXIS = 17
BRIGHTNESS_AXIS = ALPHA_AXIS
EXPOSURE_AXIS = BETA_AXIS

RETCODE_BAD_ARG = 1
RETCODE_FILE_NOT_FOUND = 2
RETCODE_PARSE_ERROR = 3

def viewfinder_bounds(img, height_ratio, aspect_ratio):
    im_height, im_width, _ = img.shape
    cap_height = int(im_height * height_ratio)
    cap_width = int(cap_height * aspect_ratio)

    ul = ((im_width / 2) - (cap_width / 2), (im_height / 2) - (cap_height / 2))
    br = (ul[0] + cap_width - 1, ul[1] + cap_height - 1)

    return cap_width, cap_height, ul, br

def extract_rectangle(img, ul, br):
    return img[ul[1]:(br[1]+1), ul[0]:(br[0]+1)]

class PictureCapture(object):
    def __init__(self, **kwargs):
        self._lock = threading.Lock()
        self._done = False
        self._brightness = kwargs.get("brightness", 60)
        self._exposure = kwargs.get("exposure", 0)

    def handle_event(self, event):
        if event.get("event", "") == "control_change":
            with self._lock:
                if event["control"] == PLAY_AXIS:
                    self._done = True
                elif event["control"] == BRIGHTNESS_AXIS:
                    self._brightness = 60 + int(event["value"] * 240)
                    print("Set brightness to %d" % self._brightness)
                elif event["control"] == EXPOSURE_AXIS:
                    self._exposure = -6 + int((event["value"] * 7.0) + 0.001)
                    print("Set exposure to %d" % self._exposure)

    def capture(self, cam_id=0, mirror=True, rotate=90, aspect_ratio=4.0/3.0, height_ratio=0.5, **kwargs):
        cam = cv2.VideoCapture(cam_id)

        cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1024)
        cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 768)

        if "contrast" in kwargs:
            cam.set(cv2.CAP_PROP_CONTRAST, kwargs["contrast"])

        #img_src = cv2.imread("test_img.jpg")

        while True:
            with self._lock:
                brightness = self._brightness
                exposure = self._exposure

            # brightness 60-300, 60 default
            if brightness is not None:
                cam.set(cv2.CAP_PROP_BRIGHTNESS, brightness)

            if exposure is not None:
                cam.set(cv2.CAP_PROP_EXPOSURE, exposure)

            ret_val, img = cam.read()
            #img = img_src[:,:]
            if rotate == 90:
                img = cv2.transpose(img)

            if mirror:
                img = cv2.flip(img, -1)

            # Extract a rectangle that has ratio `max_dim` of the height and is sized
            # according to `aspect_ratio`
            cap_width, cap_height, ul, br = viewfinder_bounds(img, height_ratio, aspect_ratio)
            captured = extract_rectangle(img, ul, br)

            # Preview is always max 480 pixels to fit the screen easy
            preview_height = 600
            preview_width = int(preview_height * aspect_ratio)
            preview_img = cv2.resize(captured, (preview_width, preview_height))

            cv2.imshow('Capture. <SPACE>/PLAY to take grab', preview_img)

            # Space or PLAY midi button to capture
            with self._lock:
                done = self._done

            if done or cv2.waitKey(1) == 32:
                break

        cv2.destroyAllWindows()

        return captured

def dither_floyd_steinberg(img):
    # Adapted from
    # https://en.wikipedia.org/wiki/Floyd-Steinberg_dithering
    # https://github.com/kehribar/Dithering-OpenCV/blob/master/main.cpp

    width = img.shape[1]
    height = img.shape[0]
    new_img = img[:, :]

    for y in xrange(height):
        # Print progress once in a while
        if (y % 50) == 0 or y == (height - 1):
            print("Floyd steinberg %d%%" % (y * 100 / (height - 1)))

        for x in xrange(width):
            if new_img[y, x] > 127:
                err = new_img[y, x] - 255
                new_img[y, x] = 255
            else:
                err = np.uint8(new_img[y, x] - 0)
                new_img[y, x] = 0

            a = (err * 7) / 16
            b = (err * 1) / 16
            c = (err * 5) / 16
            d = (err * 3) / 16

            if (y != (height - 1)) and (x != 0) and (x != (width - 1)):
                w = new_img[y  ,x+1] + a
                w = 255 if w > 255 else (0 if w < 0 else w)
                new_img[y  ,x+1] = w

                w = new_img[y+1,x+1] + b
                w = 255 if w > 255 else (0 if w < 0 else w)
                new_img[y+1,x+1] = w

                w = new_img[y+1,x  ] + c
                w = 255 if w > 255 else (0 if w < 0 else w)
                new_img[y+1,x  ] = w

                w = new_img[y+1,x-1] + d
                w = 255 if w > 255 else (0 if w < 0 else w)
                new_img[y+1,x-1] = w

    return new_img

def dither_ordered(img):
    dith_mat = np.array([[0, 8, 2, 10],[12, 4, 14, 6],[3,11,1,9],[15,7,13,5]], dtype='uint8') * 16
    width = img.shape[1]
    height = img.shape[0]
    new_img = img[:, :]

    for y in xrange(height):
        # Print progress once in a while
        if (y % 50) == 0 or (y == (height - 1)):
            print("Ordered dither %d%%" % (y * 100 / (height - 1)))

        for x in xrange(width):
            new_img[y, x] = 255 if (new_img[y, x] >= dith_mat[y&3, x&3]) else 0

    return new_img

def blit_centered(dst, src):
    src_height, src_width = src.shape[0:2]
    dst_height, dst_width = dst.shape[0:2]

    ul = ((dst_height / 2)-(src_height / 2), (dst_width / 2)-(src_width / 2))
    lr = ((dst_height / 2)+(src_height / 2), (dst_width / 2)+(src_width / 2))

    dst[ul[0]:lr[0], ul[1]:lr[1]] = src[:, :]

def blit_offset(dst, src, offset):
    offset_x, offset_y = offset

    src_height, src_width  = src.shape[0:2]
    dst_height, dst_width  = dst.shape[0:2]

    ul = (offset_y, offset_x)
    lr = (offset_y + src_height, offset_x + src_width)

    dst[ul[0]:lr[0], ul[1]:lr[1]] = src[:, :]

def convert_to_epl_string(img, offset_x_pix, offset_y_pix):
    """
    Syntax GWp1,p2,p3,p4,DATA
    Parameters This table identifies the parameters for this format:
    Parameters Details
    p1 = Horizontal start
    position
    Horizontal start position (X) in dots.
    p2 = Vertical start position Vertical start position (Y) in dots.
    p3 = Width of graphic Width of graphic in bytes. Eight (8) dots = one (1) byte of
    data.
    p4 = Length of graphic Length of graphic in dots (or print lines)
    DATA Raw binary data without graphic file formatting. Data must
    be in bytes. Multiply the width in bytes (p3) by the number of
    print lines (p4) for the total amount of graphic data. The
    printer automatically calculates the exact size of the data
    block based upon this formula.
    """
    num_bytes_per_line = img.shape[1] / 8
    num_lines = img.shape[0]

    data_bytes = np.zeros((num_bytes_per_line * num_lines,), dtype=np.uint8)
    for y in xrange(num_lines):
        for byte_idx in xrange(num_bytes_per_line):
            x = byte_idx * 8
            byte =  0x80 if (img[y, x + 0] > 128) else 0x00
            byte |= 0x40 if (img[y, x + 1] > 128) else 0x00
            byte |= 0x20 if (img[y, x + 2] > 128) else 0x00
            byte |= 0x10 if (img[y, x + 3] > 128) else 0x00
            byte |= 0x08 if (img[y, x + 4] > 128) else 0x00
            byte |= 0x04 if (img[y, x + 5] > 128) else 0x00
            byte |= 0x02 if (img[y, x + 6] > 128) else 0x00
            byte |= 0x01 if (img[y, x + 7] > 128) else 0x00

            data_bytes[y * num_bytes_per_line + byte_idx] = byte

    epl_cmd = "GW%d,%d,%d,%d,%s\r\n" % (offset_x_pix, offset_y_pix, num_bytes_per_line, num_lines, "".join([chr(b) for b in data_bytes]))

    return epl_cmd

def generate_epl_file(img, image_file, **kwargs):
    print_data = { "label_length_pix": 1218, "label_width_pix": 831, "gap_length_pix": 24,
                  "speed_idx":1, "darkness": 4, "ref_x_pix": 0, "ref_y_pix": 0}

    print_data.update(kwargs)
    print_data["image_data"] = convert_to_epl_string(img, 0, 0)
    template_header = """
I8,A,001

Q%(label_length_pix)d,%(gap_length_pix)03d
q%(label_width_pix)d
rN
S%(speed_idx)d
D%(darkness)d
ZT
JF
O
R%(ref_x_pix)d,%(ref_y_pix)d
f100

N
"""
    template_footer = """
P1
"""
    image_file.write(template_header % print_data)
    image_file.write(print_data["image_data"])
    image_file.write(template_footer % print_data)

class ZolaroidProcessor(object):
    def __init__(self, source, paper_width_in=4.0, paper_height_in=6.0,
                 frame_width_in=FRAME_WIDTH_IN, frame_height_in=FRAME_HEIGHT_IN,
                 printer_dpi=203, **kwargs):

        self._source = source
        self._paper_width_pix = int(paper_width_in * printer_dpi) / 8 * 8
        self._paper_height_pix = int(paper_height_in * printer_dpi) / 8 * 8
        self._frame_width_pix =  int(frame_width_in * printer_dpi) / 8 * 8
        self._frame_height_pix = int(frame_height_in * printer_dpi) / 8 * 8
        self._printer_dpi = printer_dpi
        self._background = kwargs.get("background")

        self._frame_off_x_pix = kwargs.get("frame_off_x_in", (paper_width_in-frame_width_in) / 2.0)
        self._frame_off_x_pix = int((self._frame_off_x_pix * printer_dpi) / 8 * 8)

        self._frame_off_y_pix = kwargs.get("frame_off_y_in", (paper_height_in-frame_height_in) / 2.0)
        self._frame_off_y_pix = int((self._frame_off_y_pix * printer_dpi) / 8 * 8)

        self._lock = threading.Lock()
        self._done = False
        self._alpha = kwargs.get("alpha", 1.0)
        self._beta = kwargs.get("beta", 0.0)

        self._result_image = None

    def handle_event(self, event):
        if event.get("event", "") == "control_change":
            with self._lock:
                if event["control"] == PLAY_AXIS:
                    self._done = True
                elif event["control"] == ALPHA_AXIS:
                    self._alpha = 0.5 + (event["value"] * (5.0 - 0.5))
                    print("Set alpha to %.3f" % self._alpha)
                elif event["control"] == BETA_AXIS:
                    self._beta = 0.0 + event["value"] * 100.0
                    print("Set beta to %.3f" % self._beta)

    def process_until_done(self):
        image_width = self._paper_width_pix - int(2.0 * FRAME_MIN_MARGIN_IN * self._printer_dpi)
        image_height = self._paper_height_pix - int(2.0 * FRAME_MIN_MARGIN_IN * self._printer_dpi)

        img = np.ones((image_height, image_width), dtype=np.uint8)

        if self._background is not None:
            background = cv2.imread(self._background)
            background = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)
            background = cv2.resize(background, (image_width, image_height))
            background[background < 10] = 0
            background[background > 245] = 255

            blit_centered(img, background)

        gray = cv2.cvtColor(self._source, cv2.COLOR_BGR2GRAY)
        while True:
            with self._lock:
                alpha = self._alpha
                beta = self._beta

            adjusted = gray.copy()
            cv2.convertScaleAbs(gray, adjusted, alpha, beta)
            resized = cv2.resize(adjusted, (self._frame_width_pix, self._frame_height_pix))
            blit_offset(img, resized, (self._frame_off_x_pix, self._frame_off_y_pix))

            preview_img = cv2.resize(img, (image_width / 2, image_height / 2))

            cv2.imshow('Adjust, <SPACE>/PLAY to print', preview_img)

            # Space or PLAY midi button to end
            with self._lock:
                done = self._done

            if done or cv2.waitKey(1) == 32:
                self._result_image = img
                break

        cv2.destroyAllWindows()

    def print_image(self, filename=None, image_type="epl", use_floyd_steinberg=False, **kwargs):
        print("Saving result image to %s (will take a while)" % filename)

        if use_floyd_steinberg:
            dithered = dither_floyd_steinberg(self._result_image)
        else:
            dithered = dither_ordered(self._result_image)

        # TODO: Support ZPL
        if filename is None:
            output_file = tempfile.NamedTemporaryFile(delete=False)
            output_filename = output_file.name
        else:
            output_file = open(filename, "wb+")
            output_filename = filename

        with output_file:
            generate_epl_file(dithered, output_file, **kwargs)
            print("Done saving result")

        if kwargs.get("printer") is not None:
            try:
                if sys.platform == "win32":
                    # On win32, use the COPY /B command to print directly to a raw port. Somehow,
                    # I could not make normal IO work (as the case below), which works under Linux
                    os.system("COPY /B %s %s" % (output_filename, kwargs["printer"]))
                else:
                    # On non-windows, simply dump the data to the printer spool path
                    with open(output_filename, "rb") as infile:
                        with open(kwargs["printer"], "wb+") as printer:
                            data = infile.read()
                            printer.write(data)
                print("Done printing")
            except IOError as e:
                print("Error while trying to print: %s", str(e))

class Controller(object):
    def __init__(self):
        self._observers = set()

    def add_observer(self, observer):
        self._observers.add(observer)

    def remove_observer(self, observer):
        if observer in self._observers:
            self._observers.remove(observer)

    def handle_event(self, event):
        for observer in self._observers:
            observer.handle_event(event)

def print_and_die(message, retcode):
    print(message, file=sys.stderr)
    sys.exit(retcode)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--printer', metavar="PATH_TO_PRINTER", action="store", help='Path for printer which will output')
    parser.add_argument('-o', '--output', metavar="FILENAME", action="store", help='Path where to save output file')
    parser.add_argument('-t', '--type', metavar="FORMAT", action="store", default="epl", help='Printer type, one of ["zpl", "epl"]')
    parser.add_argument('-l', '--list', action="store_true", help='List MIDI devices and exit')
    parser.add_argument('-n', '--midi-name', metavar="MIDI_NAME", action="store", help='Full name of MIDI input device or "default" for default')
    parser.add_argument('-N', '--midi-num', metavar="MIDI_NUM", action="store", type=int, help='Index of MIDI input device obtained from -l/--list')
    parser.add_argument('-m', '--midi-config', metavar="JSON_FILENAME", action="store", help='Load MIDI config from given JSON (otherwise, default to KORG NanoKontrol2)')
    parser.add_argument('-c', '--camera', metavar="CAMERA_NUM", action="store", default=0, type=int, help='Set camera number to use (default: 0)')
    parser.add_argument('-s', '--floyd-steinberg', action="store_true", default=False, help='Use Floyd-Steinberg dithering instead of ordered dithering')
    parser.add_argument('-W', '--width', metavar="WIDTH_INCHES", action="store", type=float,
                        default=DEFAULT_WIDTH, help='Set label width in inches (default:%.1f)' % DEFAULT_WIDTH)
    parser.add_argument('-H', '--height', metavar="HEIGHT_INCHES", action="store", type=float,
                        default=DEFAULT_WIDTH, help='Set label height in inches (default:%.1f)' % DEFAULT_HEIGHT)
    parser.add_argument('-d', '--dpi', metavar="DPI", action="store", type=int,
                        default=FRAME_DPI, help='Set printer DPI (default:%d)' % FRAME_DPI)

    # TODO: Add background config
    # TODO: Add MIDI test mode hook from midi_driver.py

    args = parser.parse_args()

    # Handle listing MIDI devices
    if args.list and MIDI_SUPPORT:
        print("MIDI Input devices:")
        for idx, midi_port in enumerate(get_midi_devices_list()):
            print("  * %d: '%s'" % (idx, midi_port))
        sys.exit(0)

    # Make sure at least one output action is provided
    if not args.printer and not args.output:
        parser.print_usage(file=sys.stderr)
        print_and_die("Need at least one of -p/--printer or -o/--output!", RETCODE_BAD_ARG)

    return args

def main():
    args = parse_args()

    # Init MIDI driver
    controller = Controller()
    midi_driver = None

    if MIDI_SUPPORT:
        midi_port = args.midi_name
        if midi_port is None and args.midi_num is not None:
            midi_devices = []
            for midi_port in get_midi_devices_list():
                midi_devices.append(midi_port)

            if len(midi_devices) == 0:
                print("WARNING: No midi devices found!")
                midi_port = None
            elif args.midi_num >= len(midi_devices):
                print("WARNING: Not using MIDI device number provide (%d), it is not valid!")
                midi_port = None
            else:
                midi_port = midi_devices[args.midi_num]
                print("Using midi device number %d '%s'" % (args.midi_num, midi_port))

        if args.midi_name == "default":
            midi_port = None

        # TODO: Load config for axes from JSON
        axes_configs = {
            ALPHA_AXIS: {"name": "alpha", "centered": False},
            BETA_AXIS: {"name": "beta", "centered": False},
            PLAY_AXIS:{"name": "button_play", "centered": False, "button_down_only": True}
        }

        try:
            midi_driver = MidiControllerDriver(midi_port, 0, controller.handle_event, axes_configs)
            print("MIDI Support Enabled!")
        except BaseException as e:
            print("WARNING: Exception trying to enable MIDI support (%s). Disabling!" % str(e))
    else:
        print("NO MIDI Support!")

    # Capture picture from webcam
    pic_capture = PictureCapture()
    controller.add_observer(pic_capture)
    captured = pic_capture.capture(cam_id=args.camera, mirror=True, aspect_ratio=FRAME_WIDTH_IN/FRAME_HEIGHT_IN, height_ratio=0.9)
    controller.remove_observer(pic_capture)

    # Adjust
    processor = ZolaroidProcessor(source=captured, background="backgrounds/frame1.png",
                                  frame_off_x_in=FRAME_OFF_X_IN, frame_off_y_in=FRAME_OFF_Y_IN,
                                  printer_dpi=args.dpi)
    controller.add_observer(processor)
    processor.process_until_done()
    controller.remove_observer(processor)

    # Print
    # FIXME: Remove hardcoded X offset
    processor.print_image(filename=args.output, image_type=args.type, use_floyd_steinberg=args.floyd_steinberg,
                          ref_x_pix=int(0.25 * args.dpi), printer=args.printer)

    # Clean-up
    if midi_driver is not None:
        midi_driver.shutdown()

if __name__ == '__main__':
    main()


text:
from IPython.display import Javascript
import string
import sys
import uuid

def js_error(cell_id, message):
    jsString = """
require([
  'base/js/namespace',
  'nbextensions/methodCell/main'
], function (Jupyter, KBaseMethodsExtension) {
    KBaseMethodsExtension.send({
        type: 'runstatus',
        cellId: '${cellid}',
        status: 'error',
        message: '${message}'
    });
});
"""
def js_test():
    js = "alert('hi');"
    return Javascript(data=js, lib=None, css=None)

def js_run_widget(cell_id, kbase_cell_id):
    jsString = """
//@ sourceUrl=whatever.js
require([
  'base/js/namespace',
  'nbextensions/methodCell/widgets/codeCellRunWidget'
], function (Jupyter, RunWidget) {
   var args = {
       cellId: '${cell_id}',
       kbaseCellId: '${kbase_cell_id}'
   };
   console.log('here with', args);
   var widget = RunWidget.make(args);
   widget.attach(args)
   .then(function () {
   console.log('IT WORKED');
   })
   .catch(function (err) {
   console.error('BOO', err, args);
   });
});

"""
    jsTemplate = string.Template(jsString)
    js = jsTemplate.substitute(cell_id=cell_id, kbase_cell_id=kbase_cell_id)
    print js
    return Javascript(data=js, lib=None, css=None)

def insert_run_widget(cell_id, kbase_cell_id):
    try:
        # return js_test()
        return js_run_widget(cell_id, kbase_cell_id)
    except Exception as e:
        error = str(e)
        return js_error(cell_id, error)


text:
package org.apache.spark.network.netty

import scala.util.Random

import org.mockito.Mockito.mock
import org.scalatest._

import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
import org.apache.spark.network.BlockDataManager

class NettyBlockTransferServiceSuite
  extends SparkFunSuite
  with BeforeAndAfterEach
  with ShouldMatchers {

  private var service0: NettyBlockTransferService = _
  private var service1: NettyBlockTransferService = _

  override def afterEach() {
    try {
      if (service0 != null) {
        service0.close()
        service0 = null
      }

      if (service1 != null) {
        service1.close()
        service1 = null
      }
    } finally {
      super.afterEach()
    }
  }

  test("can bind to a random port") {
    service0 = createService(port = 0)
    service0.port should not be 0
  }

  test("can bind to two random ports") {
    service0 = createService(port = 0)
    service1 = createService(port = 0)
    service0.port should not be service1.port
  }

  test("can bind to a specific port") {
    val port = 17634 + Random.nextInt(10000)
    logInfo("random port for test: " + port)
    service0 = createService(port)
    verifyServicePort(expectedPort = port, actualPort = service0.port)
  }

  test("can bind to a specific port twice and the second increments") {
    val port = 17634 + Random.nextInt(10000)
    logInfo("random port for test: " + port)
    service0 = createService(port)
    verifyServicePort(expectedPort = port, actualPort = service0.port)
    service1 = createService(service0.port)
    // `service0.port` is occupied, so `service1.port` should not be `service0.port`
    verifyServicePort(expectedPort = service0.port + 1, actualPort = service1.port)
  }

  private def verifyServicePort(expectedPort: Int, actualPort: Int): Unit = {
    actualPort should be >= expectedPort
    // avoid testing equality in case of simultaneous tests
    // the default value for `spark.port.maxRetries` is 100 under test
    actualPort should be <= (expectedPort + 100)
  }

  private def createService(port: Int): NettyBlockTransferService = {
    val conf = new SparkConf()
      .set("spark.app.id", s"test-${getClass.getName}")
    val securityManager = new SecurityManager(conf)
    val blockDataManager = mock(classOf[BlockDataManager])
    val service = new NettyBlockTransferService(conf, securityManager, "localhost", "localhost",
      port, 1)
    service.init(blockDataManager)
    service
  }
}


text:
using Newtonsoft.Json;

namespace MultiSafepay.Model
{
    public class DeliveryAddress
    {
        [JsonProperty("first_name")]
        public string FirstName { get; set; }
        [JsonProperty("last_name")]
		public string LastName { get; set; }
        [JsonProperty("address1")]
		public string Address1 { get; set; }
        [JsonProperty("address2")]
		public string Address2 { get; set; }
        [JsonProperty("house_number")]
		public string HouseNumber { get; set; }
        [JsonProperty("zip_code")]
		public string PostCode { get; set; }
        [JsonProperty("city")]
		public string City { get; set; }
        [JsonProperty("state")]
		public string State { get; set; }
        [JsonProperty("country")]
		public string Country { get; set; }
        [JsonProperty("phone")]
		public string Phone { get; set; }
    }
}


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var Q = require('q');  /* jshint ignore:line */
var _ = require('lodash');  /* jshint ignore:line */
var DefaultsList = require('./assistant/defaults').DefaultsList;
var DialogueList = require('./assistant/dialogue').DialogueList;
var FieldTypeList = require('./assistant/fieldType').FieldTypeList;
var ModelBuildList = require('./assistant/modelBuild').ModelBuildList;
var Page = require('../../../base/Page');  /* jshint ignore:line */
var QueryList = require('./assistant/query').QueryList;
var StyleSheetList = require('./assistant/styleSheet').StyleSheetList;
var TaskList = require('./assistant/task').TaskList;
var deserialize = require(
    '../../../base/deserialize');  /* jshint ignore:line */
var serialize = require('../../../base/serialize');  /* jshint ignore:line */
var values = require('../../../base/values');  /* jshint ignore:line */

var AssistantList;
var AssistantPage;
var AssistantInstance;
var AssistantContext;

/* jshint ignore:start */
/**
 * @description Initialize the AssistantList
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @param {Twilio.Autopilot.V1} version - Version of the resource
 */
/* jshint ignore:end */
AssistantList = function AssistantList(version) {
  /* jshint ignore:start */
  /**
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Autopilot.V1.AssistantContext}
   */
  /* jshint ignore:end */
  function AssistantListInstance(sid) {
    return AssistantListInstance.get(sid);
  }

  AssistantListInstance._version = version;
  // Path Solution
  AssistantListInstance._solution = {};
  AssistantListInstance._uri = _.template(
    '/Assistants' // jshint ignore:line
  )(AssistantListInstance._solution);
  /* jshint ignore:start */
  /**
   * Streams AssistantInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {object} [opts] - Options for request
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         each() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no pageSize is defined but a limit is defined,
   *         each() will attempt to read the limit with the most efficient
   *         page size, i.e. min(limit, 1000)
   * @param {Function} [opts.callback] -
   *         Function to process each record. If this and a positional
   *         callback are passed, this one will be used
   * @param {Function} [opts.done] -
   *          Function to be called upon completion of streaming
   * @param {Function} [callback] - Function to process each record
   */
  /* jshint ignore:end */
  AssistantListInstance.each = function each(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    if (opts.callback) {
      callback = opts.callback;
    }
    if (_.isUndefined(callback)) {
      throw new Error('Callback function must be provided');
    }

    var done = false;
    var currentPage = 1;
    var currentResource = 0;
    var limits = this._version.readLimits({
      limit: opts.limit,
      pageSize: opts.pageSize
    });

    function onComplete(error) {
      done = true;
      if (_.isFunction(opts.done)) {
        opts.done(error);
      }
    }

    function fetchNextPage(fn) {
      var promise = fn();
      if (_.isUndefined(promise)) {
        onComplete();
        return;
      }

      promise.then(function(page) {
        _.each(page.instances, function(instance) {
          if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
            done = true;
            return false;
          }

          currentResource++;
          callback(instance, onComplete);
        });

        if ((limits.pageLimit && limits.pageLimit <= currentPage)) {
          onComplete();
        } else if (!done) {
          currentPage++;
          fetchNextPage(_.bind(page.nextPage, page));
        }
      });

      promise.catch(onComplete);
    }

    fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
  };

  /* jshint ignore:start */
  /**
   * Lists AssistantInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {object} [opts] - Options for request
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         list() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no page_size is defined but a limit is defined,
   *         list() will attempt to read the limit with the most
   *         efficient page size, i.e. min(limit, 1000)
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  AssistantListInstance.list = function list(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    var deferred = Q.defer();
    var allResources = [];
    opts.callback = function(resource, done) {
      allResources.push(resource);

      if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
        done();
      }
    };

    opts.done = function(error) {
      if (_.isUndefined(error)) {
        deferred.resolve(allResources);
      } else {
        deferred.reject(error);
      }
    };

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    this.each(opts);
    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single page of AssistantInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {object} [opts] - Options for request
   * @param {string} [opts.pageToken] - PageToken provided by the API
   * @param {number} [opts.pageNumber] -
   *          Page Number, this value is simply for client state
   * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  AssistantListInstance.page = function page(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({uri: this._uri, method: 'GET', params: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new AssistantPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single target page of AssistantInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {string} [targetUrl] - API-generated URL for the requested results page
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  AssistantListInstance.getPage = function getPage(targetUrl, callback) {
    var deferred = Q.defer();

    var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl});

    promise = promise.then(function(payload) {
      deferred.resolve(new AssistantPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * create a AssistantInstance
   *
   * @param {object} [opts] - Options for request
   * @param {string} [opts.friendlyName] -
   *          A text description for the Assistant. It is non-unique and can be up to 255 characters long.
   * @param {boolean} [opts.logQueries] -
   *          A boolean that specifies whether queries should be logged for 30 days past training. If `false`, no queries will be stored. If `true`, queries will be stored for 30 days and deleted thereafter. Defaults to `true` if no value is provided.
   * @param {string} [opts.uniqueName] -
   *          A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.
   * @param {string} [opts.callbackUrl] - The callback_url
   * @param {string} [opts.callbackEvents] -
   *          A space-separated list of callback events that will trigger callbacks
   * @param {string} [opts.styleSheet] -
   *          A JSON object that defines the assistant [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet)
   * @param {string} [opts.defaults] -
   *          A JSON object that defines the assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios
   * @param {function} [callback] - Callback to handle processed record
   *
   * @returns {Promise} Resolves to processed AssistantInstance
   */
  /* jshint ignore:end */
  AssistantListInstance.create = function create(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'FriendlyName': _.get(opts, 'friendlyName'),
      'LogQueries': serialize.bool(_.get(opts, 'logQueries')),
      'UniqueName': _.get(opts, 'uniqueName'),
      'CallbackUrl': _.get(opts, 'callbackUrl'),
      'CallbackEvents': _.get(opts, 'callbackEvents'),
      'StyleSheet': serialize.object(_.get(opts, 'styleSheet')),
      'Defaults': serialize.object(_.get(opts, 'defaults'))
    });

    var promise = this._version.create({uri: this._uri, method: 'POST', data: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new AssistantInstance(this._version, payload, this._solution.sid));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Constructs a assistant
   *
   * @param {string} sid -
   *          A 34-character string that uniquely identifies this resource.
   *
   * @returns {Twilio.Autopilot.V1.AssistantContext}
   */
  /* jshint ignore:end */
  AssistantListInstance.get = function get(sid) {
    return new AssistantContext(this._version, sid);
  };

  return AssistantListInstance;
};

/* jshint ignore:start */
/**
 * Initialize the AssistantPagePLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @param {V1} version - Version of the resource
 * @param {Response<string>} response - Response from the API
 * @param {AssistantSolution} solution - Path solution
 *
 * @returns AssistantPage
 */
/* jshint ignore:end */
AssistantPage = function AssistantPage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
};

_.extend(AssistantPage.prototype, Page.prototype);
AssistantPage.prototype.constructor = AssistantPage;

/* jshint ignore:start */
/**
 * Build an instance of AssistantInstance
 *
 * @param {AssistantPayload} payload - Payload response from the API
 *
 * @returns AssistantInstance
 */
/* jshint ignore:end */
AssistantPage.prototype.getInstance = function getInstance(payload) {
  return new AssistantInstance(this._version, payload);
};

/* jshint ignore:start */
/**
 * Initialize the AssistantContextPLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @property {string} accountSid -
 *          The unique ID of the Account that created this Assistant.
 * @property {Date} dateCreated - The date that this resource was created
 * @property {Date} dateUpdated - The date that this resource was last updated
 * @property {string} friendlyName -
 *          A text description for the Assistant. It is non-unique and can be up to 255 characters long.
 * @property {string} latestModelBuildSid - The latest_model_build_sid
 * @property {string} links - The links
 * @property {boolean} logQueries -
 *          A boolean that specifies whether queries should be logged for 30 days past training. If `false`, no queries will be stored. If `true`, queries will be stored for 30 days and deleted thereafter.
 * @property {string} sid -
 *          A 34-character string that uniquely identifies this resource.
 * @property {string} uniqueName -
 *          A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.
 * @property {string} url - The url
 * @property {string} callbackUrl - The callback_url
 * @property {string} callbackEvents - The callback_events
 *
 * @param {V1} version - Version of the resource
 * @param {AssistantPayload} payload - The instance payload
 * @param {sid_like} sid -
 *          A 34-character string that uniquely identifies this resource.
 */
/* jshint ignore:end */
AssistantInstance = function AssistantInstance(version, payload, sid) {
  this._version = version;

  // Marshaled Properties
  this.accountSid = payload.account_sid; // jshint ignore:line
  this.dateCreated = deserialize.iso8601DateTime(payload.date_created); // jshint ignore:line
  this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); // jshint ignore:line
  this.friendlyName = payload.friendly_name; // jshint ignore:line
  this.latestModelBuildSid = payload.latest_model_build_sid; // jshint ignore:line
  this.links = payload.links; // jshint ignore:line
  this.logQueries = payload.log_queries; // jshint ignore:line
  this.sid = payload.sid; // jshint ignore:line
  this.uniqueName = payload.unique_name; // jshint ignore:line
  this.url = payload.url; // jshint ignore:line
  this.callbackUrl = payload.callback_url; // jshint ignore:line
  this.callbackEvents = payload.callback_events; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {sid: sid || this.sid, };
};

Object.defineProperty(AssistantInstance.prototype,
  '_proxy', {
  get: function() {
    if (!this._context) {
      this._context = new AssistantContext(this._version, this._solution.sid);
    }

    return this._context;
  }
});

/* jshint ignore:start */
/**
 * fetch a AssistantInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed AssistantInstance
 */
/* jshint ignore:end */
AssistantInstance.prototype.fetch = function fetch(callback) {
  return this._proxy.fetch(callback);
};

/* jshint ignore:start */
/**
 * update a AssistantInstance
 *
 * @param {object} [opts] - Options for request
 * @param {string} [opts.friendlyName] -
 *          A text description for the Assistant. It is non-unique and can be up to 255 characters long.
 * @param {boolean} [opts.logQueries] -
 *          A boolean that specifies whether queries should be logged for 30 days past training. If `false`, no queries will be stored. If `true`, queries will be stored for 30 days and deleted thereafter. Defaults to `true` if no value is provided.
 * @param {string} [opts.uniqueName] -
 *          A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.
 * @param {string} [opts.callbackUrl] - The callback_url
 * @param {string} [opts.callbackEvents] -
 *          A space-separated list of callback events that will trigger callbacks
 * @param {string} [opts.styleSheet] -
 *          A JSON object that defines the assistant [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet)
 * @param {string} [opts.defaults] -
 *          A JSON object that defines the assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed AssistantInstance
 */
/* jshint ignore:end */
AssistantInstance.prototype.update = function update(opts, callback) {
  return this._proxy.update(opts, callback);
};

/* jshint ignore:start */
/**
 * remove a AssistantInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed AssistantInstance
 */
/* jshint ignore:end */
AssistantInstance.prototype.remove = function remove(callback) {
  return this._proxy.remove(callback);
};

/* jshint ignore:start */
/**
 * Access the fieldTypes
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.FieldTypeList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.fieldTypes = function fieldTypes() {
  return this._proxy.fieldTypes;
};

/* jshint ignore:start */
/**
 * Access the tasks
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.TaskList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.tasks = function tasks() {
  return this._proxy.tasks;
};

/* jshint ignore:start */
/**
 * Access the modelBuilds
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.ModelBuildList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.modelBuilds = function modelBuilds() {
  return this._proxy.modelBuilds;
};

/* jshint ignore:start */
/**
 * Access the queries
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.QueryList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.queries = function queries() {
  return this._proxy.queries;
};

/* jshint ignore:start */
/**
 * Access the styleSheet
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.StyleSheetList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.styleSheet = function styleSheet() {
  return this._proxy.styleSheet;
};

/* jshint ignore:start */
/**
 * Access the defaults
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.DefaultsList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.defaults = function defaults() {
  return this._proxy.defaults;
};

/* jshint ignore:start */
/**
 * Access the dialogues
 *
 * @returns {Twilio.Autopilot.V1.AssistantContext.DialogueList}
 */
/* jshint ignore:end */
AssistantInstance.prototype.dialogues = function dialogues() {
  return this._proxy.dialogues;
};

/* jshint ignore:start */
/**
 * Produce a plain JSON object version of the AssistantInstance for serialization.
 * Removes any circular references in the object.
 *
 * @returns Object
 */
/* jshint ignore:end */
AssistantInstance.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

/* jshint ignore:start */
/**
 * Initialize the AssistantContextPLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @property {Twilio.Autopilot.V1.AssistantContext.FieldTypeList} fieldTypes -
 *          fieldTypes resource
 * @property {Twilio.Autopilot.V1.AssistantContext.TaskList} tasks - tasks resource
 * @property {Twilio.Autopilot.V1.AssistantContext.ModelBuildList} modelBuilds -
 *          modelBuilds resource
 * @property {Twilio.Autopilot.V1.AssistantContext.QueryList} queries -
 *          queries resource
 * @property {Twilio.Autopilot.V1.AssistantContext.StyleSheetList} styleSheet -
 *          styleSheet resource
 * @property {Twilio.Autopilot.V1.AssistantContext.DefaultsList} defaults -
 *          defaults resource
 * @property {Twilio.Autopilot.V1.AssistantContext.DialogueList} dialogues -
 *          dialogues resource
 *
 * @param {V1} version - Version of the resource
 * @param {sid_like} sid -
 *          A 34-character string that uniquely identifies this resource.
 */
/* jshint ignore:end */
AssistantContext = function AssistantContext(version, sid) {
  this._version = version;

  // Path Solution
  this._solution = {sid: sid, };
  this._uri = _.template(
    '/Assistants/<%= sid %>' // jshint ignore:line
  )(this._solution);

  // Dependents
  this._fieldTypes = undefined;
  this._tasks = undefined;
  this._modelBuilds = undefined;
  this._queries = undefined;
  this._styleSheet = undefined;
  this._defaults = undefined;
  this._dialogues = undefined;
};

/* jshint ignore:start */
/**
 * fetch a AssistantInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed AssistantInstance
 */
/* jshint ignore:end */
AssistantContext.prototype.fetch = function fetch(callback) {
  var deferred = Q.defer();
  var promise = this._version.fetch({uri: this._uri, method: 'GET'});

  promise = promise.then(function(payload) {
    deferred.resolve(new AssistantInstance(this._version, payload, this._solution.sid));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

/* jshint ignore:start */
/**
 * update a AssistantInstance
 *
 * @param {object} [opts] - Options for request
 * @param {string} [opts.friendlyName] -
 *          A text description for the Assistant. It is non-unique and can be up to 255 characters long.
 * @param {boolean} [opts.logQueries] -
 *          A boolean that specifies whether queries should be logged for 30 days past training. If `false`, no queries will be stored. If `true`, queries will be stored for 30 days and deleted thereafter. Defaults to `true` if no value is provided.
 * @param {string} [opts.uniqueName] -
 *          A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.
 * @param {string} [opts.callbackUrl] - The callback_url
 * @param {string} [opts.callbackEvents] -
 *          A space-separated list of callback events that will trigger callbacks
 * @param {string} [opts.styleSheet] -
 *          A JSON object that defines the assistant [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet)
 * @param {string} [opts.defaults] -
 *          A JSON object that defines the assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed AssistantInstance
 */
/* jshint ignore:end */
AssistantContext.prototype.update = function update(opts, callback) {
  if (_.isFunction(opts)) {
    callback = opts;
    opts = {};
  }
  opts = opts || {};

  var deferred = Q.defer();
  var data = values.of({
    'FriendlyName': _.get(opts, 'friendlyName'),
    'LogQueries': serialize.bool(_.get(opts, 'logQueries')),
    'UniqueName': _.get(opts, 'uniqueName'),
    'CallbackUrl': _.get(opts, 'callbackUrl'),
    'CallbackEvents': _.get(opts, 'callbackEvents'),
    'StyleSheet': serialize.object(_.get(opts, 'styleSheet')),
    'Defaults': serialize.object(_.get(opts, 'defaults'))
  });

  var promise = this._version.update({uri: this._uri, method: 'POST', data: data});

  promise = promise.then(function(payload) {
    deferred.resolve(new AssistantInstance(this._version, payload, this._solution.sid));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

/* jshint ignore:start */
/**
 * remove a AssistantInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed AssistantInstance
 */
/* jshint ignore:end */
AssistantContext.prototype.remove = function remove(callback) {
  var deferred = Q.defer();
  var promise = this._version.remove({uri: this._uri, method: 'DELETE'});

  promise = promise.then(function(payload) {
    deferred.resolve(payload);
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

Object.defineProperty(AssistantContext.prototype,
  'fieldTypes', {
  get: function() {
    if (!this._fieldTypes) {
      this._fieldTypes = new FieldTypeList(this._version, this._solution.sid);
    }
    return this._fieldTypes;
  }
});

Object.defineProperty(AssistantContext.prototype,
  'tasks', {
  get: function() {
    if (!this._tasks) {
      this._tasks = new TaskList(this._version, this._solution.sid);
    }
    return this._tasks;
  }
});

Object.defineProperty(AssistantContext.prototype,
  'modelBuilds', {
  get: function() {
    if (!this._modelBuilds) {
      this._modelBuilds = new ModelBuildList(this._version, this._solution.sid);
    }
    return this._modelBuilds;
  }
});

Object.defineProperty(AssistantContext.prototype,
  'queries', {
  get: function() {
    if (!this._queries) {
      this._queries = new QueryList(this._version, this._solution.sid);
    }
    return this._queries;
  }
});

Object.defineProperty(AssistantContext.prototype,
  'styleSheet', {
  get: function() {
    if (!this._styleSheet) {
      this._styleSheet = new StyleSheetList(this._version, this._solution.sid);
    }
    return this._styleSheet;
  }
});

Object.defineProperty(AssistantContext.prototype,
  'defaults', {
  get: function() {
    if (!this._defaults) {
      this._defaults = new DefaultsList(this._version, this._solution.sid);
    }
    return this._defaults;
  }
});

Object.defineProperty(AssistantContext.prototype,
  'dialogues', {
  get: function() {
    if (!this._dialogues) {
      this._dialogues = new DialogueList(this._version, this._solution.sid);
    }
    return this._dialogues;
  }
});

module.exports = {
  AssistantList: AssistantList,
  AssistantPage: AssistantPage,
  AssistantInstance: AssistantInstance,
  AssistantContext: AssistantContext
};


text:
package org.apache.activemq.artemis.tests.integration.cluster.failover;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage;
import org.junit.Assert;

public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase
{
   IntegrationTestLogger log = IntegrationTestLogger.LOGGER;

   protected abstract boolean isNetty();

   protected int waitForNewLive(long seconds,
                                boolean waitForNewBackup,
                                Map<Integer, TestableServer> servers,
                                int... nodes)
   {
      long time = System.currentTimeMillis();
      long toWait = seconds * 1000;
      int newLive = -1;
      while (true)
      {
         for (int node : nodes)
         {
            TestableServer backupServer = servers.get(node);
            if (newLive == -1 && backupServer.isActive())
            {
               newLive = node;
            }
            else if (newLive != -1)
            {
               if (waitForNewBackup)
               {
                  if (node != newLive && servers.get(node).isStarted())
                  {
                     return newLive;
                  }
               }
               else
               {
                  return newLive;
               }
            }
         }

         try
         {
            Thread.sleep(100);
         }
         catch (InterruptedException e)
         {
            // ignore
         }
         if (System.currentTimeMillis() > (time + toWait))
         {
            Assert.fail("backup server never started");
         }
      }
   }

   protected ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception
   {
      ClientSession session = sf.createSession(false, true, true);

      if (createQueue)
      {
         session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, false);
      }

      ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);

      final int numMessages = 1000;

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE,
                                                       false,
                                                       0,
                                                       System.currentTimeMillis(),
                                                       (byte)1);
         message.putIntProperty(new SimpleString("count"), i);
         message.getBodyBuffer().writeString("aardvarks");
         producer.send(message);
      }

      ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS);

      session.start();

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message2 = consumer.receive(10000);

         Assert.assertNotNull(message2);

         Assert.assertEquals("aardvarks", message2.getBodyBuffer().readString());

         Assert.assertEquals(i, message2.getObjectProperty(new SimpleString("count")));

         message2.acknowledge();
      }

      ClientMessage message3 = consumer.receiveImmediate();

      Assert.assertNull(message3);

      return session;
   }

   protected ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator,
                                                                                int topologyMembers) throws Exception
   {
      return createSessionFactoryAndWaitForTopology(locator, topologyMembers, null);
   }

   protected ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator,
                                                                                int topologyMembers,
                                                                                ActiveMQServer server) throws Exception
   {
      ClientSessionFactoryInternal sf;
      CountDownLatch countDownLatch = new CountDownLatch(topologyMembers);

      FailoverTestBase.LatchClusterTopologyListener topListener = new FailoverTestBase.LatchClusterTopologyListener(countDownLatch);
      locator.addClusterTopologyListener(topListener);

      sf = (ClientSessionFactoryInternal)locator.createSessionFactory();
      addSessionFactory(sf);

      boolean ok = countDownLatch.await(5, TimeUnit.SECONDS);
      locator.removeClusterTopologyListener(topListener);
      if (!ok)
      {
         if (server != null)
         {
            log.info("failed topology, Topology on server = " + server.getClusterManager().describe());
         }
      }
      Assert.assertTrue("expected " + topologyMembers + " members", ok);
      return sf;
   }

   public ServerLocator getServerLocator(int... nodes)
   {
      TransportConfiguration[] configs = new TransportConfiguration[nodes.length];
      for (int i = 0, configsLength = configs.length; i < configsLength; i++)
      {
         configs[i] = createTransportConfiguration(isNetty(), false, generateParams(nodes[i], isNetty()));
      }
      return addServerLocator(new ServerLocatorImpl(true, configs));
   }
}


text:
package org.springframework.social.twitter.api.impl;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatus.Series;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.social.DuplicateStatusException;
import org.springframework.social.InternalServerErrorException;
import org.springframework.social.InvalidAuthorizationException;
import org.springframework.social.MissingAuthorizationException;
import org.springframework.social.NotAuthorizedException;
import org.springframework.social.OperationNotPermittedException;
import org.springframework.social.RateLimitExceededException;
import org.springframework.social.ResourceNotFoundException;
import org.springframework.social.RevokedAuthorizationException;
import org.springframework.social.ServerDownException;
import org.springframework.social.ServerOverloadedException;
import org.springframework.social.UncategorizedApiException;
import org.springframework.social.twitter.api.InvalidMessageRecipientException;
import org.springframework.social.twitter.api.MessageTooLongException;
import org.springframework.web.client.DefaultResponseErrorHandler;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Subclass of {@link DefaultResponseErrorHandler} that handles errors from Twitter's
 * REST API, interpreting them into appropriate exceptions.
 * @author Craig Walls
 */
class TwitterErrorHandler extends DefaultResponseErrorHandler {

	@Override
	public void handleError(ClientHttpResponse response) throws IOException {
		HttpStatus statusCode = response.getStatusCode();
		if (statusCode.series() == Series.SERVER_ERROR) {
			handleServerErrors(statusCode);
		} else if (statusCode.series() == Series.CLIENT_ERROR) {
			handleClientErrors(response);
		}

		// if not otherwise handled, do default handling and wrap with UncategorizedApiException
		try {
			super.handleError(response);
		} catch(Exception e) {
			throw new UncategorizedApiException("twitter", "Error consuming Twitter REST API", e);
		}
	}

	private void handleClientErrors(ClientHttpResponse response) throws IOException {
		HttpStatus statusCode = response.getStatusCode();
		Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);

		String errorText = "";
		if (errorMap.containsKey("error")) {
			errorText = (String) errorMap.get("error");
		} else if(errorMap.containsKey("errors")) {
			Object errors = errorMap.get("errors");
			if (errors instanceof List) {
				@SuppressWarnings("unchecked")
				List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
				errorText = errorsList.get(0).get("message");
			} else if (errors instanceof String ) {
				errorText = (String) errors;
			}
		}

		System.out.println("ERROR:   " + statusCode + " :: " + errorText);

		if (statusCode == HttpStatus.BAD_REQUEST) {
			if (errorText.contains("Rate limit exceeded.")) {
				throw new RateLimitExceededException("twitter");
			}
		} else if (statusCode == HttpStatus.UNAUTHORIZED) {
			if (errorText == null) {
				throw new NotAuthorizedException("twitter", response.getStatusText());
			} else if (errorText.equals("Could not authenticate you.")) {
				throw new MissingAuthorizationException("twitter");
			} else if (errorText.equals("Could not authenticate with OAuth.")) { // revoked token
				throw new RevokedAuthorizationException("twitter");
			} else if (errorText.equals("Invalid / expired Token")) { // Note that Twitter doesn't actually expire tokens
				throw new InvalidAuthorizationException("twitter", errorText);
			} else {
				throw new NotAuthorizedException("twitter", errorText);
			}
		} else if (statusCode == HttpStatus.FORBIDDEN) {
			if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
				throw new DuplicateStatusException("twitter", errorText);
			} else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
				throw new MessageTooLongException(errorText);
			} else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
				throw new InvalidMessageRecipientException(errorText);
			} else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
				throw new RateLimitExceededException("twitter");
			} else {
				throw new OperationNotPermittedException("twitter", errorText);
			}
		} else if (statusCode == HttpStatus.NOT_FOUND) {
			throw new ResourceNotFoundException("twitter", errorText);
		} else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM) || statusCode == HttpStatus.valueOf(TOO_MANY_REQUESTS)) {
			throw new RateLimitExceededException("twitter");
		}

	}

	private void handleServerErrors(HttpStatus statusCode) throws IOException {
		if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
			throw new InternalServerErrorException("twitter", "Something is broken at Twitter. Please see http://dev.twitter.com/pages/support to report the issue.");
		} else if (statusCode == HttpStatus.BAD_GATEWAY) {
			throw new ServerDownException("twitter", "Twitter is down or is being upgraded.");
		} else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
			throw new ServerOverloadedException("twitter", "Twitter is overloaded with requests. Try again later.");
		}
	}

	private Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
		ObjectMapper mapper = new ObjectMapper(new JsonFactory());
		try {
			return mapper.<Map<String, Object>>readValue(response.getBody(), new TypeReference<Map<String, Object>>() {});
		} catch (JsonParseException e) {
			return Collections.emptyMap();
		}
	}

	private static final String INVALID_MESSAGE_RECIPIENT_TEXT = "You cannot send messages to users who are not following you.";
	private static final String STATUS_TOO_LONG_TEXT = "Status is over 140 characters.";
	private static final String MESSAGE_TOO_LONG_TEXT = "The text of your direct message is over 140 characters";
	private static final String DUPLICATE_STATUS_TEXT = "Status is a duplicate.";
	private static final String DAILY_RATE_LIMIT_TEXT = "User is over daily status update limit.";

	private static final int ENHANCE_YOUR_CALM = 420;
	private static final int TOO_MANY_REQUESTS = 429;
}


text:
layout: postag
title: 'DET'
shortdef: 'determiner'
---

### Definition

Determiners are words that modify nouns or noun phrases and express
the reference of the noun phrase in context. That is, a determiner may
indicate whether the noun is referring to a definite or indefinite
element of a class, to a closer or more distant element, to an element
belonging to a specified person or thing, to a particular number or
quantity, etc.

Traditionally, Turkish grammars and dictionaries do not make the distinction between a determiner and an adjective (but modern grammars do, see Göksel and Kerslake 2005, ch.15).

Turkish does not have a definite article,
but the numeral _bir_ "one" also acts as an indefinite article.
We mark it as `DET` in this usage.

### Examples

- demonstrative determiners: _bu_ "this", _şu_ "this/that", _o_ "that"
- interrogative determiners: _hangi_ "which", _kaç_ "how many"
- quantity/quantifier determiners: _bütün_ "all", _bazı_ "some",
  _hiçbir_ "none"

### References

Aslı Göksel and Celia Kerslake. _Turkish: A Comprehensive Grammar_.  London: Routledge, 2005.


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: jgimenez
 * Date: 7/29/2016
 * Time: 10:45 AM
 */

namespace Authhelper\Test\TestCase\Model\Auth0;

use Authhelper\Model\Auth0\FacebookUser;
use Cake\TestSuite\TestCase;

class FacebookUserTest extends TestCase {

    private $user = array (
        'name' => 'Jsoftb Lamp',
        'email' => 'jsoftb@email.org',
        'given_name' => 'Jsoftb',
        'family_name' => 'Lamp',
        'gender' => 'male',
        'picture' => 'https://scontent.xx.fbcdn.net/v/t1.0-1/c192.46.576.576/s50x50/377226_1214234234234_1168724481_n.jpg?oh=75dff1a0623a72ec8b3590a7bac5ff50&oe=58223335',
        'picture_large' => 'https://scontent.xx.fbcdn.net/t31.0-1/asdasdasd.jpg',
        'age_range' => [
            'min' => 21,
        ],
        'context' =>
            [
                'mutual_likes' =>
                    [
                        'data' => [],
                        'summary' => [
                            'total_count' => 48,
                        ],
                    ],
                'id' => 'dXNlcl9jb250ZAXh0OgGQY5QExhwxWNhYTAKxRoUc3A7ktOxzVsemZB4nYBIXHOMLUBIqIZC2FLcKIkdJkRkiVFJ91egONcqrZA3QVumrVdxlgPzwXVCBkcp4dLVdlwrcZBUZD',
            ],
        'cover' =>[
            'id' => '1946612312345398',
            'offset_y' => 100,
            'source' => 'https://scontent.xx.fbcdn.net/v/t1.0-9/538233_194612345398_1182642577_n.jpg?oh=05b322c5b5a01bf41493770f79fdd0b8&oe=5835CB60',
            ],
        'devices' => [
            0 => [
                'hardware' => 'iPhone',
                'os' => 'iOS',
            ],
        ],
        'updated_time' => '2014-01-14T17:28:27+0000',
        'installed' => true,
        'is_verified' => false,
        'link' => 'https://www.facebook.com/app_scoped_user_id/9312313206259/',
        'locale' => 'en_US',
        'name_format' => '{first} {last}',
        'timezone' => -6,
        'third_party_id' => 'HrUpZ123AODJweBJr2uS8w1ds',
        'verified' => true,
        'email_verified' => true,
        'updated_at' => '2016-07-26T21:47:15.716Z',
        'user_id' => 'facebook|9312313206259',
        'nickname' => 'jsoftb',
        'identities' => [
            0 =>[
                'provider' => 'facebook',
                'user_id' => '9312313206259',
                'connection' => 'facebook',
                'isSocial' => true,
            ]
        ],
        'created_at' => '2016-07-25T19:43:11.618Z',
        'last_ip' => '164.47.8.61',
        'last_login' => '2016-07-26T21:47:15.715Z',
        'logins_count' => 7,
        'blocked_for' =>[]
    );

    private $entity;

    public function setUp()
    {
        parent::setUp();
        $this->entity = new FacebookUser($this->user);
    }

    /**
     * method getFirstName
     * when always
     * should returnCorrectly
     * @test
     */
    public function getFirstName_always_returnCorrectly()
    {
        $this->assertEquals($this->user['given_name'], $this->entity->getFirstName());
    }

    /**
     * method getLastName
     * when always
     * should returnCorrectly
     * @test
     */
    public function getLastName_always_returnCorrectly()
    {
        $this->assertEquals($this->user['family_name'], $this->entity->getLastName());
    }

    /**
     * method getEmail
     * when always
     * should returnCorrectly
     * @test
     */
    public function getEmail_always_returnCorrectly()
    {
        $this->assertEquals($this->user['email'], $this->entity->getEmail());
    }

    /**
     * method getUserId
     * when always
     * should returnCorrectly
     * @test
     */
    public function getUserId_always_returnCorrectly()
    {
        $this->assertEquals($this->user['user_id'], $this->entity->getUserId());
    }

    /**
     * method getPicture
     * when always
     * should returnCorrectly
     * @test
     */
    public function getPicture_always_returnCorrectly()
    {
        $this->assertEquals($this->user['picture'], $this->entity->getPicture());
    }

    /**
     * method getLargePicture
     * when always
     * should returnCorrectly
     * @test
     */
    public function getLargePicture_always_returnCorrectly()
    {
        $this->assertEquals($this->user['picture_large'], $this->entity->getLargePicture());
    }

    /**
     * method getName
     * when always
     * should returnCorrectly
     * @test
     */
    public function getName_always_returnCorrectly()
    {
        $this->assertEquals($this->user['name'], $this->entity->getName());
    }

    /**
     * method getLoginCounts
     * when always
     * should returnCorrectly
     * @test
     */
    public function getLoginCounts_always_returnCorrectly()
    {
        $this->assertEquals($this->user['logins_count'], $this->entity->getLoginCounts());
    }

    /**
     * method getLastLogin
     * when always
     * should returnCorrectly
     * @test
     */
    public function getLastLogin_always_returnCorrectly()
    {
        $this->assertEquals($this->user['last_login'], $this->entity->getLastLogin());
    }

    /**
     * method getNickname
     * when always
     * should returnCorrectly
     * @test
     */
    public function getNickname_always_returnCorrectly()
    {
        $this->assertEquals($this->user['nickname'], $this->entity->getNickname());
    }

    /**
     * method getCreatedAt
     * when always
     * should returnCorrectly
     * @test
     */
    public function getCreatedAte_always_returnCorrectly()
    {
        $this->assertEquals($this->user['created_at'], $this->entity->getCreatedAt());
    }

    /**
     * method isSocial
     * when always
     * should returnCorrectly
     * @test
     */
    public function isSocial_always_returnCorrectly()
    {
        $this->assertTrue($this->entity->isSocial());
    }

    /**
     * method toArray
     * when always
     * should returnCorrectly
     * @test
     */
    public function toArray_always_returnCorrectly()
    {
    	$this->assertEquals($this->user, $this->entity->toArray());
    }

}


text:
import { FieldType } from '@terascope/types';
import {
    FieldTransformConfig, ProcessMode, FunctionDefinitionType,
    FunctionDefinitionExample, FunctionDefinitionCategory,
} from '../interfaces';

export interface SplitArgs {
    delimiter?: string;
}

const examples: FunctionDefinitionExample<SplitArgs>[] = [
    {
        args: {},
        config: { version: 1, fields: { testField: { type: FieldType.String } } },
        field: 'testField',
        input: 'astring',
        output: ['a', 's', 't', 'r', 'i', 'n', 'g']
    },
    {
        args: { delimiter: ',' },
        config: { version: 1, fields: { testField: { type: FieldType.String } } },
        field: 'testField',
        input: 'astring',
        output: ['astring'],
        description: 'Delimiter is not found so the whole input is returned'
    },
    {
        args: { delimiter: '-' },
        config: { version: 1, fields: { testField: { type: FieldType.String } } },
        field: 'testField',
        input: 'a-stri-ng',
        output: ['a', 'stri', 'ng']
    },
    {
        args: { delimiter: ' ' },
        config: { version: 1, fields: { testField: { type: FieldType.String } } },
        field: 'testField',
        input: 'a string',
        output: ['a', 'string']
    },
];

export const splitConfig: FieldTransformConfig<SplitArgs> = {
    name: 'split',
    type: FunctionDefinitionType.FIELD_TRANSFORM,
    process_mode: ProcessMode.INDIVIDUAL_VALUES,
    category: FunctionDefinitionCategory.STRING,
    description: 'Returns an array based off the input split by the args delimiter, defaults to splitting by each character',
    examples,
    create({ args: { delimiter = '' } }) {
        return splitFn(delimiter);
    },
    accepts: [FieldType.String],
    argument_schema: {
        delimiter: {
            type: FieldType.String,
            array: false,
            description: 'The char used to identify where to split the string'
        }
    },
    output_type({ field_config }) {
        return {
            field_config: {
                ...field_config,
                array: true,
            }
        };
    }
};

function splitFn(delimiter: string): (input: unknown) => string[] {
    return function _split(input) {
        return String(input).split(delimiter);
    };
}


text:
package file

import (
	"bufio"
	"fmt"
	"os"
	"regexp"

	"github.com/fatih/color"
	"github.com/nomad-software/grope/cli"
	"golang.org/x/sync/errgroup"
)

const nContentWorkers = 100

// contentQueue coordinates units of work.
type contentQueue struct {
	Closed chan bool
	Input  chan contentUnitOfWork
	Output *cli.Output
}

// contentUnitOfWork wraps a file path and the content pattern being matched within it.
type contentUnitOfWork struct {
	File  string
	Regex *regexp.Regexp
}

// newContentQueue creates a new content queue.
func newContentQueue() *contentQueue {
	return &contentQueue{
		Input:  make(chan contentUnitOfWork),
		Closed: make(chan bool),
		Output: cli.NewOutput(),
	}
}

// start creates worker goroutines and starts processing units of work.
func (q *contentQueue) start() {
	go q.Output.Start()

	g := new(errgroup.Group)

	for i := 0; i < nContentWorkers; i++ {
		g.Go(q.matchContent)
	}

	g.Wait()

	close(q.Output.Console)
	<-q.Output.Closed

	q.Closed <- true
}

// matchPaths processes content units of work and matches valid lines to output to the CLI.
func (q *contentQueue) matchContent() error {
	for work := range q.Input {
		file, err := os.Open(work.File)

		if err != nil {
			fmt.Fprintln(cli.Stderr, color.RedString(err.Error()))
			continue
		}

		lines := make([]cli.Line, 0)
		var lineNumber int

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			lineNumber++
			if work.Regex.MatchString(scanner.Text()) {
				lines = append(lines, cli.Line{
					Number: lineNumber,
					Line:   work.Regex.ReplaceAllString(scanner.Text(), color.New(color.FgHiRed, color.Bold).SprintFunc()("$0")),
				})
			}
		}

		if err := scanner.Err(); err != nil {
			// Completely ignore 'token too long' errors because they're usually
			// minified frontend files we're not interested in.
			if err != bufio.ErrTooLong {
				fmt.Fprintln(cli.Stderr, color.RedString(fmt.Sprintf("Error scanning %s - %s", work.File, err.Error())))
			}
			continue
		}

		if len(lines) > 0 {
			q.Output.Console <- cli.Match{
				File:  work.File,
				Lines: lines,
			}
		}

		file.Close()
	}

	return nil
}

// stop closes the content queue's input.
func (q *contentQueue) stop() {
	close(q.Input)
	<-q.Closed
}


text:
package fr.utbm.gl52.tp3.graph;

import java.util.Set;

public interface Graph <D, N extends GraphNode<D,N>> {

    public boolean isEmpty();

    public boolean addRoot(N root);

    public boolean removeRoot(N root);

    public boolean addAllRoots(Set<N> roots);

    public boolean removeAllRoots(Set<N> roots);

    public Set<N> getRoots();

}


text:
package cibuild

import (
	"github.com/dmcsorley/goblin/config"
	"testing"
)

func TestDockerPushStepParams(t *testing.T) {
	dps := &config.StepRecord{Type: string(DockerPush)}

	expectStepConstructorFailure(
		newPushStep,
		dps,
		t,
		"docker-push step should have failed with no image",
	)

	dps.Image = "${badexample}"
	dps.DecodedFields = []string{"image"}

	expectStepConstructorFailure(
		newPushStep,
		dps,
		t,
		"docker-push step should have failed for bad image value",
	)
}