text:
# ----------------------------------------------------------------------------
#
#   enso.graphics.xmltextlayout
#
# ----------------------------------------------------------------------------

"""
    Module for XML text layout.

    This module implements a high-level XML-based interface to the
    textlayout module.  It also provides a simple style mechanism that
    is heavily based on the Cascading Style Sheets (CSS) system.
"""

# ----------------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------------

import xml.sax
import xml.sax.handler

from enso.utils.memoize import memoized
from enso.graphics import measurement
from enso.graphics import textlayout
from enso.graphics import font

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

# Ordinarily, we'd use the unicodedata module for this, but it's a
# hefty file so we'll just define values here.
NON_BREAKING_SPACE = u"\u00a0"

# ----------------------------------------------------------------------------
# Utility functions
# ----------------------------------------------------------------------------

@memoized
def colorHashToRgba( colorHash ):
    """
    Converts the given HTML-style color hash (e.g., '#aabbcc') or
    HTML-with-alpha color hash (e.g. '#aabbccdd') to a quad-color (r,
    g, b, a) tuple and returns the result.

    Examples:

    >>> colorHashToRgba( '#ffffff' )
    (1.0, 1.0, 1.0, 1.0)

    >>> colorHashToRgba( '#ff000000' )
    (1.0, 0.0, 0.0, 0.0)
    """

    colorHash = colorHash[1:]
    if len(colorHash) == 6:
        # It's a RGB hash.
        alphaHex = "FF"
    elif len(colorHash) == 8:
        # It's a RGBA hash.
        alphaHex = colorHash[6:8]
    else:
        raise ValueError("Can't parse color hash for '#%s'" % colorHash)

    redHex = colorHash[0:2]
    greenHex = colorHash[2:4]
    blueHex = colorHash[4:6]

    red = float( int(redHex, 16) )
    green = float( int(greenHex, 16) )
    blue = float( int(blueHex, 16) )
    alpha = float( int(alphaHex, 16) )

    return ( red / 255.0, green / 255.0, blue / 255.0, alpha / 255.0 )

def stringToBool( string ):
    """
    Converts a string with the contents 'true' or 'false' to the
    appropriate boolean value.

    Examples:

    >>> stringToBool( 'true' )
    True

    >>> stringToBool( 'false' )
    False

    >>> stringToBool( 'True' )
    Traceback (most recent call last):
    ...
    ValueError: can't convert to boolean: True
    """

    if string == "true":
        return True
    elif string == "false":
        return False
    else:
        raise ValueError( "can't convert to boolean: %s" % string )

# ----------------------------------------------------------------------------
# Style Properties
# ----------------------------------------------------------------------------

# Style properties that are inherited from a parent element to a child
# element.
STYLE_INHERITED_PROPERTIES = [
    # The following properties are identical to the CSS properties of
    # the same name, with the exception that any underscores should be
    # replaced by hyphens.
    "width",
    "text_align",
    "line_height",
    "color",
    "font_style",
    "font_family",
    "font_size",

    # This property defines the maximum number of lines that the
    # element can contain, and is only valid for Block elements; if
    # the element's lines exceed this number and the 'ellipsify'
    # property is false, a textlayout.MaxLinesExceededError is raised.
    "max_lines",

    # This property defines whether or not to truncate a Block element
    # with an ellipsis ('...') if the Block's number of lines exceeds
    # that prescribed by the "max_lines" property.
    "ellipsify"
    ]

# Style properties that are uninherited from a parent element to a
# chid element.
STYLE_UNINHERITED_PROPERTIES = [
    # The following properties are identical to the CSS properties of
    # the same name, with the exception that any underscores should be
    # replaced by hyphens.
    "margin_top",
    "margin_bottom"
    ]

# All possibilities of styles defined by this module.
STYLE_PROPERTIES = (
    STYLE_INHERITED_PROPERTIES +
    STYLE_UNINHERITED_PROPERTIES
    )

# ----------------------------------------------------------------------------
# Style Registry
# ----------------------------------------------------------------------------

class StyleRegistry:
    """
    Registry of styles used by XML text layout markup.  Note that this
    class is not a singleton; rather, one StyleRegistry instance
    exists for each document that the client wants to layout.
    """

    def __init__( self ):
        """
        Creates an empty StyleRegistry object.
        """

        self._styleDict = {}

    def __validateKeys( self, dict ):
        """
        Makes sure that the keys of dict are the names of valid style
        properties.
        """

        invalidKeys = [ key for key in dict.keys() \
                        if key not in STYLE_PROPERTIES ]
        if len( invalidKeys ) > 0:
            raise InvalidPropertyError( str(invalidKeys) )

    def add( self, selector, **properties ):
        """
        Adds the given style selector with the given properties to the
        style registry.  If any of the properties are invalid, an
        InvalidPropertyError is thrown.

        Examples:

        >>> styles = StyleRegistry()
        >>> styles.add( 'document', width = '1000pt' )
        >>> styles.add( 'p', foo = '1000pt' )
        Traceback (most recent call last):
        ...
        InvalidPropertyError: ['foo']

        It should also be noted that the same style selector can't be
        defined more than once, e.g.:

        >>> styles.add( 'foo', width = '1000pt' )
        >>> styles.add( 'foo', width = '1000pt' )
        Traceback (most recent call last):
        ...
        ValueError: Style 'foo' already exists.
        """

        if self._styleDict.has_key( selector ):
            raise ValueError( "Style '%s' already exists." % selector )

        self.__validateKeys( properties )
        self._styleDict[ selector ] = properties

    def findMatch( self, selector ):
        """
        Given a selector, returns the style dictionary corresponding
        to it.  If no match is found, this method returns None.

        Each key of the returned style dictionary corresponds to a
        style property, while each value corresponds to the value of
        the style property.

        Examples:

        >>> styles = StyleRegistry()
        >>> styles.add( 'document', width = '1000pt' )
        >>> styles.findMatch( 'document' )
        {'width': '1000pt'}

        >>> styles.findMatch( 'mystyle' ) == None
        True
        """

        return self._styleDict.get( selector, None )

    def update( self, selector, **properties ):
        """
        Updates the styles for selector to those described by
        properties.

        Examples:

        >>> styles = StyleRegistry()
        >>> styles.add( 'document', width = '1000pt' )
        >>> styles.update( 'document', margin_top = '24pt' )
        >>> styles.findMatch( 'document' )
        {'width': '1000pt', 'margin_top': '24pt'}
        """

        assert selector in self._styleDict.keys()

        self.__validateKeys( properties )
        self._styleDict[ selector ].update( properties )

class InvalidPropertyError( Exception ):
    """
    Exception raised by the StyleRegistry when a style with invalid
    properties is added to the registry.
    """

    pass

# ----------------------------------------------------------------------------
# Cascading Style Stack
# ----------------------------------------------------------------------------

class CascadingStyleStack:
    """
    Encapsulates the CSS-like 'cascading' style mechanism supported by
    the XML text layout markup.
    """

    # This is just a set version of STYLE_UNINHERITED_PROPERTIES.
    uninheritedProps = set( STYLE_UNINHERITED_PROPERTIES )

    def __init__( self ):
        """
        Creates an empty stack.
        """

        self.__stack = []

    def push( self, newStyle ):
        """
        Push a new style onto the Cascading Style Stack, making it the
        current style.
        """

        if len( self.__stack ) > 0:
            # "Cascade" the new style by combining it with our current
            # style, removing any uninherited properties first.

            currStyle = self.__stack[-1].copy()
            props = self.uninheritedProps.intersection( currStyle.keys() )

            for key in props:
                del currStyle[key]

            currStyle.update( newStyle )
            self.__stack.append( currStyle )
        else:
            # Set this style as our current style.

            self.__stack.append( newStyle )

    def pop( self ):
        """
        Remove the current style from the Cascading Style Stack.
        """

        self.__stack.pop()

    def _strToPoints( self, unitsStr ):
        """
        Converts from a string such as '1em', '2pt', '3in', '5pc', or
        '20px' into a floating-point value measured in points.
        """

        if unitsStr.endswith( "em" ):
            currEmSizeStr = self.__stack[-1]["font_size"]
            currEmSize = self._strToPoints( currEmSizeStr )
            units = float( unitsStr[:-2] )
            return units * currEmSize
        else:
            return measurement.strToPoints( unitsStr )

    def _propertyToPoints( self, propertyName ):
        """
        Converts the value of the given property name into a
        floating-point value measured in points.
        """

        propertyStr = self.__stack[-1][propertyName]
        return self._strToPoints( propertyStr )

    def _propertyToInt( self, propertyName ):
        """
        Converts the value of the given property name into an integer
        value.
        """

        return int( self.__stack[-1][propertyName] )

    def _propertyToBool( self, propertyName ):
        """
        Converts the value of the given property name into a boolean
        value.
        """

        return stringToBool( self.__stack[-1][propertyName] )

    def _propertyToColor( self, propertyName ):
        """
        Converts the value of the given property name into a (r, g, b,
        a) color tuple.
        """

        return colorHashToRgba( self.__stack[-1][propertyName] )

    def _property( self, propertyName ):
        """
        Returns the value of the given property name as a string.
        """

        return self.__stack[-1][propertyName]

    def makeNewDocument( self ):
        """
        Makes a new document with the current style.
        """

        document = textlayout.Document(
            width = self._propertyToPoints("width"),
            marginTop = self._propertyToPoints("margin_top"),
            marginBottom = self._propertyToPoints("margin_bottom"),
            )

        return document

    def makeNewBlock( self ):
        """
        Makes a new block with the current style.
        """

        block = textlayout.Block(
            width = self._propertyToPoints("width"),
            lineHeight = self._propertyToPoints("line_height"),
            marginTop = self._propertyToPoints("margin_top"),
            marginBottom = self._propertyToPoints("margin_bottom"),
            textAlign = self._property("text_align"),
            maxLines = self._propertyToInt("max_lines"),
            ellipsify = self._propertyToBool("ellipsify")
            )

        return block

    def makeNewGlyphs( self, characters ):
        """
        Makes new glyphs with the current style.
        """

        glyphs = []

        fontObj = font.Font.get(
            self._property( "font_family" ),
            self._propertyToPoints( "font_size" ),
            self._property( "font_style" ) == "italic"
            )

        color = self._propertyToColor( "color" )

        for char in characters:
            fontGlyph = fontObj.getGlyph( char )
            glyph = textlayout.Glyph(
                fontGlyph,
                color,
                )
            glyphs.append( glyph )

        return glyphs

# ----------------------------------------------------------------------------
# XML Markup Tag Aliases
# ----------------------------------------------------------------------------

class XmlMarkupTagAliases:
    """
    Implementation of XML markup tag aliases, a simple feature that
    allows one tag name to be aliased as another tag name.
    """

    def __init__( self ):
        """
        Creates an empty set of tag aliases.
        """

        self._aliases = {}

    def add( self, name, baseElement ):
        """
        Adds a tag alias; 'name' will now be an alias for
        'baseElement'.

        The following example sets up tag aliases for <p> and
        <caption> tags:

        >>> tagAliases = XmlMarkupTagAliases()
        >>> tagAliases.add( 'p', baseElement = 'block' )
        >>> tagAliases.add( 'caption', baseElement = 'block' )

        It should also be noted the same tag alias can't be defined
        more than once, e.g.:

        >>> tagAliases.add( 'foo', baseElement = 'inline' )
        >>> tagAliases.add( 'foo', baseElement = 'block' )
        Traceback (most recent call last):
        ...
        ValueError: Tag alias 'foo' already exists.
        """

        if self._aliases.has_key( name ):
            raise ValueError( "Tag alias '%s' already exists." % name )

        self._aliases[name] = baseElement

    def get( self, name ):
        """
        Retrieves the tag that the given name is an alias for.

        Example:

        >>> tagAliases = XmlMarkupTagAliases()
        >>> tagAliases.add( 'p', baseElement = 'block' )
        >>> tagAliases.get( 'p' )
        'block'
        >>> tagAliases.get( 'caption' )
        Traceback (most recent call last):
        ...
        KeyError: 'caption'
        """

        return self._aliases[name]

    def has( self, name ):
        """
        Returns whether or not the given name is an alias for a tag.

        Example:

        >>> tagAliases = XmlMarkupTagAliases()
        >>> tagAliases.add( 'p', baseElement = 'block' )
        >>> tagAliases.has( 'p' )
        True
        >>> tagAliases.has( 'caption' )
        False
        """

        return self._aliases.has_key( name )

# ----------------------------------------------------------------------------
# XML Markup Content Handler
# ----------------------------------------------------------------------------

class _XmlMarkupHandler( xml.sax.handler.ContentHandler ):
    """
    XML content handler for XML text layout markup.
    """

    def __init__( self, styleRegistry, tagAliases=None ):
        """
        Initializes the content handler with the given style registry
        and tag aliases.
        """

        xml.sax.handler.ContentHandler.__init__( self )
        self.styleRegistry = styleRegistry

        if not tagAliases:
            tagAliases = XmlMarkupTagAliases()
        self.tagAliases = tagAliases

    def startDocument( self ):
        """
        Called by the XML parser at the beginning of parsing the XML
        document.
        """

        self.style = CascadingStyleStack()
        self.document = None
        self.block = None
        self.glyphs = None

    def _pushStyle( self, name, attrs ):
        """
        Sets the current style to the style defined by the "style"
        attribute of the given tag.  If that style doesn't exist, we
        use the style named by the tag.
        """

        styleDict = None

        styleAttr = attrs.get( "style", None )
        if styleAttr:
            styleDict = self.styleRegistry.findMatch( styleAttr )

        if styleDict == None:
            styleDict = self.styleRegistry.findMatch( name )

        if styleDict == None:
            raise ValueError, "No style found for: %s, %s" % (
                name,
                str( styleAttr )
                )

        self.style.push( styleDict )

    def startElement( self, name, attrs ):
        """
        Handles the beginning of an XML element.
        """

        if name == "document":
            self._pushStyle( name, attrs )
            self.document = self.style.makeNewDocument()
        elif name == "block":
            if not self.document:
                raise XmlMarkupUnexpectedElementError(
                    "Block element encountered outside of document element."
                    )
            self._pushStyle( name, attrs )
            self.block = self.style.makeNewBlock()
            self.glyphs = []
        elif name == "inline":
            if not self.block:
                raise XmlMarkupUnexpectedElementError(
                    "Inline element encountered outside of block element."
                    )
            self._pushStyle( name, attrs )
        elif self.tagAliases.has( name ):
            baseElement = self.tagAliases.get( name )
            self.startElement( baseElement, { "style" : name } )
        else:
            raise XmlMarkupUnknownElementError( name )

    def endElement( self, name ):
        """
        Handles the end of an XML element.
        """

        if name == "document":
            self.style.pop()
            self.document.layout()
        elif name == "block":
            ellipsisGlyph = self.style.makeNewGlyphs( u"\u2026" )[0]
            self.block.setEllipsisGlyph( ellipsisGlyph )

            self.style.pop()
            self.block.addGlyphs( self.glyphs )
            self.document.addBlock( self.block )
            self.block = None
            self.glyphs = None
        elif name == "inline":
            self.style.pop()
        else:
            baseElement = self.tagAliases.get( name )
            self.endElement( baseElement )

    def characters( self, content ):
        """
        Handles XML character data.
        """

        if self.glyphs != None:
            self.glyphs.extend( self.style.makeNewGlyphs(content) )
        else:
            # Hopefully, the content is just whitespace...
            content = content.strip()
            if content:
                raise XmlMarkupUnexpectedCharactersError( content )

class XmlMarkupUnknownElementError( Exception ):
    """
    Exception raised when an unknown XML text layout markup element is
    encountered.
    """

    pass

class XmlMarkupUnexpectedElementError( Exception ):
    """
    Exception raised when a recognized, but unexpected XML text layout
    markup element is encountered.
    """

    pass

class XmlMarkupUnexpectedCharactersError( Exception ):
    """
    Exception raised when characters are encountered in XML text
    layout in a place where they're not expected.
    """

    pass

# ----------------------------------------------------------------------------
# XML Markup to Document Conversion
# ----------------------------------------------------------------------------

def xmlMarkupToDocument( text, styleRegistry, tagAliases=None ):
    """
    Converts the given XML text into a textlayout.Document object that
    has been fully laid out and is ready for rendering, using the
    given style registry and tag alises.
    """

    import re

    # Convert all occurrences of multiple contiguous whitespace
    # characters to a single space character.
    text = re.sub( r"\s+", " ", text )

    # Convert all occurrences of the non-breaking space character
    # entity reference into its unicode equivalent (the SAX XML parser
    # doesn't recognize this one on its own, sadly).
    text = text.replace( " ", NON_BREAKING_SPACE )

    xmlMarkupHandler = _XmlMarkupHandler( styleRegistry, tagAliases )
    text = text.encode( "ascii", "xmlcharrefreplace" )
    xml.sax.parseString( text, xmlMarkupHandler )
    return xmlMarkupHandler.document


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//

package org.ecloudmanager.tmrk.cloudapi.model;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;

/**
 *
Java class for LinuxCustomizationType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="LinuxCustomizationType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="NetworkSettings" type="{}NetworkSettingsType"/>
 *         <element name="SshKey" type="{}ReferenceType" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LinuxCustomizationType", propOrder = {
    "networkSettings",
    "sshKey"
})
public class LinuxCustomizationType {

    @XmlElement(name = "NetworkSettings", required = true, nillable = true)
    protected NetworkSettingsType networkSettings;
    @XmlElementRef(name = "SshKey", type = JAXBElement.class, required = false)
    protected JAXBElement<ReferenceType> sshKey;

    /**
     * Gets the value of the networkSettings property.
     *
     * @return
     *     possible object is
     *     {@link NetworkSettingsType }
     *
     */
    public NetworkSettingsType getNetworkSettings() {
        return networkSettings;
    }

    /**
     * Sets the value of the networkSettings property.
     *
     * @param value
     *     allowed object is
     *     {@link NetworkSettingsType }
     *
     */
    public void setNetworkSettings(NetworkSettingsType value) {
        this.networkSettings = value;
    }

    /**
     * Gets the value of the sshKey property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
     *
     */
    public JAXBElement<ReferenceType> getSshKey() {
        return sshKey;
    }

    /**
     * Sets the value of the sshKey property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
     *
     */
    public void setSshKey(JAXBElement<ReferenceType> value) {
        this.sshKey = value;
    }

}

redpajama_set_name: RedPajamaGithub


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************

using Microsoft.SDKSamples.Kitchen;

using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;

namespace WRLInProcessWinRTComponent
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class OvenClient : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        public OvenClient()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// Use the custom Oven and Bread Windows Runtime components.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            Dimensions dimensions;
            dimensions.Width = 2;
            dimensions.Height = 2;
            dimensions.Depth = 2;

            // Component Creation
            Oven myOven = new Oven(dimensions);

            // Getters and setters are accessed using property syntax
            OvenClientOutput.Text += "Oven volume is: " + myOven.Volume.ToString() + "\n";

            // Register even listeners
            myOven.BreadBaked += new TypedEventHandler<Oven, Bread>(BreadCompletedHandler1);
            myOven.BreadBaked += new TypedEventHandler<Oven, Bread>(BreadCompletedHandler2);
            myOven.BreadBaked += new TypedEventHandler<Oven, Bread>(BreadCompletedHandler3);

            // Unregister from an event using the -= syntax and a delegate instance
            myOven.BreadBaked -= new TypedEventHandler<Oven, Bread>(BreadCompletedHandler3);

            // Bake a loaf of bread. This will trigger the BreadBaked event.
            myOven.BakeBread("Sourdough");

            // Trigger the event again with a different preheat time
            myOven.ConfigurePreheatTemperature(OvenTemperature.High);
            myOven.BakeBread("Wheat");
        }

        async private void BreadCompletedHandler1(Oven oven, Bread bread)
        {
            Action updateOutputText = () =>
                {
                    OvenClientOutput.Text += "Event Handler 1: Invoked\n";
                    OvenClientOutput.Text += "Event Handler 1: Oven volume is: " + oven.Volume.ToString() + "\n";
                    OvenClientOutput.Text += "Event Handler 1: Bread flavor is: " + bread.Flavor + "\n";
                };

            if (OvenClientOutput.Dispatcher.HasThreadAccess)
            {
                // If the current thread is the UI thread then execute the lambda.
                updateOutputText();
            }
            else
            {
                // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
                await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
            }
        }

        async private void BreadCompletedHandler2(Oven oven, Bread bread)
        {
            Action updateOutputText = () =>
                {
                    OvenClientOutput.Text += "Event Handler 2: Invoked\n";
                };

            if (OvenClientOutput.Dispatcher.HasThreadAccess)
            {
                // If the current thread is the UI thread then execute the lambda.
                updateOutputText();
            }
            else
            {
                // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
                await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
            }
        }

        async private void BreadCompletedHandler3(Oven oven, Bread bread)
        {
            // Event handler 3 was removed and will not be invoked
            Action updateOutputText = () =>
                {
                    OvenClientOutput.Text += "Event Handler 3: Invoked\n";
                };

            if (OvenClientOutput.Dispatcher.HasThreadAccess)
            {
                // If the current thread is the UI thread then execute the lambda.
                updateOutputText();
            }
            else
            {
                // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
                await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
            }
        }
    }
}


text:
/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#ifndef SRC_DIRECT_RES_SPEC_H_
#define SRC_DIRECT_RES_SPEC_H_

#include <bm/bm_sim/meters.h>
#include <PI/pi.h>

#include <vector>

namespace pibmv2 {

void convert_from_counter_data(const pi_counter_data_t *from,
                               uint64_t *bytes, uint64_t *packets);

void convert_to_counter_data(pi_counter_data_t *to,
                             uint64_t bytes, uint64_t packets);

std::vector<bm::Meter::rate_config_t> convert_from_meter_spec(
    const pi_meter_spec_t *meter_spec);

void convert_to_meter_spec(const pi_p4info_t *p4info, pi_p4_id_t m_id,
                           pi_meter_spec_t *meter_spec,
                           const std::vector<bm::Meter::rate_config_t> &rates);

}  // namespace pibmv2

#endif  // SRC_DIRECT_RES_SPEC_H_


text:
if True:
    if True:
        pass
    <selection>foo</selection> = 2


text:
package org.apereo.cas.oidc.token;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.principal.WebApplicationServiceFactory;
import org.apereo.cas.oidc.AbstractOidcTests;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import org.apereo.cas.support.oauth.util.OAuth20Utils;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.ticket.accesstoken.AccessToken;
import org.apereo.cas.util.CollectionUtils;

import lombok.val;
import org.junit.jupiter.api.Test;
import org.pac4j.core.context.Pac4jConstants;
import org.pac4j.core.profile.CommonProfile;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link OidcIdTokenGeneratorServiceTests}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
public class OidcIdTokenGeneratorServiceTests extends AbstractOidcTests {
    @Test
    public void verifyTokenGeneration() {
        val request = new MockHttpServletRequest();
        val profile = new CommonProfile();
        profile.setClientName("OIDC");
        profile.setId("casuser");
        request.setAttribute(Pac4jConstants.USER_PROFILES, profile);

        val response = new MockHttpServletResponse();

        val tgt = mock(TicketGrantingTicket.class);
        val callback = casProperties.getServer().getPrefix()
            + OAuth20Constants.BASE_OAUTH20_URL + '/'
            + OAuth20Constants.CALLBACK_AUTHORIZE_URL_DEFINITION;

        val service = new WebApplicationServiceFactory().createService(callback);
        when(tgt.getServices()).thenReturn(CollectionUtils.wrap("service", service));
        when(tgt.getAuthentication()).thenReturn(CoreAuthenticationTestUtils.getAuthentication());

        val accessToken = mock(AccessToken.class);
        when(accessToken.getAuthentication()).thenReturn(CoreAuthenticationTestUtils.getAuthentication("casuser"));
        when(accessToken.getTicketGrantingTicket()).thenReturn(tgt);
        when(accessToken.getId()).thenReturn(getClass().getSimpleName());

        val idToken = oidcIdTokenGenerator.generate(request, response, accessToken, 30,
            OAuth20ResponseTypes.CODE, OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, "clientid"));
        assertNotNull(idToken);
    }

    @Test
    public void verifyTokenGenerationFailsWithoutProfile() {
        assertThrows(IllegalArgumentException.class, () -> {
            val request = new MockHttpServletRequest();
            val response = new MockHttpServletResponse();
            val accessToken = mock(AccessToken.class);
            oidcIdTokenGenerator.generate(request, response, accessToken, 30,
                OAuth20ResponseTypes.CODE,
                OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, "clientid"));
        });
    }
}


text:
import play.api.GlobalSettings
import play.api.mvc.WithFilters
import play.filters.gzip.GzipFilter

object Global extends WithFilters(new GzipFilter(shouldGzip =
  (request, response) => {
    val contentType = response.headers.get("Content-Type")
    contentType.exists(_.startsWith("text/html")) || request.path.endsWith("jsroutes.js")
  }
)) with GlobalSettings


text:
package io.confluent.ksql.parser.tree;

import org.apache.kafka.streams.kstream.Initializer;
import org.apache.kafka.streams.kstream.KGroupedStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;

import java.util.Optional;

import io.confluent.ksql.GenericRow;
import io.confluent.ksql.function.UdafAggregator;

public abstract class KsqlWindowExpression extends Node {

  protected KsqlWindowExpression(Optional<NodeLocation> location) {
    super(location);
  }

  public abstract KTable applyAggregate(final KGroupedStream groupedStream,
                                        final Initializer initializer,
                                        final UdafAggregator aggregator,
                                        final Materialized<String, GenericRow, ?> materialized);
}


text:
These guidelines are universal for the entire [Neodroid](https://github.com/sintefneodroid) Platform

## Pull Requests
We welcome pull requests.

1. Fork the repo and create your branch from `develop`, we are using the git flow branching model.
2. If you've added code that should be tested, add tests.
3. If you've changed APIs, update the documentation.

## Issues
We use GitHub issues to track public bugs. Please ensure your description is
clear and has sufficient instructions to be able to reproduce the issue.

## Coding Style
...

## License
By contributing to the [Neodroid](https://github.com/sintefneodroid) platform, you agree that your contributions will be licensed under the LICENSE file in the root directory of this repository.


text:
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;

namespace System.Linq.Parallel
{
    /// <summary>
    /// This enumerator handles the actual coordination among partitions required to
    /// accomplish the repartitioning operation, as explained above.  In addition to that,
    /// it tracks order keys so that order preservation can flow through the enumerator.
    /// </summary>
    /// <typeparam name="TInputOutput">The kind of elements.</typeparam>
    /// <typeparam name="THashKey">The key used to distribute elements.</typeparam>
    /// <typeparam name="TOrderKey">The kind of keys found in the source.</typeparam>
    internal class OrderedHashRepartitionEnumerator<TInputOutput, THashKey, TOrderKey> : QueryOperatorEnumerator<Pair<TInputOutput, THashKey>, TOrderKey>
    {
        private const int ENUMERATION_NOT_STARTED = -1; // Sentinel to note we haven't begun enumerating yet.

        private readonly int _partitionCount; // The number of partitions.
        private readonly int _partitionIndex; // Our unique partition index.
        private readonly Func<TInputOutput, THashKey> _keySelector; // A key-selector function.
        private readonly HashRepartitionStream<TInputOutput, THashKey, TOrderKey> _repartitionStream; // A repartitioning stream.
        private readonly ListChunk<Pair<TInputOutput, THashKey>>[][] _valueExchangeMatrix; // Matrix to do inter-task communication of values.
        private readonly ListChunk<TOrderKey>[][] _keyExchangeMatrix; // Matrix to do inter-task communication of order keys.
        private readonly QueryOperatorEnumerator<TInputOutput, TOrderKey> _source; // The immediate source of data.
        private CountdownEvent _barrier; // Used to signal and wait for repartitions to complete.
        private readonly CancellationToken _cancellationToken; // A token for canceling the process.
        private Mutables _mutables; // Mutable fields for this enumerator.

        private class Mutables
        {
            internal int _currentBufferIndex; // Current buffer index.
            internal ListChunk<Pair<TInputOutput, THashKey>> _currentBuffer; // The buffer we're currently enumerating.
            internal ListChunk<TOrderKey> _currentKeyBuffer; // The buffer we're currently enumerating.
            internal int _currentIndex; // Current index into the buffer.

            internal Mutables()
            {
                _currentBufferIndex = ENUMERATION_NOT_STARTED;
            }
        }

        //---------------------------------------------------------------------------------------
        // Creates a new repartitioning enumerator.
        //
        // Arguments:
        //     source            - the data stream from which to pull elements
        //     useOrdinalOrderPreservation - whether order preservation is required
        //     partitionCount    - total number of partitions
        //     partitionIndex    - this operator's unique partition index
        //     repartitionStream - the stream object to use for partition selection
        //     barrier           - a latch used to signal task completion
        //     buffers           - a set of buffers for inter-task communication
        //

        internal OrderedHashRepartitionEnumerator(
            QueryOperatorEnumerator<TInputOutput, TOrderKey> source, int partitionCount, int partitionIndex,
            Func<TInputOutput, THashKey> keySelector, OrderedHashRepartitionStream<TInputOutput, THashKey, TOrderKey> repartitionStream, CountdownEvent barrier,
            ListChunk<Pair<TInputOutput, THashKey>>[][] valueExchangeMatrix, ListChunk<TOrderKey>[][] keyExchangeMatrix, CancellationToken cancellationToken)
        {
            Debug.Assert(source != null);
            Debug.Assert(keySelector != null || typeof(THashKey) == typeof(NoKeyMemoizationRequired));
            Debug.Assert(repartitionStream != null);
            Debug.Assert(barrier != null);
            Debug.Assert(valueExchangeMatrix != null);
            Debug.Assert(valueExchangeMatrix.GetLength(0) == partitionCount, "expected square matrix of buffers (NxN)");
            Debug.Assert(partitionCount > 0 && valueExchangeMatrix[0].Length == partitionCount, "expected square matrix of buffers (NxN)");
            Debug.Assert(0 <= partitionIndex && partitionIndex < partitionCount);

            _source = source;
            _partitionCount = partitionCount;
            _partitionIndex = partitionIndex;
            _keySelector = keySelector;
            _repartitionStream = repartitionStream;
            _barrier = barrier;
            _valueExchangeMatrix = valueExchangeMatrix;
            _keyExchangeMatrix = keyExchangeMatrix;
            _cancellationToken = cancellationToken;
        }

        //---------------------------------------------------------------------------------------
        // Retrieves the next element from this partition.  All repartitioning operators across
        // all partitions cooperate in a barrier-style algorithm.  The first time an element is
        // requested, the repartitioning operator will enter the 1st phase: during this phase, it
        // scans its entire input and compute the destination partition for each element.  During
        // the 2nd phase, each partition scans the elements found by all other partitions for
        // it, and yield this to callers.  The only synchronization required is the barrier itself
        // -- all other parts of this algorithm are synchronization-free.
        //
        // Notes: One rather large penalty that this algorithm incurs is higher memory usage and a
        // larger time-to-first-element latency, at least compared with our old implementation; this
        // happens because all input elements must be fetched before we can produce a single output
        // element.  In many cases this isn't too terrible: e.g. a GroupBy requires this to occur
        // anyway, so having the repartitioning operator do so isn't complicating matters much at all.
        //

        internal override bool MoveNext(ref Pair<TInputOutput, THashKey> currentElement, ref TOrderKey currentKey)
        {
            if (_partitionCount == 1)
            {
                TInputOutput current = default(TInputOutput);

                // If there's only one partition, no need to do any sort of exchanges.
                if (_source.MoveNext(ref current, ref currentKey))
                {
                    currentElement = new Pair<TInputOutput, THashKey>(
                        current, _keySelector == null ? default(THashKey) : _keySelector(current));
                    return true;
                }

                return false;
            }

            Mutables mutables = _mutables;
            if (mutables == null)
                mutables = _mutables = new Mutables();

            // If we haven't enumerated the source yet, do that now.  This is the first phase
            // of a two-phase barrier style operation.
            if (mutables._currentBufferIndex == ENUMERATION_NOT_STARTED)
            {
                EnumerateAndRedistributeElements();
                Debug.Assert(mutables._currentBufferIndex != ENUMERATION_NOT_STARTED);
            }

            // Once we've enumerated our contents, we can then go back and walk the buffers that belong
            // to the current partition.  This is phase two.  Note that we slyly move on to the first step
            // of phase two before actually waiting for other partitions.  That's because we can enumerate
            // the buffer we wrote to above, as already noted.
            while (mutables._currentBufferIndex < _partitionCount)
            {
                // If the queue is non-null and still has elements, yield them.
                if (mutables._currentBuffer != null)
                {
                    Debug.Assert(mutables._currentKeyBuffer != null);

                    if (++mutables._currentIndex < mutables._currentBuffer.Count)
                    {
                        // Return the current element.
                        currentElement = mutables._currentBuffer._chunk[mutables._currentIndex];
                        Debug.Assert(mutables._currentKeyBuffer != null, "expected same # of buffers/key-buffers");
                        currentKey = mutables._currentKeyBuffer._chunk[mutables._currentIndex];
                        return true;
                    }
                    else
                    {
                        // If the chunk is empty, advance to the next one (if any).
                        mutables._currentIndex = ENUMERATION_NOT_STARTED;
                        mutables._currentBuffer = mutables._currentBuffer.Next;
                        mutables._currentKeyBuffer = mutables._currentKeyBuffer.Next;
                        Debug.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count > 0);
                        Debug.Assert((mutables._currentBuffer == null) == (mutables._currentKeyBuffer == null));
                        Debug.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count == mutables._currentKeyBuffer.Count);
                        continue; // Go back around and invoke this same logic.
                    }
                }

                // We're done with the current partition.  Slightly different logic depending on whether
                // we're on our own buffer or one that somebody else found for us.
                if (mutables._currentBufferIndex == _partitionIndex)
                {
                    // We now need to wait at the barrier, in case some other threads aren't done.
                    // Once we wake up, we reset our index and will increment it immediately after.
                    _barrier.Wait(_cancellationToken);
                    mutables._currentBufferIndex = ENUMERATION_NOT_STARTED;
                }

                // Advance to the next buffer.
                mutables._currentBufferIndex++;
                mutables._currentIndex = ENUMERATION_NOT_STARTED;

                if (mutables._currentBufferIndex == _partitionIndex)
                {
                    // Skip our current buffer (since we already enumerated it).
                    mutables._currentBufferIndex++;
                }

                // Assuming we're within bounds, retrieve the next buffer object.
                if (mutables._currentBufferIndex < _partitionCount)
                {
                    mutables._currentBuffer = _valueExchangeMatrix[mutables._currentBufferIndex][_partitionIndex];
                    mutables._currentKeyBuffer = _keyExchangeMatrix[mutables._currentBufferIndex][_partitionIndex];
                }
            }

            // We're done. No more buffers to enumerate.
            return false;
        }

        //---------------------------------------------------------------------------------------
        // Called when this enumerator is first enumerated; it must walk through the source
        // and redistribute elements to their slot in the exchange matrix.
        //

        private void EnumerateAndRedistributeElements()
        {
            Mutables mutables = _mutables;
            Debug.Assert(mutables != null);

            ListChunk<Pair<TInputOutput, THashKey>>[] privateBuffers = new ListChunk<Pair<TInputOutput, THashKey>>[_partitionCount];
            ListChunk<TOrderKey>[] privateKeyBuffers = new ListChunk<TOrderKey>[_partitionCount];

            TInputOutput element = default(TInputOutput);
            TOrderKey key = default(TOrderKey);
            int loopCount = 0;
            while (_source.MoveNext(ref element, ref key))
            {
                if ((loopCount++ & CancellationState.POLL_INTERVAL) == 0)
                    CancellationState.ThrowIfCanceled(_cancellationToken);

                // Calculate the element's destination partition index, placing it into the
                // appropriate buffer from which partitions will later enumerate.
                int destinationIndex;
                THashKey elementHashKey = default(THashKey);
                if (_keySelector != null)
                {
                    elementHashKey = _keySelector(element);
                    destinationIndex = _repartitionStream.GetHashCode(elementHashKey) % _partitionCount;
                }
                else
                {
                    Debug.Assert(typeof(THashKey) == typeof(NoKeyMemoizationRequired));
                    destinationIndex = _repartitionStream.GetHashCode(element) % _partitionCount;
                }

                Debug.Assert(0 <= destinationIndex && destinationIndex < _partitionCount,
                                "destination partition outside of the legal range of partitions");

                // Get the buffer for the destination partition, lazily allocating if needed.  We maintain
                // this list in our own private cache so that we avoid accessing shared memory locations
                // too much.  In the original implementation, we'd access the buffer in the matrix ([N,M],
                // where N is the current partition and M is the destination), but some rudimentary
                // performance profiling indicates copying at the end performs better.
                ListChunk<Pair<TInputOutput, THashKey>> buffer = privateBuffers[destinationIndex];
                ListChunk<TOrderKey> keyBuffer = privateKeyBuffers[destinationIndex];
                if (buffer == null)
                {
                    const int INITIAL_PRIVATE_BUFFER_SIZE = 128;
                    Debug.Assert(keyBuffer == null);
                    privateBuffers[destinationIndex] = buffer = new ListChunk<Pair<TInputOutput, THashKey>>(INITIAL_PRIVATE_BUFFER_SIZE);
                    privateKeyBuffers[destinationIndex] = keyBuffer = new ListChunk<TOrderKey>(INITIAL_PRIVATE_BUFFER_SIZE);
                }

                buffer.Add(new Pair<TInputOutput, THashKey>(element, elementHashKey));
                keyBuffer.Add(key);
            }

            // Copy the local buffers to the shared space and then signal to other threads that
            // we are done.  We can then immediately move on to enumerating the elements we found
            // for the current partition before waiting at the barrier.  If we found a lot, we will
            // hopefully never have to physically wait.
            for (int i = 0; i < _partitionCount; i++)
            {
                _valueExchangeMatrix[_partitionIndex][i] = privateBuffers[i];
                _keyExchangeMatrix[_partitionIndex][i] = privateKeyBuffers[i];
            }

            _barrier.Signal();

            // Begin at our own buffer.
            mutables._currentBufferIndex = _partitionIndex;
            mutables._currentBuffer = privateBuffers[_partitionIndex];
            mutables._currentKeyBuffer = privateKeyBuffers[_partitionIndex];
            mutables._currentIndex = ENUMERATION_NOT_STARTED;
        }

        protected override void Dispose(bool disposing)
        {
            if (_barrier != null)
            {
                // Since this enumerator is being disposed, we will decrement the barrier,
                // in case other enumerators will wait on the barrier.
                if (_mutables == null || (_mutables._currentBufferIndex == ENUMERATION_NOT_STARTED))
                {
                    _barrier.Signal();
                    _barrier = null;
                }

                _source.Dispose();
            }
        }
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    $CI = & get_instance();

?>

<?php
foreach($varieties as $variety)
{
    ?>

        <input type="checkbox" name="variety_ids[]" value="<?php echo $variety['variety_id']; ?>"><?php echo $variety['variety_name'].' ('.$variety['whose'].')'; ?>

<?php
}
?>


text:
'use strict';

import intersection from 'lodash/array/intersection';
import flatten from 'lodash/array/flatten';
import unique from 'lodash/array/intersection';

/* needs subscription sets to be defined somewhere */
/* an event with a subscription set will only fire once */
/* for all of the changes in the set. */

export default ({getHashParams, subscriptionsByProperty, subscriptionsByUUID, keysWithChangedValues, event}) => {
  /* get the new params object */
  /* get the old params object */
  let oldParams = getHashParams(event.oldURL);
  let newParams = getHashParams(event.newURL);

  let subscribedKeys = Object.keys(subscriptionsByProperty.subscriptions);

  /* identify the keys with changed values */
  let keysWithChanges = keysWithChangedValues(oldParams, newParams);

  let keysWithSubscribedEvents = intersection(keysWithChanges, subscribedKeys);

  // keysWithSubscribedEvents.
  /* loop through all of the subscribedEvent names looking */
  /* for differences between newParams and oldParams */
  let subscriptionUUIDs = keysWithSubscribedEvents.map(key => {
    return Object.keys(subscriptionsByProperty.subscriptions[key]);
  });

  subscriptionUUIDs = unique(flatten(subscriptionUUIDs));

  /* trigger events for each of the events found */

  let subscriptions = subscriptionUUIDs.map(subscriptionUUID => subscriptionsByUUID[subscriptionUUID]);

  subscriptions.forEach(subscription => { subscription.callback(newParams); });
};


text:
ACCEPTED

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

#### Published in
J. Proc. Linn. Soc. , Bot. 7:69. 1863 ("1864")

#### Original name
null

### Remarks
null


text:
import getElementsByTagName from '../common/getElementsByTagName';
import once from '../common/once';

function isBroken(img) {
  return img.complete && img.naturalHeight === 0;
}

function imgToPng(img) {
  return img.src
    .replace(
      /^http:\/\/cdn\.fallensword\.com\/skin\/gold_button\.gif$/,
      'https://cdn2.fallensword.com/currency/0.png',
    ) // shop currency images
    .replace(/\.jpg$/, '.png') // creature & master realm image
    .replace(/^http:/, 'https:') // creature image
    .replace(/\.gif$/, '.png'); // master realm images
}

export default function imgFix() {
  const imgs = getElementsByTagName('img');
  for (const img of imgs) {
    // Before image load
    once(img, 'error', () => { img.src = imgToPng(img); });
    // After image load
    if (isBroken(img)) { img.src = imgToPng(img); }
  }
}


text:
			<?php get_template_part('templates/logo');?>
			<?php get_template_part('templates/header-top-navbar');?>

				<?php get_template_part('templates/carousel'); ?>


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Subjects;

namespace System.Reactive.Linq
{
    internal class QueryLanguageEx : IQueryLanguageEx
    {
        #region Create

        public virtual IObservable<TResult> Create<TResult>(Func<IObserver<TResult>, IEnumerable<IObservable<object>>> iteratorMethod)
        {
            return new AnonymousObservable<TResult>(observer =>
                iteratorMethod(observer).Concat().Subscribe(_ => { }, observer.OnError, observer.OnCompleted));
        }

        public virtual IObservable<Unit> Create(Func<IEnumerable<IObservable<object>>> iteratorMethod)
        {
            return new AnonymousObservable<Unit>(observer =>
                iteratorMethod().Concat().Subscribe(_ => { }, observer.OnError, observer.OnCompleted));
        }

        #endregion

        #region Expand

        public virtual IObservable<TSource> Expand<TSource>(IObservable<TSource> source, Func<TSource, IObservable<TSource>> selector, IScheduler scheduler)
        {
            return new AnonymousObservable<TSource>(observer =>
            {
                var outGate = new object();
                var q = new Queue<IObservable<TSource>>();
                var m = new SerialDisposable();
                var d = new CompositeDisposable { m };
                var activeCount = 0;
                var isAcquired = false;

                var ensureActive = default(Action);

                ensureActive = () =>
                {
                    var isOwner = false;

                    lock (q)
                    {
                        if (q.Count > 0)
                        {
                            isOwner = !isAcquired;
                            isAcquired = true;
                        }
                    }

                    if (isOwner)
                    {
                        m.Disposable = scheduler.Schedule(self =>
                        {
                            var work = default(IObservable<TSource>);

                            lock (q)
                            {
                                if (q.Count > 0)
                                    work = q.Dequeue();
                                else
                                {
                                    isAcquired = false;
                                    return;
                                }
                            }

                            var m1 = new SingleAssignmentDisposable();
                            d.Add(m1);
                            m1.Disposable = work.Subscribe(
                                x =>
                                {
                                    lock (outGate)
                                        observer.OnNext(x);

                                    var result = default(IObservable<TSource>);
                                    try
                                    {
                                        result = selector(x);
                                    }
                                    catch (Exception exception)
                                    {
                                        lock (outGate)
                                            observer.OnError(exception);
                                    }

                                    lock (q)
                                    {
                                        q.Enqueue(result);
                                        activeCount++;
                                    }

                                    ensureActive();
                                },
                                exception =>
                                {
                                    lock (outGate)
                                        observer.OnError(exception);
                                },
                                () =>
                                {
                                    d.Remove(m1);

                                    var done = false;
                                    lock (q)
                                    {
                                        activeCount--;
                                        if (activeCount == 0)
                                            done = true;
                                    }
                                    if (done)
                                        lock (outGate)
                                            observer.OnCompleted();
                                });
                            self();
                        });
                    }
                };

                lock (q)
                {
                    q.Enqueue(source);
                    activeCount++;
                }
                ensureActive();

                return d;
            });
        }

        public virtual IObservable<TSource> Expand<TSource>(IObservable<TSource> source, Func<TSource, IObservable<TSource>> selector)
        {
            return source.Expand(selector, SchedulerDefaults.Iteration);
        }

        #endregion

        #region ForkJoin

        public virtual IObservable<TResult> ForkJoin<TFirst, TSecond, TResult>(IObservable<TFirst> first, IObservable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
        {
            return Combine<TFirst, TSecond, TResult>(first, second, (observer, leftSubscription, rightSubscription) =>
            {
                var leftStopped = false;
                var rightStopped = false;
                var hasLeft = false;
                var hasRight = false;
                var lastLeft = default(TFirst);
                var lastRight = default(TSecond);

                return new BinaryObserver<TFirst, TSecond>(
                    left =>
                    {
                        switch (left.Kind)
                        {
                            case NotificationKind.OnNext:
                                hasLeft = true;
                                lastLeft = left.Value;
                                break;
                            case NotificationKind.OnError:
                                rightSubscription.Dispose();
                                observer.OnError(left.Exception);
                                break;
                            case NotificationKind.OnCompleted:
                                leftStopped = true;
                                if (rightStopped)
                                {
                                    if (!hasLeft)
                                        observer.OnCompleted();
                                    else if (!hasRight)
                                        observer.OnCompleted();
                                    else
                                    {
                                        TResult result;
                                        try
                                        {
                                            result = resultSelector(lastLeft, lastRight);
                                        }
                                        catch (Exception exception)
                                        {
                                            observer.OnError(exception);
                                            return;
                                        }
                                        observer.OnNext(result);
                                        observer.OnCompleted();
                                    }
                                }
                                break;
                        }
                    },
                    right =>
                    {
                        switch (right.Kind)
                        {
                            case NotificationKind.OnNext:
                                hasRight = true;
                                lastRight = right.Value;
                                break;
                            case NotificationKind.OnError:
                                leftSubscription.Dispose();
                                observer.OnError(right.Exception);
                                break;
                            case NotificationKind.OnCompleted:
                                rightStopped = true;
                                if (leftStopped)
                                {
                                    if (!hasLeft)
                                        observer.OnCompleted();
                                    else if (!hasRight)
                                        observer.OnCompleted();
                                    else
                                    {
                                        TResult result;
                                        try
                                        {
                                            result = resultSelector(lastLeft, lastRight);
                                        }
                                        catch (Exception exception)
                                        {
                                            observer.OnError(exception);
                                            return;
                                        }
                                        observer.OnNext(result);
                                        observer.OnCompleted();
                                    }
                                }
                                break;
                        }
                    });
            });
        }

        public virtual IObservable<TSource[]> ForkJoin<TSource>(params IObservable<TSource>[] sources)
        {
            return sources.ForkJoin();
        }

        public virtual IObservable<TSource[]> ForkJoin<TSource>(IEnumerable<IObservable<TSource>> sources)
        {
            return new AnonymousObservable<TSource[]>(subscriber =>
            {
                var allSources = sources.ToArray();
                var count = allSources.Length;

                if (count == 0)
                {
                    subscriber.OnCompleted();
                    return Disposable.Empty;
                }

                var group = new CompositeDisposable(allSources.Length);
                var gate = new object();

                var finished = false;
                var hasResults = new bool[count];
                var hasCompleted = new bool[count];
                var results = new List<TSource>(count);

                lock (gate)
                {
                    for (var index = 0; index < count; index++)
                    {
                        var currentIndex = index;
                        var source = allSources[index];
                        results.Add(default(TSource));
                        group.Add(source.Subscribe(
                            value =>
                            {
                                lock (gate)
                                {
                                    if (!finished)
                                    {
                                        hasResults[currentIndex] = true;
                                        results[currentIndex] = value;
                                    }
                                }
                            },
                            error =>
                            {
                                lock (gate)
                                {
                                    finished = true;
                                    subscriber.OnError(error);
                                    group.Dispose();
                                }
                            },
                            () =>
                            {
                                lock (gate)
                                {
                                    if (!finished)
                                    {
                                        if (!hasResults[currentIndex])
                                        {
                                            subscriber.OnCompleted();
                                            return;
                                        }
                                        hasCompleted[currentIndex] = true;
                                        foreach (var completed in hasCompleted)
                                        {
                                            if (!completed)
                                                return;
                                        }
                                        finished = true;
                                        subscriber.OnNext(results.ToArray());
                                        subscriber.OnCompleted();
                                    }
                                }
                            }));
                    }
                }
                return group;
            });
        }

        #endregion

        #region Let

        public virtual IObservable<TResult> Let<TSource, TResult>(IObservable<TSource> source, Func<IObservable<TSource>, IObservable<TResult>> function)
        {
            return function(source);
        }

        #endregion

        #region ManySelect

        public virtual IObservable<TResult> ManySelect<TSource, TResult>(IObservable<TSource> source, Func<IObservable<TSource>, TResult> selector)
        {
            return ManySelect(source, selector, DefaultScheduler.Instance);
        }

        public virtual IObservable<TResult> ManySelect<TSource, TResult>(IObservable<TSource> source, Func<IObservable<TSource>, TResult> selector, IScheduler scheduler)
        {
            return Observable.Defer<TResult>(() =>
            {
                var chain = default(ChainObservable<TSource>);

                return source
                    .Select(
                        x =>
                        {
                            var curr = new ChainObservable<TSource>(x);

                            if (chain != null)
                                chain.OnNext(curr);
                            chain = curr;

                            return (IObservable<TSource>)curr;
                        })
                    .Do(
                        _ => { },
                        exception =>
                        {
                            if (chain != null)
                                chain.OnError(exception);
                        },
                        () =>
                        {
                            if (chain != null)
                                chain.OnCompleted();
                        })
                    .ObserveOn(scheduler)
                    .Select(selector);
            });
        }

        class ChainObservable<T> : ISubject<IObservable<T>, T>
        {
            T head;
            AsyncSubject<IObservable<T>> tail = new AsyncSubject<IObservable<T>>();

            public ChainObservable(T head)
            {
                this.head = head;
            }

            public IDisposable Subscribe(IObserver<T> observer)
            {
                var g = new CompositeDisposable();
                g.Add(CurrentThreadScheduler.Instance.Schedule(() =>
                {
                    observer.OnNext(head);
                    g.Add(tail.Merge().Subscribe(observer));
                }));
                return g;
            }

            public void OnCompleted()
            {
                OnNext(Observable.Empty<T>());
            }

            public void OnError(Exception error)
            {
                OnNext(Observable.Throw<T>(error));
            }

            public void OnNext(IObservable<T> value)
            {
                tail.OnNext(value);
                tail.OnCompleted();
            }
        }

        #endregion

        #region ToListObservable

        public virtual ListObservable<TSource> ToListObservable<TSource>(IObservable<TSource> source)
        {
            return new ListObservable<TSource>(source);
        }

        #endregion

        #region |> Helpers <|

        private static IObservable<TResult> Combine<TLeft, TRight, TResult>(IObservable<TLeft> leftSource, IObservable<TRight> rightSource, Func<IObserver<TResult>, IDisposable, IDisposable, IObserver<Either<Notification<TLeft>, Notification<TRight>>>> combinerSelector)
        {
            return new AnonymousObservable<TResult>(observer =>
            {
                var leftSubscription = new SingleAssignmentDisposable();
                var rightSubscription = new SingleAssignmentDisposable();

                var combiner = combinerSelector(observer, leftSubscription, rightSubscription);
                var gate = new object();

                leftSubscription.Disposable = leftSource.Materialize().Select(x => Either<Notification<TLeft>, Notification<TRight>>.CreateLeft(x)).Synchronize(gate).Subscribe(combiner);
                rightSubscription.Disposable = rightSource.Materialize().Select(x => Either<Notification<TLeft>, Notification<TRight>>.CreateRight(x)).Synchronize(gate).Subscribe(combiner);

                return new CompositeDisposable(leftSubscription, rightSubscription);
            });
        }

        #endregion
    }
}


text:
package views

import (
	"github.com/gdamore/tcell"
	"unicode"
)

// SimpleStyledText is a form of Text that offers highlighting of the text
// using simple in-line markup.  Its intention is to make it easier to mark
// up hot // keys for menubars, etc.
type SimpleStyledText struct {
	styles map[rune]tcell.Style
	markup []rune
	Text
}

// SetMarkup sets the text used for the string.  It applies markup as follows
// (modeled on tcsh style prompt markup):
//
// * %% - emit a single % in current style
// * %N - normal style
// * %A - alternate style
// * %S - start standout (reverse) style
// * %B - start bold style
// * %U - start underline style
//
// Other styles can be set using %<rune>, if styles are registered.
// Upper case characters and punctuation are reserved for use by the system.
// Lower case are available for use by the user.  (Users may define mappings
// for upper case letters to override system defined styles.)
//
// Note that for simplicity, combining styles is not supported.  By default
// the alternate style is the same as standout (reverse) mode.
//
// Arguably we could have used Markdown syntax instead, but properly doing all
// of Markdown is not trivial, and these escape sequences make it clearer that
// we are not even attempting to do that.
func (t *SimpleStyledText) SetMarkup(s string) {

	markup := []rune(s)
	styl := make([]tcell.Style, 0, len(markup))
	text := make([]rune, 0, len(markup))

	style := t.styles['N']

	esc := false
	for _, r := range markup {
		if esc {
			esc = false
			switch r {
			case '%':
				text = append(text, '%')
				styl = append(styl, style)
			default:
				style = t.styles[r]
			}
			continue
		}
		switch r {
		case '%':
			esc = true
			continue
		default:
			text = append(text, r)
			styl = append(styl, style)
		}
	}

	t.Text.SetText(string(text))
	for i, s := range styl {
		t.SetStyleAt(i, s)
	}
	t.markup = markup
}

// Registers a style for the given rune.  This style will be used for
// text marked with %<r>. See SetMarkup() for more detail.  Note that
// this must be done before using any of the styles with SetMarkup().
// Only letters may be used when registering styles, and be advised that
// the system may have predefined uses for upper case letters.
func (t *SimpleStyledText) RegisterStyle(r rune, style tcell.Style) {
	if r == 'N' {
		t.Text.SetStyle(style)
	}
	if unicode.IsLetter(r) {
		t.styles[r] = style
	}
}

// LookupStyle returns the style registered for the given rune.
// Returns tcell.StyleDefault if no style was previously registered
// for the rune.
func (t *SimpleStyledText) LookupStyle(r rune) tcell.Style {
	return t.styles[r]
}

// Markup returns the text that was set, including markup.
func (t *SimpleStyledText) Markup() string {
	return string(t.markup)
}

// NewSimpleStyledText creates an empty Text.
func NewSimpleStyledText() *SimpleStyledText {
	ss := &SimpleStyledText{}
	// Create map and establish default styles.
	ss.styles = make(map[rune]tcell.Style)
	ss.styles['N'] = tcell.StyleDefault
	ss.styles['S'] = tcell.StyleDefault.Reverse(true)
	ss.styles['U'] = tcell.StyleDefault.Underline(true)
	ss.styles['B'] = tcell.StyleDefault.Bold(true)
	return ss
}


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

namespace Conference.Contracts.Models
{
    public class Speaker
    {
        public int Id
        {
            get;
            set;
        }

        public string FirstName
        {
            get;
            set;
        }

        public string LastName
        {
            get;
            set;
        }

        public string Bio
        {
            get;
            set;
        }

        public string PictureUrl
        {
            get;
            set;
        }

        public string Company
        {
            get;
            set;
        }
    }
}


text:
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')

var index = require('./routes/index');
var signup = require('./routes/signup');
var activity = require('./routes/activity');
var help =  require('./routes/help');
var login =  require('./routes/login');
var addActivity =  require('./routes/addActivity');
var tempSession =  require('./routes/tempSession');
var editActivity =  require('./routes/editActivity');
var apps =  require('./routes/apps');
var contacts =  require('./routes/contacts');
var apps =  require('./routes/apps');
var blockednotifications = require('./routes/blockednotifications');
var addAct =  require('./routes/addAct');
var editActivity2 = require('./routes/editActivity2');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// Add routes here
//app.get('/', index.view);
app.get('/', activity.view);
app.get('/focus', index.view);
app.get('/signup', signup.view);
app.get('/activity', activity.view);
app.get('/help', help.view);
app.get('/login', login.view);
app.get('/addActivity', addActivity.view);
app.get('/tempSession', tempSession.view);
app.get('/editActivity', editActivity.view);
app.get('/contacts', contacts.view);
app.get('/apps', apps.view);
app.get('/blockednotifications', blockednotifications.view);
app.get('/addAct', addAct.addActivity);
app.get('/editActivity2', editActivity.view2); //editActivity2.view);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});


text:
<?php

namespace Gradually\UtilBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\Form;
use Gradually\SearchBundle\Classes\RecruiterSearchHandler;

/**
 * RecruiterUserRepository
 */
class RecruiterUserRepository extends EntityRepository
{
	public function findAllSubscribedGraduates($recruiterId)
	{
		$query = "
			SELECT graduate FROM GraduallyUtilBundle:GraduateUser graduate
			JOIN graduate.recruiters recruiter
			WHERE recruiter.id = :recruiterId
		";

		$params['recruiterId'] = $recruiterId;

		return $this->getEntityManager()->createQuery($query)->setParameters($params)->getResult();
	}

	public function search(Form $form, array $orderBy = array('property' => 'recruiter.id', 'order' => 'ASC'))
	{
		$sh = new RecruiterSearchHandler($this->getEntityManager());

		$sh->prepareQuery($form, $orderBy);

		$query = $this->getEntityManager()->createQuery($sh->getQueryString())->setParameters($sh->getQueryParameters());
		$query->useResultCache(true, 600, 'KEY' . md5($sh->getEncodedQueryString()));

		return $query->getResult();
	}
}


text:
#import "PFObjectFileCoder.h"

#import "PFJSONSerialization.h"
#import "PFObjectFileCodingLogic.h"
#import "PFObjectPrivate.h"
#import "PFObjectState.h"

@implementation PFObjectFileCoder

///--------------------------------------
#pragma mark - Encode
///--------------------------------------

+ (NSData *)dataFromObject:(PFObject *)object usingEncoder:(PFEncoder *)encoder {
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result[@"classname"] = object._state.parseClassName;
    result[@"data"] = [object._state dictionaryRepresentationWithObjectEncoder:encoder];
    return [PFJSONSerialization dataFromJSONObject:result];
}

///--------------------------------------
#pragma mark - Decode
///--------------------------------------

+ (PFObject *)objectFromData:(NSData *)data usingDecoder:(PFDecoder *)decoder {
    NSDictionary *dictionary = [PFJSONSerialization JSONObjectFromData:data];
    NSString *className = dictionary[@"classname"] ?: dictionary[@"className"];
    NSString *objectId = dictionary[@"data"][@"objectId"] ?: dictionary[@"id"];

    PFObject *object = [PFObject objectWithoutDataWithClassName:className objectId:objectId];
    [[[object class] objectFileCodingLogic] updateObject:object fromDictionary:dictionary usingDecoder:decoder];
    return object;
}

@end


text:
brew update && brew cleanup && brew cask cleanup

# Install native apps

# brew tap caskroom/versions

brew cask install spectacle

# dev
brew cask install iterm2
brew cask install sublime-text
brew cask install imagealpha
brew cask install imageoptim

# fun
brew cask install limechat
brew cask install miro-video-converter

# browsers
# brew cask install google-chrome-canary
# brew cask install firefoxnightly
# brew cask install webkit-nightly
brew cask install chromium
# brew cask install torbrowser

# less often
brew cask install disk-inventory-x
brew cask install screenflow
brew cask install gpgtools
brew cask install licecap
brew cask install obs


text:
<?php

namespace EXS\ErrorBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ErrorControllerTest extends WebTestCase
{
    public function testBadpageAction()
    {
        $client = static::createClient();

        // Verify the controller action exists
        $crawler = $client->request('GET', '/_test/error/http/500');
        $this->assertTrue($crawler->filter('html:contains("500 Test")')->count() > 0);
    }
}


text:
package treap

import (
    "time"
    "math/rand"
)

type Treap struct {
    size int
    root *Node
}
type Item struct {
    key int
    value interface{}
}

type Node struct {
    item Item
    priority int
    left, right *Node
}

func newNode(item Item, priority int) *Node {
    return &Node{item, priority, nil, nil}
}

func init() {
    rand.Seed(time.Now().UnixNano())
}

// Returns a treap with no item
func NewTreap() *Treap {
    return &Treap{0, nil}
}

// Returns the items' size in the treap
func (t *Treap) Len() int {
    return t.size
}

// Returns the height of the treap
func (t *Treap) Height() int {
    return height(t.root)
}

func height(root *Node) int {
    if root == nil {
        return 0
    }
    leftHeight, rightHeight := height(root.left), height(root.right)
    if leftHeight > rightHeight {
        return leftHeight + 1
    } else {
        return rightHeight + 1
    }
}

// Returns true if an item with key is exist in the treap
func (t *Treap) IsExist(key int) bool {
    return t.Index(key) != nil
}

// Returns the item with key. If the item is not exist, return nil
func (t *Treap) Index(key int) *Node {
    return index(t.root, key)
}

func index(root *Node, key int) *Node {
    if root == nil {
        return nil
    }
    if root.item.key < key {
        return index(root.right, key)
    } else if root.item.key > key {
        return index(root.left, key)
    }
    return root
}

// Insert insert a new item to the treap. Currently, it support no duplicate
// keys, returns true if the item is inserted to the treap, false if there is
// already an item with the same key
func (t *Treap) Insert (item Item) bool {
    res, flag := insert(t.root, newNode(item, rand.Int()))
    if flag {
        t.root = res
        t.size++
        return true
    }
    return false
}

func rightRotate(node *Node) *Node {
    if node == nil || node.left == nil {
        panic("error occured : node and node's left child must not be nil")
    }
    res := node.left
    node.left = res.right
    res.right = node
    return res
}
func leftRotate(node *Node) *Node {
    if node == nil || node.right == nil {
        panic("error occured : node and node's right child must not be nil")
    }
    res := node.right
    node.right = res.left
    res.left = node
    return res
}
func insert(root *Node, node *Node) (*Node, bool) {
    if root == nil {
        return node, true
    }
    var flag bool = true
    var res *Node = nil
    if node.item.key < root.item.key {
        res, flag = insert(root.left, node)
        if !flag { return root, false }
        root.left = res
		if root.left.priority < root.priority {
            root = rightRotate(root)
		}
	} else if root.item.key < node.item.key {
        res, flag = insert(root.right, node)
        if !flag { return root, false }
        root.right = res
		if root.right.priority < root.priority {
			root = leftRotate(root)
		}
	}
	return root, flag
}

// Delete delete the item with the parameter key, returns true if the item
// with key is really exist in treap, false else
func (t *Treap) Remove (key int) bool {
    res, flag := remove(t.root, key)
    if flag {
        t.root = res
        t.size--
        return true
    }
    return false
}

func remove(root *Node, key int) (*Node, bool) {
    var flag bool = true
    var res *Node = nil
    if root == nil {
        return root, false
    } else if root.item.key > key { //left child
        res, flag = remove(root.left, key)
        if flag == false {
            return root, false
        }
        root.left = res
    } else if root.item.key < key {
        res, flag = remove(root.right, key)
        if flag == false {
            return root, false
        }
        root.right = res
    } else {    // found the item, remove it
        if root.left == nil && root.right == nil {  // leaf node
            return nil, true
        } else if root.left == nil {
            return root.right, true
        } else if root.right == nil {
            return root.left, true
        } else {
            pre, cur := root, root.left
            for cur.right != nil {
                pre = cur
                cur = cur.right
            }
            pre.right = nil
            cur.left = root.left
            cur.right = root.right
            cur.priority = root.priority
            return cur, true
        }
    }
    return root, flag
}

// Perform a preorder traverse using fun
func (t *Treap) Preorder(fun func(Item)) {
    preorder(t.root, fun)
}
// Perform a inorder traverse using fun
func (t *Treap) Inorder(fun func(Item)) {
    inorder(t.root, fun)
}

func preorder(root *Node, fun func(Item)) {
    if root == nil {
        return
    }
    fun(root.item)
    preorder(root.left, fun)
    preorder(root.right, fun)
}

func inorder(root *Node, fun func(Item)) {
    if root == nil {
        return
    }
    inorder(root.left, fun)
    fun(root.item)
    inorder(root.right, fun)
}


text:
<!--

Call Mediator with Clone targets points to named sequences

Log on Console
==============
STATE = INSEQ S1
STATE = SEQ1 S1
STATE = CLONE TARGET1 S1
STATE = CLONE TARGET2 S1
STATE = CLONE TARGET1 S2
STATE = CLONE TARGET2 S2
STATE = SEQ1 S2
STATE = SEQ1 S2
STATE = AGGREGATED STATE
STATE = SEQ1 P3
STATE = INSEQ S2

-->

<definitions xmlns="http://ws.apache.org/ns/synapse">

    <proxy name="TestCallProxy"
           transports="https http"
           startOnLoad="true"
           trace="disable">
        <description/>
        <target>
            <inSequence>
                <log level="custom">
                    <property name="STATE" value="INSEQ S1"/>
                </log>
                <sequence key="SEQ1"/>
                <log level="custom">
                    <property name="STATE" value="INSEQ S2"/>
                </log>
                <header name="To" action="remove"/>
                <property name="RESPONSE" value="true"/>
                <send/>
            </inSequence>
        </target>
    </proxy>

    <endpoint name="EP">
        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    </endpoint>

    <sequence name="SEQ1">
        <log level="custom">
            <property name="STATE" value="SEQ1 S1"/>
        </log>
        <clone>
            <target sequence="Target1"/>
            <target sequence="Target2"/>
        </clone>
        <log level="custom">
            <property name="STATE" value="SEQ1 S2"/>
        </log>
        <aggregate>
            <completeCondition>
                <messageCount/>
            </completeCondition>
            <onComplete xmlns:ns="http://org.apache.synapse/xsd"
                        xmlns:m0="http://services.samples"
                        expression="//m0:getQuoteResponse">
                <log level="custom">
                    <property name="STATE" value="AGGREGATED STATE"/>
                </log>
            </onComplete>
        </aggregate>
        <log level="custom">
            <property name="STATE" value="SEQ1 P3"/>
        </log>
    </sequence>

    <sequence name="Target1">
        <log level="custom">
            <property name="STATE" value="CLONE TARGET1 S1"/>
        </log>
        <call>
            <endpoint key="EP"/>
        </call>
        <log level="custom">
            <property name="STATE" value="CLONE TARGET1 S2"/>
        </log>
    </sequence>

    <sequence name="Target2">
        <log level="custom">
            <property name="STATE" value="CLONE TARGET2 S1"/>
        </log>
        <call>
            <endpoint key="EP"/>
        </call>
        <log level="custom">
            <property name="STATE" value="CLONE TARGET2 S2"/>
        </log>
    </sequence>

</definitions>


text:
function EditLocationWindow (_args) {
    var _ = require('lib/underscore'),
        theme = require('helpers/theme'),
        DoneCancelButtonBar = require('ui/components/DoneCancelButtonBar'),
        SelectLocationWindow = require('ui/components/SelectLocationWindow'),
        GeoCoding = require('network/GeoCoding'),
        GEO = require('helpers/geo'),
        opts = _args,
        location = _args.data.location ? GEO.WKT.read(_args.data.location) : {},
        address = _args.data.address,
        self = Ti.UI.createWindow({
            navBarHidden: true,
            backgroundColor: '#40000000'
        });

    var view = Ti.UI.createView({
        backgroundColor : '#fff',
        borderColor : '#A5A5A5',
        borderWidth : 2,
        left: 50,
        right: 50,
        height: 500
    }),
    headerView = Ti.UI.createView(theme.styles.popup.header.view),
    headerLabel = Ti.UI.createLabel(_.extend({text: L('select_location')},theme.styles.popup.header.label)),
    locationField = Ti.UI.createTextArea({
        editable: false,
        left: 10,
        right: 10,
        top: 110,
        bottom: 90,
        height: 200
    }),
    locationButton = Ti.UI.createButton({
        top: 320,
        height: 90,
        left: 10,
        right: 10,
        enabled: false,
        title: L('select_location')
    }),
    bottomBar = new DoneCancelButtonBar({
        parentWin: self,
        handler: function (e) {
            var result = {
                location: 'POINT('+location.longitude+' '+location.latitude+')'
            };
            self.close();

            opts.handler(result);
        }
    });

    headerView.add(headerLabel);

    view.add(headerView);
    view.add(locationField);
    view.add(locationButton);
    view.add(bottomBar);
    self.add(view);

    locationButton.addEventListener('click', function (e) {
        var selectLocationWindow = new SelectLocationWindow({
            location: location,
            handler: function (e) {
                locationField.value = e.address;
                location = _(e).pick('latitude', 'longitude');
            }
        });

        selectLocationWindow.open();
    });

    self.addEventListener('click', function (e) {
        if (e.source == self) {
            self.close();
        }
    });

    self.addEventListener('open', function (e) {
        if (!_(location).isEmpty()) {
            var latlng = location.latitude + ',' + location.longitude;
            getAddress(latlng);
        } else if (address) {
            getLatLng(address);
        }
    });

    function getAddress (latlng) {
        GeoCoding.geocode({latlng: latlng}).done(function (result) {
            if (result[0]) {
                locationField.value = result[0].formatted_address;
            }
            locationButton.enabled = true;
        }).fail(function (e) {
            locationButton.enabled = true;
        });
    }

    function getLatLng (address) {
        GeoCoding.geocode({address: address}).done(function (result) {
            if (result[0]) {
                locationField.value = result[0].formatted_address;
                location = {
                    latitude: result[0].geometry.location.lat,
                    longitude: result[0].geometry.location.lng
                };
            }
            locationButton.enabled = true;
        }).fail(function (e) {
            locationButton.enabled = true;
        });
    }

    return self;
}

module.exports = EditLocationWindow;


text:
var nock = require('nock');
var assert = require('assert');

module.exports = nock('https://apps.feedhenry.com')
.filteringRequestBody(function(path) {
  return '*';
})
.get('/box/srv/1.1/tst/version', '*')
.reply(200, function(){ return '0.5.0-39'; });